repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/lib/puppet_spec/character_encoding.rb | spec/lib/puppet_spec/character_encoding.rb | # A support module for testing character encoding
module PuppetSpec::CharacterEncoding
def self.with_external_encoding(encoding, &blk)
original_encoding = Encoding.default_external
begin
Encoding.default_external = encoding
yield
ensure
Encoding.default_external = original_encoding
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/lib/puppet_spec/modules.rb | spec/lib/puppet_spec/modules.rb | module PuppetSpec::Modules
class << self
def create(name, dir, options = {})
module_dir = File.join(dir, name)
FileUtils.mkdir_p(module_dir)
environment = options[:environment]
metadata = options[:metadata]
if metadata
metadata[:source] ||= 'github'
metadata[:author] ||= 'puppetlabs'
metadata[:version] ||= '9.9.9'
metadata[:license] ||= 'to kill'
metadata[:dependencies] ||= []
metadata[:name] = "#{metadata[:author]}/#{name}"
File.open(File.join(module_dir, 'metadata.json'), 'w') do |f|
f.write(metadata.to_json)
end
end
tasks = options[:tasks]
if tasks
tasks_dir = File.join(module_dir, 'tasks')
FileUtils.mkdir_p(tasks_dir)
tasks.each do |task_files|
task_files.each do |task_file|
if task_file.is_a?(String)
# default content to acceptable metadata
task_file = { :name => task_file, :content => "{}" }
end
File.write(File.join(tasks_dir, task_file[:name]), task_file[:content])
end
end
end
if (plans = options[:plans])
plans_dir = File.join(module_dir, 'plans')
FileUtils.mkdir_p(plans_dir)
plans.each do |plan_file|
if plan_file.is_a?(String)
# default content to acceptable metadata
plan_file = { :name => plan_file, :content => "{}" }
end
File.write(File.join(plans_dir, plan_file[:name]), plan_file[:content])
end
end
if (scripts = options[:scripts])
scripts_dir = File.join(module_dir, 'scripts')
FileUtils.mkdir_p(scripts_dir)
scripts.each do |script_file|
if script_file.is_a?(String)
script_file = { :name => script_file, :content => "" }
end
File.write(File.join(scripts_dir, script_file[:name]), script_file[:content])
end
end
(options[:files] || {}).each do |fname, content|
path = File.join(module_dir, fname)
FileUtils.mkdir_p(File.dirname(path))
File.write(path, content)
end
Puppet::Module.new(name, module_dir, environment)
end
def generate_files(name, dir, options = {})
module_dir = File.join(dir, name)
FileUtils.mkdir_p(module_dir)
if (metadata = options[:metadata])
File.open(File.join(module_dir, 'metadata.json'), 'w') do |f|
f.write(metadata.to_json)
end
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/lib/puppet_spec/pops.rb | spec/lib/puppet_spec/pops.rb | module PuppetSpec::Pops
extend RSpec::Matchers::DSL
# Checks if an Acceptor has a specific issue in its list of diagnostics
matcher :have_issue do |expected|
match do |actual|
actual.diagnostics.index { |i| i.issue == expected } != nil
end
failure_message do |actual|
"expected Acceptor[#{actual.diagnostics.collect { |i| i.issue.issue_code }.join(',')}] to contain issue #{expected.issue_code}"
end
failure_message_when_negated do |actual|
"expected Acceptor[#{actual.diagnostics.collect { |i| i.issue.issue_code }.join(',')}] to not contain issue #{expected.issue_code}"
end
end
# Checks if an Acceptor has any issues
matcher :have_any_issues do
match do |actual|
!actual.diagnostics.empty?
end
failure_message do |actual|
'expected Acceptor[] to contain at least one issue'
end
failure_message_when_negated do |actual|
"expected Acceptor[#{actual.diagnostics.collect { |i| i.issue.issue_code }.join(',')}] to not contain any issues"
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/lib/puppet_spec/module_tool/stub_source.rb | spec/lib/puppet_spec/module_tool/stub_source.rb | module PuppetSpec
module ModuleTool
class StubSource < SemanticPuppet::Dependency::Source
def inspect; "Stub Source"; end
def host
"http://nowhe.re"
end
def fetch(name)
available_releases[name.tr('/', '-')].values
end
def available_releases
return @available_releases if defined? @available_releases
@available_releases = {
'puppetlabs-java' => {
'10.0.0' => { 'puppetlabs/stdlib' => '4.1.0' },
},
'puppetlabs-stdlib' => {
'4.1.0' => {},
},
'pmtacceptance-stdlib' => {
"4.1.0" => {},
"3.2.0" => {},
"3.1.0" => {},
"3.0.0" => {},
"2.6.0" => {},
"2.5.1" => {},
"2.5.0" => {},
"2.4.0" => {},
"2.3.2" => {},
"2.3.1" => {},
"2.3.0" => {},
"2.2.1" => {},
"2.2.0" => {},
"2.1.3" => {},
"2.0.0" => {},
"1.1.0" => {},
"1.0.0" => {},
},
'pmtacceptance-keystone' => {
'3.0.0-rc2' => { "pmtacceptance/mysql" => ">=0.6.1 <1.0.0", "pmtacceptance/stdlib" => ">= 2.5.0" },
'3.0.0-rc1' => { "pmtacceptance/mysql" => ">=0.6.1 <1.0.0", "pmtacceptance/stdlib" => ">= 2.5.0" },
'2.2.0' => { "pmtacceptance/mysql" => ">=0.6.1 <1.0.0", "pmtacceptance/stdlib" => ">= 2.5.0" },
'2.2.0-rc1' => { "pmtacceptance/mysql" => ">=0.6.1 <1.0.0", "pmtacceptance/stdlib" => ">= 2.5.0" },
'2.1.0' => { "pmtacceptance/mysql" => ">=0.6.1 <1.0.0", "pmtacceptance/stdlib" => ">= 2.5.0" },
'2.0.0' => { "pmtacceptance/mysql" => ">= 0.6.1" },
'1.2.0' => { "pmtacceptance/mysql" => ">= 0.5.0" },
'1.1.1' => { "pmtacceptance/mysql" => ">= 0.5.0" },
'1.1.0' => { "pmtacceptance/mysql" => ">= 0.5.0" },
'1.0.1' => { "pmtacceptance/mysql" => ">= 0.5.0" },
'1.0.0' => { "pmtacceptance/mysql" => ">= 0.5.0" },
'0.2.0' => { "pmtacceptance/mysql" => ">= 0.5.0" },
'0.1.0' => { "pmtacceptance/mysql" => ">= 0.3.0" },
},
'pmtacceptance-mysql' => {
"2.1.0" => { "pmtacceptance/stdlib" => ">= 2.2.1" },
"2.0.1" => { "pmtacceptance/stdlib" => ">= 2.2.1" },
"2.0.0" => { "pmtacceptance/stdlib" => ">= 2.2.1" },
"2.0.0-rc5" => { "pmtacceptance/stdlib" => ">= 2.2.1" },
"2.0.0-rc4" => { "pmtacceptance/stdlib" => ">= 2.2.1" },
"2.0.0-rc3" => { "pmtacceptance/stdlib" => ">= 2.2.1" },
"2.0.0-rc2" => { "pmtacceptance/stdlib" => ">= 2.2.1" },
"2.0.0-rc1" => { "pmtacceptance/stdlib" => ">= 2.2.1" },
"1.0.0" => { "pmtacceptance/stdlib" => ">= 2.2.1" },
"0.9.0" => { "pmtacceptance/stdlib" => ">= 2.2.1" },
"0.8.1" => { "pmtacceptance/stdlib" => ">= 2.2.1" },
"0.8.0" => { "pmtacceptance/stdlib" => ">= 2.2.1" },
"0.7.1" => { "pmtacceptance/stdlib" => ">= 2.2.1" },
"0.7.0" => { "pmtacceptance/stdlib" => ">= 2.2.1" },
"0.6.1" => { "pmtacceptance/stdlib" => ">= 2.2.1" },
"0.6.0" => { "pmtacceptance/stdlib" => ">= 2.2.1" },
"0.5.0" => { "pmtacceptance/stdlib" => ">= 2.2.1" },
"0.4.0" => {},
"0.3.0" => {},
"0.2.0" => {},
},
'pmtacceptance-apache' => {
"0.10.0" => { "pmtacceptance/stdlib" => ">= 2.4.0" },
"0.9.0" => { "pmtacceptance/stdlib" => ">= 2.4.0" },
"0.8.1" => { "pmtacceptance/stdlib" => ">= 2.2.1" },
"0.8.0" => { "pmtacceptance/stdlib" => ">= 2.2.1" },
"0.7.0" => { "pmtacceptance/stdlib" => ">= 2.2.1" },
"0.6.0" => { "pmtacceptance/stdlib" => ">= 2.2.1" },
"0.5.0-rc1" => { "pmtacceptance/stdlib" => ">= 2.2.1" },
"0.4.0" => { "pmtacceptance/stdlib" => ">= 2.2.1" },
"0.3.0" => { "pmtacceptance/stdlib" => ">= 2.2.1" },
"0.2.2" => { "pmtacceptance/stdlib" => ">= 2.2.1" },
"0.2.1" => { "pmtacceptance/stdlib" => ">= 2.2.1" },
"0.2.0" => { "pmtacceptance/stdlib" => ">= 2.2.1" },
"0.1.1" => { "pmtacceptance/stdlib" => ">= 2.2.1" },
"0.0.4" => {},
"0.0.3" => {},
"0.0.2" => {},
"0.0.1" => {},
},
'pmtacceptance-bacula' => {
"0.0.3" => { "pmtacceptance/stdlib" => ">= 2.2.0", "pmtacceptance/mysql" => ">= 1.0.0" },
"0.0.2" => { "pmtacceptance/stdlib" => ">= 2.2.0", "pmtacceptance/mysql" => ">= 0.0.1" },
"0.0.1" => { "pmtacceptance/stdlib" => ">= 2.2.0" },
},
'puppetlabs-oneversion' => {
"0.0.1" => {}
}
}
@available_releases.each do |name, versions|
versions.each do |version, deps|
deps, metadata = deps.partition { |k,v| k.is_a? String }
dependencies = Hash[deps.map { |k, v| [ k.tr('/', '-'), v ] }]
versions[version] = create_release(name, version, dependencies).tap do |release|
release.meta_def(:prepare) { }
release.meta_def(:install) { |x| @install_dir = x.to_s }
release.meta_def(:install_dir) { @install_dir }
release.meta_def(:metadata) do
metadata = Hash[metadata].merge(
:name => name,
:version => version,
:source => '', # GRR, Puppet!
:author => '', # GRR, Puppet!
:license => '', # GRR, Puppet!
:dependencies => dependencies.map do |dep, range|
{ :name => dep, :version_requirement => range }
end
)
Hash[metadata.map { |k,v| [ k.to_s, v ] }]
end
end
end
end
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/lib/puppet_spec/module_tool/shared_functions.rb | spec/lib/puppet_spec/module_tool/shared_functions.rb | require 'puppet/util/json'
module PuppetSpec
module ModuleTool
module SharedFunctions
def remote_release(name, version)
remote_source.available_releases[name][version]
end
def preinstall(name, version, options = { :into => primary_dir })
release = remote_release(name, version)
raise "Could not preinstall #{name} v#{version}" if release.nil?
name = release.name[/-(.*)/, 1]
moddir = File.join(options[:into], name)
FileUtils.mkdir_p(moddir)
File.open(File.join(moddir, 'metadata.json'), 'w') do |file|
file.puts(Puppet::Util::Json.dump(release.metadata))
end
end
def mark_changed(path)
app = Puppet::ModuleTool::Applications::Checksummer
allow(app).to receive(:run).with(path).and_return(['README'])
end
def graph_should_include(name, options)
releases = flatten_graph(subject[:graph] || [])
release = releases.find { |x| x[:name] == name }
if options.nil?
expect(release).to be_nil
else
from = options.keys.find { |k| k.nil? || k.is_a?(SemanticPuppet::Version) }
to = options.delete(from)
if to or from
options[:previous_version] ||= from
options[:version] ||= to
end
expect(release).not_to be_nil
expect(release).to include options
end
end
def flatten_graph(graph)
graph + graph.map { |sub| flatten_graph(sub[:dependencies]) }.flatten
end
def v(str)
SemanticPuppet::Version.parse(str)
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/lib/puppet/certificate_factory.rb | spec/lib/puppet/certificate_factory.rb | require 'puppet/ssl'
# This class encapsulates the logic of creating and adding extensions to X509
# certificates.
#
# @api private
module Puppet::CertificateFactory
# Create a new X509 certificate and add any needed extensions to the cert.
#
# @param cert_type [Symbol] The certificate type to create, which specifies
# what extensions are added to the certificate.
# One of (:ca, :terminalsubca, :server, :ocsp, :client)
# @param csr [Puppet::SSL::CertificateRequest] The signing request associated with
# the certificate being created.
# @param issuer [OpenSSL::X509::Certificate, OpenSSL::X509::Request] An X509 CSR
# if this is a self signed certificate, or the X509 certificate of the CA if
# this is a CA signed certificate.
# @param serial [Integer] The serial number for the given certificate, which
# MUST be unique for the given CA.
# @param ttl [String] The duration of the validity for the given certificate.
#
# @api public
#
# @return [OpenSSL::X509::Certificate]
def self.build(cert_type, csr, issuer, serial, ttl = 3600)
# Work out if we can even build the requested type of certificate.
build_extensions = "build_#{cert_type}_extensions"
respond_to?(build_extensions) or
raise ArgumentError, _("%{cert_type} is an invalid certificate type!") % { cert_type: cert_type }
raise ArgumentError, _("Certificate TTL must be an integer") unless ttl.nil? || ttl.is_a?(Integer)
# set up the certificate, and start building the content.
cert = OpenSSL::X509::Certificate.new
cert.version = 2 # X509v3
cert.subject = csr.content.subject
cert.issuer = issuer.subject
cert.public_key = csr.content.public_key
cert.serial = serial
# Make the certificate valid as of yesterday, because so many people's
# clocks are out of sync. This gives one more day of validity than people
# might expect, but is better than making every person who has a messed up
# clock fail, and better than having every cert we generate expire a day
# before the user expected it to when they asked for "one year".
cert.not_before = Time.now - (60*60*24)
cert.not_after = Time.now + ttl
add_extensions_to(cert, csr, issuer, send(build_extensions))
return cert
end
# Add X509v3 extensions to the given certificate.
#
# @param cert [OpenSSL::X509::Certificate] The certificate to add the
# extensions to.
# @param csr [OpenSSL::X509::Request] The CSR associated with the given
# certificate, which may specify requested extensions for the given cert.
# See https://tools.ietf.org/html/rfc2985 Section 5.4.2 Extension request
# @param issuer [OpenSSL::X509::Certificate, OpenSSL::X509::Request] An X509 CSR
# if this is a self signed certificate, or the X509 certificate of the CA if
# this is a CA signed certificate.
# @param extensions [Hash<String, Array<String> | String>] The extensions to
# add to the certificate, based on the certificate type being created (CA,
# server, client, etc)
#
# @api private
#
# @return [void]
def self.add_extensions_to(cert, csr, issuer, extensions)
ef = OpenSSL::X509::ExtensionFactory.new
ef.subject_certificate = cert
ef.issuer_certificate = issuer.is_a?(OpenSSL::X509::Request) ? cert : issuer
# Extract the requested extensions from the CSR.
requested_exts = csr.request_extensions.inject({}) do |hash, re|
hash[re["oid"]] = [re["value"], re["critical"]]
hash
end
# Produce our final set of extensions. We deliberately order these to
# build the way we want:
# 1. "safe" default values, like the comment, that no one cares about.
# 2. request extensions, from the CSR
# 3. extensions based on the type we are generating
# 4. overrides, which we always want to have in their form
#
# This ordering *is* security-critical, but we want to allow the user
# enough rope to shoot themselves in the foot, if they want to ignore our
# advice and externally approve a CSR that sets the basicConstraints.
#
# Swapping the order of 2 and 3 would ensure that you couldn't slip a
# certificate through where the CA constraint was true, though, if
# something went wrong up there. --daniel 2011-10-11
defaults = { "nsComment" => "Puppet Ruby/OpenSSL Internal Certificate" }
# See https://www.openssl.org/docs/apps/x509v3_config.html
# for information about the special meanings of 'hash', 'keyid', 'issuer'
override = {
"subjectKeyIdentifier" => "hash",
"authorityKeyIdentifier" => "keyid,issuer"
}
exts = [defaults, requested_exts, extensions, override].
inject({}) {|ret, val| ret.merge(val) }
cert.extensions = exts.map do |oid, val|
generate_extension(ef, oid, *val)
end
end
private_class_method :add_extensions_to
# Woot! We're a CA.
def self.build_ca_extensions
{
# This was accidentally omitted in the previous version of this code: an
# effort was made to add it last, but that actually managed to avoid
# adding it to the certificate at all.
#
# We have some sort of bug, which means that when we add it we get a
# complaint that the issuer keyid can't be fetched, which breaks all
# sorts of things in our test suite and, e.g., bootstrapping the CA.
#
# https://tools.ietf.org/html/rfc5280#section-4.2.1.1 says that, to be a
# conforming CA we MAY omit the field if we are self-signed, which I
# think gives us a pass in the specific case.
#
# It also notes that we MAY derive the ID from the subject and serial
# number of the issuer, or from the key ID, and we definitely have the
# former data, should we want to restore this...
#
# Anyway, preserving this bug means we don't risk breaking anything in
# the field, even though it would be nice to have. --daniel 2011-10-11
#
# "authorityKeyIdentifier" => "keyid:always,issuer:always",
"keyUsage" => [%w{cRLSign keyCertSign}, true],
"basicConstraints" => ["CA:TRUE", true],
}
end
# We're a terminal CA, probably not self-signed.
def self.build_terminalsubca_extensions
{
"keyUsage" => [%w{cRLSign keyCertSign}, true],
"basicConstraints" => ["CA:TRUE,pathlen:0", true],
}
end
# We're a normal server.
def self.build_server_extensions
{
"keyUsage" => [%w{digitalSignature keyEncipherment}, true],
"extendedKeyUsage" => [%w{serverAuth clientAuth}, true],
"basicConstraints" => ["CA:FALSE", true],
}
end
# Um, no idea.
def self.build_ocsp_extensions
{
"keyUsage" => [%w{nonRepudiation digitalSignature}, true],
"extendedKeyUsage" => [%w{serverAuth OCSPSigning}, true],
"basicConstraints" => ["CA:FALSE", true],
}
end
# Normal client.
def self.build_client_extensions
{
"keyUsage" => [%w{nonRepudiation digitalSignature keyEncipherment}, true],
# We don't seem to use this, but that seems much more reasonable here...
"extendedKeyUsage" => [%w{clientAuth emailProtection}, true],
"basicConstraints" => ["CA:FALSE", true],
"nsCertType" => "client,email",
}
end
# Generate an extension with the given OID, value, and critical state
#
# @param oid [String] The numeric value or short name of a given OID. X509v3
# extensions must be passed by short name or long name, while custom
# extensions may be passed by short name, long name, oid numeric OID.
# @param ef [OpenSSL::X509::ExtensionFactory] The extension factory to use
# when generating the extension.
# @param val [String, Array<String>] The extension value.
# @param crit [true, false] Whether the given extension is critical, defaults
# to false.
#
# @return [OpenSSL::X509::Extension]
#
# @api private
def self.generate_extension(ef, oid, val, crit = false)
val = val.join(', ') unless val.is_a? String
# Enforce the X509v3 rules about subjectAltName being critical:
# specifically, it SHOULD NOT be critical if we have a subject, which we
# always do. --daniel 2011-10-18
crit = false if oid == "subjectAltName"
if Puppet::SSL::Oids.subtree_of?('id-ce', oid) or Puppet::SSL::Oids.subtree_of?('id-pkix', oid)
# Attempt to create a X509v3 certificate extension. Standard certificate
# extensions may need access to the associated subject certificate and
# issuing certificate, so must be created by the OpenSSL::X509::ExtensionFactory
# which provides that context.
ef.create_ext(oid, val, crit)
else
# This is not an X509v3 extension which means that the extension
# factory cannot generate it. We need to generate the extension
# manually.
OpenSSL::X509::Extension.new(oid, OpenSSL::ASN1::UTF8String.new(val).to_der, crit)
end
end
private_class_method :generate_extension
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/lib/puppet/indirector_proxy.rb | spec/lib/puppet/indirector_proxy.rb | class Puppet::IndirectorProxy
class ProxyId
attr_accessor :name
def initialize(name)
self.name = name
end
end
# We should have some way to identify if we got a valid object back with the
# current values, no?
attr_accessor :value, :proxyname
alias_method :name, :value
alias_method :name=, :value=
def initialize(value, proxyname)
self.value = value
self.proxyname = proxyname
end
def self.indirection
ProxyId.new("file_metadata")
end
def self.from_binary(raw)
new(raw)
end
def self.from_data_hash(data)
new(data['value'])
end
def to_data_hash
{ 'value' => value }
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/lib/puppet/test_ca.rb | spec/lib/puppet/test_ca.rb | module Puppet
class TestCa
CERT_VALID_FROM = Time.at(0).freeze # 1969-12-31 16:00:00 -0800
CERT_VALID_UNTIL = (Time.now + (10 * 365 * 24 * 60 * 60)).freeze # 10 years from now
CA_EXTENSIONS = [
["basicConstraints", "CA:TRUE", true],
["keyUsage", "keyCertSign, cRLSign", true],
["subjectKeyIdentifier", "hash", false],
["nsComment", "Puppet Server Internal Certificate", false],
["authorityKeyIdentifier", "keyid:always", false]
].freeze
attr_reader :ca_cert, :ca_crl, :key
@serial = 0
def self.next_serial
id = @serial
@serial += 1
id
end
def initialize(name = 'Test CA')
@digest = OpenSSL::Digest::SHA256.new
info = create_cacert(name)
@key = info[:private_key]
@ca_cert = info[:cert]
@ca_crl = create_crl(@ca_cert, @key)
end
def create_request(name)
key = OpenSSL::PKey::RSA.new(2048)
csr = OpenSSL::X509::Request.new
csr.public_key = key.public_key
csr.subject = OpenSSL::X509::Name.new([["CN", name]])
csr.version = 2
csr.sign(key, @digest)
{ private_key: key, csr: csr }
end
def create_cert(name, issuer_cert, issuer_key, opts = {})
key, cert = build_cert(name, issuer_cert.subject, opts)
ef = extension_factory_for(issuer_cert, cert)
if opts[:subject_alt_names]
ext = ef.create_extension(["subjectAltName", opts[:subject_alt_names], false])
cert.add_extension(ext)
end
if exts = opts[:extensions]
exts.each do |e|
cert.add_extension(OpenSSL::X509::Extension.new(*e))
end
end
cert.sign(issuer_key, @digest)
{ private_key: key, cert: cert }
end
def create_intermediate_cert(name, issuer_cert, issuer_key)
key, cert = build_cert(name, issuer_cert.subject)
ef = extension_factory_for(issuer_cert, cert)
CA_EXTENSIONS.each do |ext|
cert.add_extension(ef.create_extension(*ext))
end
cert.sign(issuer_key, @digest)
{ private_key: key, cert: cert }
end
def create_cacert(name)
issuer = OpenSSL::X509::Name.new([["CN", name]])
key, cert = build_cert(name, issuer)
ef = extension_factory_for(cert, cert)
CA_EXTENSIONS.each do |ext|
cert.add_extension(ef.create_extension(*ext))
end
cert.sign(key, @digest)
{ private_key: key, cert: cert }
end
def create_crl(issuer_cert, issuer_key)
crl = OpenSSL::X509::CRL.new
crl.version = 1
crl.issuer = issuer_cert.subject
ef = extension_factory_for(issuer_cert)
crl.add_extension(
ef.create_extension(["authorityKeyIdentifier", "keyid:always", false]))
crl.add_extension(
OpenSSL::X509::Extension.new("crlNumber", OpenSSL::ASN1::Integer(0)))
crl.last_update = CERT_VALID_FROM
crl.next_update = CERT_VALID_UNTIL
crl.sign(issuer_key, @digest)
crl
end
def sign(csr, opts = {})
cert = OpenSSL::X509::Certificate.new
cert.public_key = csr.public_key
cert.subject = csr.subject
cert.issuer = @ca_cert.subject
cert.version = 2
cert.serial = self.class.next_serial
cert.not_before = CERT_VALID_FROM
cert.not_after = CERT_VALID_UNTIL
ef = extension_factory_for(@ca_cert, cert)
if opts[:subject_alt_names]
ext = ef.create_extension(["subjectAltName", opts[:subject_alt_names], false])
cert.add_extension(ext)
end
cert.sign(@key, @digest)
Puppet::SSL::Certificate.from_instance(cert)
end
def revoke(cert, crl = @crl, issuer_key = @key)
revoked = OpenSSL::X509::Revoked.new
revoked.serial = cert.serial
revoked.time = Time.now
enum = OpenSSL::ASN1::Enumerated(OpenSSL::OCSP::REVOKED_STATUS_KEYCOMPROMISE)
ext = OpenSSL::X509::Extension.new("CRLReason", enum)
revoked.add_extension(ext)
crl.add_revoked(revoked)
crl.sign(issuer_key, @digest)
end
def generate(name, opts)
info = create_request(name)
cert = sign(info[:csr], opts).content
info.merge(cert: cert)
end
private
def build_cert(name, issuer, opts = {})
key = if opts[:key_type] == :ec
key = OpenSSL::PKey::EC.generate('prime256v1')
elsif opts[:reuse_key]
key = opts[:reuse_key]
else
key = OpenSSL::PKey::RSA.new(2048)
end
cert = OpenSSL::X509::Certificate.new
cert.public_key = key
cert.subject = OpenSSL::X509::Name.new([["CN", name]])
cert.issuer = issuer
cert.version = 2
cert.serial = self.class.next_serial
cert.not_before = CERT_VALID_FROM
cert.not_after = CERT_VALID_UNTIL
[key, cert]
end
def extension_factory_for(ca, cert = nil)
ef = OpenSSL::X509::ExtensionFactory.new
ef.issuer_certificate = ca
ef.subject_certificate = cert if cert
ef
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/lib/puppet/indirector_testing.rb | spec/lib/puppet/indirector_testing.rb | require 'puppet/indirector'
class Puppet::IndirectorTesting
extend Puppet::Indirector
indirects :indirector_testing
# We should have some way to identify if we got a valid object back with the
# current values, no?
attr_accessor :value
alias_method :name, :value
alias_method :name=, :value=
def initialize(value)
self.value = value
end
def self.from_binary(raw)
new(raw)
end
def self.from_data_hash(data)
new(data['value'])
end
def to_binary
value
end
def to_data_hash
{ 'value' => value }
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/lib/puppet/indirector/indirector_testing/memory.rb | spec/lib/puppet/indirector/indirector_testing/memory.rb | require 'puppet/indirector/memory'
class Puppet::IndirectorTesting::Memory < Puppet::Indirector::Memory
def supports_remote_requests?
true
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/lib/puppet/indirector/indirector_testing/msgpack.rb | spec/lib/puppet/indirector/indirector_testing/msgpack.rb | require 'puppet/indirector_testing'
require 'puppet/indirector/msgpack'
class Puppet::IndirectorTesting::Msgpack < Puppet::Indirector::Msgpack
desc "Testing the MessagePack indirector"
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/lib/puppet/indirector/indirector_testing/json.rb | spec/lib/puppet/indirector/indirector_testing/json.rb | require 'puppet/indirector_testing'
require 'puppet/indirector/json'
class Puppet::IndirectorTesting::JSON < Puppet::Indirector::JSON
desc "Testing the JSON indirector"
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/lib/puppet/face/basetest.rb | spec/lib/puppet/face/basetest.rb | require 'puppet/face'
Puppet::Face.define(:basetest, '0.0.1') do
copyright "Puppet Inc.", 2011
license "Apache 2 license; see COPYING"
summary "This is just so tests don't fail"
option "--[no-]boolean"
option "--mandatory ARGUMENT"
action :foo do
option("--action")
when_invoked do |*args| args.length end
end
action :return_true do
summary "just returns true"
when_invoked do |options| true end
end
action :return_false do
summary "just returns false"
when_invoked do |options| false end
end
action :return_nil do
summary "just returns nil"
when_invoked do |options| nil end
end
action :raise do
summary "just raises an exception"
when_invoked do |options| raise ArgumentError, "your failure" end
end
action :with_s_rendering_hook do
summary "has a rendering hook for 's'"
when_invoked do |options| "this is not the hook you are looking for" end
when_rendering :s do |value| "you invoked the 's' rendering hook" end
end
action :count_args do
summary "return the count of arguments given"
when_invoked do |*args| args.length - 1 end
end
action :with_specific_exit_code do
summary "just call exit with the desired exit code"
when_invoked do |options| exit(5) end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/lib/puppet/face/huzzah.rb | spec/lib/puppet/face/huzzah.rb | require 'puppet/face'
Puppet::Face.define(:huzzah, '2.0.1') do
copyright "Puppet Inc.", 2011
license "Apache 2 license; see COPYING"
summary "life is a thing for celebration"
action(:bar) { when_invoked { |options| "is where beer comes from" } }
action(:call_older) { when_invoked { |_| method_on_older } }
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/lib/puppet/face/version_matching.rb | spec/lib/puppet/face/version_matching.rb | require 'puppet/face'
# The set of versions here are used explicitly in the interface_spec; if you
# change this you need to ensure that is still correct. --daniel 2011-04-21
['1.0.0', '1.0.1', '1.1.0', '1.1.1', '2.0.0'].each do |version|
Puppet::Face.define(:version_matching, version) do
copyright "Puppet Inc.", 2011
license "Apache 2 license; see COPYING"
summary "version matching face #{version}"
action(:version) { when_invoked { |options| version } }
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/lib/puppet/face/1.0.0/huzzah.rb | spec/lib/puppet/face/1.0.0/huzzah.rb | require 'puppet/face'
Puppet::Face.define(:huzzah, '1.0.0') do
copyright "Puppet Inc.", 2011
license "Apache 2 license; see COPYING"
summary "life is a thing for celebration"
action(:obsolete_in_core) { when_invoked { |_| "you are in obsolete core now!" } }
action(:call_newer) { when_invoked { |_| method_on_newer } }
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/lib/puppet/face/huzzah/obsolete.rb | spec/lib/puppet/face/huzzah/obsolete.rb | Puppet::Face.define(:huzzah, '1.0.0') do
action :obsolete do
summary "This is an action on version 1.0.0 of the face"
when_invoked do |options| options end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/environments_spec.rb | spec/unit/environments_spec.rb | require 'spec_helper'
require 'puppet/environments'
require 'puppet/file_system'
describe Puppet::Environments do
FS = Puppet::FileSystem
module FsRemove
def remove
@properties[:directory?] = false
@properties[:exist?] = false
@properties[:executable?] = false
end
end
before(:each) do
Puppet.settings.initialize_global_settings
Puppet[:environment_timeout] = "unlimited"
Puppet[:versioned_environment_dirs] = true
end
let(:directory_tree) do
FS::MemoryFile.a_directory(File.expand_path("top_level_dir"), [
FS::MemoryFile.a_directory("envdir", [
FS::MemoryFile.a_regular_file_containing("ignored_file", ''),
FS::MemoryFile.a_directory("an_environment", [
FS::MemoryFile.a_missing_file("environment.conf"),
FS::MemoryFile.a_directory("modules"),
FS::MemoryFile.a_directory("manifests"),
]),
FS::MemoryFile.a_directory("another_environment", [
FS::MemoryFile.a_missing_file("environment.conf"),
]),
FS::MemoryFile.a_missing_file("doesnotexist"),
FS::MemoryFile.a_symlink("symlinked_environment", File.expand_path(File.join("top_level_dir", "versioned_env")))]),
FS::MemoryFile.a_directory("versioned_env", [
FS::MemoryFile.a_regular_file_containing("environment.conf", ''),
FS::MemoryFile.a_directory("modules"),
FS::MemoryFile.a_directory("manifests"),
]),
FS::MemoryFile.a_missing_file("missing")
])
end
describe "directories loader" do
it "lists environments" do
global_path_1_location = File.expand_path("global_path_1")
global_path_2_location = File.expand_path("global_path_2")
global_path_1 = FS::MemoryFile.a_directory(global_path_1_location)
global_path_2 = FS::MemoryFile.a_directory(global_path_2_location)
loader_from(:filesystem => [directory_tree, global_path_1, global_path_2],
:directory => directory_tree.children.first,
:modulepath => [global_path_1_location, global_path_2_location]) do |loader|
expect(loader.list).to contain_exactly(
environment(:an_environment).
with_manifest("#{FS.path_string(directory_tree)}/envdir/an_environment/manifests").
with_modulepath(["#{FS.path_string(directory_tree)}/envdir/an_environment/modules",
global_path_1_location,
global_path_2_location]),
environment(:another_environment),
environment(:symlinked_environment).
with_manifest("#{FS.path_string(directory_tree)}/versioned_env/manifests").
with_modulepath(["#{FS.path_string(directory_tree)}/versioned_env/modules",
global_path_1_location,
global_path_2_location]))
end
end
it "has search_paths" do
loader_from(:filesystem => [directory_tree],
:directory => directory_tree.children.first) do |loader|
expect(loader.search_paths).to eq(["file://#{directory_tree.children.first}"])
end
end
it "ignores directories that are not valid env names (alphanumeric and _)" do
envdir = FS::MemoryFile.a_directory(File.expand_path("envdir"), [
FS::MemoryFile.a_directory(".foo"),
FS::MemoryFile.a_directory("bar-thing"),
FS::MemoryFile.a_directory("with spaces"),
FS::MemoryFile.a_directory("some.thing"),
FS::MemoryFile.a_directory("env1", [
FS::MemoryFile.a_missing_file("environment.conf"),
]),
FS::MemoryFile.a_directory("env2", [
FS::MemoryFile.a_missing_file("environment.conf"),
]),
])
loader_from(:filesystem => [envdir],
:directory => envdir) do |loader|
expect(loader.list).to contain_exactly(environment(:env1), environment(:env2))
end
end
it "proceeds with non-existant env dir" do
loader_from(:filesystem => [directory_tree],
:directory => directory_tree.children.last) do |loader|
expect(loader.list).to eq([])
end
end
it "gets a particular environment" do
loader_from(:filesystem => [directory_tree],
:directory => directory_tree.children.first) do |loader|
expect(loader.get("an_environment")).to environment(:an_environment)
end
end
it "gets a symlinked environment" do
loader_from(:filesystem => [directory_tree],
:directory => directory_tree.children.first) do |loader|
expect(loader.get("symlinked_environment")).to environment(:symlinked_environment)
end
end
it "sets the environment's configured and resolved paths set when symlinked" do
loader_from(:filesystem => [directory_tree],
:directory => directory_tree.children.first) do |loader|
env = loader.get("symlinked_environment")
expect(env.resolved_path).to eq("#{FS.path_string(directory_tree)}/versioned_env")
expect(env.configured_path).to eq("#{FS.path_string(directory_tree)}/envdir/symlinked_environment")
end
end
it "ignores symlinked environments when `:versioned_environment_dirs` is false" do
Puppet[:versioned_environment_dirs] = false
loader_from(:filesystem => [directory_tree],
:directory => directory_tree.children.first) do |loader|
expect(loader.get("symlinked_environment")).to be_nil
end
end
it "raises error when environment not found" do
loader_from(:filesystem => [directory_tree],
:directory => directory_tree.children.first) do |loader|
expect do
loader.get!("doesnotexist")
end.to raise_error(Puppet::Environments::EnvironmentNotFound)
end
end
it "returns nil if an environment can't be found" do
loader_from(:filesystem => [directory_tree],
:directory => directory_tree.children.first) do |loader|
expect(loader.get("doesnotexist")).to be_nil
end
end
it "implements guard and unguard" do
loader_from(:filesystem => [directory_tree],
:directory => directory_tree.children.first) do |loader|
expect(loader.guard('env1')).to be_nil
expect(loader.unguard('env1')).to be_nil
end
end
context "with an environment.conf" do
let(:envdir) do
FS::MemoryFile.a_directory(File.expand_path("envdir"), [
FS::MemoryFile.a_directory("env1", [
FS::MemoryFile.a_regular_file_containing("environment.conf", content),
]),
])
end
let(:manifestdir) { FS::MemoryFile.a_directory(File.expand_path("/some/manifest/path")) }
let(:modulepath) do
[
FS::MemoryFile.a_directory(File.expand_path("/some/module/path")),
FS::MemoryFile.a_directory(File.expand_path("/some/other/path")),
]
end
let(:content) do
<<-EOF
manifest=#{manifestdir}
modulepath=#{modulepath.join(File::PATH_SEPARATOR)}
config_version=/some/script
static_catalogs=false
EOF
end
it "reads environment.conf settings" do
loader_from(:filesystem => [envdir, manifestdir, modulepath].flatten,
:directory => envdir) do |loader|
expect(loader.get("env1")).to environment(:env1).
with_manifest(manifestdir.path).
with_modulepath(modulepath.map(&:path))
end
end
it "does not append global_module_path to environment.conf modulepath setting" do
global_path_location = File.expand_path("global_path")
global_path = FS::MemoryFile.a_directory(global_path_location)
loader_from(:filesystem => [envdir, manifestdir, modulepath, global_path].flatten,
:directory => envdir,
:modulepath => [global_path]) do |loader|
expect(loader.get("env1")).to environment(:env1).
with_manifest(manifestdir.path).
with_modulepath(modulepath.map(&:path))
end
end
it "reads config_version setting" do
loader_from(:filesystem => [envdir, manifestdir, modulepath].flatten,
:directory => envdir) do |loader|
expect(loader.get("env1")).to environment(:env1).
with_manifest(manifestdir.path).
with_modulepath(modulepath.map(&:path)).
with_config_version(File.expand_path('/some/script'))
end
end
it "reads static_catalogs setting" do
loader_from(:filesystem => [envdir, manifestdir, modulepath].flatten,
:directory => envdir) do |loader|
expect(loader.get("env1")).to environment(:env1).
with_manifest(manifestdir.path).
with_modulepath(modulepath.map(&:path)).
with_config_version(File.expand_path('/some/script')).
with_static_catalogs(false)
end
end
it "accepts an empty environment.conf without warning" do
content = nil
envdir = FS::MemoryFile.a_directory(File.expand_path("envdir"), [
FS::MemoryFile.a_directory("env1", [
FS::MemoryFile.a_regular_file_containing("environment.conf", content),
]),
])
manifestdir = FS::MemoryFile.a_directory(File.join(envdir, "env1", "manifests"))
modulesdir = FS::MemoryFile.a_directory(File.join(envdir, "env1", "modules"))
global_path_location = File.expand_path("global_path")
global_path = FS::MemoryFile.a_directory(global_path_location)
loader_from(:filesystem => [envdir, manifestdir, modulesdir, global_path].flatten,
:directory => envdir,
:modulepath => [global_path]) do |loader|
expect(loader.get("env1")).to environment(:env1).
with_manifest("#{FS.path_string(envdir)}/env1/manifests").
with_modulepath(["#{FS.path_string(envdir)}/env1/modules", global_path_location]).
with_config_version(nil).
with_static_catalogs(true)
end
expect(@logs).to be_empty
end
it "logs a warning, but processes the main settings if there are extraneous sections" do
content << "[foo]"
loader_from(:filesystem => [envdir, manifestdir, modulepath].flatten,
:directory => envdir) do |loader|
expect(loader.get("env1")).to environment(:env1).
with_manifest(manifestdir.path).
with_modulepath(modulepath.map(&:path)).
with_config_version(File.expand_path('/some/script'))
end
expect(@logs.map(&:to_s).join).to match(/Invalid.*at.*\/env1.*may not have sections.*ignored: 'foo'/)
end
it "logs a warning, but processes the main settings if there are any extraneous settings" do
content << "dog=arf\n"
content << "cat=mew\n"
loader_from(:filesystem => [envdir, manifestdir, modulepath].flatten,
:directory => envdir) do |loader|
expect(loader.get("env1")).to environment(:env1).
with_manifest(manifestdir.path).
with_modulepath(modulepath.map(&:path)).
with_config_version(File.expand_path('/some/script'))
end
expect(@logs.map(&:to_s).join).to match(/Invalid.*at.*\/env1.*unknown setting.*dog, cat/)
end
it "logs a warning, but processes the main settings if there are any ignored sections" do
content << "dog=arf\n"
content << "cat=mew\n"
content << "[ignored]\n"
content << "cow=moo\n"
loader_from(:filesystem => [envdir, manifestdir, modulepath].flatten,
:directory => envdir) do |loader|
expect(loader.get("env1")).to environment(:env1).
with_manifest(manifestdir.path).
with_modulepath(modulepath.map(&:path)).
with_config_version(File.expand_path('/some/script'))
end
expect(@logs.map(&:to_s).join).to match(/Invalid.*at.*\/env1.*The following sections are being ignored: 'ignored'/)
expect(@logs.map(&:to_s).join).to match(/Invalid.*at.*\/env1.*unknown setting.*dog, cat/)
end
it "interpretes relative paths from the environment's directory" do
content = <<-EOF
manifest=relative/manifest
modulepath=relative/modules
config_version=relative/script
EOF
envdir = FS::MemoryFile.a_directory(File.expand_path("envdir"), [
FS::MemoryFile.a_directory("env1", [
FS::MemoryFile.a_regular_file_containing("environment.conf", content),
FS::MemoryFile.a_missing_file("modules"),
FS::MemoryFile.a_directory('relative', [
FS::MemoryFile.a_directory('modules'),
]),
]),
])
loader_from(:filesystem => [envdir],
:directory => envdir) do |loader|
expect(loader.get("env1")).to environment(:env1).
with_manifest(File.join(envdir, 'env1', 'relative', 'manifest')).
with_modulepath([File.join(envdir, 'env1', 'relative', 'modules')]).
with_config_version(File.join(envdir, 'env1', 'relative', 'script'))
end
end
it "interprets glob modulepaths from the environment's directory" do
allow(Dir).to receive(:glob).with(File.join(envdir, 'env1', 'other', '*', 'modules')).and_return([
File.join(envdir, 'env1', 'other', 'foo', 'modules'),
File.join(envdir, 'env1', 'other', 'bar', 'modules')
])
content = <<-EOF
manifest=relative/manifest
modulepath=relative/modules#{File::PATH_SEPARATOR}other/*/modules
config_version=relative/script
EOF
envdir = FS::MemoryFile.a_directory(File.expand_path("envdir"), [
FS::MemoryFile.a_directory("env1", [
FS::MemoryFile.a_regular_file_containing("environment.conf", content),
FS::MemoryFile.a_missing_file("modules"),
FS::MemoryFile.a_directory('relative', [
FS::MemoryFile.a_directory('modules'),
]),
FS::MemoryFile.a_directory('other', [
FS::MemoryFile.a_directory('foo', [
FS::MemoryFile.a_directory('modules'),
]),
FS::MemoryFile.a_directory('bar', [
FS::MemoryFile.a_directory('modules'),
]),
]),
]),
])
loader_from(:filesystem => [envdir],
:directory => envdir) do |loader|
expect(loader.get("env1")).to environment(:env1).
with_manifest(File.join(envdir, 'env1', 'relative', 'manifest')).
with_modulepath([File.join(envdir, 'env1', 'relative', 'modules'),
File.join(envdir, 'env1', 'other', 'foo', 'modules'),
File.join(envdir, 'env1', 'other', 'bar', 'modules')]).
with_config_version(File.join(envdir, 'env1', 'relative', 'script'))
end
end
it "interpolates other setting values correctly" do
modulepath = [
File.expand_path('/some/absolute'),
'$basemodulepath',
'modules'
].join(File::PATH_SEPARATOR)
content = <<-EOF
manifest=$confdir/whackymanifests
modulepath=#{modulepath}
config_version=$vardir/random/scripts
EOF
some_absolute_dir = FS::MemoryFile.a_directory(File.expand_path('/some/absolute'))
base_module_dirs = Puppet[:basemodulepath].split(File::PATH_SEPARATOR).map do |path|
FS::MemoryFile.a_directory(path)
end
envdir = FS::MemoryFile.a_directory(File.expand_path("envdir"), [
FS::MemoryFile.a_directory("env1", [
FS::MemoryFile.a_regular_file_containing("environment.conf", content),
FS::MemoryFile.a_directory("modules"),
]),
])
loader_from(:filesystem => [envdir, some_absolute_dir, base_module_dirs].flatten,
:directory => envdir) do |loader|
expect(loader.get("env1")).to environment(:env1).
with_manifest(File.join(Puppet[:confdir], 'whackymanifests')).
with_modulepath([some_absolute_dir.path,
base_module_dirs.map { |d| d.path },
File.join(envdir, 'env1', 'modules')].flatten).
with_config_version(File.join(Puppet[:vardir], 'random', 'scripts'))
end
end
it "uses environment.conf settings regardless of existence of modules and manifests subdirectories" do
envdir = FS::MemoryFile.a_directory(File.expand_path("envdir"), [
FS::MemoryFile.a_directory("env1", [
FS::MemoryFile.a_regular_file_containing("environment.conf", content),
FS::MemoryFile.a_directory("modules"),
FS::MemoryFile.a_directory("manifests"),
]),
])
loader_from(:filesystem => [envdir, manifestdir, modulepath].flatten,
:directory => envdir) do |loader|
expect(loader.get("env1")).to environment(:env1).
with_manifest(manifestdir.path).
with_modulepath(modulepath.map(&:path)).
with_config_version(File.expand_path('/some/script'))
end
end
it "should update environment settings if environment.conf has changed and timeout has expired" do
base_dir = File.expand_path("envdir")
original_envdir = FS::MemoryFile.a_directory(base_dir, [
FS::MemoryFile.a_directory("env3", [
FS::MemoryFile.a_regular_file_containing("environment.conf", <<-EOF)
manifest=/manifest_orig
modulepath=/modules_orig
environment_timeout=0
EOF
]),
])
cached_loader_from(:filesystem => [original_envdir], :directory => original_envdir) do |loader|
original_env = loader.get("env3") # force the environment.conf to be read
changed_envdir = FS::MemoryFile.a_directory(base_dir, [
FS::MemoryFile.a_directory("env3", [
FS::MemoryFile.a_regular_file_containing("environment.conf", <<-EOF)
manifest=/manifest_changed
modulepath=/modules_changed
environment_timeout=0
EOF
]),
])
FS.overlay(changed_envdir) do
changed_env = loader.get("env3")
expect(original_env).to environment(:env3).
with_manifest(File.expand_path("/manifest_orig")).
with_full_modulepath([File.expand_path("/modules_orig")])
expect(changed_env).to environment(:env3).
with_manifest(File.expand_path("/manifest_changed")).
with_full_modulepath([File.expand_path("/modules_changed")])
end
end
end
end
end
describe "static loaders" do
let(:static1) { Puppet::Node::Environment.create(:static1, []) }
let(:static2) { Puppet::Node::Environment.create(:static2, []) }
let(:loader) { Puppet::Environments::Static.new(static1, static2) }
it "lists environments" do
expect(loader.list).to eq([static1, static2])
end
it "has search_paths" do
expect(loader.search_paths).to eq(["data:text/plain,internal"])
end
it "gets an environment" do
expect(loader.get(:static2)).to eq(static2)
end
it "returns nil if env not found" do
expect(loader.get(:doesnotexist)).to be_nil
end
it "raises error if environment is not found" do
expect do
loader.get!(:doesnotexist)
end.to raise_error(Puppet::Environments::EnvironmentNotFound)
end
it "gets a basic conf" do
conf = loader.get_conf(:static1)
expect(conf.modulepath).to eq('')
expect(conf.manifest).to eq(:no_manifest)
expect(conf.config_version).to be_nil
expect(conf.static_catalogs).to eq(true)
end
it "returns nil if you request a configuration from an env that doesn't exist" do
expect(loader.get_conf(:doesnotexist)).to be_nil
end
it "gets the conf environment_timeout if one is specified" do
Puppet[:environment_timeout] = 8675
conf = loader.get_conf(:static1)
expect(conf.environment_timeout).to eq(8675)
end
context "that are private" do
let(:private_env) { Puppet::Node::Environment.create(:private, []) }
let(:loader) { Puppet::Environments::StaticPrivate.new(private_env) }
it "lists nothing" do
expect(loader.list).to eq([])
end
end
end
describe "combined loaders" do
let(:static1) { Puppet::Node::Environment.create(:static1, []) }
let(:static2) { Puppet::Node::Environment.create(:static2, []) }
let(:static_loader) { Puppet::Environments::Static.new(static1, static2) }
let(:directory_tree) do
FS::MemoryFile.a_directory(File.expand_path("envdir"), [
FS::MemoryFile.a_directory("an_environment", [
FS::MemoryFile.a_missing_file("environment.conf"),
FS::MemoryFile.a_directory("modules"),
FS::MemoryFile.a_directory("manifests"),
]),
FS::MemoryFile.a_missing_file("env_does_not_exist"),
FS::MemoryFile.a_missing_file("static2"),
])
end
it "lists environments" do
loader_from(:filesystem => [directory_tree], :directory => directory_tree) do |loader|
envs = Puppet::Environments::Combined.new(loader, static_loader).list
expect(envs[0]).to environment(:an_environment)
expect(envs[1]).to environment(:static1)
expect(envs[2]).to environment(:static2)
end
end
it "has search_paths" do
loader_from(:filesystem => [directory_tree], :directory => directory_tree) do |loader|
expect(Puppet::Environments::Combined.new(loader, static_loader).search_paths).to eq(["file://#{directory_tree}","data:text/plain,internal"])
end
end
it "gets an environment" do
loader_from(:filesystem => [directory_tree], :directory => directory_tree) do |loader|
expect(Puppet::Environments::Combined.new(loader, static_loader).get(:an_environment)).to environment(:an_environment)
expect(Puppet::Environments::Combined.new(loader, static_loader).get(:static2)).to environment(:static2)
end
end
it "returns nil if env not found" do
loader_from(:filesystem => [directory_tree], :directory => directory_tree) do |loader|
expect(Puppet::Environments::Combined.new(loader, static_loader).get(:env_does_not_exist)).to be_nil
end
end
it "raises an error if environment is not found" do
loader_from(:filesystem => [directory_tree], :directory => directory_tree) do |loader|
expect do
Puppet::Environments::Combined.new(loader, static_loader).get!(:env_does_not_exist)
end.to raise_error(Puppet::Environments::EnvironmentNotFound)
end
end
it "gets an environment.conf" do
loader_from(:filesystem => [directory_tree], :directory => directory_tree) do |loader|
expect(Puppet::Environments::Combined.new(loader, static_loader).get_conf(:an_environment)).to match_environment_conf(:an_environment).
with_env_path(directory_tree).
with_global_module_path([])
end
end
end
describe "cached loaders" do
it "lists environments" do
cached_loader_from(:filesystem => [directory_tree], :directory => directory_tree.children.first) do |loader|
expect(loader.list).to contain_exactly(
environment(:an_environment),
environment(:another_environment),
environment(:symlinked_environment))
end
end
it "returns the same cached environment object for list and get methods" do
cached_loader_from(:filesystem => [directory_tree], :directory => directory_tree.children.first) do |loader|
env = loader.list.find { |e| e.name == :an_environment }
expect(env).to equal(loader.get(:an_environment)) # same object
end
end
it "returns the same cached environment object for multiple list calls" do
cached_loader_from(:filesystem => [directory_tree], :directory => directory_tree.children.first) do |loader|
expect(loader.list.first).to equal(loader.list.first) # same object
end
end
it "expires environments and returns a new environment object with the same value" do
Puppet[:environment_timeout] = "0"
cached_loader_from(:filesystem => [directory_tree], :directory => directory_tree.children.first) do |loader|
a = loader.list.first
b = loader.list.first
expect(a).to eq(b) # same value
expect(a).to_not equal(b) # not same object
end
end
it "has search_paths" do
cached_loader_from(:filesystem => [directory_tree], :directory => directory_tree.children.first) do |loader|
expect(loader.search_paths).to eq(["file://#{directory_tree.children.first}"])
end
end
context "#get" do
it "gets an environment" do
cached_loader_from(:filesystem => [directory_tree], :directory => directory_tree.children.first) do |loader|
expect(loader.get(:an_environment)).to environment(:an_environment)
end
end
it "does not reload the environment if it isn't expired" do
env = Puppet::Node::Environment.create(:cached, [])
mocked_loader = double('loader')
expect(mocked_loader).to receive(:get).with(:cached).and_return(env).once
expect(mocked_loader).to receive(:get_conf).with(:cached).and_return(Puppet::Settings::EnvironmentConf.static_for(env, 20)).once
cached = Puppet::Environments::Cached.new(mocked_loader)
cached.get(:cached)
cached.get(:cached)
end
it "does not list deleted environments" do
env3 = FS::MemoryFile.a_directory("env3", [
FS::MemoryFile.a_regular_file_containing("environment.conf", '')
])
envdir = FS::MemoryFile.a_directory(File.expand_path("envdir"), [
FS::MemoryFile.a_directory("env1", [
FS::MemoryFile.a_regular_file_containing("environment.conf", '')
]),
FS::MemoryFile.a_directory("env2", [
FS::MemoryFile.a_regular_file_containing("environment.conf", '')
]),
env3
])
loader_from(:filesystem => [envdir], :directory => envdir) do |loader|
cached = Puppet::Environments::Cached.new(loader)
cached.get(:env1)
cached.get(:env2)
cached.get(:env3)
env3.extend(FsRemove).remove
expect(cached.list).to contain_exactly(environment(:env1),environment(:env2))
expect(cached.get(:env3)).to be_nil
end
end
it "normalizes environment name to symbol" do
env = Puppet::Node::Environment.create(:cached, [])
mocked_loader = double('loader')
expect(mocked_loader).not_to receive(:get).with('cached')
expect(mocked_loader).to receive(:get).with(:cached).and_return(env).once
expect(mocked_loader).to receive(:get_conf).with(:cached).and_return(Puppet::Settings::EnvironmentConf.static_for(env, 20)).once
cached = Puppet::Environments::Cached.new(mocked_loader)
cached.get('cached')
cached.get(:cached)
end
it "caches environment name as symbol and only once" do
mocked_loader = double('loader')
env = Puppet::Node::Environment.create(:cached, [])
allow(mocked_loader).to receive(:get).with(:cached).and_return(env)
allow(mocked_loader).to receive(:get_conf).with(:cached).and_return(Puppet::Settings::EnvironmentConf.static_for(env, 20))
cached = Puppet::Environments::Cached.new(mocked_loader)
cached.get(:cached)
cached.get('cached')
expect(cached.instance_variable_get(:@cache).keys).to eq([:cached])
end
it "is able to cache multiple environments" do
mocked_loader = double('loader')
env1 = Puppet::Node::Environment.create(:env1, [])
allow(mocked_loader).to receive(:get).with(:env1).and_return(env1)
allow(mocked_loader).to receive(:get_conf).with(:env1).and_return(Puppet::Settings::EnvironmentConf.static_for(env1, 20))
env2 = Puppet::Node::Environment.create(:env2, [])
allow(mocked_loader).to receive(:get).with(:env2).and_return(env2)
allow(mocked_loader).to receive(:get_conf).with(:env2).and_return(Puppet::Settings::EnvironmentConf.static_for(env2, 20))
cached = Puppet::Environments::Cached.new(mocked_loader)
cached.get('env1')
cached.get('env2')
expect(cached.instance_variable_get(:@cache).keys).to eq([:env1, :env2])
end
it "returns nil if env not found" do
cached_loader_from(:filesystem => [directory_tree], :directory => directory_tree.children.first) do |loader|
expect(loader.get(:doesnotexist)).to be_nil
end
end
end
context "#get!" do
it "gets an environment" do
cached_loader_from(:filesystem => [directory_tree], :directory => directory_tree.children.first) do |loader|
expect(loader.get!(:an_environment)).to environment(:an_environment)
end
end
it "does not reload the environment if it isn't expired" do
env = Puppet::Node::Environment.create(:cached, [])
mocked_loader = double('loader')
expect(mocked_loader).to receive(:get).with(:cached).and_return(env).once
expect(mocked_loader).to receive(:get_conf).with(:cached).and_return(Puppet::Settings::EnvironmentConf.static_for(env, 20)).once
cached = Puppet::Environments::Cached.new(mocked_loader)
cached.get!(:cached)
cached.get!(:cached)
end
it "raises error if environment is not found" do
cached_loader_from(:filesystem => [directory_tree], :directory => directory_tree.children.first) do |loader|
expect do
loader.get!(:doesnotexist)
end.to raise_error(Puppet::Environments::EnvironmentNotFound)
end
end
end
context "#get_conf" do
it "loads environment.conf" do
cached_loader_from(:filesystem => [directory_tree], :directory => directory_tree.children.first) do |loader|
expect(loader.get_conf(:an_environment)).to match_environment_conf(:an_environment).
with_env_path(directory_tree.children.first).
with_global_module_path([])
end
end
it "always reloads environment.conf" do
env = Puppet::Node::Environment.create(:cached, [])
mocked_loader = double('loader')
expect(mocked_loader).to receive(:get_conf).with(:cached).and_return(Puppet::Settings::EnvironmentConf.static_for(env, 20)).twice
cached = Puppet::Environments::Cached.new(mocked_loader)
cached.get_conf(:cached)
cached.get_conf(:cached)
end
it "normalizes environment name to symbol" do
env = Puppet::Node::Environment.create(:cached, [])
mocked_loader = double('loader')
expect(mocked_loader).to receive(:get_conf).with(:cached).and_return(Puppet::Settings::EnvironmentConf.static_for(env, 20)).twice
cached = Puppet::Environments::Cached.new(mocked_loader)
cached.get_conf('cached')
cached.get_conf(:cached)
end
it "returns nil if environment is not found" do
cached_loader_from(:filesystem => [directory_tree], :directory => directory_tree.children.first) do |loader|
expect(loader.get_conf(:doesnotexist)).to be_nil
end
end
end
context "expiration policies" do
let(:service) { ReplayExpirationService.new }
it "notifies when the environment is first created" do
with_environment_loaded(service)
expect(service.created_envs).to eq([:an_environment])
end
it "does not evict an unexpired environment" do
Puppet[:environment_timeout] = 'unlimited'
with_environment_loaded(service) do |cached|
cached.get!(:an_environment)
end
expect(service.created_envs).to eq([:an_environment])
expect(service.evicted_envs).to eq([])
end
it "evicts an expired environment" do
expect(service).to receive(:expired?).and_return(true)
with_environment_loaded(service) do |cached|
cached.get!(:an_environment)
end
expect(service.created_envs).to eq([:an_environment, :an_environment])
expect(service.evicted_envs).to eq([:an_environment])
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | true |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/hiera_puppet_spec.rb | spec/unit/hiera_puppet_spec.rb | require 'spec_helper'
require 'hiera_puppet'
require 'puppet_spec/scope'
describe 'HieraPuppet', :if => Puppet.features.hiera? do
include PuppetSpec::Scope
after(:all) do
HieraPuppet.instance_variable_set(:@hiera, nil)
end
describe 'HieraPuppet#hiera_config' do
let(:hiera_config_data) do
{ :backend => 'yaml' }
end
context "when the hiera_config_file exists" do
before do
expect(Hiera::Config).to receive(:load).and_return(hiera_config_data)
expect(HieraPuppet).to receive(:hiera_config_file).and_return(true)
end
it "should return a configuration hash" do
expected_results = {
:backend => 'yaml',
:logger => 'puppet'
}
expect(HieraPuppet.send(:hiera_config)).to eq(expected_results)
end
end
context "when the hiera_config_file does not exist" do
before do
expect(Hiera::Config).not_to receive(:load)
expect(HieraPuppet).to receive(:hiera_config_file).and_return(nil)
end
it "should return a configuration hash" do
expect(HieraPuppet.send(:hiera_config)).to eq({ :logger => 'puppet' })
end
end
end
describe 'HieraPuppet#hiera_config_file' do
it "should return nil when we cannot derive the hiera config file from Puppet.settings" do
begin
Puppet.settings[:hiera_config] = nil
rescue ArgumentError => detail
raise unless detail.message =~ /unknown setting/
end
expect(HieraPuppet.send(:hiera_config_file)).to be_nil
end
it "should use Puppet.settings[:hiera_config] as the hiera config file" do
begin
Puppet.settings[:hiera_config] = "/dev/null/my_hiera.yaml"
rescue ArgumentError => detail
raise unless detail.message =~ /unknown setting/
pending("This example does not apply to Puppet #{Puppet.version} because it does not have this setting")
end
allow(Puppet::FileSystem).to receive(:exist?).with(Puppet[:hiera_config]).and_return(true)
expect(HieraPuppet.send(:hiera_config_file)).to eq(Puppet[:hiera_config])
end
context 'when hiera_config is not set' do
let(:code_hiera_config) { File.join(Puppet[:codedir], 'hiera.yaml') }
let(:conf_hiera_config) { File.join(Puppet[:confdir], 'hiera.yaml') }
before(:each) do
Puppet.settings.setting(:hiera_config).send(:remove_instance_variable, :@evaluated_default)
Puppet.settings[:hiera_config] = nil
Puppet.settings[:codedir] = '/dev/null/puppetlabs/code'
Puppet.settings[:confdir] = '/dev/null/puppetlabs/puppet'
end
it "should use Puppet.settings[:codedir]/hiera.yaml when '$codedir/hiera.yaml' exists and '$confdir/hiera.yaml' does not exist" do
allow(Puppet::FileSystem).to receive(:exist?).with(code_hiera_config).and_return(true)
allow(Puppet::FileSystem).to receive(:exist?).with(conf_hiera_config).and_return(false)
expect(HieraPuppet.send(:hiera_config_file)).to eq(code_hiera_config)
end
it "should use Puppet.settings[:confdir]/hiera.yaml when '$codedir/hiera.yaml' does not exist and '$confdir/hiera.yaml' exists" do
allow(Puppet::FileSystem).to receive(:exist?).with(code_hiera_config).and_return(false)
allow(Puppet::FileSystem).to receive(:exist?).with(conf_hiera_config).and_return(true)
expect(HieraPuppet.send(:hiera_config_file)).to eq(conf_hiera_config)
end
it "should use Puppet.settings[:codedir]/hiera.yaml when '$codedir/hiera.yaml' exists and '$confdir/hiera.yaml' exists" do
allow(Puppet::FileSystem).to receive(:exist?).with(code_hiera_config).and_return(true)
allow(Puppet::FileSystem).to receive(:exist?).with(conf_hiera_config).and_return(true)
expect(HieraPuppet.send(:hiera_config_file)).to eq(code_hiera_config)
end
it "should return nil when neither '$codedir/hiera.yaml' nor '$confdir/hiera.yaml' exists" do
allow(Puppet::FileSystem).to receive(:exist?).with(code_hiera_config).and_return(false)
allow(Puppet::FileSystem).to receive(:exist?).with(conf_hiera_config).and_return(false)
expect(HieraPuppet.send(:hiera_config_file)).to eq(nil)
end
it "should return explicitly set option even if both '$codedir/hiera.yaml' and '$confdir/hiera.yaml' exists" do
if Puppet::Util::Platform.windows?
explicit_hiera_config = 'C:/an/explicit/hiera.yaml'
else
explicit_hiera_config = '/an/explicit/hiera.yaml'
end
Puppet.settings[:hiera_config] = explicit_hiera_config
allow(Puppet::FileSystem).to receive(:exist?).with(explicit_hiera_config).and_return(true)
allow(Puppet::FileSystem).to receive(:exist?).with(code_hiera_config).and_return(true)
allow(Puppet::FileSystem).to receive(:exist?).with(conf_hiera_config).and_return(true)
expect(HieraPuppet.send(:hiera_config_file)).to eq(explicit_hiera_config)
end
end
end
describe 'HieraPuppet#lookup' do
let :scope do create_test_scope_for_node('foo') end
before :each do
Puppet[:hiera_config] = PuppetSpec::Files.tmpfile('hiera_config')
end
it "should return the value from Hiera" do
allow_any_instance_of(Hiera).to receive(:lookup).and_return('8080')
expect(HieraPuppet.lookup('port', nil, scope, nil, :priority)).to eq('8080')
allow_any_instance_of(Hiera).to receive(:lookup).and_return(['foo', 'bar'])
expect(HieraPuppet.lookup('ntpservers', nil, scope, nil, :array)).to eq(['foo', 'bar'])
allow_any_instance_of(Hiera).to receive(:lookup).and_return({'uid' => '1000'})
expect(HieraPuppet.lookup('user', nil, scope, nil, :hash)).to eq({'uid' => '1000'})
end
it "should raise a useful error when the answer is nil" do
allow_any_instance_of(Hiera).to receive(:lookup).and_return(nil)
expect do
HieraPuppet.lookup('port', nil, scope, nil, :priority)
end.to raise_error(Puppet::ParseError,
/Could not find data item port in any Hiera data file and no default supplied/)
end
end
describe 'HieraPuppet#parse_args' do
it 'should return a 3 item array' do
args = ['foo', '8080', nil, nil]
expect(HieraPuppet.parse_args(args)).to eq(['foo', '8080', nil])
end
it 'should raise a useful error when no key is supplied' do
expect { HieraPuppet.parse_args([]) }.to raise_error(Puppet::ParseError,
/Please supply a parameter to perform a Hiera lookup/)
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/agent_spec.rb | spec/unit/agent_spec.rb | require 'spec_helper'
require 'puppet/agent'
require 'puppet/configurer'
class AgentTestClient
def initialize(transaction_uuid = nil, job_id = nil)
end
def run(client_args)
# no-op
end
def stop
# no-op
end
end
describe Puppet::Agent do
before do
@agent = Puppet::Agent.new(AgentTestClient, false)
# make Puppet::Application safe for stubbing
stub_const('Puppet::Application', Class.new(Puppet::Application))
allow(Puppet::Application).to receive(:clear?).and_return(true)
Puppet::Application.class_eval do
class << self
def controlled_run(&block)
block.call
end
end
end
ssl_context = Puppet::SSL::SSLContext.new
machine = instance_double("Puppet::SSL::StateMachine", ensure_client_certificate: ssl_context)
allow(Puppet::SSL::StateMachine).to receive(:new).and_return(machine)
end
it "should set its client class at initialization" do
expect(Puppet::Agent.new("foo", false).client_class).to eq("foo")
end
it "should include the Locker module" do
expect(Puppet::Agent.ancestors).to be_include(Puppet::Agent::Locker)
end
it "should create an instance of its client class and run it when asked to run" do
client = double('client')
allow(AgentTestClient).to receive(:new).with(nil, nil).and_return(client)
allow(@agent).to receive(:disabled?).and_return(false)
expect(client).to receive(:run)
@agent.run
end
it "should initialize the client's transaction_uuid if passed as a client_option" do
client = double('client')
transaction_uuid = 'foo'
expect(AgentTestClient).to receive(:new).with(transaction_uuid, nil).and_return(client)
expect(client).to receive(:run)
allow(@agent).to receive(:disabled?).and_return(false)
@agent.run(:transaction_uuid => transaction_uuid)
end
it "should initialize the client's job_id if passed as a client_option" do
client = double('client')
job_id = '289'
expect(AgentTestClient).to receive(:new).with(anything, job_id).and_return(client)
expect(client).to receive(:run)
allow(@agent).to receive(:disabled?).and_return(false)
@agent.run(:job_id => job_id)
end
it "should be considered running if the lock file is locked" do
lockfile = double('lockfile')
expect(@agent).to receive(:lockfile).and_return(lockfile)
expect(lockfile).to receive(:locked?).and_return(true)
expect(@agent).to be_running
end
describe "when being run" do
before do
allow(@agent).to receive(:disabled?).and_return(false)
end
it "should splay" do
Puppet[:splay] = true
expect(@agent).to receive(:splay)
@agent.run
end
it "should do nothing if disabled" do
expect(@agent).to receive(:disabled?).and_return(true)
expect(AgentTestClient).not_to receive(:new)
@agent.run
end
it "(#11057) should notify the user about why a run is skipped" do
allow(Puppet::Application).to receive(:controlled_run).and_return(false)
allow(Puppet::Application).to receive(:run_status).and_return('MOCK_RUN_STATUS')
# This is the actual test that we inform the user why the run is skipped.
# We assume this information is contained in
# Puppet::Application.run_status
expect(Puppet).to receive(:notice).with(/MOCK_RUN_STATUS/)
@agent.run
end
it "should display an informative message if the agent is administratively disabled" do
expect(@agent).to receive(:disabled?).and_return(true)
expect(@agent).to receive(:disable_message).and_return("foo")
expect(Puppet).to receive(:notice).with(/Skipping run of .*; administratively disabled.*\(Reason: 'foo'\)/)
@agent.run
end
it "should use Puppet::Application.controlled_run to manage process state behavior" do
expect(Puppet::Application).to receive(:controlled_run).ordered.and_yield
expect(AgentTestClient).to receive(:new).ordered.once
@agent.run
end
it "should not fail if a client class instance cannot be created" do
expect(AgentTestClient).to receive(:new).and_raise("eh")
expect(Puppet).to receive(:log_exception)
@agent.run
end
it "should not fail if there is an exception while running its client" do
client = AgentTestClient.new
expect(AgentTestClient).to receive(:new).and_return(client)
expect(client).to receive(:run).and_raise("eh")
expect(Puppet).to receive(:log_exception)
@agent.run
end
it "should use a filesystem lock to restrict multiple processes running the agent" do
client = AgentTestClient.new
expect(AgentTestClient).to receive(:new).and_return(client)
expect(@agent).to receive(:lock)
expect(client).not_to receive(:run) # if it doesn't run, then we know our yield is what triggers it
@agent.run
end
it "should make its client instance available while running" do
client = AgentTestClient.new
expect(AgentTestClient).to receive(:new).and_return(client)
expect(client).to receive(:run) { expect(@agent.client).to equal(client); nil }
@agent.run
end
it "should run the client instance with any arguments passed to it" do
client = AgentTestClient.new
expect(AgentTestClient).to receive(:new).and_return(client)
expect(client).to receive(:run).with({:pluginsync => true, :other => :options})
@agent.run(:other => :options)
end
it "should return the agent result" do
client = AgentTestClient.new
expect(AgentTestClient).to receive(:new).and_return(client)
expect(@agent).to receive(:lock).and_return(:result)
expect(@agent.run).to eq(:result)
end
it "should check if it's disabled after splaying and log a message" do
Puppet[:splay] = true
Puppet[:splaylimit] = '5s'
Puppet[:onetime] = true
expect(@agent).to receive(:disabled?).and_return(false, true)
allow(Puppet).to receive(:notice).and_call_original
expect(Puppet).to receive(:notice).with(/Skipping run of .*; administratively disabled.*/)
@agent.run
end
it "should check if it's disabled after acquiring the lock and log a message" do
expect(@agent).to receive(:disabled?).and_return(false, true)
allow(Puppet).to receive(:notice).and_call_original
expect(Puppet).to receive(:notice).with(/Skipping run of .*; administratively disabled.*/)
@agent.run
end
describe "and a puppet agent is already running" do
before(:each) do
allow_any_instance_of(Object).to receive(:sleep)
lockfile = double('lockfile')
expect(@agent).to receive(:lockfile).and_return(lockfile).at_least(:once)
# so the lock method raises Puppet::LockError
allow(lockfile).to receive(:lock).and_return(false)
end
it "should notify that a run is already in progress" do
client = AgentTestClient.new
expect(AgentTestClient).to receive(:new).and_return(client)
expect(Puppet).to receive(:notice).with(/Run of .* already in progress; skipping .* exists/)
@agent.run
end
it "should inform that a run is already in progress and try to run every X seconds if waitforlock is used" do
# so the locked file exists
allow(File).to receive(:file?).and_return(true)
# so we don't have to wait again for the run to exit (default maxwaitforcert is 60)
# first 0 is to get the time, second 0 is to inform user, then 1000 so the time expires
allow(Time).to receive(:now).and_return(0, 0, 1000)
allow(Puppet).to receive(:info)
client = AgentTestClient.new
expect(AgentTestClient).to receive(:new).and_return(client)
Puppet[:waitforlock] = 1
Puppet[:maxwaitforlock] = 2
expect(Puppet).to receive(:info).with(/Another puppet instance is already running; --waitforlock flag used, waiting for running instance to finish./)
expect(Puppet).to receive(:info).with(/Will try again in #{Puppet[:waitforlock]} seconds./)
@agent.run
end
it "should notify that the run is exiting if waitforlock is used and maxwaitforlock is exceeded" do
# so we don't have to wait again for the run to exit (default maxwaitforcert is 60)
# first 0 is to get the time, then 1000 so that the time expires
allow(Time).to receive(:now).and_return(0, 1000)
client = AgentTestClient.new
expect(AgentTestClient).to receive(:new).and_return(client)
Puppet[:waitforlock] = 1
expect(Puppet).to receive(:notice).with(/Exiting now because the maxwaitforlock timeout has been exceeded./)
@agent.run
end
end
describe "when should_fork is true", :if => Puppet.features.posix? && RUBY_PLATFORM != 'java' do
before do
@agent = Puppet::Agent.new(AgentTestClient, true)
# So we don't actually try to hit the filesystem.
allow(@agent).to receive(:lock).and_yield
end
it "should run the agent in a forked process" do
client = AgentTestClient.new
expect(AgentTestClient).to receive(:new).and_return(client)
expect(client).to receive(:run).and_return(0)
expect(Kernel).to receive(:fork).and_yield
expect { @agent.run }.to exit_with(0)
end
it "should exit child process if child exit" do
client = AgentTestClient.new
expect(AgentTestClient).to receive(:new).and_return(client)
expect(client).to receive(:run).and_raise(SystemExit.new(-1))
expect(Kernel).to receive(:fork).and_yield
expect { @agent.run }.to exit_with(-1)
end
it 'should exit with 1 if an exception is raised' do
client = AgentTestClient.new
expect(AgentTestClient).to receive(:new).and_return(client)
expect(client).to receive(:run).and_raise(StandardError)
expect(Kernel).to receive(:fork).and_yield
expect { @agent.run }.to exit_with(1)
end
it 'should exit with 254 if NoMemoryError exception is raised' do
client = AgentTestClient.new
expect(AgentTestClient).to receive(:new).and_return(client)
expect(client).to receive(:run).and_raise(NoMemoryError)
expect(Kernel).to receive(:fork).and_yield
expect { @agent.run }.to exit_with(254)
end
it "should return the block exit code as the child exit code" do
expect(Kernel).to receive(:fork).and_yield
expect {
@agent.run_in_fork {
777
}
}.to exit_with(777)
end
it "should return `1` exit code if the block returns `nil`" do
expect(Kernel).to receive(:fork).and_yield
expect {
@agent.run_in_fork {
nil
}
}.to exit_with(1)
end
it "should return `1` exit code if the block returns `false`" do
expect(Kernel).to receive(:fork).and_yield
expect {
@agent.run_in_fork {
false
}
}.to exit_with(1)
end
end
describe "on Windows", :if => Puppet::Util::Platform.windows? do
it "should never fork" do
agent = Puppet::Agent.new(AgentTestClient, true)
expect(agent.should_fork).to be_falsey
end
end
describe 'when runtimeout is set' do
before(:each) do
Puppet[:runtimeout] = 1
end
it 'times out when a run exceeds the set limit' do
client = AgentTestClient.new
client.instance_eval do
# Stub methods used to set test expectations.
def processing; end
def handling; end
def run(client_options = {})
# Simulate a hanging agent operation that also traps errors.
begin
::Kernel.sleep(5)
processing()
rescue
handling()
end
end
end
expect(AgentTestClient).to receive(:new).and_return(client)
expect(client).not_to receive(:processing)
expect(client).not_to receive(:handling)
expect(Puppet).to receive(:log_exception).with(be_an_instance_of(Puppet::Agent::RunTimeoutError), anything)
expect(@agent.run).to eq(nil)
end
end
end
describe "when checking execution state" do
describe 'with regular run status' do
before :each do
allow(Puppet::Application).to receive(:restart_requested?).and_return(false)
allow(Puppet::Application).to receive(:stop_requested?).and_return(false)
allow(Puppet::Application).to receive(:interrupted?).and_return(false)
allow(Puppet::Application).to receive(:clear?).and_return(true)
end
it 'should be false for :stopping?' do
expect(@agent.stopping?).to be_falsey
end
it 'should be false for :needing_restart?' do
expect(@agent.needing_restart?).to be_falsey
end
end
describe 'with a stop requested' do
before :each do
allow(Puppet::Application).to receive(:clear?).and_return(false)
allow(Puppet::Application).to receive(:restart_requested?).and_return(false)
allow(Puppet::Application).to receive(:stop_requested?).and_return(true)
allow(Puppet::Application).to receive(:interrupted?).and_return(true)
end
it 'should be true for :stopping?' do
expect(@agent.stopping?).to be_truthy
end
it 'should be false for :needing_restart?' do
expect(@agent.needing_restart?).to be_falsey
end
end
describe 'with a restart requested' do
before :each do
allow(Puppet::Application).to receive(:clear?).and_return(false)
allow(Puppet::Application).to receive(:restart_requested?).and_return(true)
allow(Puppet::Application).to receive(:stop_requested?).and_return(false)
allow(Puppet::Application).to receive(:interrupted?).and_return(true)
end
it 'should be false for :stopping?' do
expect(@agent.stopping?).to be_falsey
end
it 'should be true for :needing_restart?' do
expect(@agent.needing_restart?).to be_truthy
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/confine_collection_spec.rb | spec/unit/confine_collection_spec.rb | require 'spec_helper'
require 'puppet/confine_collection'
describe Puppet::ConfineCollection do
it "should be able to add confines" do
expect(Puppet::ConfineCollection.new("label")).to respond_to(:confine)
end
it "should require a label at initialization" do
expect { Puppet::ConfineCollection.new }.to raise_error(ArgumentError)
end
it "should make its label available" do
expect(Puppet::ConfineCollection.new("mylabel").label).to eq("mylabel")
end
describe "when creating confine instances" do
it "should create an instance of the named test with the provided values" do
test_class = double('test_class')
expect(test_class).to receive(:new).with(%w{my values}).and_return(double('confine', :label= => nil))
expect(Puppet::Confine).to receive(:test).with(:foo).and_return(test_class)
Puppet::ConfineCollection.new("label").confine :foo => %w{my values}
end
it "should copy its label to the confine instance" do
confine = double('confine')
test_class = double('test_class')
expect(test_class).to receive(:new).and_return(confine)
expect(Puppet::Confine).to receive(:test).and_return(test_class)
expect(confine).to receive(:label=).with("label")
Puppet::ConfineCollection.new("label").confine :foo => %w{my values}
end
describe "and the test cannot be found" do
it "should create a Facter test with the provided values and set the name to the test name" do
confine = Puppet::Confine.test(:variable).new(%w{my values})
expect(confine).to receive(:name=).with(:foo)
expect(confine.class).to receive(:new).with(%w{my values}).and_return(confine)
Puppet::ConfineCollection.new("label").confine(:foo => %w{my values})
end
end
describe "and the 'for_binary' option was provided" do
it "should mark the test as a binary confine" do
confine = Puppet::Confine.test(:exists).new(:bar)
expect(confine).to receive(:for_binary=).with(true)
expect(Puppet::Confine.test(:exists)).to receive(:new).with(:bar).and_return(confine)
Puppet::ConfineCollection.new("label").confine :exists => :bar, :for_binary => true
end
end
end
it "should be valid if no confines are present" do
expect(Puppet::ConfineCollection.new("label")).to be_valid
end
it "should be valid if all confines pass" do
c1 = double('c1', :valid? => true, :label= => nil)
c2 = double('c2', :valid? => true, :label= => nil)
expect(Puppet::Confine.test(:true)).to receive(:new).and_return(c1)
expect(Puppet::Confine.test(:false)).to receive(:new).and_return(c2)
confiner = Puppet::ConfineCollection.new("label")
confiner.confine :true => :bar, :false => :bee
expect(confiner).to be_valid
end
it "should not be valid if any confines fail" do
c1 = double('c1', :valid? => true, :label= => nil)
c2 = double('c2', :valid? => false, :label= => nil)
expect(Puppet::Confine.test(:true)).to receive(:new).and_return(c1)
expect(Puppet::Confine.test(:false)).to receive(:new).and_return(c2)
confiner = Puppet::ConfineCollection.new("label")
confiner.confine :true => :bar, :false => :bee
expect(confiner).not_to be_valid
end
describe "when providing a summary" do
before do
@confiner = Puppet::ConfineCollection.new("label")
end
it "should return a hash" do
expect(@confiner.summary).to be_instance_of(Hash)
end
it "should return an empty hash if the confiner is valid" do
expect(@confiner.summary).to eq({})
end
it "should add each test type's summary to the hash" do
@confiner.confine :true => :bar, :false => :bee
expect(Puppet::Confine.test(:true)).to receive(:summarize).and_return(:tsumm)
expect(Puppet::Confine.test(:false)).to receive(:summarize).and_return(:fsumm)
expect(@confiner.summary).to eq({:true => :tsumm, :false => :fsumm})
end
it "should not include tests that return 0" do
@confiner.confine :true => :bar, :false => :bee
expect(Puppet::Confine.test(:true)).to receive(:summarize).and_return(0)
expect(Puppet::Confine.test(:false)).to receive(:summarize).and_return(:fsumm)
expect(@confiner.summary).to eq({:false => :fsumm})
end
it "should not include tests that return empty arrays" do
@confiner.confine :true => :bar, :false => :bee
expect(Puppet::Confine.test(:true)).to receive(:summarize).and_return([])
expect(Puppet::Confine.test(:false)).to receive(:summarize).and_return(:fsumm)
expect(@confiner.summary).to eq({:false => :fsumm})
end
it "should not include tests that return empty hashes" do
@confiner.confine :true => :bar, :false => :bee
expect(Puppet::Confine.test(:true)).to receive(:summarize).and_return({})
expect(Puppet::Confine.test(:false)).to receive(:summarize).and_return(:fsumm)
expect(@confiner.summary).to eq({:false => :fsumm})
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/info_service_spec.rb | spec/unit/info_service_spec.rb | require 'spec_helper'
require 'puppet_spec/files'
require 'puppet_spec/modules'
require 'puppet/pops'
require 'puppet/info_service'
require 'puppet/pops/evaluator/literal_evaluator'
describe "Puppet::InfoService" do
include PuppetSpec::Files
context 'task information service' do
let(:mod_name) { 'test1' }
let(:metadata) {
{ "private" => true,
"description" => "a task that does a thing" } }
let(:task_name) { "#{mod_name}::thingtask" }
let(:modpath) { tmpdir('modpath') }
let(:env_name) { 'testing' }
let(:env) { Puppet::Node::Environment.create(env_name.to_sym, [modpath]) }
let(:env_loader) { Puppet::Environments::Static.new(env) }
context 'tasks_per_environment method' do
it "returns task data for the tasks in an environment" do
Puppet.override(:environments => env_loader) do
PuppetSpec::Modules.create(mod_name, modpath, {:environment => env,
:tasks => [['thingtask',
{:name => 'thingtask.json',
:content => metadata.to_json}]]})
expect(Puppet::InfoService.tasks_per_environment(env_name)).to eq([{:name => task_name,
:module => {:name => mod_name},
:metadata => metadata} ])
end
end
it "returns task data for valid tasks in an environment even if invalid tasks exist" do
Puppet.override(:environments => env_loader) do
@mod = PuppetSpec::Modules.create(mod_name, modpath, {:environment => env,
:tasks => [['atask',
{:name => 'atask.json',
:content => metadata.to_json}],
['btask',
{:name => 'btask.json',
:content => metadata.to_json}],
['ctask',
{:name => 'ctask.json',
:content => metadata.to_json}]]})
File.write("#{modpath}/#{mod_name}/tasks/atask.json", "NOT JSON")
expect(Puppet).to receive(:send_log).with(:err, /unexpected token at 'NOT JSON'/)
@tasks = Puppet::InfoService.tasks_per_environment(env_name)
expect(@tasks.map{|t| t[:name]}).to contain_exactly('test1::btask', 'test1::ctask')
end
end
it "should throw EnvironmentNotFound if given a nonexistent environment" do
expect{ Puppet::InfoService.tasks_per_environment('utopia') }.to raise_error(Puppet::Environments::EnvironmentNotFound)
end
end
context 'task_data method' do
context 'For a valid simple module' do
before do
Puppet.override(:environments => env_loader) do
@mod = PuppetSpec::Modules.create(mod_name, modpath,
{:environment => env,
:tasks => [['thingtask',
{:name => 'thingtask.json',
:content => '{}'}]]})
@result = Puppet::InfoService.task_data(env_name, mod_name, task_name)
end
end
it 'returns the right set of keys' do
expect(@result.keys.sort).to eq([:files, :metadata])
end
it 'specifies the metadata_file correctly' do
expect(@result[:metadata]).to eq({})
end
it 'specifies the other files correctly' do
task = @mod.tasks[0]
expect(@result[:files]).to eq(task.files)
end
end
context 'For a module with multiple implemenations and files' do
let(:other_mod_name) { "shell_helpers" }
let(:metadata) {
{ "implementations" => [
{"name" => "thingtask.rb", "requirements" => ["puppet_agent"],
"files" => ["#{mod_name}/lib/puppet/providers/"]},
{"name" => "thingtask.sh", "requirements" => ["shell"] } ],
"files" => [
"#{mod_name}/files/my_data.json",
"#{other_mod_name}/files/scripts/helper.sh",
"#{mod_name}/files/data/files/data.rb"] } }
let(:expected_files) { [ {'name' => 'thingtask.rb',
'path' => "#{modpath}/#{mod_name}/tasks/thingtask.rb"},
{ 'name' => 'thingtask.sh',
'path' => "#{modpath}/#{mod_name}/tasks/thingtask.sh"},
{ 'name' => "#{mod_name}/lib/puppet/providers/prov.rb",
'path' => "#{modpath}/#{mod_name}/lib/puppet/providers/prov.rb"},
{ 'name' => "#{mod_name}/files/data/files/data.rb",
'path' => "#{modpath}/#{mod_name}/files/data/files/data.rb"},
{ 'name' => "#{mod_name}/files/my_data.json",
'path' => "#{modpath}/#{mod_name}/files/my_data.json"},
{ 'name' => "#{other_mod_name}/files/scripts/helper.sh",
'path' => "#{modpath}/#{other_mod_name}/files/scripts/helper.sh" }
].sort_by {|f| f['name']} }
before do
Puppet.override(:environments => env_loader) do
@mod = PuppetSpec::Modules.create(mod_name, modpath,
{:environment => env,
:tasks => [['thingtask.rb',
'thingtask.sh',
{:name => 'thingtask.json',
:content => metadata.to_json}]],
:files => {
"files/data/files/data.rb" => "a file of data",
"files/my_data.json" => "{}",
"lib/puppet/providers/prov.rb" => "provider_content"} })
@other_mod = PuppetSpec::Modules.create(other_mod_name, modpath, { :environment => env,
:files =>{
"files/scripts/helper.sh" => "helper content" } } )
@result = Puppet::InfoService.task_data(env_name, mod_name, task_name)
end
end
it 'returns the right set of keys' do
expect(@result.keys.sort).to eq([:files, :metadata])
end
it 'specifies the metadata_file correctly' do
expect(@result[:metadata]).to eq(metadata)
end
it 'specifies the other file names correctly' do
expect(@result[:files].sort_by{|f| f['name']}).to eq(expected_files)
end
end
context 'For a task with files that do not exist' do
let(:metadata) {
{ "files" => [
"#{mod_name}/files/random_data",
"shell_helpers/files/scripts/helper.sh"] } }
before do
Puppet.override(:environments => env_loader) do
@mod = PuppetSpec::Modules.create(mod_name, modpath,
{:environment => env,
:tasks => [['thingtask.rb',
{:name => 'thingtask.json',
:content => metadata.to_json}]]})
@result = Puppet::InfoService.task_data(env_name, mod_name, task_name)
end
end
it 'errors when the file is not found' do
expect(@result[:error][:kind]).to eq('puppet.tasks/invalid-file')
end
end
context 'For a task with bad metadata' do
let(:metadata) {
{ "implementations" => [
{"name" => "thingtask.rb", "requirements" => ["puppet_agent"] },
{"name" => "thingtask.sh", "requirements" => ["shell"] } ] } }
before do
Puppet.override(:environments => env_loader) do
@mod = PuppetSpec::Modules.create(mod_name, modpath,
{:environment => env,
:tasks => [['thingtask.sh',
{:name => 'thingtask.json',
:content => metadata.to_json}]]})
@result = Puppet::InfoService.task_data(env_name, mod_name, task_name)
end
end
it 'returns the right set of keys' do
expect(@result.keys.sort).to eq([:error, :files, :metadata])
end
it 'returns the expected error' do
expect(@result[:error][:kind]).to eq('puppet.tasks/missing-implementation')
end
end
context 'For a task with required directories with no trailing slash' do
let(:metadata) { { "files" => [ "#{mod_name}/files" ] } }
before do
Puppet.override(:environments => env_loader) do
@mod = PuppetSpec::Modules.create(mod_name, modpath,
{:environment => env,
:tasks => [['thingtask.sh',
{:name => 'thingtask.json',
:content => metadata.to_json}]],
:files => {
"files/helper.rb" => "help"}})
@result = Puppet::InfoService.task_data(env_name, mod_name, task_name)
end
end
it 'returns the right set of keys' do
expect(@result.keys.sort).to eq([:error, :files, :metadata])
end
it 'returns the expected error' do
expect(@result[:error][:kind]).to eq('puppet.tasks/invalid-metadata')
end
end
it "should raise EnvironmentNotFound if given a nonexistent environment" do
expect{ Puppet::InfoService.task_data('utopia', mod_name, task_name) }.to raise_error(Puppet::Environments::EnvironmentNotFound)
end
it "should raise MissingModule if the module does not exist" do
Puppet.override(:environments => env_loader) do
expect { Puppet::InfoService.task_data(env_name, 'notamodule', 'notamodule::thingtask') }
.to raise_error(Puppet::Module::MissingModule)
end
end
it "should raise TaskNotFound if the task does not exist" do
Puppet.override(:environments => env_loader) do
PuppetSpec::Modules.create(mod_name, modpath)
expect { Puppet::InfoService.task_data(env_name, mod_name, 'testing1::notatask') }
.to raise_error(Puppet::Module::Task::TaskNotFound)
end
end
end
end
context 'plan information service' do
let(:mod_name) { 'test1' }
let(:plan_name) { "#{mod_name}::thingplan" }
let(:modpath) { tmpdir('modpath') }
let(:env_name) { 'testing' }
let(:env) { Puppet::Node::Environment.create(env_name.to_sym, [modpath]) }
let(:env_loader) { Puppet::Environments::Static.new(env) }
context 'plans_per_environment method' do
it "returns plan data for the plans in an environment" do
Puppet.override(:environments => env_loader) do
PuppetSpec::Modules.create(mod_name, modpath, {:environment => env, :plans => ['thingplan.pp']})
expect(Puppet::InfoService.plans_per_environment(env_name)).to eq([{:name => plan_name, :module => {:name => mod_name}}])
end
end
it "should throw EnvironmentNotFound if given a nonexistent environment" do
expect{ Puppet::InfoService.plans_per_environment('utopia') }.to raise_error(Puppet::Environments::EnvironmentNotFound)
end
end
context 'plan_data method' do
context 'For a valid simple module' do
before do
Puppet.override(:environments => env_loader) do
@mod = PuppetSpec::Modules.create(mod_name, modpath,
{:environment => env,
:plans => ['thingplan.pp']})
@result = Puppet::InfoService.plan_data(env_name, mod_name, plan_name)
end
end
it 'returns the right set of keys' do
expect(@result.keys.sort).to eq([:files, :metadata])
end
it 'specifies the metadata_file correctly' do
expect(@result[:metadata]).to eq({})
end
it 'specifies the other files correctly' do
plan = @mod.plans[0]
expect(@result[:files]).to eq(plan.files)
end
end
end
end
context 'classes_per_environment service' do
let(:code_dir) do
dir_containing('manifests', {
'foo.pp' => <<-CODE,
class foo($foo_a, Integer $foo_b, String $foo_c = 'c default value') { }
class foo2($foo2_a, Integer $foo2_b, String $foo2_c = 'c default value') { }
CODE
'bar.pp' => <<-CODE,
class bar($bar_a, Integer $bar_b, String $bar_c = 'c default value') { }
class bar2($bar2_a, Integer $bar2_b, String $bar2_c = 'c default value') { }
CODE
'intp.pp' => <<-CODE,
class intp(String $intp_a = "default with interpolated $::os_family") { }
CODE
'fee.pp' => <<-CODE,
class fee(Integer $fee_a = 1+1) { }
CODE
'fum.pp' => <<-CODE,
class fum($fum_a) { }
CODE
'nothing.pp' => <<-CODE,
# not much to see here, move along
CODE
'borked.pp' => <<-CODE,
class Borked($Herp+$Derp) {}
CODE
'json_unsafe.pp' => <<-CODE,
class json_unsafe($arg1 = /.*/, $arg2 = default, $arg3 = {1 => 1}) {}
CODE
'non_literal.pp' => <<-CODE,
class oops(Integer[1-3] $bad_int) { }
CODE
'non_literal_2.pp' => <<-CODE,
class oops_2(Optional[[String]] $double_brackets) { }
CODE
})
end
it "errors if not given a hash" do
expect{ Puppet::InfoService.classes_per_environment("you wassup?")}.to raise_error(ArgumentError, 'Given argument must be a Hash')
end
it "returns empty hash if given nothing" do
expect(Puppet::InfoService.classes_per_environment({})).to eq({})
end
it "produces classes and parameters from a given file" do
files = ['foo.pp'].map {|f| File.join(code_dir, f) }
result = Puppet::InfoService.classes_per_environment({'production' => files })
expect(result).to eq({
"production"=>{
"#{code_dir}/foo.pp"=> {:classes => [
{:name=>"foo",
:params=>[
{:name=>"foo_a"},
{:name=>"foo_b", :type=>"Integer"},
{:name=>"foo_c", :type=>"String", :default_literal=>"c default value",
:default_source=>"'c default value'"}
]},
{:name=>"foo2",
:params=>[
{:name=>"foo2_a"},
{:name=>"foo2_b", :type=>"Integer"},
{:name=>"foo2_c", :type=>"String", :default_literal=>"c default value",
:default_source=>"'c default value'"}
]
}
]}} # end production env
})
end
it "produces classes and parameters from multiple files in same environment" do
files = ['foo.pp', 'bar.pp'].map {|f| File.join(code_dir, f) }
result = Puppet::InfoService.classes_per_environment({'production' => files })
expect(result).to eq({
"production"=>{
"#{code_dir}/foo.pp"=>{:classes => [
{:name=>"foo",
:params=>[
{:name=>"foo_a"},
{:name=>"foo_b", :type=>"Integer"},
{:name=>"foo_c", :type=>"String", :default_literal=>"c default value",
:default_source=>"'c default value'"}
]},
{:name=>"foo2",
:params=>[
{:name=>"foo2_a"},
{:name=>"foo2_b", :type=>"Integer"},
{:name=>"foo2_c", :type=>"String", :default_literal=>"c default value",
:default_source=>"'c default value'"}
]
}
]},
"#{code_dir}/bar.pp"=> {:classes =>[
{:name=>"bar",
:params=>[
{:name=>"bar_a"},
{:name=>"bar_b", :type=>"Integer"},
{:name=>"bar_c", :type=>"String", :default_literal=>"c default value",
:default_source=>"'c default value'"}
]},
{:name=>"bar2",
:params=>[
{:name=>"bar2_a"},
{:name=>"bar2_b", :type=>"Integer"},
{:name=>"bar2_c", :type=>"String", :default_literal=>"c default value",
:default_source=>"'c default value'"}
]
}
]},
} # end production env
}
)
end
it "produces classes and parameters from multiple files in multiple environments" do
files_production = ['foo.pp', 'bar.pp'].map {|f| File.join(code_dir, f) }
files_test = ['fee.pp', 'fum.pp'].map {|f| File.join(code_dir, f) }
result = Puppet::InfoService.classes_per_environment({
'production' => files_production,
'test' => files_test
})
expect(result).to eq({
"production"=>{
"#{code_dir}/foo.pp"=>{:classes => [
{:name=>"foo",
:params=>[
{:name=>"foo_a"},
{:name=>"foo_b", :type=>"Integer"},
{:name=>"foo_c", :type=>"String", :default_literal=>"c default value",
:default_source=>"'c default value'"}
]},
{:name=>"foo2",
:params=>[
{:name=>"foo2_a"},
{:name=>"foo2_b", :type=>"Integer"},
{:name=>"foo2_c", :type=>"String", :default_literal=>"c default value",
:default_source=>"'c default value'"}
]
}
]},
"#{code_dir}/bar.pp"=>{:classes => [
{:name=>"bar",
:params=>[
{:name=>"bar_a"},
{:name=>"bar_b", :type=>"Integer"},
{:name=>"bar_c", :type=>"String", :default_literal=>"c default value",
:default_source=>"'c default value'"}
]},
{:name=>"bar2",
:params=>[
{:name=>"bar2_a"},
{:name=>"bar2_b", :type=>"Integer"},
{:name=>"bar2_c", :type=>"String", :default_literal=>"c default value",
:default_source=>"'c default value'"}
]
}
]},
}, # end production env
"test"=>{
"#{code_dir}/fee.pp"=>{:classes => [
{:name=>"fee",
:params=>[
{:name=>"fee_a", :type=>"Integer", :default_source=>"1+1"}
]},
]},
"#{code_dir}/fum.pp"=>{:classes => [
{:name=>"fum",
:params=>[
{:name=>"fum_a"}
]},
]},
} # end test env
}
)
end
it "avoids parsing file more than once when environments have same feature flag set" do
# in this version of puppet, all environments are equal in this respect
result = Puppet::Pops::Parser::EvaluatingParser.new.parse_file("#{code_dir}/fum.pp")
expect_any_instance_of(Puppet::Pops::Parser::EvaluatingParser).to receive(:parse_file).with("#{code_dir}/fum.pp").once.and_return(result)
files_production = ['fum.pp'].map {|f| File.join(code_dir, f) }
files_test = files_production
result = Puppet::InfoService.classes_per_environment({
'production' => files_production,
'test' => files_test
})
expect(result).to eq({
"production"=>{ "#{code_dir}/fum.pp"=>{:classes => [ {:name=>"fum", :params=>[ {:name=>"fum_a"}]}]}},
"test" =>{ "#{code_dir}/fum.pp"=>{:classes => [ {:name=>"fum", :params=>[ {:name=>"fum_a"}]}]}}
}
)
end
it "produces expression string if a default value is not literal" do
files = ['fee.pp'].map {|f| File.join(code_dir, f) }
result = Puppet::InfoService.classes_per_environment({'production' => files })
expect(result).to eq({
"production"=>{
"#{code_dir}/fee.pp"=>{:classes => [
{:name=>"fee",
:params=>[
{:name=>"fee_a", :type=>"Integer", :default_source=>"1+1"}
]},
]}} # end production env
})
end
it "produces source string for literals that are not pure json" do
files = ['json_unsafe.pp'].map {|f| File.join(code_dir, f) }
result = Puppet::InfoService.classes_per_environment({'production' => files })
expect(result).to eq({
"production"=>{
"#{code_dir}/json_unsafe.pp" => {:classes => [
{:name=>"json_unsafe",
:params => [
{:name => "arg1",
:default_source => "/.*/" },
{:name => "arg2",
:default_source => "default" },
{:name => "arg3",
:default_source => "{1 => 1}" }
]}
]}} # end production env
})
end
it "errors with a descriptive message if non-literal class parameter is given" do
files = ['non_literal.pp', 'non_literal_2.pp'].map {|f| File.join(code_dir, f) }
result = Puppet::InfoService.classes_per_environment({'production' => files })
expect(@logs).to have_matching_log_with_source(/The parameter '\$bad_int' must be a literal type, not a Puppet::Pops::Model::AccessExpression/, "#{code_dir}/non_literal.pp", 1, 37)
expect(@logs).to have_matching_log_with_source(/The parameter '\$double_brackets' must be a literal type, not a Puppet::Pops::Model::AccessExpression/, "#{code_dir}/non_literal_2.pp", 1, 44)
expect(result).to eq({
"production"=>{
"#{code_dir}/non_literal.pp" =>
{:error=> "The parameter '\$bad_int' is invalid: The expression <1-3> is not a valid type specification."},
"#{code_dir}/non_literal_2.pp" =>
{:error=> "The parameter '\$double_brackets' is invalid: The expression <Optional[[String]]> is not a valid type specification."}
} # end production env
})
end
it "produces no type entry if type is not given" do
files = ['fum.pp'].map {|f| File.join(code_dir, f) }
result = Puppet::InfoService.classes_per_environment({'production' => files })
expect(result).to eq({
"production"=>{
"#{code_dir}/fum.pp"=>{:classes => [
{:name=>"fum",
:params=>[
{:name=>"fum_a" }
]},
]}} # end production env
})
end
it 'does not evaluate default expressions' do
files = ['intp.pp'].map {|f| File.join(code_dir, f) }
result = Puppet::InfoService.classes_per_environment({'production' => files })
expect(result).to eq({
'production' =>{
"#{code_dir}/intp.pp"=>{:classes => [
{:name=> 'intp',
:params=>[
{:name=> 'intp_a',
:type=> 'String',
:default_source=>'"default with interpolated $::os_family"'}
]},
]}} # end production env
})
end
it "produces error entry if file is broken" do
files = ['borked.pp'].map {|f| File.join(code_dir, f) }
result = Puppet::InfoService.classes_per_environment({'production' => files })
expect(result).to eq({
"production"=>{
"#{code_dir}/borked.pp"=>
{:error=>"Syntax error at '+' (file: #{code_dir}/borked.pp, line: 1, column: 30)",
},
} # end production env
})
end
it "produces empty {} if parsed result has no classes" do
files = ['nothing.pp'].map {|f| File.join(code_dir, f) }
result = Puppet::InfoService.classes_per_environment({'production' => files })
expect(result).to eq({
"production"=>{
"#{code_dir}/nothing.pp"=> {:classes => [] }
},
})
end
it "produces error when given a file that does not exist" do
files = ['the_tooth_fairy_does_not_exist.pp'].map {|f| File.join(code_dir, f) }
result = Puppet::InfoService.classes_per_environment({'production' => files })
expect(result).to eq({
"production"=>{
"#{code_dir}/the_tooth_fairy_does_not_exist.pp" => {:error => "The file #{code_dir}/the_tooth_fairy_does_not_exist.pp does not exist"}
},
})
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/version_spec.rb | spec/unit/version_spec.rb | require "spec_helper"
require "puppet/version"
require 'pathname'
describe "Puppet.version Public API" do
before :each do
@current_ver = Puppet.version
Puppet.instance_eval do
if @puppet_version
@puppet_version = nil
end
end
end
after :each do
Puppet.version = @current_ver
end
context "without a VERSION file" do
before :each do
allow(Puppet).to receive(:read_version_file).and_return(nil)
end
it "is Puppet::PUPPETVERSION" do
expect(Puppet.version).to eq(Puppet::PUPPETVERSION)
end
it "respects the version= setter" do
Puppet.version = '1.2.3'
expect(Puppet.version).to eq('1.2.3')
expect(Puppet.minor_version).to eq('1.2')
end
end
context "with a VERSION file" do
it "is the content of the file" do
expect(Puppet).to receive(:read_version_file) do |path|
pathname = Pathname.new(path)
pathname.basename.to_s == "VERSION"
end.and_return('3.0.1-260-g9ca4e54')
expect(Puppet.version).to eq('3.0.1-260-g9ca4e54')
expect(Puppet.minor_version).to eq('3.0')
end
it "respects the version= setter" do
Puppet.version = '1.2.3'
expect(Puppet.version).to eq('1.2.3')
expect(Puppet.minor_version).to eq('1.2')
end
end
context "Using version setter" do
it "does not read VERSION file if using set version" do
expect(Puppet).not_to receive(:read_version_file)
Puppet.version = '1.2.3'
expect(Puppet.version).to eq('1.2.3')
expect(Puppet.minor_version).to eq('1.2')
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/certificate_factory_spec.rb | spec/unit/certificate_factory_spec.rb | require 'spec_helper'
require 'puppet/test_ca'
require 'puppet/certificate_factory'
describe Puppet::CertificateFactory, :unless => RUBY_PLATFORM == 'java' do
let :serial do OpenSSL::BN.new('12') end
let :name do "example.local" end
let :x509_name do OpenSSL::X509::Name.new([['CN', name]]) end
let :key do OpenSSL::PKey::RSA.new(Puppet[:keylength]) end
let :csr do
csr = Puppet::SSL::CertificateRequest.new(name)
csr.generate(key)
csr
end
let(:issuer) { Puppet::TestCa.new.ca_cert }
describe "when generating the certificate" do
it "should return a new X509 certificate" do
a = subject.build(:server, csr, issuer, serial)
b = subject.build(:server, csr, issuer, serial)
# The two instances are equal in every aspect except that they are
# different instances - they are `==`, but not hash `eql?`
expect(a).not_to eql(b)
end
it "should set the certificate's version to 2" do
expect(subject.build(:server, csr, issuer, serial).version).to eq(2)
end
it "should set the certificate's subject to the CSR's subject" do
cert = subject.build(:server, csr, issuer, serial)
expect(cert.subject).to eq x509_name
end
it "should set the certificate's issuer to the Issuer's subject" do
cert = subject.build(:server, csr, issuer, serial)
expect(cert.issuer).to eq issuer.subject
end
it "should set the certificate's public key to the CSR's public key" do
cert = subject.build(:server, csr, issuer, serial)
expect(cert.public_key).to be_public
expect(cert.public_key.to_s).to eq(csr.content.public_key.to_s)
end
it "should set the certificate's serial number to the provided serial number" do
cert = subject.build(:server, csr, issuer, serial)
expect(cert.serial).to eq(serial)
end
it "should have 24 hours grace on the start of the cert" do
cert = subject.build(:server, csr, issuer, serial)
expect(cert.not_before).to be_within(30).of(Time.now - 24*60*60)
end
it "should not allow a non-integer TTL" do
[ 'foo', 1.2, Time.now, true ].each do |ttl|
expect { subject.build(:server, csr, issuer, serial, ttl) }.to raise_error(ArgumentError)
end
end
it "should respect a custom TTL for the CA" do
now = Time.now.utc
expect(Time).to receive(:now).at_least(:once).and_return(now)
cert = subject.build(:server, csr, issuer, serial, 12)
expect(cert.not_after.to_i).to eq(now.to_i + 12)
end
it "should adds an extension for the nsComment" do
cert = subject.build(:server, csr, issuer, serial)
expect(cert.extensions.map {|x| x.to_h }.find {|x| x["oid"] == "nsComment" }).to eq(
{ "oid" => "nsComment",
# Note that this output is due to a bug in OpenSSL::X509::Extensions
# where the values of some extensions are not properly decoded
"value" => ".(Puppet Ruby/OpenSSL Internal Certificate",
"critical" => false }
)
end
it "should add an extension for the subjectKeyIdentifer" do
cert = subject.build(:server, csr, issuer, serial)
ef = OpenSSL::X509::ExtensionFactory.new(issuer, cert)
expect(cert.extensions.map { |x| x.to_h }.find {|x| x["oid"] == "subjectKeyIdentifier" }).to eq(
ef.create_extension("subjectKeyIdentifier", "hash", false).to_h
)
end
it "should add an extension for the authorityKeyIdentifer" do
cert = subject.build(:server, csr, issuer, serial)
ef = OpenSSL::X509::ExtensionFactory.new(issuer, cert)
expect(cert.extensions.map { |x| x.to_h }.find {|x| x["oid"] == "authorityKeyIdentifier" }).to eq(
ef.create_extension("authorityKeyIdentifier", "keyid:always", false).to_h
)
end
# See #2848 for why we are doing this: we need to make sure that
# subjectAltName is set if the CSR has it, but *not* if it is set when the
# certificate is built!
it "should not add subjectAltNames from dns_alt_names" do
Puppet[:dns_alt_names] = 'one, two'
# Verify the CSR still has no extReq, just in case...
expect(csr.request_extensions).to eq([])
cert = subject.build(:server, csr, issuer, serial)
expect(cert.extensions.find {|x| x.oid == 'subjectAltName' }).to be_nil
end
it "should add subjectAltName when the CSR requests them" do
Puppet[:dns_alt_names] = ''
expect = %w{one two} + [name]
csr = Puppet::SSL::CertificateRequest.new(name)
csr.generate(key, :dns_alt_names => expect.join(', '))
expect(csr.request_extensions).not_to be_nil
expect(csr.subject_alt_names).to match_array(expect.map{|x| "DNS:#{x}"})
cert = subject.build(:server, csr, issuer, serial)
san = cert.extensions.find {|x| x.oid == 'subjectAltName' }
expect(san).not_to be_nil
expect.each do |name|
expect(san.value).to match(/DNS:#{name}\b/i)
end
end
it "can add custom extension requests" do
csr = Puppet::SSL::CertificateRequest.new(name)
csr.generate(key)
allow(csr).to receive(:request_extensions).and_return([
{'oid' => '1.3.6.1.4.1.34380.1.2.1', 'value' => 'some-value'},
{'oid' => 'pp_uuid', 'value' => 'some-uuid'},
])
cert = subject.build(:client, csr, issuer, serial)
# The cert must be signed before being later DER-decoding
signer = Puppet::SSL::CertificateSigner.new
signer.sign(cert, key)
wrapped_cert = Puppet::SSL::Certificate.from_instance cert
priv_ext = wrapped_cert.custom_extensions.find {|ext| ext['oid'] == '1.3.6.1.4.1.34380.1.2.1'}
uuid_ext = wrapped_cert.custom_extensions.find {|ext| ext['oid'] == 'pp_uuid'}
# The expected results should be DER encoded, the Puppet cert wrapper will turn
# these into normal strings.
expect(priv_ext['value']).to eq 'some-value'
expect(uuid_ext['value']).to eq 'some-uuid'
end
# Can't check the CA here, since that requires way more infrastructure
# that I want to build up at this time. We can verify the critical
# values, though, which are non-CA certs. --daniel 2011-10-11
{ :ca => 'CA:TRUE',
:terminalsubca => ['CA:TRUE', 'pathlen:0'],
:server => 'CA:FALSE',
:ocsp => 'CA:FALSE',
:client => 'CA:FALSE',
}.each do |name, value|
it "should set basicConstraints for #{name} #{value.inspect}" do
cert = subject.build(name, csr, issuer, serial)
bc = cert.extensions.find {|x| x.oid == 'basicConstraints' }
expect(bc).to be
expect(bc.value.split(/\s*,\s*/)).to match_array(Array(value))
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/relationship_spec.rb | spec/unit/relationship_spec.rb | require 'spec_helper'
require 'puppet/relationship'
describe Puppet::Relationship do
before do
@edge = Puppet::Relationship.new(:a, :b)
end
it "should have a :source attribute" do
expect(@edge).to respond_to(:source)
end
it "should have a :target attribute" do
expect(@edge).to respond_to(:target)
end
it "should have a :callback attribute" do
@edge.callback = :foo
expect(@edge.callback).to eq(:foo)
end
it "should have an :event attribute" do
@edge.event = :NONE
expect(@edge.event).to eq(:NONE)
end
it "should require a callback if a non-NONE event is specified" do
expect { @edge.event = :something }.to raise_error(ArgumentError)
end
it "should have a :label attribute" do
expect(@edge).to respond_to(:label)
end
it "should provide a :ref method that describes the edge" do
@edge = Puppet::Relationship.new("a", "b")
expect(@edge.ref).to eq("a => b")
end
it "should be able to produce a label as a hash with its event and callback" do
@edge.callback = :foo
@edge.event = :bar
expect(@edge.label).to eq({:callback => :foo, :event => :bar})
end
it "should work if nil options are provided" do
expect { Puppet::Relationship.new("a", "b", nil) }.not_to raise_error
end
end
describe Puppet::Relationship, " when initializing" do
before do
@edge = Puppet::Relationship.new(:a, :b)
end
it "should use the first argument as the source" do
expect(@edge.source).to eq(:a)
end
it "should use the second argument as the target" do
expect(@edge.target).to eq(:b)
end
it "should set the rest of the arguments as the event and callback" do
@edge = Puppet::Relationship.new(:a, :b, :callback => :foo, :event => :bar)
expect(@edge.callback).to eq(:foo)
expect(@edge.event).to eq(:bar)
end
it "should accept events specified as strings" do
@edge = Puppet::Relationship.new(:a, :b, "event" => :NONE)
expect(@edge.event).to eq(:NONE)
end
it "should accept callbacks specified as strings" do
@edge = Puppet::Relationship.new(:a, :b, "callback" => :foo)
expect(@edge.callback).to eq(:foo)
end
end
describe Puppet::Relationship, " when matching edges with no specified event" do
before do
@edge = Puppet::Relationship.new(:a, :b)
end
it "should not match :NONE" do
expect(@edge).not_to be_match(:NONE)
end
it "should not match :ALL_EVENTS" do
expect(@edge).not_to be_match(:ALL_EVENTS)
end
it "should not match any other events" do
expect(@edge).not_to be_match(:whatever)
end
end
describe Puppet::Relationship, " when matching edges with :NONE as the event" do
before do
@edge = Puppet::Relationship.new(:a, :b, :event => :NONE)
end
it "should not match :NONE" do
expect(@edge).not_to be_match(:NONE)
end
it "should not match :ALL_EVENTS" do
expect(@edge).not_to be_match(:ALL_EVENTS)
end
it "should not match other events" do
expect(@edge).not_to be_match(:yayness)
end
end
describe Puppet::Relationship, " when matching edges with :ALL as the event" do
before do
@edge = Puppet::Relationship.new(:a, :b, :event => :ALL_EVENTS, :callback => :whatever)
end
it "should not match :NONE" do
expect(@edge).not_to be_match(:NONE)
end
it "should match :ALL_EVENTS" do
expect(@edge).to be_match(:ALL_EVENTS)
end
it "should match all other events" do
expect(@edge).to be_match(:foo)
end
end
describe Puppet::Relationship, " when matching edges with a non-standard event" do
before do
@edge = Puppet::Relationship.new(:a, :b, :event => :random, :callback => :whatever)
end
it "should not match :NONE" do
expect(@edge).not_to be_match(:NONE)
end
it "should not match :ALL_EVENTS" do
expect(@edge).not_to be_match(:ALL_EVENTS)
end
it "should match events with the same name" do
expect(@edge).to be_match(:random)
end
end
describe Puppet::Relationship, "when converting to json" do
before do
@edge = Puppet::Relationship.new('a', 'b', :event => :random, :callback => :whatever)
end
it "should store the stringified source as the source in the data" do
expect(JSON.parse(@edge.to_json)["source"]).to eq("a")
end
it "should store the stringified target as the target in the data" do
expect(JSON.parse(@edge.to_json)['target']).to eq("b")
end
it "should store the jsonified event as the event in the data" do
expect(JSON.parse(@edge.to_json)["event"]).to eq("random")
end
it "should not store an event when none is set" do
@edge.event = nil
expect(JSON.parse(@edge.to_json)).not_to include('event')
end
it "should store the jsonified callback as the callback in the data" do
@edge.callback = "whatever"
expect(JSON.parse(@edge.to_json)["callback"]).to eq("whatever")
end
it "should not store a callback when none is set in the edge" do
@edge.callback = nil
expect(JSON.parse(@edge.to_json)).not_to include('callback')
end
end
describe Puppet::Relationship, "when converting from json" do
it "should pass the source in as the first argument" do
expect(Puppet::Relationship.from_data_hash("source" => "mysource", "target" => "mytarget").source).to eq('mysource')
end
it "should pass the target in as the second argument" do
expect(Puppet::Relationship.from_data_hash("source" => "mysource", "target" => "mytarget").target).to eq('mytarget')
end
it "should pass the event as an argument if it's provided" do
expect(Puppet::Relationship.from_data_hash("source" => "mysource", "target" => "mytarget", "event" => "myevent", "callback" => "eh").event).to eq(:myevent)
end
it "should pass the callback as an argument if it's provided" do
expect(Puppet::Relationship.from_data_hash("source" => "mysource", "target" => "mytarget", "callback" => "mycallback").callback).to eq(:mycallback)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/confiner_spec.rb | spec/unit/confiner_spec.rb | require 'spec_helper'
require 'puppet/confiner'
describe Puppet::Confiner do
let(:coll) { Puppet::ConfineCollection.new('') }
before do
@object = Object.new
@object.extend(Puppet::Confiner)
end
it "should have a method for defining confines" do
expect(@object).to respond_to(:confine)
end
it "should have a method for returning its confine collection" do
expect(@object).to respond_to(:confine_collection)
end
it "should have a method for testing suitability" do
expect(@object).to respond_to(:suitable?)
end
it "should delegate its confine method to its confine collection" do
allow(@object).to receive(:confine_collection).and_return(coll)
expect(coll).to receive(:confine).with({:foo => :bar, :bee => :baz})
@object.confine(:foo => :bar, :bee => :baz)
end
it "should create a new confine collection if one does not exist" do
expect(Puppet::ConfineCollection).to receive(:new).with("mylabel").and_return("mycoll")
expect(@object).to receive(:to_s).and_return("mylabel")
expect(@object.confine_collection).to eq("mycoll")
end
it "should reuse the confine collection" do
expect(@object.confine_collection).to equal(@object.confine_collection)
end
describe "when testing suitability" do
before do
allow(@object).to receive(:confine_collection).and_return(coll)
end
it "should return true if the confine collection is valid" do
expect(coll).to receive(:valid?).and_return(true)
expect(@object).to be_suitable
end
it "should return false if the confine collection is invalid" do
expect(coll).to receive(:valid?).and_return(false)
expect(@object).not_to be_suitable
end
it "should return the summary of the confine collection if a long result is asked for" do
expect(coll).to receive(:summary).and_return("myresult")
expect(@object.suitable?(false)).to eq("myresult")
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/interface_spec.rb | spec/unit/interface_spec.rb | require 'spec_helper'
require 'puppet/face'
require 'puppet/interface'
describe Puppet::Interface do
subject { Puppet::Interface }
before :each do
@faces = Puppet::Interface::FaceCollection.
instance_variable_get("@faces").dup
@dq = $".dup
$".delete_if do |path| path =~ %r{/face/.*\.rb$} end
Puppet::Interface::FaceCollection.instance_variable_get("@faces").clear
end
after :each do
Puppet::Interface::FaceCollection.instance_variable_set("@faces", @faces)
$".clear ; @dq.each do |item| $" << item end
end
describe "#[]" do
it "should fail when no version is requested" do
expect { subject[:huzzah] }.to raise_error ArgumentError
end
it "should raise an exception when the requested version is unavailable" do
expect { subject[:huzzah, '17.0.0'] }.to raise_error(Puppet::Error, /Could not find version/)
end
it "should raise an exception when the requested face doesn't exist" do
expect { subject[:burrble_toot, :current] }.to raise_error(Puppet::Error, /Could not find Puppet Face/)
end
describe "version matching" do
{ '1' => '1.1.1',
'1.0' => '1.0.1',
'1.0.1' => '1.0.1',
'1.1' => '1.1.1',
'1.1.1' => '1.1.1'
}.each do |input, expect|
it "should match #{input.inspect} to #{expect.inspect}" do
face = subject[:version_matching, input]
expect(face).to be
expect(face.version).to eq(expect)
end
end
%w{1.0.2 1.2}.each do |input|
it "should not match #{input.inspect} to any version" do
expect { subject[:version_matching, input] }.
to raise_error Puppet::Error, /Could not find version/
end
end
end
end
describe "#define" do
it "should register the face" do
face = subject.define(:face_test_register, '0.0.1')
expect(face).to eq(subject[:face_test_register, '0.0.1'])
end
it "should load actions" do
expect_any_instance_of(subject).to receive(:load_actions)
subject.define(:face_test_load_actions, '0.0.1')
end
it "should require a version number" do
expect { subject.define(:no_version) }.to raise_error ArgumentError
end
it "should support summary builder and accessor methods" do
expect(subject.new(:foo, '1.0.0')).to respond_to(:summary).with(0).arguments
expect(subject.new(:foo, '1.0.0')).to respond_to(:summary=).with(1).arguments
end
# Required documentation methods...
{ :summary => "summary",
:description => "This is the description of the stuff\n\nWhee",
:examples => "This is my example",
:short_description => "This is my custom short description",
:notes => "These are my notes...",
:author => "This is my authorship data",
}.each do |attr, value|
it "should support #{attr} in the builder" do
face = subject.new(:builder, '1.0.0') do
self.send(attr, value)
end
expect(face.send(attr)).to eq(value)
end
end
end
describe "#initialize" do
it "should require a version number" do
expect { subject.new(:no_version) }.to raise_error ArgumentError
end
it "should require a valid version number" do
expect { subject.new(:bad_version, 'Rasins') }.
to raise_error ArgumentError
end
it "should instance-eval any provided block" do
face = subject.new(:face_test_block, '0.0.1') do
action(:something) do
when_invoked {|_| "foo" }
end
end
expect(face.something).to eq("foo")
end
end
it "should have a name" do
expect(subject.new(:me, '0.0.1').name).to eq(:me)
end
it "should stringify with its own name" do
expect(subject.new(:me, '0.0.1').to_s).to match(/\bme\b/)
end
it "should try to require faces that are not known" do
expect(subject::FaceCollection).to receive(:load_face).with(:foo, :current)
expect(subject::FaceCollection).to receive(:load_face).with(:foo, '0.0.1')
expect { subject[:foo, '0.0.1'] }.to raise_error Puppet::Error
end
describe 'when raising NoMethodErrors' do
subject { described_class.new(:foo, '1.0.0') }
if RUBY_VERSION.to_f >= 3.3
it 'includes the face name in the error message' do
expect { subject.boombaz }.to raise_error(NoMethodError, /for an instance of Puppet::Interface/)
end
it 'includes the face version in the error message' do
expect { subject.boombaz }.to raise_error(NoMethodError, /for an instance of Puppet::Interface/)
end
else
it 'includes the face name in the error message' do
expect { subject.boombaz }.to raise_error(NoMethodError, /#{subject.name}/)
end
it 'includes the face version in the error message' do
expect { subject.boombaz }.to raise_error(NoMethodError, /#{subject.version}/)
end
end
end
it_should_behave_like "things that declare options" do
def add_options_to(&block)
subject.new(:with_options, '0.0.1', &block)
end
end
context "when deprecating a face" do
let(:face) { subject.new(:foo, '0.0.1') }
describe "#deprecate" do
it "should respond to #deprecate" do
expect(subject.new(:foo, '0.0.1')).to respond_to(:deprecate)
end
it "should set the deprecated value to true" do
expect(face.deprecated?).to be_falsey
face.deprecate
expect(face.deprecated?).to be_truthy
end
end
describe "#deprecated?" do
it "should return a nil (falsey) value by default" do
expect(face.deprecated?).to be_falsey
end
it "should return true if the face has been deprecated" do
expect(face.deprecated?).to be_falsey
face.deprecate
expect(face.deprecated?).to be_truthy
end
end
end
describe "with face-level display_global_options" do
it "should not return any action level display_global_options" do
face = subject.new(:with_display_global_options, '0.0.1') do
display_global_options "environment"
action :baz do
when_invoked {|_| true }
display_global_options "modulepath"
end
end
expect(face.display_global_options).to match(["environment"])
end
it "should not fail when a face d_g_o duplicates an action d_g_o" do
expect {
subject.new(:action_level_display_global_options, '0.0.1') do
action :bar do
when_invoked {|_| true }
display_global_options "environment"
end
display_global_options "environment"
end
}.to_not raise_error
end
it "should work when two actions have the same d_g_o" do
face = subject.new(:with_display_global_options, '0.0.1') do
action :foo do when_invoked {|_| true} ; display_global_options "environment" end
action :bar do when_invoked {|_| true} ; display_global_options "environment" end
end
expect(face.get_action(:foo).display_global_options).to match(["environment"])
expect(face.get_action(:bar).display_global_options).to match(["environment"])
end
end
describe "with inherited display_global_options" do
end
describe "with face-level options" do
it "should not return any action-level options" do
face = subject.new(:with_options, '0.0.1') do
option "--foo"
option "--bar"
action :baz do
when_invoked {|_| true }
option "--quux"
end
end
expect(face.options).to match_array([:foo, :bar])
end
it "should fail when a face option duplicates an action option" do
expect {
subject.new(:action_level_options, '0.0.1') do
action :bar do
when_invoked {|_| true }
option "--foo"
end
option "--foo"
end
}.to raise_error ArgumentError, /Option foo conflicts with existing option foo on/i
end
it "should work when two actions have the same option" do
face = subject.new(:with_options, '0.0.1') do
action :foo do when_invoked {|_| true } ; option "--quux" end
action :bar do when_invoked {|_| true } ; option "--quux" end
end
expect(face.get_action(:foo).options).to match_array([:quux])
expect(face.get_action(:bar).options).to match_array([:quux])
end
it "should only list options and not aliases" do
face = subject.new(:face_options, '0.0.1') do
option "--bar", "-b", "--foo-bar"
end
expect(face.options).to match_array([:bar])
end
end
describe "with inherited options" do
let :parent do
parent = Class.new(subject)
parent.option("--inherited")
parent.action(:parent_action) do when_invoked {|_| true } end
parent
end
let :face do
face = parent.new(:example, '0.2.1')
face.option("--local")
face.action(:face_action) do when_invoked {|_| true } end
face
end
describe "#options" do
it "should list inherited options" do
expect(face.options).to match_array([:inherited, :local])
end
it "should see all options on face actions" do
expect(face.get_action(:face_action).options).to match_array([:inherited, :local])
end
it "should see all options on inherited actions accessed on the subclass" do
expect(face.get_action(:parent_action).options).to match_array([:inherited, :local])
end
it "should not see subclass actions on the parent class" do
expect(parent.options).to match_array([:inherited])
end
it "should not see subclass actions on actions accessed on the parent class" do
expect(parent.get_action(:parent_action).options).to match_array([:inherited])
end
end
describe "#get_option" do
it "should return an inherited option object" do
expect(face.get_option(:inherited)).to be_an_instance_of subject::Option
end
end
end
it_should_behave_like "documentation on faces" do
subject do
Puppet::Interface.new(:face_documentation, '0.0.1')
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/provider_spec.rb | spec/unit/provider_spec.rb | require 'spec_helper'
def existing_command
Puppet::Util::Platform.windows? ? "cmd" : "echo"
end
describe Puppet::Provider do
before :each do
Puppet::Type.newtype(:test) do
newparam(:name) { isnamevar }
end
end
after :each do
Puppet::Type.type(:test).provider_hash.clear
Puppet::Type.rmtype(:test)
end
let :type do Puppet::Type.type(:test) end
let :provider do type.provide(:default) {} end
subject { provider }
describe "has command" do
it "installs a method to run the command specified by the path" do
echo_command = expect_command_executed(:echo, "/bin/echo", "an argument")
allow_creation_of(echo_command)
provider = provider_of do
has_command(:echo, "/bin/echo")
end
provider.echo("an argument")
end
it "installs a command that is run with a given environment" do
echo_command = expect_command_executed(:echo, "/bin/echo", "an argument")
allow_creation_of(echo_command, {
:EV => "value",
:OTHER => "different"
})
provider = provider_of do
has_command(:echo, "/bin/echo") do
environment :EV => "value", :OTHER => "different"
end
end
provider.echo("an argument")
end
it "is required by default" do
provider = provider_of do
has_command(:does_not_exist, "/does/not/exist")
end
expect(provider).not_to be_suitable
end
it "is required by default" do
provider = provider_of do
has_command(:does_exist, File.expand_path("/exists/somewhere"))
end
file_exists_and_is_executable(File.expand_path("/exists/somewhere"))
expect(provider).to be_suitable
end
it "can be specified as optional" do
provider = provider_of do
has_command(:does_not_exist, "/does/not/exist") do
is_optional
end
end
expect(provider).to be_suitable
end
end
describe "has required commands" do
it "installs methods to run executables by path" do
echo_command = expect_command_executed(:echo, "/bin/echo", "an argument")
ls_command = expect_command_executed(:ls, "/bin/ls")
allow_creation_of(echo_command)
allow_creation_of(ls_command)
provider = provider_of do
commands :echo => "/bin/echo", :ls => "/bin/ls"
end
provider.echo("an argument")
provider.ls
end
it "allows the provider to be suitable if the executable is present" do
provider = provider_of do
commands :always_exists => File.expand_path("/this/command/exists")
end
file_exists_and_is_executable(File.expand_path("/this/command/exists"))
expect(provider).to be_suitable
end
it "does not allow the provider to be suitable if the executable is not present" do
provider = provider_of do
commands :does_not_exist => "/this/command/does/not/exist"
end
expect(provider).not_to be_suitable
end
end
describe "has optional commands" do
it "installs methods to run executables" do
echo_command = expect_command_executed(:echo, "/bin/echo", "an argument")
ls_command = expect_command_executed(:ls, "/bin/ls")
allow_creation_of(echo_command)
allow_creation_of(ls_command)
provider = provider_of do
optional_commands :echo => "/bin/echo", :ls => "/bin/ls"
end
provider.echo("an argument")
provider.ls
end
it "allows the provider to be suitable even if the executable is not present" do
provider = provider_of do
optional_commands :does_not_exist => "/this/command/does/not/exist"
end
expect(provider).to be_suitable
end
end
it "should have a specifity class method" do
expect(Puppet::Provider).to respond_to(:specificity)
end
it "should be Comparable" do
res = Puppet::Type.type(:notify).new(:name => "res")
# Normally I wouldn't like the stubs, but the only way to name a class
# otherwise is to assign it to a constant, and that hurts more here in
# testing world. --daniel 2012-01-29
a = Class.new(Puppet::Provider).new(res)
allow(a.class).to receive(:name).and_return("Puppet::Provider::Notify::A")
b = Class.new(Puppet::Provider).new(res)
allow(b.class).to receive(:name).and_return("Puppet::Provider::Notify::B")
c = Class.new(Puppet::Provider).new(res)
allow(c.class).to receive(:name).and_return("Puppet::Provider::Notify::C")
[[a, b, c], [a, c, b], [b, a, c], [b, c, a], [c, a, b], [c, b, a]].each do |this|
expect(this.sort).to eq([a, b, c])
end
expect(a).to be < b
expect(a).to be < c
expect(b).to be > a
expect(b).to be < c
expect(c).to be > a
expect(c).to be > b
[a, b, c].each {|x| expect(a).to be <= x }
[a, b, c].each {|x| expect(c).to be >= x }
expect(b).to be_between(a, c)
end
context "when creating instances" do
context "with a resource" do
let :resource do type.new(:name => "fred") end
subject { provider.new(resource) }
it "should set the resource correctly" do
expect(subject.resource).to equal resource
end
it "should set the name from the resource" do
expect(subject.name).to eq(resource.name)
end
end
context "with a hash" do
subject { provider.new(:name => "fred") }
it "should set the name" do
expect(subject.name).to eq("fred")
end
it "should not have a resource" do expect(subject.resource).to be_nil end
end
context "with no arguments" do
subject { provider.new }
it "should raise an internal error if asked for the name" do
expect { subject.name }.to raise_error Puppet::DevError
end
it "should not have a resource" do expect(subject.resource).to be_nil end
end
end
context "when confining" do
it "should be suitable by default" do
expect(subject).to be_suitable
end
it "should not be default by default" do
expect(subject).not_to be_default
end
{ { :true => true } => true,
{ :true => false } => false,
{ :false => false } => true,
{ :false => true } => false,
{ 'os.name' => Puppet.runtime[:facter].value('os.name') } => true,
{ 'os.name' => :yayness } => false,
{ :nothing => :yayness } => false,
{ :exists => Puppet::Util.which(existing_command) } => true,
{ :exists => "/this/file/does/not/exist" } => false,
{ :true => true, :exists => Puppet::Util.which(existing_command) } => true,
{ :true => true, :exists => "/this/file/does/not/exist" } => false,
{ 'os.name' => Puppet.runtime[:facter].value('os.name'),
:exists => Puppet::Util.which(existing_command) } => true,
{ 'os.name' => :yayness,
:exists => Puppet::Util.which(existing_command) } => false,
{ 'os.name' => Puppet.runtime[:facter].value('os.name'),
:exists => "/this/file/does/not/exist" } => false,
{ 'os.name' => :yayness,
:exists => "/this/file/does/not/exist" } => false,
}.each do |confines, result|
it "should confine #{confines.inspect} to #{result}" do
confines.each {|test, value| subject.confine test => value }
if result
expect(subject).to be_suitable
else
expect(subject).to_not be_suitable
end
end
end
it "should not override a confine even if a second has the same type" do
subject.confine :true => false
expect(subject).not_to be_suitable
subject.confine :true => true
expect(subject).not_to be_suitable
end
it "should not be suitable if any confine fails" do
subject.confine :true => false
expect(subject).not_to be_suitable
10.times do
subject.confine :true => true
expect(subject).not_to be_suitable
end
end
end
context "default providers" do
let :os do Puppet.runtime[:facter].value('os.name') end
it { is_expected.to respond_to :specificity }
it "should find the default provider" do
type.provide(:nondefault) {}
subject.defaultfor 'os.name' => os
expect(subject.name).to eq(type.defaultprovider.name)
end
describe "regex matches" do
it "should match a singular regex" do
expect(Facter).to receive(:value).with('os.family').at_least(:once).and_return("solaris")
one = type.provide(:one) do
defaultfor 'os.family' => /solaris/
end
expect(one).to be_default
end
it "should not match a non-matching regex " do
expect(Facter).to receive(:value).with('os.family').at_least(:once).and_return("redhat")
one = type.provide(:one) do
defaultfor 'os.family' => /solaris/
end
expect(one).to_not be_default
end
it "should allow a mix of regex and string" do
expect(Facter).to receive(:value).with('os.name').at_least(:once).and_return("fedora")
expect(Facter).to receive(:value).with('os.release.major').at_least(:once).and_return("24")
one = type.provide(:one) do
defaultfor 'os.name' => "fedora", 'os.release.major' => /^2[2-9]$/
end
two = type.provide(:two) do
defaultfor 'os.name' => /fedora/, 'os.release.major' => '24'
end
expect(one).to be_default
expect(two).to be_default
end
end
describe "when there are multiple defaultfor's of equal specificity" do
before :each do
subject.defaultfor 'os.name' => :os1
subject.defaultfor 'os.name' => :os2
end
let(:alternate) { type.provide(:alternate) {} }
it "should be default for the first defaultfor" do
expect(Facter).to receive(:value).with('os.name').at_least(:once).and_return(:os1)
expect(provider).to be_default
expect(alternate).not_to be_default
end
it "should be default for the last defaultfor" do
expect(Facter).to receive(:value).with('os.name').at_least(:once).and_return(:os2)
expect(provider).to be_default
expect(alternate).not_to be_default
end
end
describe "when there are multiple defaultfor's with different specificity" do
before :each do
subject.defaultfor 'os.name' => :os1
subject.defaultfor 'os.name' => :os2, 'os.release.major' => "42"
subject.defaultfor 'os.name' => :os3, 'os.release.major' => /^4[2-9]$/
end
let(:alternate) { type.provide(:alternate) {} }
it "should be default for a more specific, but matching, defaultfor" do
expect(Facter).to receive(:value).with('os.name').at_least(:once).and_return(:os2)
expect(Facter).to receive(:value).with('os.release.major').at_least(:once).and_return("42")
expect(provider).to be_default
expect(alternate).not_to be_default
end
it "should be default for a more specific, but matching, defaultfor with regex" do
expect(Facter).to receive(:value).with('os.name').at_least(:once).and_return(:os3)
expect(Facter).to receive(:value).with('os.release.major').at_least(:once).and_return("42")
expect(provider).to be_default
expect(alternate).not_to be_default
end
it "should be default for a less specific, but matching, defaultfor" do
expect(Facter).to receive(:value).with('os.name').at_least(:once).and_return(:os1)
expect(provider).to be_default
expect(alternate).not_to be_default
end
end
it "should consider any true value enough to be default" do
alternate = type.provide(:alternate) {}
subject.defaultfor 'os.name' => [:one, :two, :three, os]
expect(subject.name).to eq(type.defaultprovider.name)
expect(subject).to be_default
expect(alternate).not_to be_default
end
it "should not be default if the defaultfor doesn't match" do
expect(subject).not_to be_default
subject.defaultfor 'os.name' => :one
expect(subject).not_to be_default
end
it "should not be default if the notdefaultfor does match" do
expect(Facter).to receive(:value).with('os.name').at_least(:once).and_return("fedora")
expect(Facter).to receive(:value).with('os.release.major').at_least(:once).and_return("24")
one = type.provide(:one) do
defaultfor 'os.name' => "fedora"
notdefaultfor 'os.name' => "fedora", 'os.release.major' => 24
end
expect(one).not_to be_default
end
it "should be default if the notdefaultfor doesn't match" do
expect(Facter).to receive(:value).with('os.name').at_least(:once).and_return("fedora")
expect(Facter).to receive(:value).with('os.release.major').at_least(:once).and_return("24")
one = type.provide(:one) do
defaultfor 'os.name' => "fedora"
notdefaultfor 'os.name' => "fedora", 'os.release.major' => 42
end
expect(one).to be_default
end
# Key: spec has 4 required and 1 optional part:
# one-defaultfor, one-notdefaultfor, two-defaultfor, two-notdefaultfor
# d = defaultfor, n = notdefaultfor,
# d2 - two clauses in defaultfor constraint,
# ! = constraint exists but doesn't match
# none = no constraint
# d+/!d+/none+ - provider class has deeper inheritence
context "defaultfor/notdefaultfor configurable tests" do
[
# Two default? group - ties go to first to register
%w{d none d none pickone},
# Two default? group - second is selected for specificity
%w{d !n d2 !n },
%w{d !n d2 none },
# Two default? group - second is selected for inheritence
%w{d !n d+ !n },
%w{d !n d+ none },
# One default? group - second (only default?) always is selected
%w{!d !n d none },
%w{!d !n d !n },
%w{!d n d none },
%w{!d n d !n },
%w{d n d none },
%w{d n d !n },
# No default? group:
%w{d !n d !n pickone},
%w{d !n d none pickone},
%w{!d !n !d !n pickone},
%w{!d !n !d none pickone},
%w{!d none !d none pickone},
%w{none !n none !n pickone},
%w{none none none none pickone},
# No default? but deeper class inheritence group:
%w{!d !n !d+ !n },
%w{!d !n !d+ none },
%w{!d none !d+ none },
%w{none !n none+ !n },
%w{none none none+ none },
].each do |thisspec|
defaultforspec = {
:one => {},
:two => {},
:expect_one => false #Default expectation is to expect provider two for these tests
}
fail "Inheritence not supported on first provider" if thisspec[0].end_with?('+')
case thisspec[0] # First provider defaultfor spec
when 'd'
defaultforspec[:one][:defaultfor] = true
when '!d'
defaultforspec[:one][:defaultfor] = false
when 'none'
# Do not include a defaultfor constraint
else
fail "Did not understand first spec: %{spec}" % { spec: thisspec[0] }
end
case thisspec[1] # First provider notdefaultfor spec
when 'n'
defaultforspec[:one][:notdefaultfor] = true
when '!n'
defaultforspec[:one][:notdefaultfor] = false
when 'none'
# Do not include a notdefaultfor constraint
else
fail "Did not understand second spec: %{spec}" % { spec: thisspec[1] }
end
if thisspec[2].end_with?('+') then # d+ !d+ none+
defaultforspec[:two][:derived] = true
thisspec[2] = thisspec[2][0 .. -2]
end
case thisspec[2]
when 'd'
defaultforspec[:two][:defaultfor] = true
when 'd2'
defaultforspec[:two][:extradefaultfor] = true
when '!d'
defaultforspec[:two][:defaultfor] = false
when 'none'
# Do not include a defaultfor constraint
else
fail "Did not understand third spec: %{spec}" % { spec: thisspec[2] }
end
case thisspec[3] # Second provider notdefaultfor spec
when 'n'
defaultforspec[:two][:notdefaultfor] = true
when '!n'
defaultforspec[:two][:notdefaultfor] = false
when 'none'
# Do not include a notdefaultfor constraint
else
fail "Did not understand fourth spec: %{spec}" % { spec: thisspec[3] }
end
if thisspec.length == 5 && thisspec[4] == "pickone" then
defaultforspec[:expect_one] = true
end
it "with the specification: %{spec}" % { spec: thisspec.join(', ') } do
allow(Facter).to receive(:value).with('os.family').and_return("redhat")
allow(Facter).to receive(:value).with('os.name').and_return("centos")
allow(Facter).to receive(:value).with('os.release.full').and_return("27")
one = type.provide(:one) do
if defaultforspec[:one].key?(:defaultfor)
defaultfor 'os.family' => "redhat" if defaultforspec[:one][:defaultfor]
defaultfor 'os.family' => "ubuntu" if !defaultforspec[:one][:defaultfor]
end
if defaultforspec[:one].key?(:notdefaultfor)
notdefaultfor 'os.name' => "centos" if defaultforspec[:one][:notdefaultfor]
notdefaultfor 'os.name' => "ubuntu" if !defaultforspec[:one][:notdefaultfor]
end
end
provider_options = {}
provider_options[:parent] = one if defaultforspec[:two][:derived] # :two inherits from one, if spec'd
two = type.provide(:two, provider_options) do
if defaultforspec[:two].key?(:defaultfor) || defaultforspec[:two].key?(:extradefaultfor)
defaultfor 'os.family' => "redhat" if defaultforspec[:two][:defaultfor]
defaultfor 'os.family' => "redhat",# defaultforspec[:two][:extradefaultfor] has two parts
'os.name' => "centos" if defaultforspec[:two][:extradefaultfor]
defaultfor 'os.family' => "ubuntu" if !defaultforspec[:two][:defaultfor]
end
if defaultforspec[:two].key?(:notdefaultfor)
notdefaultfor 'os.release.full' => "27" if defaultforspec[:two][:notdefaultfor]
notdefaultfor 'os.release.full' => "99" if !defaultforspec[:two][:notdefaultfor]
end
end
if defaultforspec[:expect_one] then
expect(Puppet).to receive(:warning).with(/Found multiple default providers/)
expect(type.defaultprovider).to eq(one)
else
expect(type.defaultprovider).to eq(two)
end
end
end
end
describe "using a :feature key" do
before :each do
Puppet.features.add(:yay) do true end
Puppet.features.add(:boo) do false end
end
it "is default for an available feature" do
one = type.provide(:one) do
defaultfor :feature => :yay
end
expect(one).to be_default
end
it "is not default for a missing feature" do
two = type.provide(:two) do
defaultfor :feature => :boo
end
expect(two).not_to be_default
end
end
end
context "provider commands" do
it "should raise for unknown commands" do
expect { subject.command(:something) }.to raise_error(Puppet::DevError)
end
it "should handle command inheritance" do
parent = type.provide("parent")
child = type.provide("child", :parent => parent.name)
command = Puppet::Util.which('sh') || Puppet::Util.which('cmd.exe')
parent.commands :sh => command
expect(Puppet::FileSystem.exist?(parent.command(:sh))).to be_truthy
expect(parent.command(:sh)).to match(/#{Regexp.escape(command)}$/)
expect(Puppet::FileSystem.exist?(child.command(:sh))).to be_truthy
expect(child.command(:sh)).to match(/#{Regexp.escape(command)}$/)
end
it "#1197: should find commands added in the same run" do
subject.commands :testing => "puppet-bug-1197"
expect(subject.command(:testing)).to be_nil
allow(subject).to receive(:which).with("puppet-bug-1197").and_return("/puppet-bug-1197")
expect(subject.command(:testing)).to eq("/puppet-bug-1197")
# Ideally, we would also test that `suitable?` returned the right thing
# here, but it is impossible to get access to the methods that do that
# without digging way down into the implementation. --daniel 2012-03-20
end
context "with optional commands" do
before :each do
subject.optional_commands :cmd => "/no/such/binary/exists"
end
it { is_expected.to be_suitable }
it "should not be suitable if a mandatory command is also missing" do
subject.commands :foo => "/no/such/binary/either"
expect(subject).not_to be_suitable
end
it "should define a wrapper for the command" do
expect(subject).to respond_to(:cmd)
end
it "should return nil if the command is requested" do
expect(subject.command(:cmd)).to be_nil
end
it "should raise if the command is invoked" do
expect { subject.cmd }.to raise_error(Puppet::Error, /Command cmd is missing/)
end
end
end
context "execution" do
before :each do
expect(Puppet).not_to receive(:deprecation_warning)
end
it "delegates instance execute to Puppet::Util::Execution" do
expect(Puppet::Util::Execution).to receive(:execute).with("a_command", { :option => "value" })
provider.new.execute("a_command", { :option => "value" })
end
it "delegates class execute to Puppet::Util::Execution" do
expect(Puppet::Util::Execution).to receive(:execute).with("a_command", { :option => "value" })
provider.execute("a_command", { :option => "value" })
end
it "delegates instance execpipe to Puppet::Util::Execution" do
allow(Puppet::Util::Execution).to receive(:execpipe).with("a_command", true).and_yield('some output')
expect { |b| provider.new.execpipe("a_command", true, &b) }.to yield_with_args('some output')
end
it "delegates class execpipe to Puppet::Util::Execution" do
allow(Puppet::Util::Execution).to receive(:execpipe).with("a_command", true).and_yield('some output')
expect { |b| provider.execpipe("a_command", true, &b) }.to yield_with_args('some output')
end
end
context "mk_resource_methods" do
before :each do
type.newproperty(:prop)
type.newparam(:param)
provider.mk_resource_methods
end
let(:instance) { provider.new(nil) }
it "defaults to :absent" do
expect(instance.prop).to eq(:absent)
expect(instance.param).to eq(:absent)
end
it "should update when set" do
instance.prop = 'hello'
instance.param = 'goodbye'
expect(instance.prop).to eq('hello')
expect(instance.param).to eq('goodbye')
end
it "treats nil the same as absent" do
instance.prop = "value"
instance.param = "value"
instance.prop = nil
instance.param = nil
expect(instance.prop).to eq(:absent)
expect(instance.param).to eq(:absent)
end
it "preserves false as false" do
instance.prop = false
instance.param = false
expect(instance.prop).to eq(false)
expect(instance.param).to eq(false)
end
end
context "source" do
it "should default to the provider name" do
expect(subject.source).to eq(:default)
end
it "should default to the provider name for a child provider" do
expect(type.provide(:sub, :parent => subject.name).source).to eq(:sub)
end
it "should override if requested" do
provider = type.provide(:sub, :parent => subject.name, :source => subject.source)
expect(provider.source).to eq(subject.source)
end
it "should override to anything you want" do
expect { subject.source = :banana }.to change { subject.source }.
from(:default).to(:banana)
end
end
context "features" do
before :each do
type.feature :numeric, '', :methods => [:one, :two]
type.feature :alpha, '', :methods => [:a, :b]
type.feature :nomethods, ''
end
{ :no => { :alpha => false, :numeric => false, :methods => [] },
:numeric => { :alpha => false, :numeric => true, :methods => [:one, :two] },
:alpha => { :alpha => true, :numeric => false, :methods => [:a, :b] },
:all => {
:alpha => true, :numeric => true,
:methods => [:a, :b, :one, :two]
},
:alpha_and_partial => {
:alpha => true, :numeric => false,
:methods => [:a, :b, :one]
},
:numeric_and_partial => {
:alpha => false, :numeric => true,
:methods => [:a, :one, :two]
},
:all_partial => { :alpha => false, :numeric => false, :methods => [:a, :one] },
:other_and_none => { :alpha => false, :numeric => false, :methods => [:foo, :bar] },
:other_and_alpha => {
:alpha => true, :numeric => false,
:methods => [:foo, :bar, :a, :b]
},
}.each do |name, setup|
context "with #{name.to_s.gsub('_', ' ')} features" do
let :provider do
provider = type.provide(name)
setup[:methods].map do |method|
provider.send(:define_method, method) do true end
end
type.provider(name)
end
context "provider class" do
subject { provider }
it { is_expected.to respond_to(:has_features) }
it { is_expected.to respond_to(:has_feature) }
it { is_expected.to respond_to(:nomethods?) }
it { is_expected.not_to be_nomethods }
it { is_expected.to respond_to(:numeric?) }
if setup[:numeric]
it { is_expected.to be_numeric }
it { is_expected.to be_satisfies(:numeric) }
else
it { is_expected.not_to be_numeric }
it { is_expected.not_to be_satisfies(:numeric) }
end
it { is_expected.to respond_to(:alpha?) }
if setup[:alpha]
it { is_expected.to be_alpha }
it { is_expected.to be_satisfies(:alpha) }
else
it { is_expected.not_to be_alpha }
it { is_expected.not_to be_satisfies(:alpha) }
end
end
context "provider instance" do
subject { provider.new }
it { is_expected.to respond_to(:numeric?) }
if setup[:numeric]
it { is_expected.to be_numeric }
it { is_expected.to be_satisfies(:numeric) }
else
it { is_expected.not_to be_numeric }
it { is_expected.not_to be_satisfies(:numeric) }
end
it { is_expected.to respond_to(:alpha?) }
if setup[:alpha]
it { is_expected.to be_alpha }
it { is_expected.to be_satisfies(:alpha) }
else
it { is_expected.not_to be_alpha }
it { is_expected.not_to be_satisfies(:alpha) }
end
end
end
end
context "feature with no methods" do
before :each do
type.feature :undemanding, ''
end
it { is_expected.to respond_to(:undemanding?) }
context "when the feature is not declared" do
it { is_expected.not_to be_undemanding }
it { is_expected.not_to be_satisfies(:undemanding) }
end
context "when the feature is declared" do
before :each do
subject.has_feature :undemanding
end
it { is_expected.to be_undemanding }
it { is_expected.to be_satisfies(:undemanding) }
end
end
context "supports_parameter?" do
before :each do
type.newparam(:no_feature)
type.newparam(:one_feature, :required_features => :alpha)
type.newparam(:two_features, :required_features => [:alpha, :numeric])
end
let :providers do
{
:zero => type.provide(:zero),
:one => type.provide(:one) do has_features :alpha end,
:two => type.provide(:two) do has_features :alpha, :numeric end
}
end
{ :zero => { :yes => [:no_feature], :no => [:one_feature, :two_features] },
:one => { :yes => [:no_feature, :one_feature], :no => [:two_features] },
:two => { :yes => [:no_feature, :one_feature, :two_features], :no => [] }
}.each do |name, data|
data[:yes].each do |param|
it "should support #{param} with provider #{name}" do
expect(providers[name]).to be_supports_parameter(param)
end
end
data[:no].each do |param|
it "should not support #{param} with provider #{name}" do
expect(providers[name]).not_to be_supports_parameter(param)
end
end
end
end
end
def provider_of(options = {}, &block)
type = Puppet::Type.newtype(:dummy) do
provide(:dummy, options, &block)
end
type.provider(:dummy)
end
def expect_command_executed(name, path, *args)
command = Puppet::Provider::Command.new(name, path, Puppet::Util, Puppet::Util::Execution)
args = [no_args] if args.empty?
expect(command).to receive(:execute).with(*args)
command
end
def allow_creation_of(command, environment = {})
allow(Puppet::Provider::Command).to receive(:new).with(command.name, command.executable, Puppet::Util, Puppet::Util::Execution, { :failonfail => true, :combine => true, :custom_environment => environment }).and_return(command)
end
def file_exists_and_is_executable(path)
expect(FileTest).to receive(:file?).with(path).and_return(true)
expect(FileTest).to receive(:executable?).with(path).and_return(true)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/face_spec.rb | spec/unit/face_spec.rb | # You should look at interface_spec.rb
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/confine_spec.rb | spec/unit/confine_spec.rb | require 'spec_helper'
require 'puppet/confine'
class Puppet::TestConfine < Puppet::Confine
def pass?(value)
false
end
end
describe Puppet::Confine do
it "should require a value" do
expect { Puppet::Confine.new }.to raise_error(ArgumentError)
end
it "should always convert values to an array" do
expect(Puppet::Confine.new("/some/file").values).to be_instance_of(Array)
end
it "should have a 'true' test" do
expect(Puppet::Confine.test(:true)).to be_instance_of(Class)
end
it "should have a 'false' test" do
expect(Puppet::Confine.test(:false)).to be_instance_of(Class)
end
it "should have a 'feature' test" do
expect(Puppet::Confine.test(:feature)).to be_instance_of(Class)
end
it "should have an 'exists' test" do
expect(Puppet::Confine.test(:exists)).to be_instance_of(Class)
end
it "should have a 'variable' test" do
expect(Puppet::Confine.test(:variable)).to be_instance_of(Class)
end
describe "when testing all values" do
before do
@confine = Puppet::TestConfine.new(%w{a b c})
@confine.label = "foo"
end
it "should be invalid if any values fail" do
allow(@confine).to receive(:pass?).and_return(true)
expect(@confine).to receive(:pass?).with("b").and_return(false)
expect(@confine).not_to be_valid
end
it "should be valid if all values pass" do
allow(@confine).to receive(:pass?).and_return(true)
expect(@confine).to be_valid
end
it "should short-cut at the first failing value" do
expect(@confine).to receive(:pass?).once.and_return(false)
@confine.valid?
end
it "should log failing confines with the label and message" do
Puppet[:log_level] = 'debug'
allow(@confine).to receive(:pass?).and_return(false)
expect(@confine).to receive(:message).and_return("My message")
expect(@confine).to receive(:label).and_return("Mylabel")
expect(Puppet).to receive(:debug) { |&b| expect(b.call).to eq("Mylabel: My message") }
@confine.valid?
end
end
describe "when testing the result of the values" do
before { @confine = Puppet::TestConfine.new(%w{a b c d}) }
it "should return an array with the result of the test for each value" do
allow(@confine).to receive(:pass?).and_return(true)
expect(@confine).to receive(:pass?).with("b").and_return(false)
expect(@confine).to receive(:pass?).with("d").and_return(false)
expect(@confine.result).to eq([true, false, true, false])
end
end
describe "when requiring" do
it "does not cache failed requires when always_retry_plugins is true" do
Puppet[:always_retry_plugins] = true
expect(Puppet::Confine).to receive(:require).with('puppet/confine/os.family').twice.and_raise(LoadError)
Puppet::Confine.test('os.family')
Puppet::Confine.test('os.family')
end
it "caches failed requires when always_retry_plugins is false" do
Puppet[:always_retry_plugins] = false
expect(Puppet::Confine).to receive(:require).with('puppet/confine/os.family').once.and_raise(LoadError)
Puppet::Confine.test('os.family')
Puppet::Confine.test('os.family')
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/context_spec.rb | spec/unit/context_spec.rb | require 'spec_helper'
describe Puppet::Context do
let(:context) { Puppet::Context.new({ :testing => "value" }) }
describe "with additional context" do
before :each do
context.push("a" => 1)
end
it "allows rebinding values in a nested context" do
inner = nil
context.override("a" => 2) do
inner = context.lookup("a")
end
expect(inner).to eq(2)
end
it "outer bindings are available in an overridden context" do
inner_a = nil
inner_b = nil
context.override("b" => 2) do
inner_a = context.lookup("a")
inner_b = context.lookup("b")
end
expect(inner_a).to eq(1)
expect(inner_b).to eq(2)
end
it "overridden bindings do not exist outside of the override" do
context.override("a" => 2) do
end
expect(context.lookup("a")).to eq(1)
end
it "overridden bindings do not exist outside of the override even when leaving via an error" do
begin
context.override("a" => 2) do
raise "this should still cause the bindings to leave"
end
rescue
end
expect(context.lookup("a")).to eq(1)
end
end
context "a rollback" do
it "returns to the mark" do
context.push("a" => 1)
context.mark("start")
context.push("a" => 2)
context.push("a" => 3)
context.pop
context.rollback("start")
expect(context.lookup("a")).to eq(1)
end
it "rolls back to the mark across a scoped override" do
context.push("a" => 1)
context.mark("start")
context.override("a" => 3) do
context.rollback("start")
expect(context.lookup("a")).to eq(1)
end
expect(context.lookup("a")).to eq(1)
end
it "fails to rollback to an unknown mark" do
expect do
context.rollback("unknown")
end.to raise_error(Puppet::Context::UnknownRollbackMarkError)
end
it "does not allow the same mark to be set twice" do
context.mark("duplicate")
expect do
context.mark("duplicate")
end.to raise_error(Puppet::Context::DuplicateRollbackMarkError)
end
end
context "with multiple threads" do
it "a value pushed in another thread is not seen in the original thread" do
context.push(a: 1)
t = Thread.new do
context.push(a: 2, b: 5)
end
t.join
expect(context.lookup(:a)).to eq(1)
expect{ context.lookup(:b) }.to raise_error(Puppet::Context::UndefinedBindingError)
end
it "pops on a different thread do not interfere" do
context.push(a: 1)
t = Thread.new do
context.pop
end
t.join
# Raises exception if the binding we pushed has already been popped
context.pop
end
it "a mark in one thread is not seen in another thread" do
t = Thread.new do
context.push(b: 2)
context.mark('point b')
end
t.join
expect { context.rollback('point b') }.to raise_error(Puppet::Context::UnknownRollbackMarkError)
end
end
end
describe Puppet::Context::EmptyStack do
let(:empty_stack) { Puppet::Context::EmptyStack.new }
it "raises undefined binding on lookup" do
expect { empty_stack.lookup("a") }.to raise_error(Puppet::Context::UndefinedBindingError)
end
it "calls a provided block for a default value when none is found" do
expect(empty_stack.lookup("a") { "default" }).to eq("default")
end
it "raises an error when trying to pop" do
expect { empty_stack.pop }.to raise_error(Puppet::Context::StackUnderflow)
end
it "returns a stack when something is pushed" do
stack = empty_stack.push(a: 1)
expect(stack).to be_a(Puppet::Context::Stack)
end
it "returns a new stack with no bindings when pushed nil" do
stack = empty_stack.push(nil)
expect(stack).not_to be(empty_stack)
expect(stack.pop).to be(empty_stack)
end
end
describe Puppet::Context::Stack do
let(:empty_stack) { Puppet::Context::EmptyStack.new }
context "a stack with depth of 1" do
let(:stack) { empty_stack.push(a: 1) }
it "returns the empty stack when popped" do
expect(stack.pop).to be(empty_stack)
end
it "calls a provided block for a default value when none is found" do
expect(stack.lookup("a") { "default" }).to eq("default")
end
it "returns a new but equivalent stack when pushed nil" do
stackier = stack.push(nil)
expect(stackier).not_to be(stack)
expect(stackier.pop).to be(stack)
expect(stackier.bindings).to eq(stack.bindings)
end
end
context "a stack with more than 1 element" do
let(:level_one) { empty_stack.push(a: 1, c: 4) }
let(:level_two) { level_one.push(b: 2, c: 3) }
it "falls back to lower levels on lookup" do
expect(level_two.lookup(:c)).to eq(3)
expect(level_two.lookup(:a)).to eq(1)
expect{ level_two.lookup(:d) }.to raise_error(Puppet::Context::UndefinedBindingError)
end
it "the parent is immutable" do
expect(level_one.lookup(:c)).to eq(4)
expect{ level_one.lookup(:b) }.to raise_error(Puppet::Context::UndefinedBindingError)
end
end
context 'supports lazy entries' do
it 'by evaluating a bound proc' do
stack = empty_stack.push(a: lambda { || 'yay' })
expect(stack.lookup(:a)).to eq('yay')
end
it 'by memoizing the bound value' do
original = 'yay'
stack = empty_stack.push(:a => lambda {|| tmp = original; original = 'no'; tmp})
expect(stack.lookup(:a)).to eq('yay')
expect(original).to eq('no')
expect(stack.lookup(:a)).to eq('yay')
end
it 'the bound value is memoized only at the top level of the stack' do
# I'm just characterizing the current behavior here
original = 'yay'
stack = empty_stack.push(:a => lambda {|| tmp = original; original = 'no'; tmp})
stack_two = stack.push({})
expect(stack.lookup(:a)).to eq('yay')
expect(original).to eq('no')
expect(stack.lookup(:a)).to eq('yay')
expect(stack_two.lookup(:a)).to eq('no')
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/plan_spec.rb | spec/unit/plan_spec.rb | require 'spec_helper'
require 'puppet_spec/files'
require 'puppet_spec/modules'
require 'puppet/module/plan'
describe Puppet::Module::Plan do
include PuppetSpec::Files
let(:modpath) { tmpdir('plan_modpath') }
let(:mymodpath) { File.join(modpath, 'mymod') }
let(:othermodpath) { File.join(modpath, 'othermod') }
let(:mymod) { Puppet::Module.new('mymod', mymodpath, nil) }
let(:othermod) { Puppet::Module.new('othermod', othermodpath, nil) }
let(:plans_path) { File.join(mymodpath, 'plans') }
let(:other_plans_path) { File.join(othermodpath, 'plans') }
let(:plans_glob) { File.join(mymodpath, 'plans', '*') }
describe :naming do
word = (Puppet::Module::Plan::RESERVED_WORDS - Puppet::Module::Plan::RESERVED_DATA_TYPES).sample
datatype = (Puppet::Module::Plan::RESERVED_DATA_TYPES - Puppet::Module::Plan::RESERVED_WORDS).sample
test_cases = { 'iLegal.pp' => 'Plan names must start with a lowercase letter and be composed of only lowercase letters, numbers, and underscores',
'name.md' => 'Plan name cannot have extension .md, must be .pp or .yaml',
"#{word}.pp" => "Plan name cannot be a reserved word, but was '#{word}'",
"#{datatype}.pp" => "Plan name cannot be a Puppet data type, but was '#{datatype}'",
'test_1.pp' => nil,
'test_2.yaml' => nil }
test_cases.each do |filename, error|
it "constructs plans when needed with #{filename}" do
name = File.basename(filename, '.*')
if error
expect { Puppet::Module::Plan.new(mymod, name, [File.join(plans_path, filename)]) }
.to raise_error(Puppet::Module::Plan::InvalidName,
error)
else
expect { Puppet::Module::Plan.new(mymod, name, [filename]) }
.not_to raise_error
end
end
end
end
it "finds all plans in module" do
og_files = %w{plan1.pp plan2.yaml not-a-plan.ok}.map { |bn| "#{plans_path}/#{bn}" }
expect(Dir).to receive(:glob).with(plans_glob).and_return(og_files)
plans = Puppet::Module::Plan.plans_in_module(mymod)
expect(plans.count).to eq(2)
end
it "selects .pp file before .yaml" do
og_files = %w{plan1.pp plan1.yaml}.map { |bn| "#{plans_path}/#{bn}" }
expect(Dir).to receive(:glob).with(plans_glob).and_return(og_files)
plans = Puppet::Module::Plan.plans_in_module(mymod)
expect(plans.count).to eq(1)
expect(plans.first.files.count).to eq(1)
expect(plans.first.files.first['name']).to eq('plan1.pp')
end
it "gives the 'init' plan a name that is just the module's name" do
expect(Puppet::Module::Plan.new(mymod, 'init', ["#{plans_path}/init.pp"]).name).to eq('mymod')
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/type_spec.rb | spec/unit/type_spec.rb | require 'spec_helper'
require 'puppet_spec/compiler'
require 'puppet/property/boolean'
Puppet::Type.newtype(:type_test) do
ensurable
newparam(:name, isnamevar: true)
newproperty(:device)
newproperty(:blockdevice)
newproperty(:fstype)
newproperty(:options)
newproperty(:pass)
newproperty(:atboot, parent: Puppet::Property::Boolean) do
def munge(value)
munged = super
if munged
:yes
else
:no
end
end
end
newparam(:remounts) do
newvalues(:true, :false)
defaultto do
true
end
end
end
Puppet::Type.type(:type_test).provide(:type_test) do
mk_resource_methods
end
describe Puppet::Type, :unless => Puppet::Util::Platform.windows? do
include PuppetSpec::Files
include PuppetSpec::Compiler
let(:resource_type) { :type_test }
let(:klass) { Puppet::Type.type(resource_type) }
let(:ref_type) { klass.name.to_s.capitalize }
it "should be Comparable" do
a = Puppet::Type.type(:notify).new(:name => "a")
b = Puppet::Type.type(:notify).new(:name => "b")
c = Puppet::Type.type(:notify).new(:name => "c")
[[a, b, c], [a, c, b], [b, a, c], [b, c, a], [c, a, b], [c, b, a]].each do |this|
expect(this.sort).to eq([a, b, c])
end
expect(a).to be < b
expect(a).to be < c
expect(b).to be > a
expect(b).to be < c
expect(c).to be > a
expect(c).to be > b
[a, b, c].each {|x| expect(a).to be <= x }
[a, b, c].each {|x| expect(c).to be >= x }
expect(b).to be_between(a, c)
end
it "should consider a parameter to be valid if it is a valid parameter" do
expect(klass).to be_valid_parameter(:name)
end
it "should consider a parameter to be valid if it is a valid property" do
expect(klass).to be_valid_parameter(:fstype)
end
it "should consider a parameter to be valid if it is a valid metaparam" do
expect(klass).to be_valid_parameter(:noop)
end
it "should be able to retrieve a property by name" do
resource = klass.new(:name => "foo", :fstype => "bar", :pass => 1, :ensure => :present)
expect(resource.property(:fstype)).to be_instance_of(klass.attrclass(:fstype))
end
it "should be able to retrieve a parameter by name" do
resource = klass.new(:name => "foo", :fstype => "bar", :pass => 1, :ensure => :present)
expect(resource.parameter(:name)).to be_instance_of(klass.attrclass(:name))
end
it "should be able to retrieve a property by name using the :parameter method" do
resource = klass.new(:name => "foo", :fstype => "bar", :pass => 1, :ensure => :present)
expect(resource.parameter(:fstype)).to be_instance_of(klass.attrclass(:fstype))
end
it "should be able to retrieve all set properties" do
resource = klass.new(:name => "foo", :fstype => "bar", :pass => 1, :ensure => :present)
props = resource.properties
expect(props).not_to be_include(nil)
[:fstype, :ensure, :pass].each do |name|
expect(props).to be_include(resource.parameter(name))
end
end
it "can retrieve all set parameters" do
resource = klass.new(:name => "foo", :fstype => "bar", :pass => 1, :ensure => :present, :tag => 'foo')
params = resource.parameters_with_value
[:name, :provider, :ensure, :fstype, :pass, :loglevel, :tag].each do |name|
expect(params).to be_include(resource.parameter(name))
end
end
it "can not return any `nil` values when retrieving all set parameters" do
resource = klass.new(:name => "foo", :fstype => "bar", :pass => 1, :ensure => :present, :tag => 'foo')
params = resource.parameters_with_value
expect(params).not_to be_include(nil)
end
it "can return an iterator for all set parameters" do
resource = Puppet::Type.type(:notify).new(:name=>'foo',:message=>'bar',:tag=>'baz',:require=> "File['foo']")
params = [:name, :message, :withpath, :loglevel, :tag, :require]
resource.eachparameter { |param|
expect(params).to be_include(param.to_s.to_sym)
}
end
it "should have a method for setting default values for resources" do
expect(klass.new(:name => "foo")).to respond_to(:set_default)
end
it "should do nothing for attributes that have no defaults and no specified value" do
expect(klass.new(:name => "foo").parameter(:noop)).to be_nil
end
it "should have a method for adding tags" do
expect(klass.new(:name => "foo")).to respond_to(:tags)
end
it "should use the tagging module" do
expect(klass.ancestors).to be_include(Puppet::Util::Tagging)
end
it "should delegate to the tagging module when tags are added" do
resource = klass.new(:name => "foo")
allow(resource).to receive(:tag).with(resource_type)
expect(resource).to receive(:tag).with(:tag1, :tag2)
resource.tags = [:tag1,:tag2]
end
it "should add the current type as tag" do
resource = klass.new(:name => "foo")
allow(resource).to receive(:tag)
expect(resource).to receive(:tag).with(resource_type)
resource.tags = [:tag1,:tag2]
end
it "should have a method to know if the resource is exported" do
expect(klass.new(:name => "foo")).to respond_to(:exported?)
end
it "should have a method to know if the resource is virtual" do
expect(klass.new(:name => "foo")).to respond_to(:virtual?)
end
it "should consider its version to be zero if it has no catalog" do
expect(klass.new(:name => "foo").version).to eq(0)
end
it "reports the correct path even after path is used during setup of the type" do
Puppet::Type.newtype(:testing) do
newparam(:name) do
isnamevar
validate do |value|
path # forces the computation of the path
end
end
end
ral = compile_to_ral(<<-MANIFEST)
class something {
testing { something: }
}
include something
MANIFEST
expect(ral.resource("Testing[something]").path).to eq("/Stage[main]/Something/Testing[something]")
end
context "alias metaparam" do
it "creates a new name that can be used for resource references" do
ral = compile_to_ral(<<-MANIFEST)
notify { a: alias => c }
MANIFEST
expect(ral.resource("Notify[a]")).to eq(ral.resource("Notify[c]"))
end
end
context 'aliased resource' do
it 'fails if a resource is defined and then redefined using name that results in the same alias' do
drive = Puppet::Util::Platform.windows? ? 'C:' : ''
code = <<~PUPPET
$dir='#{drive}/tmp/test'
$same_dir='#{drive}/tmp/test/'
file {$dir:
ensure => directory
}
file { $same_dir:
ensure => directory
}
PUPPET
expect { compile_to_ral(code) }.to raise_error(/resource \["File", "#{drive}\/tmp\/test"\] already declared/)
end
end
context "resource attributes" do
let(:resource) {
resource = klass.new(:name => "foo")
catalog = Puppet::Resource::Catalog.new
catalog.version = 50
catalog.add_resource resource
resource
}
it "should consider its version to be its catalog version" do
expect(resource.version).to eq(50)
end
it "should have tags" do
expect(resource).to be_tagged(resource_type.to_s)
expect(resource).to be_tagged("foo")
end
it "should have a path" do
expect(resource.path).to eq("/#{ref_type}[foo]")
end
end
it "should consider its type to be the name of its class" do
expect(klass.new(:name => "foo").type).to eq(resource_type)
end
it "should use any provided noop value" do
expect(klass.new(:name => "foo", :noop => true)).to be_noop
end
it "should use the global noop value if none is provided" do
Puppet[:noop] = true
expect(klass.new(:name => "foo")).to be_noop
end
it "should not be noop if in a non-host_config catalog" do
resource = klass.new(:name => "foo")
catalog = Puppet::Resource::Catalog.new
catalog.add_resource resource
expect(resource).not_to be_noop
end
describe "when creating an event" do
before do
@resource = klass.new :name => "foo"
end
it "should have the resource's reference as the resource" do
expect(@resource.event.resource).to eq("#{ref_type}[foo]")
end
it "should have the resource's log level as the default log level" do
@resource[:loglevel] = :warning
expect(@resource.event.default_log_level).to eq(:warning)
end
{:file => "/my/file", :line => 50}.each do |attr, value|
it "should set the #{attr}" do
allow(@resource).to receive(attr).and_return(value)
expect(@resource.event.send(attr)).to eq(value)
end
end
it "should set the tags" do
@resource.tag("abc", "def")
expect(@resource.event).to be_tagged("abc")
expect(@resource.event).to be_tagged("def")
end
it "should allow specification of event attributes" do
expect(@resource.event(:status => "noop").status).to eq("noop")
end
end
describe "when creating a provider" do
before :each do
@type = Puppet::Type.newtype(:provider_test_type) do
newparam(:name) { isnamevar }
newparam(:foo)
newproperty(:bar)
end
end
after :each do
@type.provider_hash.clear
end
describe "when determining if instances of the type are managed" do
it "should not consider audit only resources to be managed" do
expect(@type.new(:name => "foo", :audit => 'all').managed?).to be_falsey
end
it "should not consider resources with only parameters to be managed" do
expect(@type.new(:name => "foo", :foo => 'did someone say food?').managed?).to be_falsey
end
it "should consider resources with any properties set to be managed" do
expect(@type.new(:name => "foo", :bar => 'Let us all go there').managed?).to be_truthy
end
end
it "should have documentation for the 'provider' parameter if there are providers" do
@type.provide(:test_provider)
expect(@type.paramdoc(:provider)).to match(/`provider_test_type`[\s]+resource/)
end
it "should not have documentation for the 'provider' parameter if there are no providers" do
expect { @type.paramdoc(:provider) }.to raise_error(NoMethodError)
end
it "should create a subclass of Puppet::Provider for the provider" do
provider = @type.provide(:test_provider)
expect(provider.ancestors).to include(Puppet::Provider)
end
it "should use a parent class if specified" do
parent_provider = @type.provide(:parent_provider)
child_provider = @type.provide(:child_provider, :parent => parent_provider)
expect(child_provider.ancestors).to include(parent_provider)
end
it "should use a parent class if specified by name" do
parent_provider = @type.provide(:parent_provider)
child_provider = @type.provide(:child_provider, :parent => :parent_provider)
expect(child_provider.ancestors).to include(parent_provider)
end
it "should raise an error when the parent class can't be found" do
expect {
@type.provide(:child_provider, :parent => :parent_provider)
}.to raise_error(Puppet::DevError, /Could not find parent provider.+parent_provider/)
end
it "should ensure its type has a 'provider' parameter" do
@type.provide(:test_provider)
expect(@type.parameters).to include(:provider)
end
it "should remove a previously registered provider with the same name" do
old_provider = @type.provide(:test_provider)
new_provider = @type.provide(:test_provider)
expect(old_provider).not_to equal(new_provider)
end
it "should register itself as a provider for the type" do
provider = @type.provide(:test_provider)
expect(provider).to eq(@type.provider(:test_provider))
end
it "should create a provider when a provider with the same name previously failed" do
@type.provide(:test_provider) do
raise "failed to create this provider"
end rescue nil
provider = @type.provide(:test_provider)
expect(provider.ancestors).to include(Puppet::Provider)
expect(provider).to eq(@type.provider(:test_provider))
end
describe "with a parent class from another type" do
before :each do
@parent_type = Puppet::Type.newtype(:provider_parent_type) do
newparam(:name) { isnamevar }
end
@parent_provider = @parent_type.provide(:parent_provider)
end
it "should be created successfully" do
child_provider = @type.provide(:child_provider, :parent => @parent_provider)
expect(child_provider.ancestors).to include(@parent_provider)
end
it "should be registered as a provider of the child type" do
@type.provide(:child_provider, :parent => @parent_provider)
expect(@type.providers).to include(:child_provider)
expect(@parent_type.providers).not_to include(:child_provider)
end
end
end
describe "when choosing a default provider" do
it "should choose the provider with the highest specificity" do
# Make a fake type
type = Puppet::Type.newtype(:defaultprovidertest) do
newparam(:name) do end
end
basic = type.provide(:basic) {}
greater = type.provide(:greater) {}
allow(basic).to receive(:specificity).and_return(1)
allow(greater).to receive(:specificity).and_return(2)
expect(type.defaultprovider).to equal(greater)
end
end
context "autorelations" do
before :each do
Puppet::Type.newtype(:autorelation_one) do
newparam(:name) { isnamevar }
end
end
describe "when building autorelations" do
it "should be able to autorequire puppet resources" do
Puppet::Type.newtype(:autorelation_two) do
newparam(:name) { isnamevar }
autorequire(:autorelation_one) { Puppet::Type.type(:notify).new(name: 'test') }
end
relationship_graph = compile_to_relationship_graph(<<-MANIFEST)
autorelation_one { 'Notify[test]': }
autorelation_two { 'bar': }
MANIFEST
src = relationship_graph.vertices.select{ |x| x.ref.to_s == 'Notify[test]' }.first
dst = relationship_graph.vertices.select{ |x| x.ref.to_s == 'Autorelation_two[bar]' }.first
expect(relationship_graph.edge?(src,dst)).to be_truthy
expect(relationship_graph.edges_between(src,dst).first.event).to eq(:NONE)
end
it "should be able to autorequire resources" do
Puppet::Type.newtype(:autorelation_two) do
newparam(:name) { isnamevar }
autorequire(:autorelation_one) { ['foo'] }
end
relationship_graph = compile_to_relationship_graph(<<-MANIFEST)
autorelation_one { 'foo': }
autorelation_two { 'bar': }
MANIFEST
src = relationship_graph.vertices.select{ |x| x.ref.to_s == 'Autorelation_one[foo]' }.first
dst = relationship_graph.vertices.select{ |x| x.ref.to_s == 'Autorelation_two[bar]' }.first
expect(relationship_graph.edge?(src,dst)).to be_truthy
expect(relationship_graph.edges_between(src,dst).first.event).to eq(:NONE)
end
it 'should not fail autorequire contains undef entries' do
Puppet::Type.newtype(:autorelation_two) do
newparam(:name) { isnamevar }
autorequire(:autorelation_one) { [nil, 'foo'] }
end
relationship_graph = compile_to_relationship_graph(<<-MANIFEST)
autorelation_one { 'foo': }
autorelation_two { 'bar': }
MANIFEST
src = relationship_graph.vertices.select{ |x| x.ref.to_s == 'Autorelation_one[foo]' }.first
dst = relationship_graph.vertices.select{ |x| x.ref.to_s == 'Autorelation_two[bar]' }.first
expect(relationship_graph.edge?(src,dst)).to be_truthy
expect(relationship_graph.edges_between(src,dst).first.event).to eq(:NONE)
end
it "should be able to autosubscribe resources" do
Puppet::Type.newtype(:autorelation_two) do
newparam(:name) { isnamevar }
autosubscribe(:autorelation_one) { ['foo'] }
end
relationship_graph = compile_to_relationship_graph(<<-MANIFEST)
autorelation_one { 'foo': }
autorelation_two { 'bar': }
MANIFEST
src = relationship_graph.vertices.select{ |x| x.ref.to_s == 'Autorelation_one[foo]' }.first
dst = relationship_graph.vertices.select{ |x| x.ref.to_s == 'Autorelation_two[bar]' }.first
expect(relationship_graph.edge?(src,dst)).to be_truthy
expect(relationship_graph.edges_between(src,dst).first.event).to eq(:ALL_EVENTS)
end
it 'should not fail if autosubscribe contains undef entries' do
Puppet::Type.newtype(:autorelation_two) do
newparam(:name) { isnamevar }
autosubscribe(:autorelation_one) { [nil, 'foo'] }
end
relationship_graph = compile_to_relationship_graph(<<-MANIFEST)
autorelation_one { 'foo': }
autorelation_two { 'bar': }
MANIFEST
src = relationship_graph.vertices.select{ |x| x.ref.to_s == 'Autorelation_one[foo]' }.first
dst = relationship_graph.vertices.select{ |x| x.ref.to_s == 'Autorelation_two[bar]' }.first
expect(relationship_graph.edge?(src,dst)).to be_truthy
expect(relationship_graph.edges_between(src,dst).first.event).to eq(:ALL_EVENTS)
end
it "should be able to autobefore resources" do
Puppet::Type.newtype(:autorelation_two) do
newparam(:name) { isnamevar }
autobefore(:autorelation_one) { ['foo'] }
end
relationship_graph = compile_to_relationship_graph(<<-MANIFEST)
autorelation_one { 'foo': }
autorelation_two { 'bar': }
MANIFEST
src = relationship_graph.vertices.select{ |x| x.ref.to_s == 'Autorelation_two[bar]' }.first
dst = relationship_graph.vertices.select{ |x| x.ref.to_s == 'Autorelation_one[foo]' }.first
expect(relationship_graph.edge?(src,dst)).to be_truthy
expect(relationship_graph.edges_between(src,dst).first.event).to eq(:NONE)
end
it "should not fail when autobefore contains undef entries" do
Puppet::Type.newtype(:autorelation_two) do
newparam(:name) { isnamevar }
autobefore(:autorelation_one) { [nil, 'foo'] }
end
relationship_graph = compile_to_relationship_graph(<<-MANIFEST)
autorelation_one { 'foo': }
autorelation_two { 'bar': }
MANIFEST
src = relationship_graph.vertices.select{ |x| x.ref.to_s == 'Autorelation_two[bar]' }.first
dst = relationship_graph.vertices.select{ |x| x.ref.to_s == 'Autorelation_one[foo]' }.first
expect(relationship_graph.edge?(src,dst)).to be_truthy
expect(relationship_graph.edges_between(src,dst).first.event).to eq(:NONE)
end
it "should be able to autonotify resources" do
Puppet::Type.newtype(:autorelation_two) do
newparam(:name) { isnamevar }
autonotify(:autorelation_one) { ['foo'] }
end
relationship_graph = compile_to_relationship_graph(<<-MANIFEST)
autorelation_one { 'foo': }
autorelation_two { 'bar': }
MANIFEST
src = relationship_graph.vertices.select{ |x| x.ref.to_s == 'Autorelation_two[bar]' }.first
dst = relationship_graph.vertices.select{ |x| x.ref.to_s == 'Autorelation_one[foo]' }.first
expect(relationship_graph.edge?(src,dst)).to be_truthy
expect(relationship_graph.edges_between(src,dst).first.event).to eq(:ALL_EVENTS)
end
it 'should not fail if autonotify contains undef entries' do
Puppet::Type.newtype(:autorelation_two) do
newparam(:name) { isnamevar }
autonotify(:autorelation_one) { [nil, 'foo'] }
end
relationship_graph = compile_to_relationship_graph(<<-MANIFEST)
autorelation_one { 'foo': }
autorelation_two { 'bar': }
MANIFEST
src = relationship_graph.vertices.select{ |x| x.ref.to_s == 'Autorelation_two[bar]' }.first
dst = relationship_graph.vertices.select{ |x| x.ref.to_s == 'Autorelation_one[foo]' }.first
expect(relationship_graph.edge?(src,dst)).to be_truthy
expect(relationship_graph.edges_between(src,dst).first.event).to eq(:ALL_EVENTS)
end
end
end
describe "when initializing" do
describe "and passed a Puppet::Resource instance" do
it "should set its title to the title of the resource if the resource type is equal to the current type" do
resource = Puppet::Resource.new(resource_type, "/foo", :parameters => {:name => "/other"})
expect(klass.new(resource).title).to eq("/foo")
end
it "should set its title to the resource reference if the resource type is not equal to the current type" do
resource = Puppet::Resource.new(:user, "foo")
expect(klass.new(resource).title).to eq("User[foo]")
end
[:line, :file, :catalog, :exported, :virtual].each do |param|
it "should copy '#{param}' from the resource if present" do
resource = Puppet::Resource.new(resource_type, "/foo")
resource.send(param.to_s + "=", "foo")
resource.send(param.to_s + "=", "foo")
expect(klass.new(resource).send(param)).to eq("foo")
end
end
it "should copy any tags from the resource" do
resource = Puppet::Resource.new(resource_type, "/foo")
resource.tag "one", "two"
tags = klass.new(resource).tags
expect(tags).to be_include("one")
expect(tags).to be_include("two")
end
it "should copy the resource's parameters as its own" do
resource = Puppet::Resource.new(resource_type, "/foo", :parameters => {:atboot => :yes, :fstype => "boo"})
params = klass.new(resource).to_hash
expect(params[:fstype]).to eq("boo")
expect(params[:atboot]).to eq(:yes)
end
it "copies sensitive parameters to the appropriate properties" do
resource = Puppet::Resource.new(resource_type, "/foo",
:parameters => {:atboot => :yes, :fstype => "boo"},
:sensitive_parameters => [:fstype])
type = klass.new(resource)
expect(type.property(:fstype).sensitive).to eq true
end
it "logs a warning when a parameter is marked as sensitive" do
resource = Puppet::Resource.new(resource_type, "/foo",
:parameters => {:atboot => :yes, :fstype => "boo", :remounts => true},
:sensitive_parameters => [:remounts])
expect_any_instance_of(klass).to receive(:warning).with(/Unable to mark 'remounts' as sensitive: remounts is a parameter and not a property/)
klass.new(resource)
end
it "logs a warning when a property is not set but is marked as sensitive" do
resource = Puppet::Resource.new(resource_type, "/foo",
:parameters => {:atboot => :yes, :fstype => "boo"},
:sensitive_parameters => [:device])
expect_any_instance_of(klass).to receive(:warning).with("Unable to mark 'device' as sensitive: the property itself was not assigned a value.")
klass.new(resource)
end
it "logs an error when a property is not defined on the type but is marked as sensitive" do
resource = Puppet::Resource.new(resource_type, "/foo",
:parameters => {:atboot => :yes, :fstype => "boo"},
:sensitive_parameters => [:content])
expect_any_instance_of(klass).to receive(:err).with("Unable to mark 'content' as sensitive: the property itself is not defined on #{resource_type}.")
klass.new(resource)
end
end
describe "and passed a Hash" do
it "should extract the title from the hash" do
expect(klass.new(:title => "/yay").title).to eq("/yay")
end
it "should work when hash keys are provided as strings" do
expect(klass.new("title" => "/yay").title).to eq("/yay")
end
it "should work when hash keys are provided as symbols" do
expect(klass.new(:title => "/yay").title).to eq("/yay")
end
it "should use the name from the hash as the title if no explicit title is provided" do
expect(klass.new(:name => "/yay").title).to eq("/yay")
end
it "should use the Resource Type's namevar to determine how to find the name in the hash" do
yay = make_absolute('/yay')
expect(Puppet::Type.type(:file).new(:path => yay).title).to eq(yay)
end
[:catalog].each do |param|
it "should extract '#{param}' from the hash if present" do
expect(klass.new(:name => "/yay", param => "foo").send(param)).to eq("foo")
end
end
it "should use any remaining hash keys as its parameters" do
resource = klass.new(:title => "/foo", :catalog => "foo", :atboot => :yes, :fstype => "boo")
expect(resource[:fstype]).to eq("boo")
expect(resource[:atboot]).to eq(:yes)
end
end
it "should fail if any invalid attributes have been provided" do
expect { klass.new(:title => "/foo", :nosuchattr => "whatever") }.to raise_error(Puppet::Error, /no parameter named 'nosuchattr'/)
end
context "when an attribute fails validation" do
it "should fail with Puppet::ResourceError when PuppetError raised" do
expect { Puppet::Type.type(:file).new(:title => "/foo", :source => "unknown:///") }.to raise_error(Puppet::ResourceError, /Parameter source failed on File\[.*foo\]/)
end
it "should fail with Puppet::ResourceError when ArgumentError raised" do
expect { Puppet::Type.type(:file).new(:title => "/foo", :mode => "abcdef") }.to raise_error(Puppet::ResourceError, /Parameter mode failed on File\[.*foo\]/)
end
it "should include the file/line in the error" do
allow_any_instance_of(Puppet::Type.type(:file)).to receive(:file).and_return("example.pp")
allow_any_instance_of(Puppet::Type.type(:file)).to receive(:line).and_return(42)
expect { Puppet::Type.type(:file).new(:title => "/foo", :source => "unknown:///") }.to raise_error(Puppet::ResourceError, /\(file: example\.pp, line: 42\)/)
end
end
it "should set its name to the resource's title if the resource does not have a :name or namevar parameter set" do
resource = Puppet::Resource.new(resource_type, "/foo")
expect(klass.new(resource).name).to eq("/foo")
end
it "should fail if no title, name, or namevar are provided" do
expect { klass.new(:atboot => :yes) }.to raise_error(Puppet::Error)
end
it "should set the attributes in the order returned by the class's :allattrs method" do
allow(klass).to receive(:allattrs).and_return([:name, :atboot, :noop])
resource = Puppet::Resource.new(resource_type, "/foo", :parameters => {:name => "myname", :atboot => :yes, :noop => "whatever"})
set = []
allow_any_instance_of(klass).to receive(:newattr) do |_, param, hash|
set << param
double("a property", :value= => nil, :default => nil, :name => nil)
end
klass.new(resource)
expect(set[-1]).to eq(:noop)
expect(set[-2]).to eq(:atboot)
end
it "should always set the name and then default provider before anything else" do
allow(klass).to receive(:allattrs).and_return([:provider, :name, :atboot])
resource = Puppet::Resource.new(resource_type, "/foo", :parameters => {:name => "myname", :atboot => :yes})
set = []
allow_any_instance_of(klass).to receive(:newattr) do |_, param, hash|
set << param
double("a property", :value= => nil, :default => nil, :name => nil)
end
klass.new(resource)
expect(set[0]).to eq(:name)
expect(set[1]).to eq(:provider)
end
# This one is really hard to test :/
it "should set each default immediately if no value is provided" do
# We have a :confine block that calls execute in our upstart provider, which fails
# on jruby. Thus, we stub it out here since we don't care to do any assertions on it.
# This is only an issue if you're running these unit tests on a platform where upstart
# is a default provider, like Ubuntu trusty.
allow(Puppet::Util::Execution).to receive(:execute)
defaults = []
allow_any_instance_of(Puppet::Type.type(:service)).to receive(:set_default) { |_, value| defaults << value }
Puppet::Type.type(:service).new :name => "whatever"
expect(defaults[0]).to eq(:provider)
end
it "should retain a copy of the originally provided parameters" do
expect(klass.new(:name => "foo", :atboot => :yes, :noop => false).original_parameters).to eq({:atboot => :yes, :noop => false})
end
it "should delete the name via the namevar from the originally provided parameters" do
expect(Puppet::Type.type(:file).new(:name => make_absolute('/foo')).original_parameters[:path]).to be_nil
end
context "when validating the resource" do
it "should call the type's validate method if present" do
expect_any_instance_of(Puppet::Type.type(:file)).to receive(:validate)
Puppet::Type.type(:file).new(:name => make_absolute('/foo'))
end
it "should raise Puppet::ResourceError with resource name when Puppet::Error raised" do
expect do
Puppet::Type.type(:file).new(
:name => make_absolute('/foo'),
:source => "puppet:///",
:content => "foo"
)
end.to raise_error(Puppet::ResourceError, /Validation of File\[.*foo.*\]/)
end
it "should raise Puppet::ResourceError with manifest file and line on failure" do
allow_any_instance_of(Puppet::Type.type(:file)).to receive(:file).and_return("example.pp")
allow_any_instance_of(Puppet::Type.type(:file)).to receive(:line).and_return(42)
expect do
Puppet::Type.type(:file).new(
:name => make_absolute('/foo'),
:source => "puppet:///",
:content => "foo"
)
end.to raise_error(Puppet::ResourceError, /Validation.*\(file: example\.pp, line: 42\)/)
end
end
end
describe "#set_sensitive_parameters" do
let(:sensitive_type) do
Puppet::Type.newtype(:sensitive_test) do
newparam(:name) { isnamevar }
newproperty(:secret) do
newvalues(/.*/)
sensitive true
end
newproperty(:transparency) do
newvalues(/.*/)
sensitive false
end
newproperty(:things) { newvalues(/.*/) }
end
end
it "should mark properties as sensitive" do
resource = sensitive_type.new(:name => 'foo', :secret => 'uber classified')
expect(resource.parameters[:secret].sensitive).to be true
end
it "should not have a sensitive flag when not set" do
resource = sensitive_type.new(:name => 'foo', :things => '1337')
expect(resource.parameters[:things].sensitive).to be_nil
end
it "should define things as not sensitive" do
resource = sensitive_type.new(:name => 'foo', :transparency => 'public knowledge')
expect(resource.parameters[:transparency].sensitive).to be false
end
it "should honor when sensitivity is set in a manifest" do
resource = sensitive_type.new(:name => 'foo',
:transparency => Puppet::Pops::Types::PSensitiveType::Sensitive.new('top secret'),
:sensitive_parameters => [:transparency]
)
expect(resource.parameters[:transparency].sensitive).to be true
end
end
describe "when #finish is called on a type" do
let(:post_hook_type) do
Puppet::Type.newtype(:finish_test) do
newparam(:name) { isnamevar }
newparam(:post) do
def post_compile
raise "post_compile hook ran"
end
end
end
end
let(:post_hook_resource) do
post_hook_type.new(:name => 'foo',:post => 'fake_value')
end
it "should call #post_compile on parameters that implement it" do
expect { post_hook_resource.finish }.to raise_error(RuntimeError, "post_compile hook ran")
end
end
it "should have a class method for converting a hash into a Puppet::Resource instance" do
expect(klass).to respond_to(:hash2resource)
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | true |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/file_system_spec.rb | spec/unit/file_system_spec.rb | require 'spec_helper'
require 'puppet/file_system'
require 'puppet/util/platform'
describe "Puppet::FileSystem" do
include PuppetSpec::Files
# different UTF-8 widths
# 1-byte A
# 2-byte ۿ - http://www.fileformat.info/info/unicode/char/06ff/index.htm - 0xDB 0xBF / 219 191
# 3-byte ᚠ - http://www.fileformat.info/info/unicode/char/16A0/index.htm - 0xE1 0x9A 0xA0 / 225 154 160
# 4-byte 𠜎 - http://www.fileformat.info/info/unicode/char/2070E/index.htm - 0xF0 0xA0 0x9C 0x8E / 240 160 156 142
let (:mixed_utf8) { "A\u06FF\u16A0\u{2070E}" } # Aۿᚠ𠜎
def with_file_content(content)
path = tmpfile('file-system')
file = File.new(path, 'wb')
file.sync = true
file.print content
yield path
ensure
file.close
end
SYSTEM_SID_BYTES = [1, 1, 0, 0, 0, 0, 0, 5, 18, 0, 0, 0]
def is_current_user_system?
SYSTEM_SID_BYTES == Puppet::Util::Windows::ADSI::User.current_user_sid.sid_bytes
end
def expects_public_file(path)
if Puppet::Util::Platform.windows?
current_sid = Puppet::Util::Windows::SID.name_to_sid(Puppet::Util::Windows::ADSI::User.current_user_name)
sd = Puppet::Util::Windows::Security.get_security_descriptor(path)
expect(sd.dacl).to contain_exactly(
an_object_having_attributes(sid: Puppet::Util::Windows::SID::LocalSystem, mask: 0x1f01ff),
an_object_having_attributes(sid: Puppet::Util::Windows::SID::BuiltinAdministrators, mask: 0x1f01ff),
an_object_having_attributes(sid: current_sid, mask: 0x1f01ff),
an_object_having_attributes(sid: Puppet::Util::Windows::SID::BuiltinUsers, mask: 0x120089)
)
else
expect(File.stat(path).mode & 07777).to eq(0644)
end
end
def expects_private_file(path)
if Puppet::Util::Platform.windows?
current_sid = Puppet::Util::Windows::SID.name_to_sid(Puppet::Util::Windows::ADSI::User.current_user_name)
sd = Puppet::Util::Windows::Security.get_security_descriptor(path)
expect(sd.dacl).to contain_exactly(
an_object_having_attributes(sid: Puppet::Util::Windows::SID::LocalSystem, mask: 0x1f01ff),
an_object_having_attributes(sid: Puppet::Util::Windows::SID::BuiltinAdministrators, mask: 0x1f01ff),
an_object_having_attributes(sid: current_sid, mask: 0x1f01ff)
)
else
expect(File.stat(path).mode & 07777).to eq(0640)
end
end
context "#open" do
it "uses the same default mode as File.open, when specifying a nil mode (umask used on non-Windows)" do
file = tmpfile('file_to_update')
expect(Puppet::FileSystem.exist?(file)).to be_falsey
Puppet::FileSystem.open(file, nil, 'a') { |fh| fh.write('') }
expected_perms = Puppet::Util::Platform.windows? ?
# default Windows mode based on temp file storage for SYSTEM user or regular user
# for Jenkins or other services running as SYSTEM writing to c:\windows\temp
# the permissions will typically be SYSTEM(F) / Administrators(F) which is 770
# but sometimes there are extra users like IIS_IUSRS granted rights which adds the "extra ace" 2
# for local Administrators writing to their own temp folders under c:\users\USER
# they will have (F) for themselves, and Users will not have a permission, hence 700
(is_current_user_system? ? ['770', '2000770'] : '2000700') :
# or for *nix determine expected mode via bitwise AND complement of umask
(0100000 | 0666 & ~File.umask).to_s(8)
expect([expected_perms].flatten).to include(Puppet::FileSystem.stat(file).mode.to_s(8))
default_file = tmpfile('file_to_update2')
expect(Puppet::FileSystem.exist?(default_file)).to be_falsey
File.open(default_file, 'a') { |fh| fh.write('') }
# which matches the behavior of File.open
expect(Puppet::FileSystem.stat(file).mode).to eq(Puppet::FileSystem.stat(default_file).mode)
end
it "can accept an octal mode integer" do
file = tmpfile('file_to_update')
# NOTE: 777 here returns 755, but due to Ruby?
Puppet::FileSystem.open(file, 0444, 'a') { |fh| fh.write('') }
# Behavior may change in the future on Windows, to *actually* change perms
# but for now, setting a mode doesn't touch them
expected_perms = Puppet::Util::Platform.windows? ?
(is_current_user_system? ? ['770', '2000770'] : '2000700') :
'100444'
expect([expected_perms].flatten).to include(Puppet::FileSystem.stat(file).mode.to_s(8))
expected_ruby_mode = Puppet::Util::Platform.windows? ?
# The Windows behavior has been changed to ignore the mode specified by open
# given it's unlikely a caller expects Windows file attributes to be set
# therefore mode is explicitly not managed (until PUP-6959 is fixed)
#
# In default Ruby on Windows a mode controls file attribute setting
# (like archive, read-only, etc)
# The GetFileInformationByHandle API returns an attributes value that is
# a bitmask of Windows File Attribute Constants at
# https://msdn.microsoft.com/en-us/library/windows/desktop/gg258117(v=vs.85).aspx
'100644' :
# On other platforms, the mode should be what was set by octal 0444
'100444'
expect(File.stat(file).mode.to_s(8)).to eq(expected_ruby_mode)
end
it "cannot accept a mode string" do
file = tmpfile('file_to_update')
expect {
Puppet::FileSystem.open(file, "444", 'a') { |fh| fh.write('') }
}.to raise_error(TypeError)
end
it "opens, creates ands allows updating of a new file, using by default, the external system encoding" do
begin
original_encoding = Encoding.default_external
# this must be set through Ruby API and cannot be mocked - it sets internal state used by File.open
# pick a bizarre encoding unlikely to be used in any real tests
Encoding.default_external = Encoding::CP737
file = tmpfile('file_to_update')
# test writing a UTF-8 string when Default external encoding is something different
Puppet::FileSystem.open(file, 0660, 'w') do |fh|
# note Ruby behavior which has no external_encoding, but implicitly uses Encoding.default_external
expect(fh.external_encoding).to be_nil
# write a UTF-8 string to this file
fh.write(mixed_utf8)
end
# prove that Ruby implicitly converts read strings back to Encoding.default_external
# and that it did that in the previous write
written = Puppet::FileSystem.read(file)
expect(written.encoding).to eq(Encoding.default_external)
expect(written).to eq(mixed_utf8.force_encoding(Encoding.default_external))
ensure
# carefully roll back to the previous
Encoding.default_external = original_encoding
end
end
end
context "#exclusive_open" do
it "opens ands allows updating of an existing file" do
file = file_containing("file_to_update", "the contents")
Puppet::FileSystem.exclusive_open(file, 0660, 'r+') do |fh|
old = fh.read
fh.truncate(0)
fh.rewind
fh.write("updated #{old}")
end
expect(Puppet::FileSystem.read(file)).to eq("updated the contents")
end
it "opens, creates ands allows updating of a new file, using by default, the external system encoding" do
begin
original_encoding = Encoding.default_external
# this must be set through Ruby API and cannot be mocked - it sets internal state used by File.open
# pick a bizarre encoding unlikely to be used in any real tests
Encoding.default_external = Encoding::CP737
file = tmpfile('file_to_update')
# test writing a UTF-8 string when Default external encoding is something different
Puppet::FileSystem.exclusive_open(file, 0660, 'w') do |fh|
# note Ruby behavior which has no external_encoding, but implicitly uses Encoding.default_external
expect(fh.external_encoding).to be_nil
# write a UTF-8 string to this file
fh.write(mixed_utf8)
end
# prove that Ruby implicitly converts read strings back to Encoding.default_external
# and that it did that in the previous write
written = Puppet::FileSystem.read(file)
expect(written.encoding).to eq(Encoding.default_external)
expect(written).to eq(mixed_utf8.force_encoding(Encoding.default_external))
ensure
# carefully roll back to the previous
Encoding.default_external = original_encoding
end
end
it "excludes other processes from updating at the same time",
unless: Puppet::Util::Platform.windows? || Puppet::Util::Platform.jruby? do
file = file_containing("file_to_update", "0")
increment_counter_in_multiple_processes(file, 5, 'r+')
expect(Puppet::FileSystem.read(file)).to eq("5")
end
it "excludes other processes from updating at the same time even when creating the file",
unless: Puppet::Util::Platform.windows? || Puppet::Util::Platform.jruby? do
file = tmpfile("file_to_update")
increment_counter_in_multiple_processes(file, 5, 'a+')
expect(Puppet::FileSystem.read(file)).to eq("5")
end
it "times out if the lock cannot be acquired in a specified amount of time",
unless: Puppet::Util::Platform.windows? || Puppet::Util::Platform.jruby? do
file = tmpfile("file_to_update")
child = spawn_process_that_locks(file)
expect do
Puppet::FileSystem.exclusive_open(file, 0666, 'a', 0.1) do |f|
end
end.to raise_error(Timeout::Error, /Timeout waiting for exclusive lock on #{file}/)
Process.kill(9, child)
end
def spawn_process_that_locks(file)
read, write = IO.pipe
child = Kernel.fork do
read.close
Puppet::FileSystem.exclusive_open(file, 0666, 'a') do |fh|
write.write(true)
write.close
sleep 10
end
end
write.close
read.read
read.close
child
end
def increment_counter_in_multiple_processes(file, num_procs, options)
children = []
num_procs.times do
children << Kernel.fork do
Puppet::FileSystem.exclusive_open(file, 0660, options) do |fh|
fh.rewind
contents = (fh.read || 0).to_i
fh.truncate(0)
fh.rewind
fh.write((contents + 1).to_s)
end
exit(0)
end
end
children.each { |pid| Process.wait(pid) }
end
end
context "read_preserve_line_endings" do
it "should read a file with line feed" do
with_file_content("file content \n") do |file|
expect(Puppet::FileSystem.read_preserve_line_endings(file)).to eq("file content \n")
end
end
it "should read a file with carriage return line feed" do
with_file_content("file content \r\n") do |file|
expect(Puppet::FileSystem.read_preserve_line_endings(file)).to eq("file content \r\n")
end
end
it "should read a mixed file using only the first line newline when lf" do
with_file_content("file content \nsecond line \r\n") do |file|
expect(Puppet::FileSystem.read_preserve_line_endings(file)).to eq("file content \nsecond line \r\n")
end
end
it "should read a mixed file using only the first line newline when crlf" do
with_file_content("file content \r\nsecond line \n") do |file|
expect(Puppet::FileSystem.read_preserve_line_endings(file)).to eq("file content \r\nsecond line \n")
end
end
it "should ignore leading BOM" do
with_file_content("\uFEFFfile content \n") do |file|
expect(Puppet::FileSystem.read_preserve_line_endings(file)).to eq("file content \n")
end
end
it "should not warn about misusage of BOM with non-UTF encoding" do
allow(Encoding).to receive(:default_external).and_return(Encoding::US_ASCII)
with_file_content("file content \n") do |file|
expect{ Puppet::FileSystem.read_preserve_line_endings(file) }.not_to output(/BOM with non-UTF encoding US-ASCII is nonsense/).to_stderr
end
end
end
context "read without an encoding specified" do
it "returns strings as Encoding.default_external" do
temp_file = file_containing('test.txt', 'hello world')
contents = Puppet::FileSystem.read(temp_file)
expect(contents.encoding).to eq(Encoding.default_external)
expect(contents).to eq('hello world')
end
end
context "read should allow an encoding to be specified" do
# First line of Rune version of Rune poem at http://www.columbia.edu/~fdc/utf8/
# characters chosen since they will not parse on Windows with codepage 437 or 1252
# Section 3.2.1.3 of Ruby spec guarantees that \u strings are encoded as UTF-8
let (:rune_utf8) { "\u16A0\u16C7\u16BB" } # 'ᚠᛇᚻ'
it "and should read a UTF8 file properly" do
temp_file = file_containing('utf8.txt', rune_utf8)
contents = Puppet::FileSystem.read(temp_file, :encoding => 'utf-8')
expect(contents.encoding).to eq(Encoding::UTF_8)
expect(contents).to eq(rune_utf8)
end
it "does not strip the UTF8 BOM (Byte Order Mark) if present in a file" do
bom = "\uFEFF"
temp_file = file_containing('utf8bom.txt', "#{bom}#{rune_utf8}")
contents = Puppet::FileSystem.read(temp_file, :encoding => 'utf-8')
expect(contents.encoding).to eq(Encoding::UTF_8)
expect(contents).to eq("#{bom}#{rune_utf8}")
end
end
describe "symlink",
:if => ! Puppet.features.manages_symlinks? &&
Puppet::Util::Platform.windows? do
let(:file) { tmpfile("somefile") }
let(:missing_file) { tmpfile("missingfile") }
let(:expected_msg) { "This version of Windows does not support symlinks. Windows Vista / 2008 or higher is required." }
before :each do
FileUtils.touch(file)
end
it "should raise an error when trying to create a symlink" do
expect { Puppet::FileSystem.symlink(file, 'foo') }.to raise_error(Puppet::Util::Windows::Error)
end
it "should return false when trying to check if a path is a symlink" do
expect(Puppet::FileSystem.symlink?(file)).to be_falsey
end
it "should raise an error when trying to read a symlink" do
expect { Puppet::FileSystem.readlink(file) }.to raise_error(Puppet::Util::Windows::Error)
end
it "should return a File::Stat instance when calling stat on an existing file" do
expect(Puppet::FileSystem.stat(file)).to be_instance_of(File::Stat)
end
it "should raise Errno::ENOENT when calling stat on a missing file" do
expect { Puppet::FileSystem.stat(missing_file) }.to raise_error(Errno::ENOENT)
end
it "should fall back to stat when trying to lstat a file" do
expect(Puppet::Util::Windows::File).to receive(:stat).with(Puppet::FileSystem.assert_path(file))
Puppet::FileSystem.lstat(file)
end
end
describe "symlink", :if => Puppet.features.manages_symlinks? do
let(:file) { tmpfile("somefile") }
let(:missing_file) { tmpfile("missingfile") }
let(:dir) { tmpdir("somedir") }
before :each do
FileUtils.touch(file)
end
it "should return true for exist? on a present file" do
expect(Puppet::FileSystem.exist?(file)).to be_truthy
end
it "should return true for file? on a present file" do
expect(Puppet::FileSystem.file?(file)).to be_truthy
end
it "should return false for exist? on a non-existent file" do
expect(Puppet::FileSystem.exist?(missing_file)).to be_falsey
end
it "should return true for exist? on a present directory" do
expect(Puppet::FileSystem.exist?(dir)).to be_truthy
end
it "should return false for exist? on a dangling symlink" do
symlink = tmpfile("somefile_link")
Puppet::FileSystem.symlink(missing_file, symlink)
expect(Puppet::FileSystem.exist?(missing_file)).to be_falsey
expect(Puppet::FileSystem.exist?(symlink)).to be_falsey
end
it "should return true for exist? on valid symlinks" do
[file, dir].each do |target|
symlink = tmpfile("#{Puppet::FileSystem.basename(target).to_s}_link")
Puppet::FileSystem.symlink(target, symlink)
expect(Puppet::FileSystem.exist?(target)).to be_truthy
expect(Puppet::FileSystem.exist?(symlink)).to be_truthy
end
end
it "should return false for exist? when resolving a cyclic symlink chain" do
# point symlink -> file
symlink = tmpfile("somefile_link")
Puppet::FileSystem.symlink(file, symlink)
# point symlink2 -> symlink
symlink2 = tmpfile("somefile_link2")
Puppet::FileSystem.symlink(symlink, symlink2)
# point symlink3 -> symlink2
symlink3 = tmpfile("somefile_link3")
Puppet::FileSystem.symlink(symlink2, symlink3)
# yank file, temporarily dangle
::File.delete(file)
# and trash it so that we can recreate it OK on windows
Puppet::FileSystem.unlink(symlink)
# point symlink -> symlink3 to create a cycle
Puppet::FileSystem.symlink(symlink3, symlink)
expect(Puppet::FileSystem.exist?(symlink3)).to be_falsey
end
it "should return true for exist? when resolving a symlink chain pointing to a file" do
# point symlink -> file
symlink = tmpfile("somefile_link")
Puppet::FileSystem.symlink(file, symlink)
# point symlink2 -> symlink
symlink2 = tmpfile("somefile_link2")
Puppet::FileSystem.symlink(symlink, symlink2)
# point symlink3 -> symlink2
symlink3 = tmpfile("somefile_link3")
Puppet::FileSystem.symlink(symlink2, symlink3)
expect(Puppet::FileSystem.exist?(symlink3)).to be_truthy
end
it "should return false for exist? when resolving a symlink chain that dangles" do
# point symlink -> file
symlink = tmpfile("somefile_link")
Puppet::FileSystem.symlink(file, symlink)
# point symlink2 -> symlink
symlink2 = tmpfile("somefile_link2")
Puppet::FileSystem.symlink(symlink, symlink2)
# point symlink3 -> symlink2
symlink3 = tmpfile("somefile_link3")
Puppet::FileSystem.symlink(symlink2, symlink3)
# yank file, and make symlink dangle
::File.delete(file)
# symlink3 is now indirectly dangled
expect(Puppet::FileSystem.exist?(symlink3)).to be_falsey
end
it "should not create a symlink when the :noop option is specified" do
[file, dir].each do |target|
symlink = tmpfile("#{Puppet::FileSystem.basename(target)}_link")
Puppet::FileSystem.symlink(target, symlink, { :noop => true })
expect(Puppet::FileSystem.exist?(target)).to be_truthy
expect(Puppet::FileSystem.exist?(symlink)).to be_falsey
end
end
it "should raise Errno::EEXIST if trying to create a file / directory symlink when the symlink path already exists as a file" do
existing_file = tmpfile("#{Puppet::FileSystem.basename(file)}_link")
FileUtils.touch(existing_file)
[file, dir].each do |target|
expect { Puppet::FileSystem.symlink(target, existing_file) }.to raise_error(Errno::EEXIST)
expect(Puppet::FileSystem.exist?(existing_file)).to be_truthy
expect(Puppet::FileSystem.symlink?(existing_file)).to be_falsey
end
end
it "should silently fail if trying to create a file / directory symlink when the symlink path already exists as a directory" do
existing_dir = tmpdir("#{Puppet::FileSystem.basename(file)}_dir")
[file, dir].each do |target|
expect(Puppet::FileSystem.symlink(target, existing_dir)).to eq(0)
expect(Puppet::FileSystem.exist?(existing_dir)).to be_truthy
expect(File.directory?(existing_dir)).to be_truthy
expect(Puppet::FileSystem.symlink?(existing_dir)).to be_falsey
end
end
it "should silently fail to modify an existing directory symlink to reference a new file or directory" do
[file, dir].each do |target|
existing_dir = tmpdir("#{Puppet::FileSystem.basename(target)}_dir")
symlink = tmpfile("#{Puppet::FileSystem.basename(existing_dir)}_link")
Puppet::FileSystem.symlink(existing_dir, symlink)
expect(Puppet::FileSystem.readlink(symlink)).to eq(Puppet::FileSystem.path_string(existing_dir))
# now try to point it at the new target, no error raised, but file system unchanged
expect(Puppet::FileSystem.symlink(target, symlink)).to eq(0)
expect(Puppet::FileSystem.readlink(symlink)).to eq(existing_dir.to_s)
end
end
it "should raise Errno::EEXIST if trying to modify a file symlink to reference a new file or directory" do
symlink = tmpfile("#{Puppet::FileSystem.basename(file)}_link")
file_2 = tmpfile("#{Puppet::FileSystem.basename(file)}_2")
FileUtils.touch(file_2)
# symlink -> file_2
Puppet::FileSystem.symlink(file_2, symlink)
[file, dir].each do |target|
expect { Puppet::FileSystem.symlink(target, symlink) }.to raise_error(Errno::EEXIST)
expect(Puppet::FileSystem.readlink(symlink)).to eq(file_2.to_s)
end
end
it "should delete the existing file when creating a file / directory symlink with :force when the symlink path exists as a file" do
[file, dir].each do |target|
existing_file = tmpfile("#{Puppet::FileSystem.basename(target)}_existing")
FileUtils.touch(existing_file)
expect(Puppet::FileSystem.symlink?(existing_file)).to be_falsey
Puppet::FileSystem.symlink(target, existing_file, { :force => true })
expect(Puppet::FileSystem.symlink?(existing_file)).to be_truthy
expect(Puppet::FileSystem.readlink(existing_file)).to eq(target.to_s)
end
end
it "should modify an existing file symlink when using :force to reference a new file or directory" do
[file, dir].each do |target|
existing_file = tmpfile("#{Puppet::FileSystem.basename(target)}_existing")
FileUtils.touch(existing_file)
existing_symlink = tmpfile("#{Puppet::FileSystem.basename(existing_file)}_link")
Puppet::FileSystem.symlink(existing_file, existing_symlink)
expect(Puppet::FileSystem.readlink(existing_symlink)).to eq(existing_file.to_s)
Puppet::FileSystem.symlink(target, existing_symlink, { :force => true })
expect(Puppet::FileSystem.readlink(existing_symlink)).to eq(target.to_s)
end
end
it "should silently fail if trying to overwrite an existing directory with a new symlink when using :force to reference a file or directory" do
[file, dir].each do |target|
existing_dir = tmpdir("#{Puppet::FileSystem.basename(target)}_existing")
expect(Puppet::FileSystem.symlink(target, existing_dir, { :force => true })).to eq(0)
expect(Puppet::FileSystem.symlink?(existing_dir)).to be_falsey
end
end
it "should silently fail if trying to modify an existing directory symlink when using :force to reference a new file or directory" do
[file, dir].each do |target|
existing_dir = tmpdir("#{Puppet::FileSystem.basename(target)}_existing")
existing_symlink = tmpfile("#{Puppet::FileSystem.basename(existing_dir)}_link")
Puppet::FileSystem.symlink(existing_dir, existing_symlink)
expect(Puppet::FileSystem.readlink(existing_symlink)).to eq(existing_dir.to_s)
expect(Puppet::FileSystem.symlink(target, existing_symlink, { :force => true })).to eq(0)
expect(Puppet::FileSystem.readlink(existing_symlink)).to eq(existing_dir.to_s)
end
end
it "should accept a string, Pathname or object with to_str (Puppet::Util::WatchedFile) for exist?" do
[ tmpfile('bogus1'),
Pathname.new(tmpfile('bogus2')),
Puppet::Util::WatchedFile.new(tmpfile('bogus3'))
].each { |f| expect(Puppet::FileSystem.exist?(f)).to be_falsey }
end
it "should return a File::Stat instance when calling stat on an existing file" do
expect(Puppet::FileSystem.stat(file)).to be_instance_of(File::Stat)
end
it "should raise Errno::ENOENT when calling stat on a missing file" do
expect { Puppet::FileSystem.stat(missing_file) }.to raise_error(Errno::ENOENT)
end
it "should be able to create a symlink, and verify it with symlink?" do
symlink = tmpfile("somefile_link")
Puppet::FileSystem.symlink(file, symlink)
expect(Puppet::FileSystem.symlink?(symlink)).to be_truthy
end
it "should report symlink? as false on file, directory and missing files" do
[file, dir, missing_file].each do |f|
expect(Puppet::FileSystem.symlink?(f)).to be_falsey
end
end
it "should return a File::Stat with ftype 'link' when calling lstat on a symlink pointing to existing file" do
symlink = tmpfile("somefile_link")
Puppet::FileSystem.symlink(file, symlink)
stat = Puppet::FileSystem.lstat(symlink)
expect(stat).to be_instance_of(File::Stat)
expect(stat.ftype).to eq('link')
end
it "should return a File::Stat of ftype 'link' when calling lstat on a symlink pointing to missing file" do
symlink = tmpfile("somefile_link")
Puppet::FileSystem.symlink(missing_file, symlink)
stat = Puppet::FileSystem.lstat(symlink)
expect(stat).to be_instance_of(File::Stat)
expect(stat.ftype).to eq('link')
end
it "should return a File::Stat of ftype 'file' when calling stat on a symlink pointing to existing file" do
symlink = tmpfile("somefile_link")
Puppet::FileSystem.symlink(file, symlink)
stat = Puppet::FileSystem.stat(symlink)
expect(stat).to be_instance_of(File::Stat)
expect(stat.ftype).to eq('file')
end
it "should return a File::Stat of ftype 'directory' when calling stat on a symlink pointing to existing directory" do
symlink = tmpfile("somefile_link")
Puppet::FileSystem.symlink(dir, symlink)
stat = Puppet::FileSystem.stat(symlink)
expect(stat).to be_instance_of(File::Stat)
expect(stat.ftype).to eq('directory')
# on Windows, this won't get cleaned up if still linked
Puppet::FileSystem.unlink(symlink)
end
it "should return a File::Stat of ftype 'file' when calling stat on a symlink pointing to another symlink" do
# point symlink -> file
symlink = tmpfile("somefile_link")
Puppet::FileSystem.symlink(file, symlink)
# point symlink2 -> symlink
symlink2 = tmpfile("somefile_link2")
Puppet::FileSystem.symlink(symlink, symlink2)
expect(Puppet::FileSystem.stat(symlink2).ftype).to eq('file')
end
it "should raise Errno::ENOENT when calling stat on a dangling symlink" do
symlink = tmpfile("somefile_link")
Puppet::FileSystem.symlink(missing_file, symlink)
expect { Puppet::FileSystem.stat(symlink) }.to raise_error(Errno::ENOENT)
end
it "should be able to readlink to resolve the physical path to a symlink" do
symlink = tmpfile("somefile_link")
Puppet::FileSystem.symlink(file, symlink)
expect(Puppet::FileSystem.exist?(file)).to be_truthy
expect(Puppet::FileSystem.readlink(symlink)).to eq(file.to_s)
end
it "should not resolve entire symlink chain with readlink on a symlink'd symlink" do
# point symlink -> file
symlink = tmpfile("somefile_link")
Puppet::FileSystem.symlink(file, symlink)
# point symlink2 -> symlink
symlink2 = tmpfile("somefile_link2")
Puppet::FileSystem.symlink(symlink, symlink2)
expect(Puppet::FileSystem.exist?(file)).to be_truthy
expect(Puppet::FileSystem.readlink(symlink2)).to eq(symlink.to_s)
end
it "should be able to readlink to resolve the physical path to a dangling symlink" do
symlink = tmpfile("somefile_link")
Puppet::FileSystem.symlink(missing_file, symlink)
expect(Puppet::FileSystem.exist?(missing_file)).to be_falsey
expect(Puppet::FileSystem.readlink(symlink)).to eq(missing_file.to_s)
end
it "should be able to unlink a dangling symlink pointed at a file" do
symlink = tmpfile("somefile_link")
Puppet::FileSystem.symlink(file, symlink)
::File.delete(file)
Puppet::FileSystem.unlink(symlink)
expect(Puppet::FileSystem).to_not be_exist(file)
expect(Puppet::FileSystem).to_not be_exist(symlink)
end
it "should be able to unlink a dangling symlink pointed at a directory" do
symlink = tmpfile("somedir_link")
Puppet::FileSystem.symlink(dir, symlink)
Dir.rmdir(dir)
Puppet::FileSystem.unlink(symlink)
expect(Puppet::FileSystem).to_not be_exist(dir)
expect(Puppet::FileSystem).to_not be_exist(symlink)
end
it "should delete only the symlink and not the target when calling unlink instance method" do
[file, dir].each do |target|
symlink = tmpfile("#{Puppet::FileSystem.basename(target)}_link")
Puppet::FileSystem.symlink(target, symlink)
expect(Puppet::FileSystem.exist?(target)).to be_truthy
expect(Puppet::FileSystem.readlink(symlink)).to eq(target.to_s)
expect(Puppet::FileSystem.unlink(symlink)).to eq(1) # count of files
expect(Puppet::FileSystem.exist?(target)).to be_truthy
expect(Puppet::FileSystem.exist?(symlink)).to be_falsey
end
end
it "should delete only the symlink and not the target when calling unlink class method" do
[file, dir].each do |target|
symlink = tmpfile("#{Puppet::FileSystem.basename(target)}_link")
Puppet::FileSystem.symlink(target, symlink)
expect(Puppet::FileSystem.exist?(target)).to be_truthy
expect(Puppet::FileSystem.readlink(symlink)).to eq(target.to_s)
expect(Puppet::FileSystem.unlink(symlink)).to eq(1) # count of files
expect(Puppet::FileSystem.exist?(target)).to be_truthy
expect(Puppet::FileSystem.exist?(symlink)).to be_falsey
end
end
describe "unlink" do
it "should delete files with unlink" do
expect(Puppet::FileSystem.exist?(file)).to be_truthy
expect(Puppet::FileSystem.unlink(file)).to eq(1) # count of files
expect(Puppet::FileSystem.exist?(file)).to be_falsey
end
it "should delete files with unlink class method" do
expect(Puppet::FileSystem.exist?(file)).to be_truthy
expect(Puppet::FileSystem.unlink(file)).to eq(1) # count of files
expect(Puppet::FileSystem.exist?(file)).to be_falsey
end
it "should delete multiple files with unlink class method" do
paths = (1..3).collect do |i|
f = tmpfile("somefile_#{i}")
FileUtils.touch(f)
expect(Puppet::FileSystem.exist?(f)).to be_truthy
f.to_s
end
expect(Puppet::FileSystem.unlink(*paths)).to eq(3) # count of files
paths.each { |p| expect(Puppet::FileSystem.exist?(p)).to be_falsey }
end
it "should raise Errno::EPERM or Errno::EISDIR when trying to delete a directory with the unlink class method" do
expect(Puppet::FileSystem.exist?(dir)).to be_truthy
ex = nil
begin
Puppet::FileSystem.unlink(dir)
rescue Exception => e
ex = e
end
expect([
Errno::EPERM, # Windows and OSX
Errno::EISDIR # Linux
]).to include(ex.class)
expect(Puppet::FileSystem.exist?(dir)).to be_truthy
end
it "should raise Errno::EACCESS when trying to delete a file whose parent directory does not allow execute/traverse", unless: Puppet::Util::Platform.windows? do
dir = tmpdir('file_system_unlink')
path = File.join(dir, 'deleteme')
mode = Puppet::FileSystem.stat(dir).mode
Puppet::FileSystem.chmod(0, dir)
begin
# JRuby 9.2.21.0 drops the path from the message..
message = Puppet::Util::Platform.jruby? ? /^Permission denied/ : /^Permission denied .* #{path}/
expect {
Puppet::FileSystem.unlink(path)
}.to raise_error(Errno::EACCES, message)
ensure
Puppet::FileSystem.chmod(mode, dir)
end
end
end
describe "exclusive_create" do
it "should create a file that doesn't exist" do
expect(Puppet::FileSystem.exist?(missing_file)).to be_falsey
Puppet::FileSystem.exclusive_create(missing_file, nil) {}
expect(Puppet::FileSystem.exist?(missing_file)).to be_truthy
end
it "should raise Errno::EEXIST creating a file that does exist" do
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | true |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/puppet_spec.rb | spec/unit/puppet_spec.rb | require 'spec_helper'
require 'puppet'
require 'puppet_spec/files'
describe Puppet do
include PuppetSpec::Files
context "#version" do
it "should be valid semver" do
expect(SemanticPuppet::Version).to be_valid Puppet.version
end
end
Puppet::Util::Log.eachlevel do |level|
it "should have a method for sending '#{level}' logs" do
expect(Puppet).to respond_to(level)
end
end
it "should be able to change the path" do
newpath = ENV["PATH"] + File::PATH_SEPARATOR + "/something/else"
Puppet[:path] = newpath
expect(ENV["PATH"]).to eq(newpath)
end
it 'should propagate --modulepath to base environment' do
expect(Puppet::Node::Environment).to receive(:create).with(
be_a(Symbol), ['/my/modules'], Puppet::Node::Environment::NO_MANIFEST)
Puppet.base_context({
:environmentpath => '/envs',
:basemodulepath => '/base/modules',
:modulepath => '/my/modules'
})
end
it 'empty modulepath does not override basemodulepath' do
expect(Puppet::Node::Environment).to receive(:create).with(
be_a(Symbol), ['/base/modules'], Puppet::Node::Environment::NO_MANIFEST)
Puppet.base_context({
:environmentpath => '/envs',
:basemodulepath => '/base/modules',
:modulepath => ''
})
end
it 'nil modulepath does not override basemodulepath' do
expect(Puppet::Node::Environment).to receive(:create).with(
be_a(Symbol), ['/base/modules'], Puppet::Node::Environment::NO_MANIFEST)
Puppet.base_context({
:environmentpath => '/envs',
:basemodulepath => '/base/modules',
:modulepath => nil
})
end
context "Puppet::OLDEST_RECOMMENDED_RUBY_VERSION" do
it "should have an oldest recommended ruby version constant" do
expect(Puppet::OLDEST_RECOMMENDED_RUBY_VERSION).not_to be_nil
end
it "should be a string" do
expect(Puppet::OLDEST_RECOMMENDED_RUBY_VERSION).to be_a_kind_of(String)
end
it "should match a semver version" do
expect(SemanticPuppet::Version).to be_valid(Puppet::OLDEST_RECOMMENDED_RUBY_VERSION)
end
end
context "Settings" do
before(:each) do
@old_settings = Puppet.settings
end
after(:each) do
Puppet.replace_settings_object(@old_settings)
end
it "should allow for settings to be redefined with a custom object" do
new_settings = double()
Puppet.replace_settings_object(new_settings)
expect(Puppet.settings).to eq(new_settings)
end
end
context 'when registering implementations' do
it 'does not register an implementation by default' do
Puppet.initialize_settings
expect(Puppet.runtime[:http]).to be_an_instance_of(Puppet::HTTP::Client)
end
it 'allows a http implementation to be registered' do
http_impl = double('http')
Puppet.initialize_settings([], true, true, http: http_impl)
expect(Puppet.runtime[:http]).to eq(http_impl)
end
it 'allows a facter implementation to be registered' do
facter_impl = double('facter')
Puppet.initialize_settings([], true, true, facter: facter_impl)
expect(Puppet.runtime[:facter]).to eq(facter_impl)
end
end
context "initializing $LOAD_PATH" do
it "should add libdir and module paths to the load path" do
libdir = tmpdir('libdir_test')
vendor_dir = tmpdir('vendor_modules')
module_libdir = File.join(vendor_dir, 'amodule_core', 'lib')
FileUtils.mkdir_p(module_libdir)
Puppet[:libdir] = libdir
Puppet[:vendormoduledir] = vendor_dir
Puppet.initialize_settings
expect($LOAD_PATH).to include(libdir)
expect($LOAD_PATH).to include(module_libdir)
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/facter_impl_spec.rb | spec/unit/facter_impl_spec.rb | require 'spec_helper'
describe 'Puppet::FacterImpl' do
subject(:facter_impl) { Puppet::FacterImpl.new }
it { is_expected.to respond_to(:value) }
it { is_expected.to respond_to(:add) }
describe '.value' do
let(:method_name) { :value }
before { allow(Facter).to receive(method_name) }
it 'delegates to Facter API' do
facter_impl.value('test_fact')
expect(Facter).to have_received(method_name).with('test_fact')
end
end
describe '.add' do
let(:block) { Proc.new { setcode 'test' } }
let(:method_name) { :add }
before { allow(Facter).to receive(method_name) }
it 'delegates to Facter API' do
facter_impl.add('test_fact', &block)
expect(Facter).to have_received(method_name).with('test_fact', &block)
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/configurer_spec.rb | spec/unit/configurer_spec.rb | require 'spec_helper'
require 'puppet/configurer'
describe Puppet::Configurer do
include PuppetSpec::Files
before do
Puppet[:server] = "puppetmaster"
Puppet[:report] = true
catalog.add_resource(resource)
Puppet[:lastrunfile] = file_containing('last_run_summary.yaml', <<~SUMMARY)
---
version:
config: 1624882680
puppet: #{Puppet.version}
application:
initial_environment: #{Puppet[:environment]}
converged_environment: #{Puppet[:environment]}
run_mode: agent
SUMMARY
end
let(:node_name) { Puppet[:node_name_value] }
let(:configurer) { Puppet::Configurer.new }
let(:report) { Puppet::Transaction::Report.new }
let(:catalog) { Puppet::Resource::Catalog.new(node_name, Puppet::Node::Environment.remote(Puppet[:environment].to_sym)) }
let(:resource) { Puppet::Resource.new(:notice, 'a') }
let(:facts) { Puppet::Node::Facts.new(node_name) }
describe "when executing a pre-run hook" do
it "should do nothing if the hook is set to an empty string" do
Puppet.settings[:prerun_command] = ""
expect(Puppet::Util::Execution).not_to receive(:execute)
configurer.execute_prerun_command
end
it "should execute any pre-run command provided via the 'prerun_command' setting" do
Puppet.settings[:prerun_command] = "/my/command"
expect(Puppet::Util::Execution).to receive(:execute).with(["/my/command"]).and_raise(Puppet::ExecutionFailure, "Failed")
configurer.execute_prerun_command
end
it "should fail if the command fails" do
Puppet.settings[:prerun_command] = "/my/command"
expect(Puppet::Util::Execution).to receive(:execute).with(["/my/command"]).and_raise(Puppet::ExecutionFailure, "Failed")
expect(configurer.execute_prerun_command).to be_falsey
end
end
describe "when executing a post-run hook" do
it "should do nothing if the hook is set to an empty string" do
Puppet.settings[:postrun_command] = ""
expect(Puppet::Util::Execution).not_to receive(:execute)
configurer.execute_postrun_command
end
it "should execute any post-run command provided via the 'postrun_command' setting" do
Puppet.settings[:postrun_command] = "/my/command"
expect(Puppet::Util::Execution).to receive(:execute).with(["/my/command"]).and_raise(Puppet::ExecutionFailure, "Failed")
configurer.execute_postrun_command
end
it "should fail if the command fails" do
Puppet.settings[:postrun_command] = "/my/command"
expect(Puppet::Util::Execution).to receive(:execute).with(["/my/command"]).and_raise(Puppet::ExecutionFailure, "Failed")
expect(configurer.execute_postrun_command).to be_falsey
end
end
describe "when executing a catalog run without stubbing valid_server_environment?" do
before do
Puppet::Resource::Catalog.indirection.terminus_class = :rest
allow(Puppet::Resource::Catalog.indirection).to receive(:find).and_return(catalog)
end
it 'skips initial plugin sync if environment is not found and no strict_environment_mode' do
body = "{\"message\":\"Not Found: Could not find environment 'fasdfad'\",\"issue_kind\":\"RUNTIME_ERROR\"}"
stub_request(:get, %r{/puppet/v3/file_metadatas/plugins?}).to_return(
status: 404, body: body, headers: {'Content-Type' => 'application/json'}
)
configurer.run(:pluginsync => true)
expect(@logs).to include(an_object_having_attributes(level: :notice, message: %r{Environment 'production' not found on server, skipping initial pluginsync.}))
expect(@logs).to include(an_object_having_attributes(level: :notice, message: /Applied catalog in .* seconds/))
end
it 'if strict_environment_mode is set and environment is not found, aborts the puppet run' do
Puppet[:strict_environment_mode] = true
body = "{\"message\":\"Not Found: Could not find environment 'fasdfad'\",\"issue_kind\":\"RUNTIME_ERROR\"}"
stub_request(:get, %r{/puppet/v3/file_metadatas/plugins?}).to_return(
status: 404, body: body, headers: {'Content-Type' => 'application/json'}
)
configurer.run(:pluginsync => true)
expect(@logs).to include(an_object_having_attributes(level: :err, message: %r{Failed to apply catalog: Environment 'production' not found on server, aborting run.}))
end
end
describe "when executing a catalog run" do
before do
Puppet::Resource::Catalog.indirection.terminus_class = :rest
allow(Puppet::Resource::Catalog.indirection).to receive(:find).and_return(catalog)
allow_any_instance_of(described_class).to(
receive(:valid_server_environment?).and_return(true)
)
end
it "downloads plugins when told" do
expect(configurer).to receive(:download_plugins)
configurer.run(:pluginsync => true)
end
it "does not download plugins when told" do
expect(configurer).not_to receive(:download_plugins)
configurer.run(:pluginsync => false)
end
it "does not download plugins when specified environment is not vaild on server" do
expect(configurer).to receive(:valid_server_environment?).and_return(false)
expect(configurer).not_to receive(:download_plugins)
configurer.run(:pluginsync => true)
end
it "fails the run if pluginsync fails when usecacheonfailure is false" do
Puppet[:ignore_plugin_errors] = false
# --test implies these, set them so we don't fall back to a cached catalog
Puppet[:use_cached_catalog] = false
Puppet[:usecacheonfailure] = false
body = "{\"message\":\"Not Found: Could not find environment 'fasdfad'\",\"issue_kind\":\"RUNTIME_ERROR\"}"
stub_request(:get, %r{/puppet/v3/file_metadatas/pluginfacts}).to_return(
status: 404, body: body, headers: {'Content-Type' => 'application/json'}
)
stub_request(:get, %r{/puppet/v3/file_metadata/pluginfacts}).to_return(
status: 404, body: body, headers: {'Content-Type' => 'application/json'}
)
configurer.run(pluginsync: true)
expect(@logs).to include(an_object_having_attributes(level: :err, message: %r{Failed to apply catalog: Failed to retrieve pluginfacts: Could not retrieve information from environment production source\(s\) puppet:///pluginfacts}))
end
it "applies a cached catalog if pluginsync fails when usecacheonfailure is true" do
Puppet[:ignore_plugin_errors] = false
Puppet[:use_cached_catalog] = false
Puppet[:usecacheonfailure] = true
body = "{\"message\":\"Not Found: Could not find environment 'fasdfad'\",\"issue_kind\":\"RUNTIME_ERROR\"}"
stub_request(:get, %r{/puppet/v3/file_metadatas/pluginfacts}).to_return(
status: 404, body: body, headers: {'Content-Type' => 'application/json'}
)
stub_request(:get, %r{/puppet/v3/file_metadata/pluginfacts}).to_return(
status: 404, body: body, headers: {'Content-Type' => 'application/json'}
)
expect(configurer.run(pluginsync: true, :report => report)).to eq(0)
expect(report.cached_catalog_status).to eq('on_failure')
end
it "applies a cached catalog when it can't connect to the master" do
error = Errno::ECONNREFUSED.new('Connection refused - connect(2)')
expect(Puppet::Resource::Catalog.indirection).to receive(:find).with(anything, hash_including(:ignore_cache => true)).and_raise(error)
expect(Puppet::Resource::Catalog.indirection).to receive(:find).with(anything, hash_including(:ignore_terminus => true)).and_return(catalog)
expect(configurer.run).to eq(0)
end
it "should initialize a transaction report if one is not provided" do
# host and settings catalogs each create a report...
expect(Puppet::Transaction::Report).to receive(:new).and_return(report).twice
configurer.run
end
it "should respect node_name_fact when setting the host on a report" do
Puppet[:node_name_value] = nil
Puppet[:node_name_fact] = 'my_name_fact'
facts.values = {'my_name_fact' => 'node_name_from_fact'}
Puppet::Node::Facts.indirection.save(facts)
configurer.run(:report => report)
expect(report.host).to eq('node_name_from_fact')
end
it "should warn the user when the fact value length limits are exceeded" do
Puppet[:fact_name_length_soft_limit] = 0
Puppet[:fact_value_length_soft_limit] = 1
Puppet[:top_level_facts_soft_limit] = 0
Puppet[:number_of_facts_soft_limit] = 0
Puppet[:payload_soft_limit] = 0
facts.values = { 'processors' => {
'isa' => "i386" }
}
Puppet::Node::Facts.indirection.save(facts)
expect(Puppet).to receive(:warning).with(/Fact processors.isa with value i386 with the value length: 4 exceeds the value length limit: 1/)
configurer.run
end
it "should warn the user when the payload limits are exceeded" do
Puppet[:fact_name_length_soft_limit] = 0
Puppet[:fact_value_length_soft_limit] = 0
Puppet[:top_level_facts_soft_limit] = 0
Puppet[:number_of_facts_soft_limit] = 0
Puppet[:payload_soft_limit] = 1
facts.values = { 'processors' => {
'cores' => 1,
'count' => 2,
'isa' => "i386",
'models' => [
"CPU1 @ 2.80GHz"
],
'physicalcount' => 4 }
}
Puppet::Node::Facts.indirection.save(facts)
expect(Puppet).to receive(:warning).with(/Payload with the current size of: \d* exceeds the payload size limit: \d*/)
configurer.run
end
it "should warn the user when the total number of facts limit is exceeded" do
Puppet[:fact_name_length_soft_limit] = 0
Puppet[:fact_value_length_soft_limit] = 0
Puppet[:top_level_facts_soft_limit] = 0
Puppet[:number_of_facts_soft_limit] = 1
Puppet[:payload_soft_limit] = 0
facts.values = {
'processors' => {
'cores' => 1,
'count' => 2,
'isa' => "i386",
'models' => [
"CPU1 @ 2.80GHz",
"CPU1 @ 2.80GHz",
"CPU1 @ 2.80GHz",
"CPU1 @ 2.80GHz",
"CPU1 @ 2.80GHz",
{
'processors' => {
'cores' => [1,2]
}
}
],
'physicalcount' => 4
}
}
Puppet::Node::Facts.indirection.save(facts)
expect(Puppet).to receive(:warning).with(/The current total number of fact values: [1-9]* exceeds the fact values limit: [1-9]*/)
configurer.run
end
it "should warn the user when the top level facts size limits are exceeded" do
Puppet[:fact_name_length_soft_limit] = 0
Puppet[:fact_value_length_soft_limit] = 0
Puppet[:top_level_facts_soft_limit] = 1
Puppet[:number_of_facts_soft_limit] = 0
Puppet[:payload_soft_limit] = 0
facts.values = {'my_new_fact_name' => 'my_new_fact_value',
'my_new_fact_name2' => 'my_new_fact_value2'}
Puppet::Node::Facts.indirection.save(facts)
expect(Puppet).to receive(:warning).with(/The current number of top level facts: [1-9]* exceeds the top facts limit: [1-9]*/)
configurer.run
end
it "should warn the user when the fact name length limits are exceeded" do
Puppet[:fact_name_length_soft_limit] = 1
Puppet[:fact_value_length_soft_limit] = 0
Puppet[:top_level_facts_soft_limit] = 0
Puppet[:number_of_facts_soft_limit] = 0
Puppet[:payload_soft_limit] = 0
facts.values = { 'processors' => {
'isa' => "i386" }
}
Puppet::Node::Facts.indirection.save(facts)
expect(Puppet).to receive(:warning).with(/Fact processors.isa with length: 25 exceeds the fact name length limit: 1/)
configurer.run
end
it "shouldn't warn the user when the fact limit settings are set to 0" do
Puppet[:fact_name_length_soft_limit] = 0
Puppet[:fact_value_length_soft_limit] = 0
Puppet[:top_level_facts_soft_limit] = 0
Puppet[:number_of_facts_soft_limit] = 0
Puppet[:payload_soft_limit] = 0
facts.values = {'my_new_fact_name' => 'my_new_fact_value'}
Puppet::Node::Facts.indirection.save(facts)
expect(Puppet).not_to receive(:warning)
configurer.run
end
it "creates a new report when applying the catalog" do
options = {}
configurer.run(options)
expect(options[:report].metrics['time']['catalog_application']).to be_an_instance_of(Float)
end
it "uses the provided report when applying the catalog" do
configurer.run(:report => report)
expect(report.metrics['time']['catalog_application']).to be_an_instance_of(Float)
end
it "should log a failure and do nothing if no catalog can be retrieved" do
expect(configurer).to receive(:retrieve_catalog).and_return(nil)
expect(Puppet).to receive(:err).with("Could not retrieve catalog; skipping run")
configurer.run
end
it "passes arbitrary options when applying the catalog" do
expect(catalog).to receive(:apply).with(hash_including(one: true))
configurer.run(catalog: catalog, one: true)
end
it "should benchmark how long it takes to apply the catalog" do
configurer.run(report: report)
expect(report.logs).to include(an_object_having_attributes(level: :notice, message: /Applied catalog in .* seconds/))
end
it "should create report with passed transaction_uuid and job_id" do
configurer = Puppet::Configurer.new("test_tuuid", "test_jid")
report = Puppet::Transaction::Report.new(nil, "test", "aaaa")
expect(Puppet::Transaction::Report).to receive(:new).with(anything, anything, 'test_tuuid', 'test_jid', anything).and_return(report)
expect(configurer).to receive(:send_report).with(report)
configurer.run
end
it "should send the report" do
report = Puppet::Transaction::Report.new(nil, "test", "aaaa")
expect(Puppet::Transaction::Report).to receive(:new).and_return(report)
expect(configurer).to receive(:send_report).with(report)
expect(report.environment).to eq("test")
expect(report.transaction_uuid).to eq("aaaa")
configurer.run
end
it "should send the transaction report even if the catalog could not be retrieved" do
expect(configurer).to receive(:retrieve_catalog).and_return(nil)
report = Puppet::Transaction::Report.new(nil, "test", "aaaa")
expect(Puppet::Transaction::Report).to receive(:new).and_return(report)
expect(configurer).to receive(:send_report).with(report)
expect(report.environment).to eq("test")
expect(report.transaction_uuid).to eq("aaaa")
configurer.run
end
it "should send the transaction report even if there is a failure" do
expect(configurer).to receive(:retrieve_catalog).and_raise("whatever")
report = Puppet::Transaction::Report.new(nil, "test", "aaaa")
expect(Puppet::Transaction::Report).to receive(:new).and_return(report)
expect(configurer).to receive(:send_report).with(report)
expect(report.environment).to eq("test")
expect(report.transaction_uuid).to eq("aaaa")
expect(configurer.run).to be_nil
end
it "should remove the report as a log destination when the run is finished" do
configurer.run(report: report)
expect(Puppet::Util::Log.destinations).not_to include(report)
end
it "should return an exit status of 2 due to the notify resource 'changing'" do
cat = Puppet::Resource::Catalog.new("tester", Puppet::Node::Environment.remote(Puppet[:environment].to_sym))
cat.add_resource(Puppet::Type.type(:notify).new(:name => 'something changed'))
expect(configurer.run(catalog: cat, report: report)).to eq(2)
end
it "should return nil if catalog application fails" do
expect(catalog).to receive(:apply).and_raise(Puppet::Error, 'One or more resource dependency cycles detected in graph')
expect(configurer.run(catalog: catalog, report: report)).to be_nil
end
it "should send the transaction report even if the pre-run command fails" do
expect(Puppet::Transaction::Report).to receive(:new).and_return(report)
Puppet.settings[:prerun_command] = "/my/command"
expect(Puppet::Util::Execution).to receive(:execute).with(["/my/command"]).and_raise(Puppet::ExecutionFailure, "Failed")
expect(configurer).to receive(:send_report).with(report)
expect(configurer.run).to be_nil
end
it "should include the pre-run command failure in the report" do
Puppet.settings[:prerun_command] = "/my/command"
expect(Puppet::Util::Execution).to receive(:execute).with(["/my/command"]).and_raise(Puppet::ExecutionFailure, "Failed")
expect(configurer.run(report: report)).to be_nil
expect(report.logs.find { |x| x.message =~ /Could not run command from prerun_command/ }).to be
end
it "should send the transaction report even if the post-run command fails" do
Puppet.settings[:postrun_command] = "/my/command"
expect(Puppet::Util::Execution).to receive(:execute).with(["/my/command"]).and_raise(Puppet::ExecutionFailure, "Failed")
expect(configurer).to receive(:send_report).with(report)
expect(configurer.run(report: report)).to be_nil
end
it "should include the post-run command failure in the report" do
Puppet.settings[:postrun_command] = "/my/command"
expect(Puppet::Util::Execution).to receive(:execute).with(["/my/command"]).and_raise(Puppet::ExecutionFailure, "Failed")
expect(report).to receive(:<<) { |log, _| expect(log.message).to match(/Could not run command from postrun_command/) }.at_least(:once)
expect(configurer.run(report: report)).to be_nil
end
it "should execute post-run command even if the pre-run command fails" do
Puppet.settings[:prerun_command] = "/my/precommand"
Puppet.settings[:postrun_command] = "/my/postcommand"
expect(Puppet::Util::Execution).to receive(:execute).with(["/my/precommand"]).and_raise(Puppet::ExecutionFailure, "Failed")
expect(Puppet::Util::Execution).to receive(:execute).with(["/my/postcommand"])
expect(configurer.run).to be_nil
end
it "should finalize the report" do
expect(report).to receive(:finalize_report)
configurer.run(report: report)
end
it "should not apply the catalog if the pre-run command fails" do
Puppet.settings[:prerun_command] = "/my/command"
expect(Puppet::Util::Execution).to receive(:execute).with(["/my/command"]).and_raise(Puppet::ExecutionFailure, "Failed")
expect_any_instance_of(Puppet::Resource::Catalog).not_to receive(:apply)
expect(configurer).to receive(:send_report)
expect(configurer.run(report: report)).to be_nil
end
it "should apply the catalog, send the report, and return nil if the post-run command fails" do
Puppet.settings[:postrun_command] = "/my/command"
expect(Puppet::Util::Execution).to receive(:execute).with(["/my/command"]).and_raise(Puppet::ExecutionFailure, "Failed")
expect_any_instance_of(Puppet::Resource::Catalog).to receive(:apply)
expect(configurer).to receive(:send_report)
expect(configurer.run(report: report)).to be_nil
end
it 'includes total time metrics in the report after successfully applying the catalog' do
configurer.run(report: report)
expect(report.metrics['time']).to be
expect(report.metrics['time']['total']).to be_a_kind_of(Numeric)
end
it 'includes total time metrics in the report even if prerun fails' do
Puppet.settings[:prerun_command] = "/my/command"
expect(Puppet::Util::Execution).to receive(:execute).with(["/my/command"]).and_raise(Puppet::ExecutionFailure, "Failed")
configurer.run(report: report)
expect(report.metrics['time']).to be
expect(report.metrics['time']['total']).to be_a_kind_of(Numeric)
end
it 'includes total time metrics in the report even if catalog retrieval fails' do
allow(configurer).to receive(:prepare_and_retrieve_catalog_from_cache).and_raise
configurer.run(:report => report)
expect(report.metrics['time']).to be
expect(report.metrics['time']['total']).to be_a_kind_of(Numeric)
end
it "should refetch the catalog if the server specifies a new environment in the catalog" do
catalog = Puppet::Resource::Catalog.new(node_name, Puppet::Node::Environment.remote('second_env'))
expect(configurer).to receive(:retrieve_catalog).and_return(catalog).twice
configurer.run
end
it "changes the configurer's environment if the server specifies a new environment in the catalog" do
allow_any_instance_of(Puppet::Resource::Catalog).to receive(:environment).and_return("second_env")
configurer.run
expect(configurer.environment).to eq("second_env")
end
it "changes the report's environment if the server specifies a new environment in the catalog" do
allow_any_instance_of(Puppet::Resource::Catalog).to receive(:environment).and_return("second_env")
configurer.run(report: report)
expect(report.environment).to eq("second_env")
end
it "sends the transaction uuid in a catalog request" do
configurer = Puppet::Configurer.new('aaa')
expect(Puppet::Resource::Catalog.indirection).to receive(:find).with(anything, hash_including(transaction_uuid: 'aaa'))
configurer.run
end
it "sends the transaction uuid in a catalog request" do
configurer = Puppet::Configurer.new('b', 'aaa')
expect(Puppet::Resource::Catalog.indirection).to receive(:find).with(anything, hash_including(job_id: 'aaa'))
configurer.run
end
it "sets the static_catalog query param to true in a catalog request" do
expect(Puppet::Resource::Catalog.indirection).to receive(:find).with(anything, hash_including(static_catalog: true))
configurer.run
end
it "sets the checksum_type query param to the default supported_checksum_types in a catalog request" do
expect(Puppet::Resource::Catalog.indirection).to receive(:find).with(anything,
hash_including(checksum_type: 'sha256.sha384.sha512.sha224.md5'))
configurer.run
end
it "sets the checksum_type query param to the supported_checksum_types setting in a catalog request" do
Puppet[:supported_checksum_types] = ['sha256']
# Regenerate the agent to pick up the new setting
configurer = Puppet::Configurer.new
expect(Puppet::Resource::Catalog.indirection).to receive(:find).with(anything, hash_including(checksum_type: 'sha256'))
configurer.run
end
describe "when not using a REST terminus for catalogs" do
it "should not pass any facts when retrieving the catalog" do
# This is weird, we collect facts when constructing the node,
# but we don't send them in the indirector request. Then the compiler
# looks up the node, and collects its facts, which we could have sent
# in the first place. This seems like a bug.
Puppet::Resource::Catalog.indirection.terminus_class = :compiler
expect(Puppet::Resource::Catalog.indirection).to receive(:find) do |name, options|
expect(options[:facts]).to be_nil
end.and_return(catalog)
configurer.run
end
end
describe "when using a REST terminus for catalogs" do
it "should pass the url encoded facts and facts format as arguments when retrieving the catalog" do
Puppet::Resource::Catalog.indirection.terminus_class = :rest
facts.values = { 'foo' => 'bar' }
Puppet::Node::Facts.indirection.save(facts)
expect(
Puppet::Resource::Catalog.indirection
).to receive(:find) do |_, options|
expect(options[:facts_format]).to eq("application/json")
unescaped = JSON.parse(CGI.unescape(options[:facts]))
expect(unescaped).to include("values" => {"foo" => "bar"})
end.and_return(catalog)
configurer.run
end
end
end
describe "when sending a report" do
include PuppetSpec::Files
before do
Puppet[:lastrunfile] = tmpfile('last_run_file')
Puppet[:reports] = "none"
end
it "should print a report summary if configured to do so" do
Puppet.settings[:summarize] = true
expect(report).to receive(:summary).and_return("stuff")
expect(configurer).to receive(:puts).with("stuff")
configurer.send_report(report)
end
it "should not print a report summary if not configured to do so" do
Puppet.settings[:summarize] = false
expect(configurer).not_to receive(:puts)
configurer.send_report(report)
end
it "should save the report if reporting is enabled" do
Puppet.settings[:report] = true
expect(Puppet::Transaction::Report.indirection).to receive(:save).with(report, nil, instance_of(Hash)).twice
configurer.send_report(report)
end
it "should not save the report if reporting is disabled" do
Puppet.settings[:report] = false
expect(Puppet::Transaction::Report.indirection).not_to receive(:save).with(report, nil, instance_of(Hash))
configurer.send_report(report)
end
it "should save the last run summary if reporting is enabled" do
Puppet.settings[:report] = true
expect(configurer).to receive(:save_last_run_summary).with(report)
configurer.send_report(report)
end
it "should save the last run summary if reporting is disabled" do
Puppet.settings[:report] = false
expect(configurer).to receive(:save_last_run_summary).with(report)
configurer.send_report(report)
end
it "should log but not fail if saving the report fails" do
Puppet.settings[:report] = true
expect(Puppet::Transaction::Report.indirection).to receive(:save).with(report, nil, hash_including(ignore_cache: true)).and_raise("whatever")
expect(Puppet::Transaction::Report.indirection).to receive(:save).with(report, nil, hash_including(ignore_terminus: true))
configurer.send_report(report)
expect(@logs).to include(an_object_having_attributes(level: :err, message: 'Could not send report: whatever'))
end
it "should save the cached report if fails to send the report" do
allow(Puppet::Transaction::Report.indirection).to receive(:save).with(report, nil, hash_including(ignore_terminus: true)).and_call_original
allow(Puppet::Transaction::Report.indirection).to receive(:save).with(report, nil, hash_including(ignore_cache: true)).and_raise("whatever")
expect(File).to_not be_exist(Puppet[:lastrunfile])
configurer.send_report(report)
expect(File.read(Puppet[:lastrunfile])).to match(/puppet: #{Puppet::PUPPETVERSION}/)
end
end
describe "when saving the summary report file" do
include PuppetSpec::Files
before do
Puppet[:lastrunfile] = tmpfile('last_run_file')
end
it "should write the last run file" do
configurer.save_last_run_summary(report)
expect(Puppet::FileSystem.exist?(Puppet[:lastrunfile])).to be_truthy
end
it "should write the raw summary as yaml" do
expect(report).to receive(:raw_summary).and_return("summary")
configurer.save_last_run_summary(report)
expect(File.read(Puppet[:lastrunfile])).to eq(YAML.dump("summary"))
end
it "should log but not fail if saving the last run summary fails" do
# The mock will raise an exception on any method used. This should
# simulate a nice hard failure from the underlying OS for us.
fh = Class.new(Object) do
def method_missing(*args)
raise "failed to do #{args[0]}"
end
end.new
expect(Puppet::Util).to receive(:replace_file).and_yield(fh)
configurer.save_last_run_summary(report)
expect(@logs).to include(an_object_having_attributes(level: :err, message: 'Could not save last run local report: failed to do print'))
end
it "should create the last run file with the correct mode" do
expect(Puppet.settings.setting(:lastrunfile)).to receive(:mode).and_return('664')
configurer.save_last_run_summary(report)
if Puppet::Util::Platform.windows?
require 'puppet/util/windows/security'
mode = Puppet::Util::Windows::Security.get_mode(Puppet[:lastrunfile])
else
mode = Puppet::FileSystem.stat(Puppet[:lastrunfile]).mode
end
expect(mode & 0777).to eq(0664)
end
it "should report invalid last run file permissions" do
expect(Puppet.settings.setting(:lastrunfile)).to receive(:mode).and_return('892')
configurer.save_last_run_summary(report)
expect(@logs).to include(an_object_having_attributes(level: :err, message: /Could not save last run local report.*892 is invalid/))
end
end
def expects_pluginsync
metadata = "[{\"path\":\"/etc/puppetlabs/code\",\"relative_path\":\".\",\"links\":\"follow\",\"owner\":0,\"group\":0,\"mode\":420,\"checksum\":{\"type\":\"ctime\",\"value\":\"{ctime}2020-07-10 14:00:00 -0700\"},\"type\":\"directory\",\"destination\":null}]"
stub_request(:get, %r{/puppet/v3/file_metadatas/(plugins|locales)}).to_return(status: 200, body: metadata, headers: {'Content-Type' => 'application/json'})
# response retains owner/group/mode due to source_permissions => use
facts_metadata = "[{\"path\":\"/etc/puppetlabs/code\",\"relative_path\":\".\",\"links\":\"follow\",\"owner\":500,\"group\":500,\"mode\":493,\"checksum\":{\"type\":\"ctime\",\"value\":\"{ctime}2020-07-10 14:00:00 -0700\"},\"type\":\"directory\",\"destination\":null}]"
stub_request(:get, %r{/puppet/v3/file_metadatas/pluginfacts}).to_return(status: 200, body: facts_metadata, headers: {'Content-Type' => 'application/json'})
end
def expects_new_catalog_only(catalog)
expect(Puppet::Resource::Catalog.indirection).to receive(:find).with(anything, hash_including(ignore_cache: true, check_environment: true)).and_return(catalog)
expect(Puppet::Resource::Catalog.indirection).not_to receive(:find).with(anything, hash_including(ignore_terminus: true))
end
def expects_cached_catalog_only(catalog)
expect(Puppet::Resource::Catalog.indirection).to receive(:find).with(anything, hash_including(ignore_terminus: true)).and_return(catalog)
expect(Puppet::Resource::Catalog.indirection).not_to receive(:find).with(anything, hash_including(ignore_cache: true))
end
def expects_fallback_to_cached_catalog(catalog)
expect(Puppet::Resource::Catalog.indirection).to receive(:find).with(anything, hash_including(ignore_cache: true)).and_return(nil)
expect(Puppet::Resource::Catalog.indirection).to receive(:find).with(anything, hash_including(ignore_terminus: true)).and_return(catalog)
end
def expects_fallback_to_new_catalog(catalog)
expects_pluginsync
expect(Puppet::Resource::Catalog.indirection).to receive(:find).with(anything, hash_including(ignore_terminus: true)).and_return(nil)
expect(Puppet::Resource::Catalog.indirection).to receive(:find).with(anything, hash_including(ignore_cache: true, check_environment: true)).and_return(catalog)
end
def expects_neither_new_or_cached_catalog
expect(Puppet::Resource::Catalog.indirection).to receive(:find).with(anything, hash_including(ignore_cache: true)).and_return(nil)
expect(Puppet::Resource::Catalog.indirection).to receive(:find).with(anything, hash_including(ignore_terminus: true)).and_return(nil)
end
describe "when retrieving a catalog" do
before do
allow(Puppet::Resource::Catalog.indirection).to receive(:terminus_class).and_return(:rest)
end
describe "and configured to only retrieve a catalog from the cache" do
before do
Puppet.settings[:use_cached_catalog] = true
end
it "should first look in the cache for a catalog" do
expects_cached_catalog_only(catalog)
configurer.run
end
it "should not pluginsync when a cached catalog is successfully retrieved" do
expects_cached_catalog_only(catalog)
expect(configurer).not_to receive(:download_plugins)
configurer.run
end
it "should set its cached_catalog_status to 'explicitly_requested'" do
expects_cached_catalog_only(catalog)
options = {}
configurer.run(options)
expect(options[:report].cached_catalog_status).to eq('explicitly_requested')
end
it "should set its cached_catalog_status to 'explicitly requested' if the cached catalog is from a different environment" do
cached_catalog = Puppet::Resource::Catalog.new(node_name, Puppet::Node::Environment.remote('second_env'))
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | true |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/module_spec.rb | spec/unit/module_spec.rb | require 'spec_helper'
require 'puppet_spec/files'
require 'puppet_spec/modules'
require 'puppet/module_tool/checksums'
describe Puppet::Module do
include PuppetSpec::Files
let(:env) { double("environment") }
let(:path) { "/path" }
let(:name) { "mymod" }
let(:mod) { Puppet::Module.new(name, path, env) }
before do
# This is necessary because of the extra checks we have for the deprecated
# 'plugins' directory
allow(Puppet::FileSystem).to receive(:exist?).and_return(false)
end
it "should have a class method that returns a named module from a given environment" do
env = Puppet::Node::Environment.create(:myenv, [])
expect(env).to receive(:module).with(name).and_return("yep")
Puppet.override(:environments => Puppet::Environments::Static.new(env)) do
expect(Puppet::Module.find(name, "myenv")).to eq("yep")
end
end
it "should return nil if asked for a named module that doesn't exist" do
env = Puppet::Node::Environment.create(:myenv, [])
expect(env).to receive(:module).with(name).and_return(nil)
Puppet.override(:environments => Puppet::Environments::Static.new(env)) do
expect(Puppet::Module.find(name, "myenv")).to be_nil
end
end
describe "is_module_directory?" do
let(:first_modulepath) { tmpdir('firstmodules') }
let(:not_a_module) { tmpfile('thereisnomodule', first_modulepath) }
it "should return false for a non-directory" do
expect(Puppet::Module.is_module_directory?('thereisnomodule', first_modulepath)).to be_falsey
end
it "should return true for a well named directories" do
PuppetSpec::Modules.generate_files('foo', first_modulepath)
PuppetSpec::Modules.generate_files('foo2', first_modulepath)
PuppetSpec::Modules.generate_files('foo_bar', first_modulepath)
expect(Puppet::Module.is_module_directory?('foo', first_modulepath)).to be_truthy
expect(Puppet::Module.is_module_directory?('foo2', first_modulepath)).to be_truthy
expect(Puppet::Module.is_module_directory?('foo_bar', first_modulepath)).to be_truthy
end
it "should return false for badly named directories" do
PuppetSpec::Modules.generate_files('foo=bar', first_modulepath)
PuppetSpec::Modules.generate_files('.foo', first_modulepath)
expect(Puppet::Module.is_module_directory?('foo=bar', first_modulepath)).to be_falsey
expect(Puppet::Module.is_module_directory?('.foo', first_modulepath)).to be_falsey
end
end
describe "is_module_directory_name?" do
it "should return true for a valid directory module name" do
expect(Puppet::Module.is_module_directory_name?('foo')).to be_truthy
expect(Puppet::Module.is_module_directory_name?('foo2')).to be_truthy
expect(Puppet::Module.is_module_directory_name?('foo_bar')).to be_truthy
end
it "should return false for badly formed directory module names" do
expect(Puppet::Module.is_module_directory_name?('foo-bar')).to be_falsey
expect(Puppet::Module.is_module_directory_name?('foo=bar')).to be_falsey
expect(Puppet::Module.is_module_directory_name?('foo bar')).to be_falsey
expect(Puppet::Module.is_module_directory_name?('foo.bar')).to be_falsey
expect(Puppet::Module.is_module_directory_name?('-foo')).to be_falsey
expect(Puppet::Module.is_module_directory_name?('foo-')).to be_falsey
expect(Puppet::Module.is_module_directory_name?('foo--bar')).to be_falsey
expect(Puppet::Module.is_module_directory_name?('.foo')).to be_falsey
end
end
describe "is_module_namespaced_name?" do
it "should return true for a valid namespaced module name" do
expect(Puppet::Module.is_module_namespaced_name?('foo-bar')).to be_truthy
end
it "should return false for badly formed namespaced module names" do
expect(Puppet::Module.is_module_namespaced_name?('foo')).to be_falsey
expect(Puppet::Module.is_module_namespaced_name?('.foo-bar')).to be_falsey
expect(Puppet::Module.is_module_namespaced_name?('foo2')).to be_falsey
expect(Puppet::Module.is_module_namespaced_name?('foo_bar')).to be_falsey
expect(Puppet::Module.is_module_namespaced_name?('foo=bar')).to be_falsey
expect(Puppet::Module.is_module_namespaced_name?('foo bar')).to be_falsey
expect(Puppet::Module.is_module_namespaced_name?('foo.bar')).to be_falsey
expect(Puppet::Module.is_module_namespaced_name?('-foo')).to be_falsey
expect(Puppet::Module.is_module_namespaced_name?('foo-')).to be_falsey
expect(Puppet::Module.is_module_namespaced_name?('foo--bar')).to be_falsey
end
end
describe "attributes" do
it "should support a 'version' attribute" do
mod.version = 1.09
expect(mod.version).to eq(1.09)
end
it "should support a 'source' attribute" do
mod.source = "http://foo/bar"
expect(mod.source).to eq("http://foo/bar")
end
it "should support a 'project_page' attribute" do
mod.project_page = "http://foo/bar"
expect(mod.project_page).to eq("http://foo/bar")
end
it "should support an 'author' attribute" do
mod.author = "Luke Kanies <luke@madstop.com>"
expect(mod.author).to eq("Luke Kanies <luke@madstop.com>")
end
it "should support a 'license' attribute" do
mod.license = "GPL2"
expect(mod.license).to eq("GPL2")
end
it "should support a 'summary' attribute" do
mod.summary = "GPL2"
expect(mod.summary).to eq("GPL2")
end
it "should support a 'description' attribute" do
mod.description = "GPL2"
expect(mod.description).to eq("GPL2")
end
end
describe "when finding unmet dependencies" do
before do
allow(Puppet::FileSystem).to receive(:exist?).and_call_original
@modpath = tmpdir('modpath')
Puppet.settings[:modulepath] = @modpath
end
it "should resolve module dependencies using forge names" do
parent = PuppetSpec::Modules.create(
'parent',
@modpath,
:metadata => {
:author => 'foo',
:dependencies => [{
"name" => "foo/child"
}]
},
:environment => env
)
child = PuppetSpec::Modules.create(
'child',
@modpath,
:metadata => {
:author => 'foo',
:dependencies => []
},
:environment => env
)
expect(env).to receive(:module_by_forge_name).with('foo/child').and_return(child)
expect(parent.unmet_dependencies).to eq([])
end
it "should list modules that are missing" do
mod = PuppetSpec::Modules.create(
'needy',
@modpath,
:metadata => {
:dependencies => [{
"version_requirement" => ">= 2.2.0",
"name" => "baz/foobar"
}]
},
:environment => env
)
expect(env).to receive(:module_by_forge_name).with('baz/foobar').and_return(nil)
expect(mod.unmet_dependencies).to eq([{
:reason => :missing,
:name => "baz/foobar",
:version_constraint => ">= 2.2.0",
:parent => { :name => 'puppetlabs/needy', :version => 'v9.9.9' },
:mod_details => { :installed_version => nil }
}])
end
it "should list modules that are missing and have invalid names" do
mod = PuppetSpec::Modules.create(
'needy',
@modpath,
:metadata => {
:dependencies => [{
"version_requirement" => ">= 2.2.0",
"name" => "baz/foobar=bar"
}]
},
:environment => env
)
expect(env).to receive(:module_by_forge_name).with('baz/foobar=bar').and_return(nil)
expect(mod.unmet_dependencies).to eq([{
:reason => :missing,
:name => "baz/foobar=bar",
:version_constraint => ">= 2.2.0",
:parent => { :name => 'puppetlabs/needy', :version => 'v9.9.9' },
:mod_details => { :installed_version => nil }
}])
end
it "should list modules with unmet version requirement" do
env = Puppet::Node::Environment.create(:testing, [@modpath])
['test_gte_req', 'test_specific_req', 'foobar'].each do |mod_name|
mod_dir = "#{@modpath}/#{mod_name}"
metadata_file = "#{mod_dir}/metadata.json"
allow(Puppet::FileSystem).to receive(:exist?).with(metadata_file).and_return(true)
end
mod = PuppetSpec::Modules.create(
'test_gte_req',
@modpath,
:metadata => {
:dependencies => [{
"version_requirement" => ">= 2.2.0",
"name" => "baz/foobar"
}]
},
:environment => env
)
mod2 = PuppetSpec::Modules.create(
'test_specific_req',
@modpath,
:metadata => {
:dependencies => [{
"version_requirement" => "1.0.0",
"name" => "baz/foobar"
}]
},
:environment => env
)
PuppetSpec::Modules.create(
'foobar',
@modpath,
:metadata => { :version => '2.0.0', :author => 'baz' },
:environment => env
)
expect(mod.unmet_dependencies).to eq([{
:reason => :version_mismatch,
:name => "baz/foobar",
:version_constraint => ">= 2.2.0",
:parent => { :version => "v9.9.9", :name => "puppetlabs/test_gte_req" },
:mod_details => { :installed_version => "2.0.0" }
}])
expect(mod2.unmet_dependencies).to eq([{
:reason => :version_mismatch,
:name => "baz/foobar",
:version_constraint => "v1.0.0",
:parent => { :version => "v9.9.9", :name => "puppetlabs/test_specific_req" },
:mod_details => { :installed_version => "2.0.0" }
}])
end
it "should consider a dependency without a version requirement to be satisfied" do
env = Puppet::Node::Environment.create(:testing, [@modpath])
mod = PuppetSpec::Modules.create(
'foobar',
@modpath,
:metadata => {
:dependencies => [{
"name" => "baz/foobar"
}]
},
:environment => env
)
PuppetSpec::Modules.create(
'foobar',
@modpath,
:metadata => {
:version => '2.0.0',
:author => 'baz'
},
:environment => env
)
expect(mod.unmet_dependencies).to be_empty
end
it "should consider a dependency without a semantic version to be unmet" do
env = Puppet::Node::Environment.create(:testing, [@modpath])
mod = PuppetSpec::Modules.create(
'foobar',
@modpath,
:metadata => {
:dependencies => [{
"name" => "baz/foobar"
}]
},
:environment => env
)
PuppetSpec::Modules.create(
'foobar',
@modpath,
:metadata => {
:version => '5.1',
:author => 'baz'
},
:environment => env
)
expect(mod.unmet_dependencies).to eq([{
:reason => :non_semantic_version,
:parent => { :version => "v9.9.9", :name => "puppetlabs/foobar" },
:mod_details => { :installed_version => "5.1" },
:name => "baz/foobar",
:version_constraint => ">= 0.0.0"
}])
end
it "should have valid dependencies when no dependencies have been specified" do
mod = PuppetSpec::Modules.create(
'foobar',
@modpath,
:metadata => {
:dependencies => []
}
)
expect(mod.unmet_dependencies).to eq([])
end
it "should throw an error if invalid dependencies are specified" do
expect {
PuppetSpec::Modules.create(
'foobar',
@modpath,
:metadata => {
:dependencies => ""
}
)
}.to raise_error(
Puppet::Module::MissingMetadata,
/dependencies in the file metadata.json of the module foobar must be an array, not: ''/)
end
it "should only list unmet dependencies" do
env = Puppet::Node::Environment.create(:testing, [@modpath])
mod = PuppetSpec::Modules.create(
name,
@modpath,
:metadata => {
:dependencies => [
{
"version_requirement" => ">= 2.2.0",
"name" => "baz/satisfied"
},
{
"version_requirement" => ">= 2.2.0",
"name" => "baz/notsatisfied"
}
]
},
:environment => env
)
PuppetSpec::Modules.create(
'satisfied',
@modpath,
:metadata => {
:version => '3.3.0',
:author => 'baz'
},
:environment => env
)
expect(mod.unmet_dependencies).to eq([{
:reason => :missing,
:mod_details => { :installed_version => nil },
:parent => { :version => "v9.9.9", :name => "puppetlabs/#{name}" },
:name => "baz/notsatisfied",
:version_constraint => ">= 2.2.0"
}])
end
it "should be empty when all dependencies are met" do
env = Puppet::Node::Environment.create(:testing, [@modpath])
mod = PuppetSpec::Modules.create(
'mymod2',
@modpath,
:metadata => {
:dependencies => [
{
"version_requirement" => ">= 2.2.0",
"name" => "baz/satisfied"
},
{
"version_requirement" => "< 2.2.0",
"name" => "baz/alsosatisfied"
}
]
},
:environment => env
)
PuppetSpec::Modules.create(
'satisfied',
@modpath,
:metadata => {
:version => '3.3.0',
:author => 'baz'
},
:environment => env
)
PuppetSpec::Modules.create(
'alsosatisfied',
@modpath,
:metadata => {
:version => '2.1.0',
:author => 'baz'
},
:environment => env
)
expect(mod.unmet_dependencies).to be_empty
end
end
describe "when managing supported platforms" do
it "should support specifying a supported platform" do
mod.supports "solaris"
end
it "should support specifying a supported platform and version" do
mod.supports "solaris", 1.0
end
end
it "should return nil if asked for a module whose name is 'nil'" do
expect(Puppet::Module.find(nil, "myenv")).to be_nil
end
it "should provide support for logging" do
expect(Puppet::Module.ancestors).to be_include(Puppet::Util::Logging)
end
it "should be able to be converted to a string" do
expect(mod.to_s).to eq("Module #{name}(#{path})")
end
it "should fail if its name is not alphanumeric" do
expect { Puppet::Module.new(".something", "/path", env) }.to raise_error(Puppet::Module::InvalidName)
end
it "should require a name at initialization" do
expect { Puppet::Module.new }.to raise_error(ArgumentError)
end
it "should accept an environment at initialization" do
expect(Puppet::Module.new("foo", "/path", env).environment).to eq(env)
end
describe '#modulepath' do
it "should return the directory the module is installed in, if a path exists" do
mod = Puppet::Module.new("foo", "/a/foo", env)
expect(mod.modulepath).to eq('/a')
end
end
[:plugins, :pluginfacts, :templates, :files, :manifests, :scripts].each do |filetype|
case filetype
when :plugins
dirname = "lib"
when :pluginfacts
dirname = "facts.d"
else
dirname = filetype.to_s
end
it "should be able to return individual #{filetype}" do
module_file = File.join(path, dirname, "my/file")
expect(Puppet::FileSystem).to receive(:exist?).with(module_file).and_return(true)
expect(mod.send(filetype.to_s.sub(/s$/, ''), "my/file")).to eq(module_file)
end
it "should consider #{filetype} to be present if their base directory exists" do
module_file = File.join(path, dirname)
expect(Puppet::FileSystem).to receive(:exist?).with(module_file).and_return(true)
expect(mod.send(filetype.to_s + "?")).to be_truthy
end
it "should consider #{filetype} to be absent if their base directory does not exist" do
module_file = File.join(path, dirname)
expect(Puppet::FileSystem).to receive(:exist?).with(module_file).and_return(false)
expect(mod.send(filetype.to_s + "?")).to be_falsey
end
it "should return nil if asked to return individual #{filetype} that don't exist" do
module_file = File.join(path, dirname, "my/file")
expect(Puppet::FileSystem).to receive(:exist?).with(module_file).and_return(false)
expect(mod.send(filetype.to_s.sub(/s$/, ''), "my/file")).to be_nil
end
it "should return the base directory if asked for a nil path" do
base = File.join(path, dirname)
expect(Puppet::FileSystem).to receive(:exist?).with(base).and_return(true)
expect(mod.send(filetype.to_s.sub(/s$/, ''), nil)).to eq(base)
end
end
it "should return the path to the plugin directory" do
expect(mod.plugin_directory).to eq(File.join(path, "lib"))
end
it "should return the path to the tasks directory" do
expect(mod.tasks_directory).to eq(File.join(path, "tasks"))
end
it "should return the path to the plans directory" do
expect(mod.plans_directory).to eq(File.join(path, "plans"))
end
describe "when finding tasks" do
before do
allow(Puppet::FileSystem).to receive(:exist?).and_call_original
@modpath = tmpdir('modpath')
Puppet.settings[:modulepath] = @modpath
end
it "should have an empty array for the tasks when the tasks directory does not exist" do
mod = PuppetSpec::Modules.create('tasks_test_nodir', @modpath, :environment => env)
expect(mod.tasks).to eq([])
end
it "should have an empty array for the tasks when the tasks directory does exist and is empty" do
mod = PuppetSpec::Modules.create('tasks_test_empty', @modpath, {:environment => env,
:tasks => []})
expect(mod.tasks).to eq([])
end
it "should list the expected tasks when the required files exist" do
fake_tasks = [['task1'], ['task2.sh', 'task2.json']]
mod = PuppetSpec::Modules.create('tasks_smoke', @modpath, {:environment => env,
:tasks => fake_tasks})
expect(mod.tasks.count).to eq(2)
expect(mod.tasks.map{|t| t.name}.sort).to eq(['tasks_smoke::task1', 'tasks_smoke::task2'])
expect(mod.tasks.map{|t| t.class}).to eq([Puppet::Module::Task] * 2)
end
it "should be able to find individual task files when they exist" do
task_exe = 'stateskatetask.stk'
mod = PuppetSpec::Modules.create('task_file_smoke', @modpath, {:environment => env,
:tasks => [[task_exe]]})
expect(mod.task_file(task_exe)).to eq("#{mod.path}/tasks/#{task_exe}")
end
it "should list files from the scripts directory if required by the task" do
mod = 'loads_scripts'
task_dep = 'myscript.sh'
script_ref = "#{mod}/scripts/#{task_dep}"
task_json = JSON.generate({'files' => [script_ref]})
task = [['task', { name: 'task.json', content: task_json }]]
mod = PuppetSpec::Modules.create(mod, @modpath, {:environment => env,
:scripts => [task_dep],
:tasks => task})
expect(mod.tasks.first.files).to include({'name' => script_ref,
'path' => /#{script_ref}/})
end
it "should return nil when asked for an individual task file if it does not exist" do
mod = PuppetSpec::Modules.create('task_file_neg', @modpath, {:environment => env,
:tasks => []})
expect(mod.task_file('nosuchtask')).to be_nil
end
describe "does the task finding" do
let(:mod_name) { 'tasks_test_lazy' }
let(:mod_tasks_dir) { File.join(@modpath, mod_name, 'tasks') }
it "after the module is initialized" do
expect(Puppet::FileSystem).not_to receive(:exist?).with(mod_tasks_dir)
expect(Puppet::Module::Task).not_to receive(:tasks_in_module)
Puppet::Module.new(mod_name, @modpath, env)
end
it "when the tasks method is called" do
expect(Puppet::Module::Task).to receive(:tasks_in_module)
mod = PuppetSpec::Modules.create(mod_name, @modpath, {:environment => env,
:tasks => [['itascanstaccatotask']]})
mod.tasks
end
it "only once for the lifetime of the module object" do
expect(Dir).to receive(:glob).with("#{mod_tasks_dir}/*").once.and_return(['allalaskataskattacktactics'])
mod = PuppetSpec::Modules.create(mod_name, @modpath, {:environment => env,
:tasks => []})
mod.tasks
mod.tasks
end
end
end
describe "when finding plans" do
before do
allow(Puppet::FileSystem).to receive(:exist?).and_call_original
@modpath = tmpdir('modpath')
Puppet.settings[:modulepath] = @modpath
end
it "should have an empty array for the plans when the plans directory does not exist" do
mod = PuppetSpec::Modules.create('plans_test_nodir', @modpath, :environment => env)
expect(mod.plans).to eq([])
end
it "should have an empty array for the plans when the plans directory does exist and is empty" do
mod = PuppetSpec::Modules.create('plans_test_empty', @modpath, {:environment => env,
:plans => []})
expect(mod.plans).to eq([])
end
it "should list the expected plans when the required files exist" do
fake_plans = ['plan1.pp', 'plan2.yaml']
mod = PuppetSpec::Modules.create('plans_smoke', @modpath, {:environment => env,
:plans => fake_plans})
expect(mod.plans.count).to eq(2)
expect(mod.plans.map{|t| t.name}.sort).to eq(['plans_smoke::plan1', 'plans_smoke::plan2'])
expect(mod.plans.map{|t| t.class}).to eq([Puppet::Module::Plan] * 2)
end
it "should be able to find individual plan files when they exist" do
plan_exe = 'stateskateplan.pp'
mod = PuppetSpec::Modules.create('plan_file_smoke', @modpath, {:environment => env,
:plans => [plan_exe]})
expect(mod.plan_file(plan_exe)).to eq("#{mod.path}/plans/#{plan_exe}")
end
it "should return nil when asked for an individual plan file if it does not exist" do
mod = PuppetSpec::Modules.create('plan_file_neg', @modpath, {:environment => env,
:plans => []})
expect(mod.plan_file('nosuchplan')).to be_nil
end
describe "does the plan finding" do
let(:mod_name) { 'plans_test_lazy' }
let(:mod_plans_dir) { File.join(@modpath, mod_name, 'plans') }
it "after the module is initialized" do
expect(Puppet::FileSystem).not_to receive(:exist?).with(mod_plans_dir)
expect(Puppet::Module::Plan).not_to receive(:plans_in_module)
Puppet::Module.new(mod_name, @modpath, env)
end
it "when the plans method is called" do
expect(Puppet::Module::Plan).to receive(:plans_in_module)
mod = PuppetSpec::Modules.create(mod_name, @modpath, {:environment => env,
:plans => ['itascanstaccatoplan.yaml']})
mod.plans
end
it "only once for the lifetime of the module object" do
expect(Dir).to receive(:glob).with("#{mod_plans_dir}/*").once.and_return(['allalaskaplanattacktactics'])
mod = PuppetSpec::Modules.create(mod_name, @modpath, {:environment => env,
:plans => []})
mod.plans
mod.plans
end
end
end
end
describe Puppet::Module, "when finding matching manifests" do
before do
@mod = Puppet::Module.new("mymod", "/a", double("environment"))
@pq_glob_with_extension = "yay/*.xx"
@fq_glob_with_extension = "/a/manifests/#{@pq_glob_with_extension}"
end
it "should return all manifests matching the glob pattern" do
expect(Dir).to receive(:glob).with(@fq_glob_with_extension).and_return(%w{foo bar})
allow(FileTest).to receive(:directory?).and_return(false)
expect(@mod.match_manifests(@pq_glob_with_extension)).to eq(%w{foo bar})
end
it "should not return directories" do
expect(Dir).to receive(:glob).with(@fq_glob_with_extension).and_return(%w{foo bar})
expect(FileTest).to receive(:directory?).with("foo").and_return(false)
expect(FileTest).to receive(:directory?).with("bar").and_return(true)
expect(@mod.match_manifests(@pq_glob_with_extension)).to eq(%w{foo})
end
it "should default to the 'init' file if no glob pattern is specified" do
expect(Puppet::FileSystem).to receive(:exist?).with("/a/manifests/init.pp").and_return(true)
expect(@mod.match_manifests(nil)).to eq(%w{/a/manifests/init.pp})
end
it "should return all manifests matching the glob pattern in all existing paths" do
expect(Dir).to receive(:glob).with(@fq_glob_with_extension).and_return(%w{a b})
expect(@mod.match_manifests(@pq_glob_with_extension)).to eq(%w{a b})
end
it "should match the glob pattern plus '.pp' if no extension is specified" do
expect(Dir).to receive(:glob).with("/a/manifests/yay/foo.pp").and_return(%w{yay})
expect(@mod.match_manifests("yay/foo")).to eq(%w{yay})
end
it "should return an empty array if no manifests matched" do
expect(Dir).to receive(:glob).with(@fq_glob_with_extension).and_return([])
expect(@mod.match_manifests(@pq_glob_with_extension)).to eq([])
end
it "should raise an error if the pattern tries to leave the manifest directory" do
expect do
@mod.match_manifests("something/../../*")
end.to raise_error(Puppet::Module::InvalidFilePattern, 'The pattern "something/../../*" to find manifests in the module "mymod" is invalid and potentially unsafe.')
end
end
describe Puppet::Module do
include PuppetSpec::Files
let!(:modpath) do
path = tmpdir('modpath')
PuppetSpec::Modules.create('mymod', path)
path
end
let!(:mymodpath) { File.join(modpath, 'mymod') }
let!(:mymod_metadata) { File.join(mymodpath, 'metadata.json') }
let(:mymod) { Puppet::Module.new('mymod', mymodpath, nil) }
it "should use 'License' in its current path as its metadata file" do
expect(mymod.license_file).to eq("#{modpath}/mymod/License")
end
it "should cache the license file" do
expect(mymod).to receive(:path).once.and_return(nil)
mymod.license_file
mymod.license_file
end
it "should use 'metadata.json' in its current path as its metadata file" do
expect(mymod_metadata).to eq("#{modpath}/mymod/metadata.json")
end
it "should not have metadata if it has a metadata file and its data is valid but empty json hash" do
allow(File).to receive(:read).with(mymod_metadata, {:encoding => 'utf-8'}).and_return("{}")
expect(mymod).not_to be_has_metadata
end
it "should not have metadata if it has a metadata file and its data is empty" do
Puppet[:strict] = :warning
allow(File).to receive(:read).with(mymod_metadata, {:encoding => 'utf-8'}).and_return("")
expect(mymod).not_to be_has_metadata
end
it "should not have metadata if has a metadata file and its data is invalid" do
Puppet[:strict] = :warning
allow(File).to receive(:read).with(mymod_metadata, {:encoding => 'utf-8'}).and_return("This is some invalid json.\n")
expect(mymod).not_to be_has_metadata
end
it "should know if it is missing a metadata file" do
allow(File).to receive(:read).with(mymod_metadata, {:encoding => 'utf-8'}).and_raise(Errno::ENOENT)
expect(mymod).not_to be_has_metadata
end
it "should be able to parse its metadata file" do
expect(mymod).to respond_to(:load_metadata)
end
it "should parse its metadata file on initialization if it is present" do
expect_any_instance_of(Puppet::Module).to receive(:load_metadata)
Puppet::Module.new("yay", "/path", double("env"))
end
describe 'when --strict is warning' do
before :each do
Puppet[:strict] = :warning
end
it "should warn about a failure to parse" do
allow(File).to receive(:read).with(mymod_metadata, {:encoding => 'utf-8'}).and_return(my_fixture('trailing-comma.json'))
expect(mymod.has_metadata?).to be_falsey
expect(@logs).to have_matching_log(/mymod has an invalid and unparsable metadata\.json file/)
end
end
describe 'when --strict is off' do
before :each do
Puppet[:strict] = :off
end
it "should not warn about a failure to parse" do
allow(File).to receive(:read).with(mymod_metadata, {:encoding => 'utf-8'}).and_return(my_fixture('trailing-comma.json'))
expect(mymod.has_metadata?).to be_falsey
expect(@logs).to_not have_matching_log(/mymod has an invalid and unparsable metadata\.json file.*/)
end
it "should log debug output about a failure to parse when --debug is on" do
Puppet[:log_level] = :debug
allow(File).to receive(:read).with(mymod_metadata, {:encoding => 'utf-8'}).and_return(my_fixture('trailing-comma.json'))
expect(mymod.has_metadata?).to be_falsey
expect(@logs).to have_matching_log(/mymod has an invalid and unparsable metadata\.json file.*/)
end
end
describe 'when --strict is error' do
before :each do
Puppet[:strict] = :error
end
it "should fail on a failure to parse" do
allow(File).to receive(:read).with(mymod_metadata, {:encoding => 'utf-8'}).and_return(my_fixture('trailing-comma.json'))
expect do
expect(mymod.has_metadata?).to be_falsey
end.to raise_error(/mymod has an invalid and unparsable metadata\.json file/)
end
end
def a_module_with_metadata(data)
allow(File).to receive(:read).with("/path/metadata.json", {:encoding => 'utf-8'}).and_return(data.to_json)
Puppet::Module.new("foo", "/path", double("env"))
end
describe "when loading the metadata file" do
let(:data) do
{
:license => "GPL2",
:author => "luke",
:version => "1.0",
:source => "http://foo/",
:dependencies => []
}
end
%w{source author version license}.each do |attr|
it "should set #{attr} if present in the metadata file" do
mod = a_module_with_metadata(data)
expect(mod.send(attr)).to eq(data[attr.to_sym])
end
it "should fail if #{attr} is not present in the metadata file" do
data.delete(attr.to_sym)
expect { a_module_with_metadata(data) }.to raise_error(
Puppet::Module::MissingMetadata,
"No #{attr} module metadata provided for foo"
)
end
end
end
describe "when loading the metadata file from disk" do
it "should properly parse utf-8 contents" do
rune_utf8 = "\u16A0\u16C7\u16BB" # ᚠᛇᚻ
metadata_json = tmpfile('metadata.json')
File.open(metadata_json, 'w:UTF-8') do |file|
file.puts <<-EOF
{
"license" : "GPL2",
"author" : "#{rune_utf8}",
"version" : "1.0",
"source" : "http://foo/",
"dependencies" : []
}
EOF
end
allow_any_instance_of(Puppet::Module).to receive(:metadata_file).and_return(metadata_json)
mod = Puppet::Module.new('foo', '/path', double('env'))
mod.load_metadata
expect(mod.author).to eq(rune_utf8)
end
end
it "should be able to tell if there are local changes" do
modpath = tmpdir('modpath')
foo_checksum = 'acbd18db4cc2f85cedef654fccc4a4d8'
checksummed_module = PuppetSpec::Modules.create(
'changed',
modpath,
:metadata => {
:checksums => {
"foo" => foo_checksum,
}
}
)
foo_path = Pathname.new(File.join(checksummed_module.path, 'foo'))
IO.binwrite(foo_path, 'notfoo')
expect(Puppet::ModuleTool::Checksums.new(foo_path).checksum(foo_path)).not_to eq(foo_checksum)
IO.binwrite(foo_path, 'foo')
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | true |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/forge_spec.rb | spec/unit/forge_spec.rb | require 'spec_helper'
require 'spec_helper'
require 'net/http'
require 'puppet/forge'
require 'puppet/module_tool'
describe Puppet::Forge do
let(:http_response) do
File.read(my_fixture('bacula.json'))
end
let(:search_results) do
JSON.parse(http_response)['results'].map do |hash|
hash.merge(
"author" => "puppetlabs",
"name" => "bacula",
"tag_list" => ["backup", "bacula"],
"full_name" => "puppetlabs/bacula",
"version" => "0.0.2",
"project_url" => "https://github.com/puppetlabs/puppetlabs-bacula",
"desc" => "bacula"
)
end
end
let(:release_response) do
releases = JSON.parse(http_response)
releases['results'] = []
JSON.dump(releases)
end
let(:forge) { Puppet::Forge.new }
it "returns a list of matches from the forge when there are matches for the search term" do
stub_request(:get, "https://forgeapi.puppet.com/v3/modules?query=bacula").to_return(status: 200, body: http_response)
expect(forge.search('bacula')).to eq(search_results)
end
context "when module_groups are defined" do
before :each do
Puppet[:module_groups] = "foo"
end
it "passes module_groups with search" do
stub_request(:get, "https://forgeapi.puppet.com/v3/modules")
.with(query: hash_including("module_groups" => "foo"))
.to_return(status: 200, body: release_response)
forge.search('bacula')
end
it "passes module_groups with fetch" do
stub_request(:get, "https://forgeapi.puppet.com/v3/releases")
.with(query: hash_including("module_groups" => "foo"))
.to_return(status: 200, body: release_response)
forge.fetch('puppetlabs-bacula')
end
end
# See PUP-8008
context "when multiple module_groups are defined" do
context "with space seperator" do
before :each do
Puppet[:module_groups] = "foo bar"
end
it "passes module_groups with search" do
stub_request(:get, %r{forgeapi.puppet.com/v3/modules}).with do |req|
expect(req.uri.query).to match(/module_groups=foo%20bar/)
end.to_return(status: 200, body: release_response)
forge.search('bacula')
end
it "passes module_groups with fetch" do
stub_request(:get, %r{forgeapi.puppet.com/v3/releases}).with do |req|
expect(req.uri.query).to match(/module_groups=foo%20bar/)
end.to_return(status: 200, body: release_response)
forge.fetch('puppetlabs-bacula')
end
end
context "with plus seperator" do
before :each do
Puppet[:module_groups] = "foo+bar"
end
it "passes module_groups with search" do
stub_request(:get, %r{forgeapi.puppet.com/v3/modules}).with do |req|
expect(req.uri.query).to match(/module_groups=foo%20bar/)
end.to_return(status: 200, body: release_response)
forge.search('bacula')
end
it "passes module_groups with fetch" do
stub_request(:get, %r{forgeapi.puppet.com/v3/releases}).with do |req|
expect(req.uri.query).to match(/module_groups=foo%20bar/)
end.to_return(status: 200, body: release_response)
forge.fetch('puppetlabs-bacula')
end
end
# See PUP-8008
context "when there are multiple pages of results" do
before(:each) do
stub_request(:get, %r{forgeapi.puppet.com}).with do |req|
expect(req.uri.query).to match(/module_groups=foo%20bar/)
end.to_return(status: 200, body: first_page)
.to_return(status: 200, body: last_page)
end
context "with space seperator" do
before(:each) do
Puppet[:module_groups] = "foo bar"
end
let(:first_page) do
resp = JSON.parse(http_response)
resp['results'] = []
resp['pagination']['next'] = "/v3/modules?limit=1&offset=1&module_groups=foo%20bar"
JSON.dump(resp)
end
let(:last_page) do
resp = JSON.parse(http_response)
resp['results'] = []
resp['pagination']['current'] = "/v3/modules?limit=1&offset=1&module_groups=foo%20bar"
JSON.dump(resp)
end
it "traverses pages during search" do
forge.search('bacula')
end
it "traverses pages during fetch" do
forge.fetch('puppetlabs-bacula')
end
end
context "with plus seperator" do
before(:each) do
Puppet[:module_groups] = "foo+bar"
end
let(:first_page) do
resp = JSON.parse(http_response)
resp['results'] = []
resp['pagination']['next'] = "/v3/modules?limit=1&offset=1&module_groups=foo+bar"
JSON.dump(resp)
end
let(:last_page) do
resp = JSON.parse(http_response)
resp['results'] = []
resp['pagination']['current'] = "/v3/modules?limit=1&offset=1&module_groups=foo+bar"
JSON.dump(resp)
end
it "traverses pages during search" do
forge.search('bacula')
end
it "traverses pages during fetch" do
forge.fetch('puppetlabs-bacula')
end
end
end
end
context "when the connection to the forge fails" do
before :each do
stub_request(:get, /forgeapi.puppet.com/).to_return(status: [404, 'not found'])
end
it "raises an error for search" do
expect { forge.search('bacula') }.to raise_error Puppet::Forge::Errors::ResponseError, "Request to Puppet Forge failed. Detail: 404 not found."
end
it "raises an error for fetch" do
expect { forge.fetch('puppetlabs/bacula') }.to raise_error Puppet::Forge::Errors::ResponseError, "Request to Puppet Forge failed. Detail: 404 not found."
end
end
context "when the API responds with an error" do
it "raises an error for fetch" do
stub_request(:get, /forgeapi.puppet.com/).to_return(status: [410, 'Gone'], body: '{"error":"invalid module"}')
expect { forge.fetch('puppetlabs/bacula') }.to raise_error Puppet::Forge::Errors::ResponseError, "Request to Puppet Forge failed. Detail: 410 Gone."
end
end
context "when the forge returns a module with unparseable dependencies" do
it "ignores modules with unparseable dependencies" do
response = JSON.parse(http_response)
release = response['results'][0]['current_release']
release['metadata']['dependencies'] = [{'name' => 'broken-garbage >= 1.0.0', 'version_requirement' => 'banana'}]
response['results'] = [release]
stub_request(:get, /forgeapi.puppet.com/).to_return(status: 200, body: JSON.dump(response))
expect(forge.fetch('puppetlabs/bacula')).to be_empty
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/indirector_spec.rb | spec/unit/indirector_spec.rb | require 'spec_helper'
require 'puppet/defaults'
require 'puppet/indirector'
describe Puppet::Indirector, "when configuring routes" do
before :each do
Puppet::Node.indirection.reset_terminus_class
Puppet::Node.indirection.cache_class = nil
end
after :each do
Puppet::Node.indirection.reset_terminus_class
Puppet::Node.indirection.cache_class = nil
end
it "should configure routes as requested" do
routes = {
"node" => {
"terminus" => "exec",
"cache" => "plain"
}
}
Puppet::Indirector.configure_routes(routes)
expect(Puppet::Node.indirection.terminus_class).to eq("exec")
expect(Puppet::Node.indirection.cache_class).to eq("plain")
end
it "should fail when given an invalid indirection" do
routes = {
"fake_indirection" => {
"terminus" => "exec",
"cache" => "plain"
}
}
expect { Puppet::Indirector.configure_routes(routes) }.to raise_error(/fake_indirection does not exist/)
end
it "should fail when given an invalid terminus" do
routes = {
"node" => {
"terminus" => "fake_terminus",
"cache" => "plain"
}
}
expect { Puppet::Indirector.configure_routes(routes) }.to raise_error(/Could not find terminus fake_terminus/)
end
it "should fail when given an invalid cache" do
routes = {
"node" => {
"terminus" => "exec",
"cache" => "fake_cache"
}
}
expect { Puppet::Indirector.configure_routes(routes) }.to raise_error(/Could not find terminus fake_cache/)
end
end
describe Puppet::Indirector, " when available to a model" do
before do
@thingie = Class.new do
extend Puppet::Indirector
end
end
it "should provide a way for the model to register an indirection under a name" do
expect(@thingie).to respond_to(:indirects)
end
end
describe Puppet::Indirector, "when registering an indirection" do
before do
@thingie = Class.new do
extend Puppet::Indirector
# override Class#name, since we're not naming this ephemeral class
def self.name
'Thingie'
end
attr_reader :name
def initialize(name)
@name = name
end
end
end
it "should require a name when registering a model" do
expect {@thingie.send(:indirects) }.to raise_error(ArgumentError)
end
it "should create an indirection instance to manage each indirecting model" do
@indirection = @thingie.indirects(:test)
expect(@indirection).to be_instance_of(Puppet::Indirector::Indirection)
end
it "should not allow a model to register under multiple names" do
# Keep track of the indirection instance so we can delete it on cleanup
@indirection = @thingie.indirects :first
expect { @thingie.indirects :second }.to raise_error(ArgumentError)
end
it "should make the indirection available via an accessor" do
@indirection = @thingie.indirects :first
expect(@thingie.indirection).to equal(@indirection)
end
it "should pass any provided options to the indirection during initialization" do
expect(Puppet::Indirector::Indirection).to receive(:new).with(@thingie, :first, {:doc => 'some docs', :indirected_class => 'Thingie'})
@indirection = @thingie.indirects :first, :doc => 'some docs'
end
it "should extend the class to handle serialization" do
@indirection = @thingie.indirects :first
expect(@thingie).to respond_to(:convert_from)
end
after do
@indirection.delete if @indirection
end
end
describe Puppet::Indirector, "when redirecting a model" do
before do
@thingie = Class.new do
extend Puppet::Indirector
attr_reader :name
def initialize(name)
@name = name
end
end
@indirection = @thingie.send(:indirects, :test)
end
it "should include the Envelope module in the model" do
expect(@thingie.ancestors).to be_include(Puppet::Indirector::Envelope)
end
after do
@indirection.delete
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/puppet_pal_catalog_spec.rb | spec/unit/puppet_pal_catalog_spec.rb | #! /usr/bin/env ruby
require 'spec_helper'
require 'puppet_spec/files'
require 'puppet_pal'
describe 'Puppet Pal' do
include PuppetSpec::Files
let(:testing_env) do
{
'pal_env' => {
'functions' => functions,
'lib' => { 'puppet' => lib_puppet },
'manifests' => manifests,
'modules' => modules,
'plans' => plans,
'tasks' => tasks,
'types' => types,
},
'other_env1' => { 'modules' => {} },
'other_env2' => { 'modules' => {} },
}
end
let(:functions) { {} }
let(:manifests) { {} }
let(:modules) { {} }
let(:plans) { {} }
let(:lib_puppet) { {} }
let(:tasks) { {} }
let(:types) { {} }
let(:environments_dir) { Puppet[:environmentpath] }
let(:testing_env_dir) do
dir_contained_in(environments_dir, testing_env)
env_dir = File.join(environments_dir, 'pal_env')
PuppetSpec::Files.record_tmp(env_dir)
PuppetSpec::Files.record_tmp(File.join(environments_dir, 'other_env1'))
PuppetSpec::Files.record_tmp(File.join(environments_dir, 'other_env2'))
env_dir
end
let(:modules_dir) { File.join(testing_env_dir, 'modules') }
# Without any facts - this speeds up the tests that do not require $facts to have any values
let(:node_facts) { Hash.new }
# TODO: to be used in examples for running in an existing env
# let(:env) { Puppet::Node::Environment.create(:testing, [modules_dir]) }
context 'in general - without code in modules or env' do
let(:modulepath) { [] }
context "with a catalog compiler" do
it 'errors if given both configured_by_env and manifest_file' do
expect {
Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
ctx.with_catalog_compiler(configured_by_env: true, manifest_file: 'undef.pp') {|c| }
end
}.to raise_error(/manifest_file or code_string cannot be given when configured_by_env is true/)
end
it 'errors if given both configured_by_env and code_string' do
expect {
Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
ctx.with_catalog_compiler(configured_by_env: true, code_string: 'undef') {|c| }
end
}.to raise_error(/manifest_file or code_string cannot be given when configured_by_env is true/)
end
it 'shadows target variables that collide with plan variables' do
facts = { 'var' => 'fact' }
target_vars = { 'var' => 'target' }
expect(Puppet).to receive(:warning).with(/Target variable \$var will be overridden by fact of the same name/)
result = Puppet::Pal.in_tmp_environment('pal_env', facts: {}) do |ctx|
ctx.with_catalog_compiler(facts: facts, target_variables: target_vars ) do |c|
c.evaluate_string('$var')
end
end
expect(result).to eq('fact')
end
it 'shadows target variables that collide with facts' do
plan_vars = { 'var' => 'plan' }
target_vars = { 'var' => 'target' }
expect(Puppet).to receive(:warning).with(/Target variable \$var will be overridden by plan variable of the same name/)
result = Puppet::Pal.in_tmp_environment('pal_env', facts: {}) do |ctx|
ctx.with_catalog_compiler(variables: plan_vars, target_variables: target_vars ) do |c|
c.evaluate_string('$var')
end
end
expect(result).to eq('plan')
end
it 'shadows plan variables that collide with facts' do
facts = { 'var' => 'fact' }
plan_vars = { 'var' => 'plan' }
expect(Puppet).to receive(:warning).with(/Plan variable \$var will be overridden by fact of the same name/)
result = Puppet::Pal.in_tmp_environment('pal_env', facts: {}) do |ctx|
ctx.with_catalog_compiler(facts: facts, variables: plan_vars ) do |c|
c.evaluate_string('$var')
end
end
expect(result).to eq('fact')
end
context "evaluate_string method" do
it 'evaluates code string in a given tmp environment' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
ctx.with_catalog_compiler {|c| c.evaluate_string('1+2+3') }
end
expect(result).to eq(6)
end
it 'can be evaluated more than once in a given tmp environment - each in fresh compiler' do
Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
expect( ctx.with_catalog_compiler {|c| c.evaluate_string('$a = 1+2+3')}).to eq(6)
expect { ctx.with_catalog_compiler {|c| c.evaluate_string('$a') }}.to raise_error(/Unknown variable: 'a'/)
end
end
it 'instantiates a function definition in the given code string' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |pal|
pal.with_catalog_compiler do |compiler|
compiler.evaluate_string(<<-CODE)
function run_me() { "worked1" }
run_me()
CODE
end
end
expect(result).to eq('worked1')
end
it 'instantiates a user defined resource definition in the given code string' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |pal|
pal.with_catalog_compiler do |compiler|
compiler.evaluate_string(<<-CODE)
define run_me() { }
run_me { test: }
CODE
end
end
resource = result[0]
expect(resource).to be_a(Puppet::Pops::Types::PResourceType)
expect(resource.type_name).to eq("Run_me")
expect(resource.title).to eq('test')
end
context 'catalog_data_hash' do
it 'produces a data_hash encoding of a catalog' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |pal|
pal.with_catalog_compiler {|c|
c.evaluate_string("notify {'test': message => /a regexp/}")
c.catalog_data_hash
}
end
expect(result['resources']).to include(include('type' => 'Notify'))
end
end
context 'the with_json_encoding()' do
it 'produces json for a catalog' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |pal|
pal.with_catalog_compiler {|c|
c.evaluate_string("notify {'test': message => /a regexp/}")
c.with_json_encoding() {|encoder| encoder.encode }
}
end
parsed = JSON.parse(result)
expect(parsed['resources']).to include(include('type' => 'Notify'))
end
it 'produces pretty json by default' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |pal|
pal.with_catalog_compiler {|c|
c.evaluate_string("notify {'test': message => /a regexp/}")
c.with_json_encoding() {|encoder| encoder.encode }
}
end
expect(result.count("\n")).to be > 10
end
it 'produces compact (non pretty) json when pretty is false' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |pal|
pal.with_catalog_compiler {|c|
c.evaluate_string("notify {'test': message => /a regexp/}")
c.with_json_encoding(pretty: false) {|encoder| encoder.encode }
}
end
expect(result.count("\n")).to be < 10
end
it 'produces json for an individual resource by giving type and title to encode_resource()' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |pal|
pal.with_catalog_compiler {|c|
c.evaluate_string("notify {'test': message => 'yay'}")
c.with_json_encoding() {|encoder| encoder.encode_resource('notify', 'test') }
}
end
expect(result).to match(/"message":"yay"/)
end
it 'encodes values as rich data when needed' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |pal|
pal.with_catalog_compiler {|c|
c.evaluate_string("notify {'test': message => /a regexp/}")
c.with_json_encoding(pretty: true) {|encoder| encoder.encode_resource('notify', 'test') }
}
end
expect(result).to match(/"__ptype":"Regexp"/)
end
end
end
context "evaluate_file method" do
it 'evaluates a manifest file in a given tmp environment' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
manifest = file_containing('testing.pp', "1+2+3+4")
ctx.with_catalog_compiler {|c| c.evaluate_file(manifest) }
end
expect(result).to eq(10)
end
it 'instantiates definitions in the given code string' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |pal|
pal.with_catalog_compiler do |compiler|
manifest = file_containing('testing.pp', (<<-CODE))
function run_me() { "worked1" }
run_me()
CODE
pal.with_catalog_compiler {|c| c.evaluate_file(manifest) }
end
end
expect(result).to eq('worked1')
end
end
context "variables are supported such that" do
it 'they can be set in any scope' do
vars = {'a'=> 10, 'x::y' => 20}
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts, variables: vars) do |ctx|
ctx.with_catalog_compiler {|c| c.evaluate_string("1+2+3+4+$a+$x::y")}
end
expect(result).to eq(40)
end
it 'an error is raised if a variable name is illegal' do
vars = {'_a::b'=> 10}
expect do
Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts, variables: vars) do |ctx|
manifest = file_containing('testing.pp', "ok")
ctx.with_catalog_compiler {|c| c.evaluate_file(manifest) }
end
end.to raise_error(/has illegal name/)
end
it 'an error is raised if variable value is not RichData compliant' do
vars = {'a'=> ArgumentError.new("not rich data")}
expect do
Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts, variables: vars) do |ctx|
ctx.with_catalog_compiler {|c| }
end
end.to raise_error(/has illegal type - got: ArgumentError/)
end
it 'variable given to script_compiler overrides those given for environment' do
vars = {'a'=> 10, 'x::y' => 20}
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts, variables: vars) do |ctx|
ctx.with_catalog_compiler(variables: {'x::y' => 40}) {|c| c.evaluate_string("1+2+3+4+$a+$x::y")}
end
expect(result).to eq(60)
end
end
context "functions are supported such that" do
it '"call_function" calls a function' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
manifest = file_containing('afunc.pp', "function myfunc($a) { $a * 2 } ")
ctx.with_catalog_compiler(manifest_file: manifest) {|c| c.call_function('myfunc', 6) }
end
expect(result).to eq(12)
end
it '"call_function" accepts a call with a ruby block' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
ctx.with_catalog_compiler {|c| c.call_function('with', 6) {|x| x * 2} }
end
expect(result).to eq(12)
end
it '"function_signature" returns a signature of a function' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
manifest = file_containing('afunc.pp', "function myfunc(Integer $a) { $a * 2 } ")
ctx.with_catalog_compiler(manifest_file: manifest) do |c|
c.function_signature('myfunc')
end
end
expect(result.class).to eq(Puppet::Pal::FunctionSignature)
end
it '"FunctionSignature#callable_with?" returns boolean if function is callable with given argument values' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
manifest = file_containing('afunc.pp', "function myfunc(Integer $a) { $a * 2 } ")
ctx.with_catalog_compiler(manifest_file: manifest) do |c|
signature = c.function_signature('myfunc')
[ signature.callable_with?([10]),
signature.callable_with?(['nope'])
]
end
end
expect(result).to eq([true, false])
end
it '"FunctionSignature#callable_with?" calls a given lambda if there is an error' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
manifest = file_containing('afunc.pp', "function myfunc(Integer $a) { $a * 2 } ")
ctx.with_catalog_compiler(manifest_file: manifest) do |c|
signature = c.function_signature('myfunc')
local_result = 'not yay'
signature.callable_with?(['nope']) {|error| local_result = error }
local_result
end
end
expect(result).to match(/'myfunc' parameter 'a' expects an Integer value, got String/)
end
it '"FunctionSignature#callable_with?" does not call a given lambda when there is no error' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
manifest = file_containing('afunc.pp', "function myfunc(Integer $a) { $a * 2 } ")
ctx.with_catalog_compiler(manifest_file: manifest) do |c|
signature = c.function_signature('myfunc')
local_result = 'yay'
signature.callable_with?([10]) {|error| local_result = 'not yay' }
local_result
end
end
expect(result).to eq('yay')
end
it '"function_signature" gets the signatures from a ruby function with multiple dispatch' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
ctx.with_catalog_compiler {|c| c.function_signature('lookup') }
end
# check two different signatures of the lookup function
expect(result.callable_with?(['key'])).to eq(true)
expect(result.callable_with?(['key'], lambda() {|k| })).to eq(true)
end
it '"function_signature" returns nil if function is not found' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
ctx.with_catalog_compiler {|c| c.function_signature('no_where_to_be_found') }
end
expect(result).to eq(nil)
end
it '"FunctionSignature#callables" returns an array of callables' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
manifest = file_containing('afunc.pp', "function myfunc(Integer $a) { $a * 2 } ")
ctx.with_catalog_compiler(manifest_file: manifest) do |c|
c.function_signature('myfunc').callables
end
end
expect(result.class).to eq(Array)
expect(result.all? {|c| c.is_a?(Puppet::Pops::Types::PCallableType)}).to eq(true)
end
it '"list_functions" returns an array with all function names that can be loaded' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
ctx.with_catalog_compiler {|c| c.list_functions() }
end
expect(result.is_a?(Array)).to eq(true)
expect(result.all? {|s| s.is_a?(Puppet::Pops::Loader::TypedName) }).to eq(true)
# there are certainly more than 30 functions in puppet - (56 when writing this, but some refactoring
# may take place, so don't want an exact number here - jsut make sure it found "all of them"
expect(result.count).to be > 30
end
it '"list_functions" filters on name based on a given regexp' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
ctx.with_catalog_compiler {|c| c.list_functions(/epp/) }
end
expect(result.is_a?(Array)).to eq(true)
expect(result.all? {|s| s.is_a?(Puppet::Pops::Loader::TypedName) }).to eq(true)
# there are two functions currently that have 'epp' in their name
expect(result.count).to eq(2)
end
end
context 'supports puppet data types such that' do
it '"type" parses and returns a Type from a string specification' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
manifest = file_containing('main.pp', "type MyType = Float")
ctx.with_catalog_compiler(manifest_file: manifest) {|c| c.type('Variant[Integer, Boolean, MyType]') }
end
expect(result.is_a?(Puppet::Pops::Types::PVariantType)).to eq(true)
expect(result.types.size).to eq(3)
expect(result.instance?(3.14)).to eq(true)
end
it '"create" creates a new object from a puppet data type and args' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
ctx.with_catalog_compiler { |c| c.create(Puppet::Pops::Types::PIntegerType::DEFAULT, '0x10') }
end
expect(result).to eq(16)
end
it '"create" creates a new object from puppet data type in string form and args' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
ctx.with_catalog_compiler { |c| c.create('Integer', '010') }
end
expect(result).to eq(8)
end
end
end
context 'supports parsing such that' do
it '"parse_string" parses a puppet language string' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
ctx.with_catalog_compiler { |c| c.parse_string('$a = 10') }
end
expect(result.class).to eq(Puppet::Pops::Model::Program)
end
{ nil => Puppet::Error,
'0xWAT' => Puppet::ParseErrorWithIssue,
'$0 = 1' => Puppet::ParseErrorWithIssue,
'else 32' => Puppet::ParseErrorWithIssue,
}.each_pair do |input, error_class|
it "'parse_string' raises an error for invalid input: '#{input}'" do
expect {
Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
ctx.with_catalog_compiler { |c| c.parse_string(input) }
end
}.to raise_error(error_class)
end
end
it '"parse_file" parses a puppet language string' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
manifest = file_containing('main.pp', "$a = 10")
ctx.with_catalog_compiler { |c| c.parse_file(manifest) }
end
expect(result.class).to eq(Puppet::Pops::Model::Program)
end
it "'parse_file' raises an error for invalid input: 'else 32'" do
expect {
Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
manifest = file_containing('main.pp', "else 32")
ctx.with_catalog_compiler { |c| c.parse_file(manifest) }
end
}.to raise_error(Puppet::ParseErrorWithIssue)
end
it "'parse_file' raises an error for invalid input, file is not a string" do
expect {
Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
ctx.with_catalog_compiler { |c| c.parse_file(42) }
end
}.to raise_error(Puppet::Error)
end
it 'the "evaluate" method evaluates the parsed AST' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
ctx.with_catalog_compiler { |c| c.evaluate(c.parse_string('10 + 20')) }
end
expect(result).to eq(30)
end
it 'the "evaluate" method instantiates definitions when given a Program' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
ctx.with_catalog_compiler { |c| c.evaluate(c.parse_string('function foo() { "yay"}; foo()')) }
end
expect(result).to eq('yay')
end
it 'the "evaluate" method does not instantiates definitions when given ast other than Program' do
expect do
Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
ctx.with_catalog_compiler do |c|
program= c.parse_string('function foo() { "yay"}; foo()')
c.evaluate(program.body)
end
end
end.to raise_error(/Unknown function: 'foo'/)
end
it 'the "evaluate_literal" method evaluates AST being a representation of a literal value' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
ctx.with_catalog_compiler { |c| c.evaluate_literal(c.parse_string('{10 => "hello"}')) }
end
expect(result).to eq({10 => 'hello'})
end
it 'the "evaluate_literal" method errors if ast is not representing a literal value' do
expect do
Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
ctx.with_catalog_compiler { |c| c.evaluate_literal(c.parse_string('{10+1 => "hello"}')) }
end
end.to raise_error(/does not represent a literal value/)
end
it 'the "evaluate_literal" method errors if ast contains definitions' do
expect do
Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
ctx.with_catalog_compiler { |c| c.evaluate_literal(c.parse_string('function foo() { }; 42')) }
end
end.to raise_error(/does not represent a literal value/)
end
it 'the "evaluate" method evaluates but does not evaluate lazy constructs' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
ctx.with_catalog_compiler do |c|
c.evaluate(c.parse_string('define foo() { notify {nope: }} foo { test: }'))
c.with_json_encoding() {|encoder| encoder.encode }
end
end
parsed = JSON.parse(result)
expect(parsed['resources']).to_not include(include('type' => 'Notify'))
end
it 'an "evaluate" followed by "compile_additions" evaluates lazy constructs' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
ctx.with_catalog_compiler do |c|
c.evaluate(c.parse_string('define foo() { notify {nope: }} foo { test: }'))
c.compile_additions
c.with_json_encoding() {|encoder| encoder.encode }
end
end
parsed = JSON.parse(result)
expect(parsed['resources']).to include(include('type' => 'Notify'))
end
it 'an "evaluate" followed by "compile_additions" validates the result' do
expect do
Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
ctx.with_catalog_compiler do |c|
c.evaluate(c.parse_string('define foo() { notify {nope: }} foo { test: before =>"Bar[nope]"}'))
c.compile_additions
end
end
end.to raise_error(Puppet::Error, /Could not find resource 'Bar\[nope\]'/)
end
it 'an "evaluate" followed by "evaluate_additions" does not validate the result' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
ctx.with_catalog_compiler do |c|
c.evaluate(c.parse_string('define foo() { notify {nope: }} foo { test: before =>"Bar[nope]"}'))
c.evaluate_additions
c.with_json_encoding() {|encoder| encoder.encode }
end
end
parsed = JSON.parse(result)
expect(parsed['resources']).to include(include('type' => 'Notify'))
end
it 'an "evaluate" followed by "evaluate_additions" and "validate" validates the result' do
expect do
Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
ctx.with_catalog_compiler do |c|
c.evaluate(c.parse_string('define foo() { notify {nope: }} foo { test: before =>"Bar[nope]"}'))
c.compile_additions
c.validate
end
end
end.to raise_error(Puppet::Error, /Could not find resource 'Bar\[nope\]'/)
end
it 'an "evaluate" followed by "evaluate_ast_node" will correctly parse a node definition' do
Puppet[:node_name_value] = 'testing_node'
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
ctx.with_catalog_compiler do |c|
c.evaluate(c.parse_string("node 'testing_node' { notify {'PASSED': } }"))
c.evaluate_ast_node
c.compile_additions
c.with_json_encoding() {|encoder| encoder.encode }
end
end
parsed = JSON.parse(result)
expect(parsed['resources']).to include(include('type' => 'Notify'))
end
end
end
context 'with code in modules and env' do
let(:modulepath) { [modules_dir] }
let(:metadata_json_a) {
{
'name' => 'example/a',
'version' => '0.1.0',
'source' => 'git@github.com/example/example-a.git',
'dependencies' => [{'name' => 'c', 'version_range' => '>=0.1.0'}],
'author' => 'Bob the Builder',
'license' => 'Apache-2.0'
}
}
let(:metadata_json_b) {
{
'name' => 'example/b',
'version' => '0.1.0',
'source' => 'git@github.com/example/example-b.git',
'dependencies' => [{'name' => 'c', 'version_range' => '>=0.1.0'}],
'author' => 'Bob the Builder',
'license' => 'Apache-2.0'
}
}
let(:metadata_json_c) {
{
'name' => 'example/c',
'version' => '0.1.0',
'source' => 'git@github.com/example/example-c.git',
'dependencies' => [],
'author' => 'Bob the Builder',
'license' => 'Apache-2.0'
}
}
# TODO: there is something amiss with the metadata wrt dependencies - when metadata is present there is an error
# that dependencies could not be resolved. Metadata is therefore commented out.
# Dependency based visibility is probably something that we should remove...
let(:modules) {
{
'a' => {
'functions' => a_functions,
'lib' => { 'puppet' => a_lib_puppet },
'types' => a_types,
},
'b' => {
'functions' => b_functions,
'lib' => b_lib,
'types' => b_types,
},
'c' => {
'types' => c_types,
},
}
}
let(:a_types) {
{
'atype.pp' => <<-PUPPET.unindent,
type A::Atype = Integer
PUPPET
}
}
let(:a_functions) {
{
'afunc.pp' => 'function a::afunc() { "a::afunc value" }',
}
}
let(:a_lib_puppet) {
{
'functions' => {
'a' => {
'arubyfunc.rb' => <<-RUBY.unindent,
require 'stuff/something'
Puppet::Functions.create_function(:'a::arubyfunc') do
def arubyfunc
Stuff::SOMETHING
end
end
RUBY
'mycatalogcompilerfunc.rb' => <<-RUBY.unindent,
Puppet::Functions.create_function(:'a::mycatalogcompilerfunc', Puppet::Functions::InternalFunction) do
dispatch :mycatalogcompilerfunc do
compiler_param
param 'String',:name
end
def mycatalogcompilerfunc(the_compiler, name)
the_compiler.is_a?(Puppet::Pal::CatalogCompiler) ? name : 'no go'
end
end
RUBY
}
},
'datatypes' => {
'mytype.rb' => <<-RUBY.unindent,
Puppet::DataTypes.create_type('Mytype') do
interface <<-PUPPET
attributes => {
name => { type => String },
year_of_birth => { type => Integer },
age => { type => Integer, kind => derived },
}
PUPPET
implementation do
def age
DateTime.now.year - @year_of_birth
end
end
end
RUBY
}
}
}
let(:b_types) {
{
'atype.pp' => <<-PUPPET.unindent,
type B::Atype = Integer
PUPPET
}
}
let(:b_functions) {
{
'afunc.pp' => 'function b::afunc() {}',
}
}
let(:b_lib) {
{
'puppet' => b_lib_puppet,
'stuff' => {
'something.rb' => "module Stuff; SOMETHING = 'something'; end"
}
}
}
let(:b_lib_puppet) {
{
'functions' => {
'b' => {
'arubyfunc.rb' => "Puppet::Functions.create_function(:'b::arubyfunc') { def arubyfunc; 'arubyfunc_value'; end }",
}
}
}
}
let(:c_types) {
{
'atype.pp' => <<-PUPPET.unindent,
type C::Atype = Integer
PUPPET
}
}
context 'configured as temporary environment such that' do
it 'modules are available' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
ctx.with_catalog_compiler {|c| c.evaluate_string('a::afunc()') }
end
expect(result).to eq("a::afunc value")
end
it 'libs in a given "modulepath" are added to the Ruby $LOAD_PATH' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
ctx.with_catalog_compiler {|c| c.evaluate_string('a::arubyfunc()') }
end
expect(result).to eql('something')
end
it 'errors if a block is not given to in_tmp_environment' do
expect do
Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts)
end.to raise_error(/A block must be given to 'in_tmp_environment/)
end
it 'errors if an env_name is given and is not a String[1]' do
expect do
Puppet::Pal.in_tmp_environment('', modulepath: modulepath, facts: node_facts) { |ctx| }
end.to raise_error(/temporary environment name has wrong type/)
expect do
Puppet::Pal.in_tmp_environment(32, modulepath: modulepath, facts: node_facts) { |ctx| }
end.to raise_error(/temporary environment name has wrong type/)
end
{ 'a hash' => {'a' => 'hm'},
'an integer' => 32,
'separated strings' => 'dir1;dir2',
'empty string in array' => ['']
}.each_pair do |what, value|
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | true |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util_spec.rb | spec/unit/util_spec.rb | require 'spec_helper'
describe Puppet::Util do
include PuppetSpec::Files
if Puppet::Util::Platform.windows?
def set_mode(mode, file)
Puppet::Util::Windows::Security.set_mode(mode, file)
end
def get_mode(file)
Puppet::Util::Windows::Security.get_mode(file) & 07777
end
else
def set_mode(mode, file)
File.chmod(mode, file)
end
def get_mode(file)
Puppet::FileSystem.lstat(file).mode & 07777
end
end
describe "#withenv" do
let(:mode) { Puppet::Util::Platform.windows? ? :windows : :posix }
before :each do
@original_path = ENV["PATH"]
@new_env = {:PATH => "/some/bogus/path"}
end
it "should change environment variables within the block then reset environment variables to their original values" do
Puppet::Util.withenv @new_env, mode do
expect(ENV["PATH"]).to eq("/some/bogus/path")
end
expect(ENV["PATH"]).to eq(@original_path)
end
it "should reset environment variables to their original values even if the block fails" do
begin
Puppet::Util.withenv @new_env, mode do
expect(ENV["PATH"]).to eq("/some/bogus/path")
raise "This is a failure"
end
rescue
end
expect(ENV["PATH"]).to eq(@original_path)
end
it "should reset environment variables even when they are set twice" do
# Setting Path & Environment parameters in Exec type can cause weirdness
@new_env["PATH"] = "/someother/bogus/path"
Puppet::Util.withenv @new_env, mode do
# When assigning duplicate keys, can't guarantee order of evaluation
expect(ENV["PATH"]).to match(/\/some.*\/bogus\/path/)
end
expect(ENV["PATH"]).to eq(@original_path)
end
it "should remove any new environment variables after the block ends" do
@new_env[:FOO] = "bar"
ENV["FOO"] = nil
Puppet::Util.withenv @new_env, mode do
expect(ENV["FOO"]).to eq("bar")
end
expect(ENV["FOO"]).to eq(nil)
end
it "accepts symbolic keys" do
Puppet::Util.withenv(:FOO => "bar") do
expect(ENV["FOO"]).to eq("bar")
end
end
it "coerces invalid keys to strings" do
Puppet::Util.withenv(12345678 => "bar") do
expect(ENV["12345678"]).to eq("bar")
end
end
it "rejects keys with leading equals" do
expect {
Puppet::Util.withenv("=foo" => "bar") {}
}.to raise_error(Errno::EINVAL, /Invalid argument/)
end
it "includes keys with unicode replacement characters" do
Puppet::Util.withenv("foo\uFFFD" => "bar") do
expect(ENV).to be_include("foo\uFFFD")
end
end
it "accepts a unicode key" do
key = "\u16A0\u16C7\u16BB\u16EB\u16D2\u16E6\u16A6\u16EB\u16A0\u16B1\u16A9\u16A0\u16A2\u16B1\u16EB\u16A0\u16C1\u16B1\u16AA\u16EB\u16B7\u16D6\u16BB\u16B9\u16E6\u16DA\u16B3\u16A2\u16D7"
Puppet::Util.withenv(key => "bar") do
expect(ENV[key]).to eq("bar")
end
end
it "accepts a unicode value" do
value = "\u16A0\u16C7\u16BB\u16EB\u16D2\u16E6\u16A6\u16EB\u16A0\u16B1\u16A9\u16A0\u16A2\u16B1\u16EB\u16A0\u16C1\u16B1\u16AA\u16EB\u16B7\u16D6\u16BB\u16B9\u16E6\u16DA\u16B3\u16A2\u16D7"
Puppet::Util.withenv("runes" => value) do
expect(ENV["runes"]).to eq(value)
end
end
it "rejects a non-string value" do
expect {
Puppet::Util.withenv("reject" => 123) {}
}.to raise_error(TypeError, /no implicit conversion of Integer into String/)
end
it "accepts a nil value" do
Puppet::Util.withenv("foo" => nil) do
expect(ENV["foo"]).to eq(nil)
end
end
end
describe "#withenv on POSIX", :unless => Puppet::Util::Platform.windows? do
it "compares keys case sensitively" do
# start with lower case key,
env_key = SecureRandom.uuid.downcase
begin
original_value = 'hello'
ENV[env_key] = original_value
new_value = 'goodbye'
Puppet::Util.withenv(env_key.upcase => new_value) do
expect(ENV[env_key]).to eq(original_value)
expect(ENV[env_key.upcase]).to eq(new_value)
end
expect(ENV[env_key]).to eq(original_value)
expect(ENV[env_key.upcase]).to be_nil
ensure
ENV.delete(env_key)
end
end
end
describe "#withenv on Windows", :if => Puppet::Util::Platform.windows? do
let(:process) { Puppet::Util::Windows::Process }
it "compares keys case-insensitively" do
# start with lower case key, ensuring string is not entirely numeric
env_key = SecureRandom.uuid.downcase + 'a'
begin
original_value = 'hello'
ENV[env_key] = original_value
new_value = 'goodbye'
Puppet::Util.withenv(env_key.upcase => new_value) do
expect(ENV[env_key]).to eq(new_value)
expect(ENV[env_key.upcase]).to eq(new_value)
end
expect(ENV[env_key]).to eq(original_value)
expect(ENV[env_key.upcase]).to eq(original_value)
ensure
ENV.delete(env_key)
end
end
def withenv_utf8(&block)
env_var_name = SecureRandom.uuid
utf_8_bytes = [225, 154, 160] # rune ᚠ
utf_8_key = env_var_name + utf_8_bytes.pack('c*').force_encoding(Encoding::UTF_8)
utf_8_value = utf_8_key + 'value'
codepage_key = utf_8_key.dup.force_encoding(Encoding.default_external)
Puppet::Util.withenv(utf_8_key => utf_8_value) do
# the true Windows environment APIs see the variables correctly
expect(process.get_environment_strings[utf_8_key]).to eq(utf_8_value)
# the string contain the same bytes, but have different Ruby metadata
expect(utf_8_key.bytes.to_a).to eq(codepage_key.bytes.to_a)
yield utf_8_key, utf_8_value, codepage_key
end
# real environment shouldn't have env var anymore
expect(process.get_environment_strings[utf_8_key]).to eq(nil)
end
it "should preseve existing environment and should not corrupt UTF-8 environment variables" do
env_var_name = SecureRandom.uuid
utf_8_bytes = [225, 154, 160] # rune ᚠ
utf_8_str = env_var_name + utf_8_bytes.pack('c*').force_encoding(Encoding::UTF_8)
env_var_name_utf_8 = utf_8_str
begin
# UTF-8 name and value
process.set_environment_variable(env_var_name_utf_8, utf_8_str)
# ASCII name / UTF-8 value
process.set_environment_variable(env_var_name, utf_8_str)
original_keys = process.get_environment_strings.keys.to_a
Puppet::Util.withenv({}) { }
env = process.get_environment_strings
expect(env[env_var_name]).to eq(utf_8_str)
expect(env[env_var_name_utf_8]).to eq(utf_8_str)
expect(env.keys.to_a).to eq(original_keys)
ensure
process.set_environment_variable(env_var_name_utf_8, nil)
process.set_environment_variable(env_var_name, nil)
end
end
end
describe "#absolute_path?" do
describe "on posix systems", :if => Puppet.features.posix? do
it "should default to the platform of the local system" do
expect(Puppet::Util).to be_absolute_path('/foo')
expect(Puppet::Util).not_to be_absolute_path('C:/foo')
end
end
describe "on windows", :if => Puppet::Util::Platform.windows? do
it "should default to the platform of the local system" do
expect(Puppet::Util).to be_absolute_path('C:/foo')
expect(Puppet::Util).not_to be_absolute_path('/foo')
end
end
describe "when using platform :posix" do
%w[/ /foo /foo/../bar //foo //Server/Foo/Bar //?/C:/foo/bar /\Server/Foo /foo//bar/baz].each do |path|
it "should return true for #{path}" do
expect(Puppet::Util).to be_absolute_path(path, :posix)
end
end
%w[. ./foo \foo C:/foo \\Server\Foo\Bar \\?\C:\foo\bar \/?/foo\bar \/Server/foo foo//bar/baz].each do |path|
it "should return false for #{path}" do
expect(Puppet::Util).not_to be_absolute_path(path, :posix)
end
end
end
describe "when using platform :windows" do
%w[C:/foo C:\foo \\\\Server\Foo\Bar \\\\?\C:\foo\bar //Server/Foo/Bar //?/C:/foo/bar /\?\C:/foo\bar \/Server\Foo/Bar c:/foo//bar//baz].each do |path|
it "should return true for #{path}" do
expect(Puppet::Util).to be_absolute_path(path, :windows)
end
end
%w[/ . ./foo \foo /foo /foo/../bar //foo C:foo/bar foo//bar/baz].each do |path|
it "should return false for #{path}" do
expect(Puppet::Util).not_to be_absolute_path(path, :windows)
end
end
end
end
describe "#path_to_uri" do
# different UTF-8 widths
# 1-byte A
# 2-byte ۿ - http://www.fileformat.info/info/unicode/char/06ff/index.htm - 0xDB 0xBF / 219 191
# 3-byte ᚠ - http://www.fileformat.info/info/unicode/char/16A0/index.htm - 0xE1 0x9A 0xA0 / 225 154 160
# 4-byte - http://www.fileformat.info/info/unicode/char/2070E/index.htm - 0xF0 0xA0 0x9C 0x8E / 240 160 156 142
let (:mixed_utf8) { "A\u06FF\u16A0\u{2070E}" } # Aۿᚠ
let (:mixed_utf8_urlencoded) { "A%DB%BF%E1%9A%A0%F0%A0%9C%8E" }
%w[. .. foo foo/bar foo/../bar].each do |path|
it "should reject relative path: #{path}" do
expect { Puppet::Util.path_to_uri(path) }.to raise_error(Puppet::Error)
end
end
it "should perform URI escaping" do
expect(Puppet::Util.path_to_uri("/foo bar").path).to eq("/foo%20bar")
end
it "should properly URI encode + and space in path" do
expect(Puppet::Util.path_to_uri("/foo+foo bar").path).to eq("/foo+foo%20bar")
end
# reserved characters are different for each part
# https://web.archive.org/web/20151229061347/http://blog.lunatech.com/2009/02/03/what-every-web-developer-must-know-about-url-encoding#Thereservedcharactersaredifferentforeachpart
# "?" is allowed unescaped anywhere within a query part,
# "/" is allowed unescaped anywhere within a query part,
# "=" is allowed unescaped anywhere within a path parameter or query parameter value, and within a path segment,
# ":@-._~!$&'()*+,;=" are allowed unescaped anywhere within a path segment part,
# "/?:@-._~!$&'()*+,;=" are allowed unescaped anywhere within a fragment part.
it "should properly URI encode + and space in path and query" do
path = "/foo+foo bar?foo+foo bar"
uri = Puppet::Util.path_to_uri(path)
expected_encoding = Encoding::UTF_8
expect(uri.to_s.encoding).to eq(expected_encoding)
expect(uri.path).to eq("/foo+foo%20bar")
# either + or %20 is correct for an encoded space in query
# + is usually used for backward compatibility, but %20 is preferred for compat with Puppet::Util.uri_unescape
expect(uri.query).to eq("foo%2Bfoo%20bar")
# complete roundtrip
expect(Puppet::Util.uri_unescape(uri.to_s).sub(%r{^file:(//)?}, '')).to eq(path)
expect(Puppet::Util.uri_unescape(uri.to_s).encoding).to eq(expected_encoding)
end
it "should perform UTF-8 URI escaping" do
uri = Puppet::Util.path_to_uri("/#{mixed_utf8}")
expect(uri.path.encoding).to eq(Encoding::UTF_8)
expect(uri.path).to eq("/#{mixed_utf8_urlencoded}")
end
describe "when using platform :posix" do
before :each do
allow(Puppet.features).to receive(:posix?).and_return(true)
allow(Puppet::Util::Platform).to receive(:windows?).and_return(false)
end
%w[/ /foo /foo/../bar].each do |path|
it "should convert #{path} to URI" do
expect(Puppet::Util.path_to_uri(path).path).to eq(path)
end
end
end
describe "when using platform :windows" do
before :each do
allow(Puppet.features).to receive(:posix?).and_return(false)
allow(Puppet::Util::Platform).to receive(:windows?).and_return(true)
end
it "should normalize backslashes" do
expect(Puppet::Util.path_to_uri('c:\\foo\\bar\\baz').path).to eq('/' + 'c:/foo/bar/baz')
end
%w[C:/ C:/foo/bar].each do |path|
it "should convert #{path} to absolute URI" do
expect(Puppet::Util.path_to_uri(path).path).to eq('/' + path)
end
end
%w[share C$].each do |path|
it "should convert UNC #{path} to absolute URI" do
uri = Puppet::Util.path_to_uri("\\\\server\\#{path}")
expect(uri.host).to eq('server')
expect(uri.path).to eq('/' + Puppet::Util.uri_encode(path))
end
end
end
end
describe "#uri_query_encode" do
# different UTF-8 widths
# 1-byte A
# 2-byte ۿ - http://www.fileformat.info/info/unicode/char/06ff/index.htm - 0xDB 0xBF / 219 191
# 3-byte ᚠ - http://www.fileformat.info/info/unicode/char/16A0/index.htm - 0xE1 0x9A 0xA0 / 225 154 160
# 4-byte 𠜎 - http://www.fileformat.info/info/unicode/char/2070E/index.htm - 0xF0 0xA0 0x9C 0x8E / 240 160 156 142
let (:mixed_utf8) { "A\u06FF\u16A0\u{2070E}" } # Aۿᚠ𠜎
let (:mixed_utf8_urlencoded) { "A%DB%BF%E1%9A%A0%F0%A0%9C%8E" }
it "should perform basic URI escaping that includes space and +" do
expect(Puppet::Util.uri_query_encode("foo bar+foo")).to eq("foo%20bar%2Bfoo")
end
it "should URI encode any special characters: = + <space> & * and #" do
expect(Puppet::Util.uri_query_encode("foo=bar+foo baz&bar=baz qux&special= *&qux=not fragment#")).to eq("foo%3Dbar%2Bfoo%20baz%26bar%3Dbaz%20qux%26special%3D%20%2A%26qux%3Dnot%20fragment%23")
end
[
"A\u06FF\u16A0\u{2070E}",
"A\u06FF\u16A0\u{2070E}".force_encoding(Encoding::BINARY)
].each do |uri_string|
it "should perform UTF-8 URI escaping, even when input strings are not UTF-8" do
uri = Puppet::Util.uri_query_encode(mixed_utf8)
expect(uri.encoding).to eq(Encoding::UTF_8)
expect(uri).to eq(mixed_utf8_urlencoded)
end
end
it "should be usable by URI::parse" do
uri = URI::parse("puppet://server/path?" + Puppet::Util.uri_query_encode(mixed_utf8))
expect(uri.scheme).to eq('puppet')
expect(uri.host).to eq('server')
expect(uri.path).to eq('/path')
expect(uri.query).to eq(mixed_utf8_urlencoded)
end
it "should be usable by URI::Generic.build" do
params = {
:scheme => 'file',
:host => 'foobar',
:path => '/path/to',
:query => Puppet::Util.uri_query_encode(mixed_utf8)
}
uri = URI::Generic.build(params)
expect(uri.scheme).to eq('file')
expect(uri.host).to eq('foobar')
expect(uri.path).to eq("/path/to")
expect(uri.query).to eq(mixed_utf8_urlencoded)
end
end
describe "#uri_encode" do
# different UTF-8 widths
# 1-byte A
# 2-byte ۿ - http://www.fileformat.info/info/unicode/char/06ff/index.htm - 0xDB 0xBF / 219 191
# 3-byte ᚠ - http://www.fileformat.info/info/unicode/char/16A0/index.htm - 0xE1 0x9A 0xA0 / 225 154 160
# 4-byte - http://www.fileformat.info/info/unicode/char/2070E/index.htm - 0xF0 0xA0 0x9C 0x8E / 240 160 156 142
let (:mixed_utf8) { "A\u06FF\u16A0\u{2070E}" } # Aۿᚠ
let (:mixed_utf8_urlencoded) { "A%DB%BF%E1%9A%A0%F0%A0%9C%8E" }
it "should perform URI escaping" do
expect(Puppet::Util.uri_encode("/foo bar")).to eq("/foo%20bar")
end
[
"A\u06FF\u16A0\u{2070E}",
"A\u06FF\u16A0\u{2070E}".force_encoding(Encoding::BINARY)
].each do |uri_string|
it "should perform UTF-8 URI escaping, even when input strings are not UTF-8" do
uri = Puppet::Util.uri_encode(mixed_utf8)
expect(uri.encoding).to eq(Encoding::UTF_8)
expect(uri).to eq(mixed_utf8_urlencoded)
end
end
it "should treat & and = as delimiters in a query string, but URI encode other special characters: + <space> * and #" do
input = "http://foo.bar.com/path?foo=bar+foo baz&bar=baz qux&special= *&qux=not fragment#"
expected_output = "http://foo.bar.com/path?foo=bar%2Bfoo%20baz&bar=baz%20qux&special=%20%2A&qux=not%20fragment%23"
expect(Puppet::Util.uri_encode(input)).to eq(expected_output)
end
it "should be usable by URI::parse" do
uri = URI::parse(Puppet::Util.uri_encode("puppet://server/path/to/#{mixed_utf8}"))
expect(uri.scheme).to eq('puppet')
expect(uri.host).to eq('server')
expect(uri.path).to eq("/path/to/#{mixed_utf8_urlencoded}")
end
it "should be usable by URI::Generic.build" do
params = {
:scheme => 'file',
:host => 'foobar',
:path => Puppet::Util.uri_encode("/path/to/#{mixed_utf8}")
}
uri = URI::Generic.build(params)
expect(uri.scheme).to eq('file')
expect(uri.host).to eq('foobar')
expect(uri.path).to eq("/path/to/#{mixed_utf8_urlencoded}")
end
describe "when using platform :posix" do
before :each do
allow(Puppet.features).to receive(:posix?).and_return(true)
allow(Puppet::Util::Platform).to receive(:windows?).and_return(false)
end
%w[/ /foo /foo/../bar].each do |path|
it "should not replace / in #{path} with %2F" do
expect(Puppet::Util.uri_encode(path)).to eq(path)
end
end
end
describe "with fragment support" do
context "disabled by default" do
it "should encode # as %23 in path" do
encoded = Puppet::Util.uri_encode("/foo bar#fragment")
expect(encoded).to eq("/foo%20bar%23fragment")
end
it "should encode # as %23 in query" do
encoded = Puppet::Util.uri_encode("/foo bar?baz+qux#fragment")
expect(encoded).to eq("/foo%20bar?baz%2Bqux%23fragment")
end
end
context "optionally enabled" do
it "should leave fragment delimiter # after encoded paths" do
encoded = Puppet::Util.uri_encode("/foo bar#fragment", { :allow_fragment => true })
expect(encoded).to eq("/foo%20bar#fragment")
end
it "should leave fragment delimiter # after encoded query" do
encoded = Puppet::Util.uri_encode("/foo bar?baz+qux#fragment", { :allow_fragment => true })
expect(encoded).to eq("/foo%20bar?baz%2Bqux#fragment")
end
end
end
describe "when using platform :windows" do
before :each do
allow(Puppet.features).to receive(:posix?).and_return(false)
allow(Puppet::Util::Platform).to receive(:windows?).and_return(true)
end
it "should url encode \\ as %5C, but not replace : as %3F" do
expect(Puppet::Util.uri_encode('c:\\foo\\bar\\baz')).to eq('c:%5Cfoo%5Cbar%5Cbaz')
end
%w[C:/ C:/foo/bar].each do |path|
it "should not replace / in #{path} with %2F" do
expect(Puppet::Util.uri_encode(path)).to eq(path)
end
end
end
end
describe ".uri_to_path" do
require 'uri'
# different UTF-8 widths
# 1-byte A
# 2-byte ۿ - http://www.fileformat.info/info/unicode/char/06ff/index.htm - 0xDB 0xBF / 219 191
# 3-byte ᚠ - http://www.fileformat.info/info/unicode/char/16A0/index.htm - 0xE1 0x9A 0xA0 / 225 154 160
# 4-byte 𠜎 - http://www.fileformat.info/info/unicode/char/2070E/index.htm - 0xF0 0xA0 0x9C 0x8E / 240 160 156 142
let (:mixed_utf8) { "A\u06FF\u16A0\u{2070E}" } # Aۿᚠ𠜎
it "should strip host component" do
expect(Puppet::Util.uri_to_path(URI.parse('http://foo/bar'))).to eq('/bar')
end
it "should accept puppet URLs" do
expect(Puppet::Util.uri_to_path(URI.parse('puppet:///modules/foo'))).to eq('/modules/foo')
end
it "should return unencoded path" do
expect(Puppet::Util.uri_to_path(URI.parse('http://foo/bar%20baz'))).to eq('/bar baz')
end
[
"http://foo/A%DB%BF%E1%9A%A0%F0%A0%9C%8E",
"http://foo/A%DB%BF%E1%9A%A0%F0%A0%9C%8E".force_encoding(Encoding::ASCII)
].each do |uri_string|
it "should return paths as UTF-8" do
path = Puppet::Util.uri_to_path(URI.parse(uri_string))
expect(path).to eq("/#{mixed_utf8}")
expect(path.encoding).to eq(Encoding::UTF_8)
end
end
it "should be nil-safe" do
expect(Puppet::Util.uri_to_path(nil)).to be_nil
end
describe "when using platform :posix",:if => Puppet.features.posix? do
it "should accept root" do
expect(Puppet::Util.uri_to_path(URI.parse('file:/'))).to eq('/')
end
it "should accept single slash" do
expect(Puppet::Util.uri_to_path(URI.parse('file:/foo/bar'))).to eq('/foo/bar')
end
it "should accept triple slashes" do
expect(Puppet::Util.uri_to_path(URI.parse('file:///foo/bar'))).to eq('/foo/bar')
end
end
describe "when using platform :windows", :if => Puppet::Util::Platform.windows? do
it "should accept root" do
expect(Puppet::Util.uri_to_path(URI.parse('file:/C:/'))).to eq('C:/')
end
it "should accept single slash" do
expect(Puppet::Util.uri_to_path(URI.parse('file:/C:/foo/bar'))).to eq('C:/foo/bar')
end
it "should accept triple slashes" do
expect(Puppet::Util.uri_to_path(URI.parse('file:///C:/foo/bar'))).to eq('C:/foo/bar')
end
it "should accept file scheme with double slashes as a UNC path" do
expect(Puppet::Util.uri_to_path(URI.parse('file://host/share/file'))).to eq('//host/share/file')
end
end
end
describe "safe_posix_fork on Windows and JRuby", if: Puppet::Util::Platform.windows? || Puppet::Util::Platform.jruby? do
it "raises not implemented error" do
expect {
Puppet::Util.safe_posix_fork
}.to raise_error(NotImplementedError, /fork/)
end
end
describe "safe_posix_fork", unless: Puppet::Util::Platform.windows? || Puppet::Util::Platform.jruby? do
let(:pid) { 5501 }
before :each do
# Most of the things this method does are bad to do during specs. :/
allow(Kernel).to receive(:fork).and_return(pid).and_yield
allow($stdin).to receive(:reopen)
allow($stdout).to receive(:reopen)
allow($stderr).to receive(:reopen)
# ensure that we don't really close anything!
allow(IO).to receive(:new)
end
it "should close all open file descriptors except stdin/stdout/stderr when /proc/self/fd exists" do
# This is ugly, but I can't really think of a better way to do it without
# letting it actually close fds, which seems risky
fds = [".", "..","0","1","2","3","5","100","1000"]
fds.each do |fd|
if fd == '.' || fd == '..'
next
elsif ['0', '1', '2'].include? fd
expect(IO).not_to receive(:new).with(fd.to_i)
else
expect(IO).to receive(:new).with(fd.to_i).and_return(double('io', close: nil))
end
end
dir_expectation = receive(:foreach).with('/proc/self/fd')
fds.each do |fd|
dir_expectation = dir_expectation.and_yield(fd)
end
allow(Dir).to dir_expectation
Puppet::Util.safe_posix_fork
end
it "should close all open file descriptors except stdin/stdout/stderr when /proc/self/fd doesn't exist" do
# This is ugly, but I can't really think of a better way to do it without
# letting it actually close fds, which seems risky
(0..2).each {|n| expect(IO).not_to receive(:new).with(n)}
(3..256).each {|n| expect(IO).to receive(:new).with(n).and_return(double('io', close: nil)) }
allow(Dir).to receive(:foreach).with('/proc/self/fd').and_raise(Errno::ENOENT)
Puppet::Util.safe_posix_fork
end
it "should close all open file descriptors except stdin/stdout/stderr when /proc/self is not a directory" do
# This is ugly, but I can't really think of a better way to do it without
# letting it actually close fds, which seems risky
(0..2).each {|n| expect(IO).not_to receive(:new).with(n)}
(3..256).each {|n| expect(IO).to receive(:new).with(n).and_return(double('io', close: nil)) }
allow(Dir).to receive(:foreach).with('/proc/self/fd').and_raise(Errno::ENOTDIR)
Puppet::Util.safe_posix_fork
end
it "should fork a child process to execute the block" do
expect(Kernel).to receive(:fork).and_return(pid).and_yield
Puppet::Util.safe_posix_fork do
"Fork this!"
end
end
it "should return the pid of the child process" do
expect(Puppet::Util.safe_posix_fork).to eq(pid)
end
end
describe "#which" do
let(:base) { File.expand_path('/bin') }
let(:path) { File.join(base, 'foo') }
before :each do
allow(FileTest).to receive(:file?).and_return(false)
allow(FileTest).to receive(:file?).with(path).and_return(true)
allow(FileTest).to receive(:executable?).and_return(false)
allow(FileTest).to receive(:executable?).with(path).and_return(true)
end
it "should accept absolute paths" do
expect(Puppet::Util.which(path)).to eq(path)
end
it "should return nil if no executable found" do
expect(Puppet::Util.which('doesnotexist')).to be_nil
end
it "should reject directories" do
expect(Puppet::Util.which(base)).to be_nil
end
it "should ignore ~user directories if the user doesn't exist" do
# Windows treats *any* user as a "user that doesn't exist", which means
# that this will work correctly across all our platforms, and should
# behave consistently. If they ever implement it correctly (eg: to do
# the lookup for real) it should just work transparently.
baduser = 'if_this_user_exists_I_will_eat_my_hat'
Puppet::Util.withenv("PATH" => "~#{baduser}#{File::PATH_SEPARATOR}#{base}") do
expect(Puppet::Util.which('foo')).to eq(path)
end
end
describe "on POSIX systems" do
before :each do
allow(Puppet.features).to receive(:posix?).and_return(true)
allow(Puppet::Util::Platform).to receive(:windows?).and_return(false)
end
it "should walk the search PATH returning the first executable" do
allow(ENV).to receive(:fetch).with('PATH').and_return(File.expand_path('/bin'))
allow(ENV).to receive(:fetch).with('PATHEXT', anything).and_return(nil)
expect(Puppet::Util.which('foo')).to eq(path)
end
end
describe "on Windows systems" do
let(:path) { File.expand_path(File.join(base, 'foo.CMD')) }
before :each do
allow(Puppet.features).to receive(:posix?).and_return(false)
allow(Puppet::Util::Platform).to receive(:windows?).and_return(true)
end
describe "when a file extension is specified" do
it "should walk each directory in PATH ignoring PATHEXT" do
allow(ENV).to receive(:fetch).with('PATH').and_return(%w[/bar /bin].map{|dir| File.expand_path(dir)}.join(File::PATH_SEPARATOR))
allow(ENV).to receive(:fetch).with('PATHEXT', anything).and_return('.FOOBAR')
expect(FileTest).to receive(:file?).with(File.join(File.expand_path('/bar'), 'foo.CMD')).and_return(false)
expect(Puppet::Util.which('foo.CMD')).to eq(path)
end
end
describe "when a file extension is not specified" do
it "should walk each extension in PATHEXT until an executable is found" do
bar = File.expand_path('/bar')
allow(ENV).to receive(:fetch).with('PATH').and_return("#{bar}#{File::PATH_SEPARATOR}#{base}")
allow(ENV).to receive(:fetch).with('PATHEXT', anything).and_return(".EXE#{File::PATH_SEPARATOR}.CMD")
expect(FileTest).to receive(:file?).ordered().with(File.join(bar, 'foo.EXE')).and_return(false)
expect(FileTest).to receive(:file?).ordered().with(File.join(bar, 'foo.CMD')).and_return(false)
expect(FileTest).to receive(:file?).ordered().with(File.join(base, 'foo.EXE')).and_return(false)
expect(FileTest).to receive(:file?).ordered().with(path).and_return(true)
expect(Puppet::Util.which('foo')).to eq(path)
end
it "should walk the default extension path if the environment variable is not defined" do
allow(ENV).to receive(:fetch).with('PATH').and_return(base)
allow(ENV).to receive(:fetch).with('PATHEXT', anything).and_return(nil)
%w[.COM .EXE .BAT].each do |ext|
expect(FileTest).to receive(:file?).ordered().with(File.join(base, "foo#{ext}")).and_return(false)
end
expect(FileTest).to receive(:file?).ordered().with(path).and_return(true)
expect(Puppet::Util.which('foo')).to eq(path)
end
it "should fall back if no extension matches" do
allow(ENV).to receive(:fetch).with('PATH').and_return(base)
allow(ENV).to receive(:fetch).with('PATHEXT', anything).and_return(".EXE")
allow(FileTest).to receive(:file?).with(File.join(base, 'foo.EXE')).and_return(false)
allow(FileTest).to receive(:file?).with(File.join(base, 'foo')).and_return(true)
allow(FileTest).to receive(:executable?).with(File.join(base, 'foo')).and_return(true)
expect(Puppet::Util.which('foo')).to eq(File.join(base, 'foo'))
end
end
end
end
describe "hash symbolizing functions" do
let (:myhash) { { "foo" => "bar", :baz => "bam" } }
let (:resulthash) { { :foo => "bar", :baz => "bam" } }
describe "#symbolizehash" do
it "should return a symbolized hash" do
newhash = Puppet::Util.symbolizehash(myhash)
expect(newhash).to eq(resulthash)
end
end
end
context "#replace_file" do
subject { Puppet::Util }
it { is_expected.to respond_to :replace_file }
let :target do
target = Tempfile.new("puppet-util-replace-file")
target.puts("hello, world")
target.flush # make sure content is on disk.
target.fsync rescue nil
target.close
target
end
it "should fail if no block is given" do
expect { subject.replace_file(target.path, 0600) }.to raise_error(/block/)
end
it "should replace a file when invoked" do
# Check that our file has the expected content.
expect(File.read(target.path)).to eq("hello, world\n")
# Replace the file.
subject.replace_file(target.path, 0600) do |fh|
fh.puts "I am the passenger..."
end
# ...and check the replacement was complete.
expect(File.read(target.path)).to eq("I am the passenger...\n")
end
# When running with the same user and group sid, which is the default,
# Windows collapses the owner and group modes into a single ACE, resulting
# in set(0600) => get(0660) and so forth. --daniel 2012-03-30
modes = [0555, 0660, 0770]
modes += [0600, 0700] unless Puppet::Util::Platform.windows?
modes.each do |mode|
it "should copy 0#{mode.to_s(8)} permissions from the target file by default" do
set_mode(mode, target.path)
expect(get_mode(target.path)).to eq(mode)
subject.replace_file(target.path, 0000) {|fh| fh.puts "bazam" }
expect(get_mode(target.path)).to eq(mode)
expect(File.read(target.path)).to eq("bazam\n")
end
end
it "should copy the permissions of the source file after yielding on Unix", :if => !Puppet::Util::Platform.windows? do
set_mode(0555, target.path)
inode = Puppet::FileSystem.stat(target.path).ino
yielded = false
subject.replace_file(target.path, 0660) do |fh|
expect(get_mode(fh.path)).to eq(0600)
yielded = true
end
expect(yielded).to be_truthy
expect(Puppet::FileSystem.stat(target.path).ino).not_to eq(inode)
expect(get_mode(target.path)).to eq(0555)
end
it "should be able to create a new file with read-only permissions when it doesn't already exist" do
temp_file = Tempfile.new('puppet-util-replace-file')
temp_path = temp_file.path
temp_file.close
temp_file.unlink
subject.replace_file(temp_path, 0440) do |fh|
fh.puts('some text in there')
end
expect(File.read(temp_path)).to eq("some text in there\n")
expect(get_mode(temp_path)).to eq(0440)
end
it "should use the default permissions if the source file doesn't exist" do
new_target = target.path + '.foo'
expect(Puppet::FileSystem.exist?(new_target)).to be_falsey
begin
subject.replace_file(new_target, 0555) {|fh| fh.puts "foo" }
expect(get_mode(new_target)).to eq(0555)
ensure
Puppet::FileSystem.unlink(new_target) if Puppet::FileSystem.exist?(new_target)
end
end
it "should use a temporary staging location if provided" do
new_target = File.join(tmpdir('new_file'), 'new_file.baz')
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | true |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/daemon_spec.rb | spec/unit/daemon_spec.rb | require 'spec_helper'
require 'puppet/daemon'
require 'puppet/agent'
require 'puppet/configurer'
describe Puppet::Daemon, :unless => Puppet::Util::Platform.windows? do
include PuppetSpec::Files
class RecordingScheduler
attr_reader :jobs
def run_loop(jobs)
@jobs = jobs
end
end
let(:agent) { Puppet::Agent.new(Puppet::Configurer, false) }
let(:server) { double("Server", :start => nil, :wait_for_shutdown => nil) }
let(:pidfile) { double("PidFile", :lock => true, :unlock => true, :file_path => 'fake.pid') }
let(:scheduler) { RecordingScheduler.new }
let(:daemon) { Puppet::Daemon.new(agent, pidfile, scheduler) }
before(:each) do
allow(Signal).to receive(:trap)
allow(daemon).to receive(:close_streams).and_return(nil)
end
it "should fail when no agent is provided" do
expect { Puppet::Daemon.new(nil, pidfile, scheduler) }.to raise_error(Puppet::DevError)
end
it "should reopen the Log logs when told to reopen logs" do
expect(Puppet::Util::Log).to receive(:reopen)
daemon.reopen_logs
end
describe "when setting signal traps" do
[:INT, :TERM].each do |signal|
it "logs a notice and exits when sent #{signal}" do
allow(Signal).to receive(:trap).with(signal).and_yield
expect(Puppet).to receive(:notice).with("Caught #{signal}; exiting")
expect(daemon).to receive(:stop)
daemon.set_signal_traps
end
end
{:HUP => :restart, :USR1 => :reload, :USR2 => :reopen_logs}.each do |signal, method|
it "logs a notice and remembers to call #{method} when it receives #{signal}" do
allow(Signal).to receive(:trap).with(signal).and_yield
expect(Puppet).to receive(:notice).with("Caught #{signal}; storing #{method}")
daemon.set_signal_traps
expect(daemon.signals).to eq([method])
end
end
end
describe "when starting" do
let(:reparse_run) { scheduler.jobs[0] }
let(:agent_run) { scheduler.jobs[1] }
before do
allow(daemon).to receive(:set_signal_traps)
end
it "should create its pidfile" do
expect(pidfile).to receive(:lock).and_return(true)
daemon.start
end
it "should fail if it cannot lock" do
expect(pidfile).to receive(:lock).and_return(false)
expect { daemon.start }.to raise_error(RuntimeError, "Could not create PID file: #{pidfile.file_path}")
end
it "disables the reparse of configs if the filetimeout is 0" do
Puppet[:filetimeout] = 0
daemon.start
expect(reparse_run).not_to be_enabled
end
it "does not splay the agent run by default" do
daemon.start
expect(agent_run.splay).to eq(0)
end
describe "and calculating splay" do
before do
# Set file timeout so the daemon reparses
Puppet[:filetimeout] = 1
Puppet[:splay] = true
end
it "recalculates when splaylimit changes" do
daemon.start
Puppet[:splaylimit] = 60
init_splay = agent_run.splay
next_splay = init_splay + 1
allow(agent_run).to receive(:rand).and_return(next_splay)
reparse_run.run(Time.now)
expect(agent_run.splay).to eq(next_splay)
end
it "does not change splay if splaylimit is unmodified" do
daemon.start
init_splay = agent_run.splay
reparse_run.run(Time.now)
expect(agent_run.splay).to eq(init_splay)
end
it "recalculates when splay is enabled later" do
Puppet[:splay] = false
daemon.start
Puppet[:splay] = true
allow(agent_run).to receive(:rand).and_return(999)
reparse_run.run(Time.now)
expect(agent_run.splay).to eq(999)
end
it "sets splay to 0 when splay is disabled" do
daemon.start
Puppet[:splay] = false
reparse_run.run(Time.now)
expect(agent_run.splay).to eq(0)
end
it "recalculates splay when runinterval is decreased" do
Puppet[:runinterval] = 60
daemon.start
Puppet[:runinterval] = Puppet[:runinterval] - 30
new_splay = agent_run.splay + 1
allow(agent_run).to receive(:rand).and_return(new_splay)
reparse_run.run(Time.now)
expect(agent_run.splay).to eq(new_splay)
end
it "recalculates splay when runinterval is increased" do
Puppet[:runinterval] = 60
daemon.start
Puppet[:runinterval] = Puppet[:runinterval] + 30
new_splay = agent_run.splay - 1
allow(agent_run).to receive(:rand).and_return(new_splay)
reparse_run.run(Time.now)
expect(agent_run.splay).to eq(new_splay)
end
end
end
describe "when stopping" do
before do
allow(Puppet::Util::Log).to receive(:close_all)
# to make the global safe to mock, set it to a subclass of itself
stub_const('Puppet::Application', Class.new(Puppet::Application))
end
it 'should request a stop from Puppet::Application' do
expect(Puppet::Application).to receive(:stop!)
expect { daemon.stop }.to exit_with 0
end
it "should remove its pidfile" do
expect(pidfile).to receive(:unlock)
expect { daemon.stop }.to exit_with 0
end
it "should close all logs" do
expect(Puppet::Util::Log).to receive(:close_all)
expect { daemon.stop }.to exit_with 0
end
it "should exit unless called with ':exit => false'" do
expect { daemon.stop }.to exit_with 0
end
it "should not exit if called with ':exit => false'" do
daemon.stop :exit => false
end
end
describe "when reloading" do
it "should do nothing if the agent is running" do
expect(agent).to receive(:run).with({:splay => false}).and_raise(Puppet::LockError, 'Failed to aquire lock')
expect(Puppet).to receive(:notice).with('Not triggering already-running agent')
daemon.reload
end
it "should run the agent if one is available and it is not running" do
expect(agent).to receive(:run).with({:splay => false})
expect(Puppet).not_to receive(:notice).with('Not triggering already-running agent')
daemon.reload
end
end
describe "when restarting" do
before do
stub_const('Puppet::Application', Class.new(Puppet::Application))
end
it 'should set Puppet::Application.restart!' do
expect(Puppet::Application).to receive(:restart!)
allow(daemon).to receive(:reexec)
daemon.restart
end
it "should reexec itself if no agent is available" do
expect(daemon).to receive(:reexec)
daemon.restart
end
it "should reexec itself if the agent is not running" do
expect(daemon).to receive(:reexec)
daemon.restart
end
end
describe "when reexecing it self" do
before do
allow(daemon).to receive(:exec)
allow(daemon).to receive(:stop)
end
it "should fail if no argv values are available" do
expect(daemon).to receive(:argv).and_return(nil)
expect { daemon.reexec }.to raise_error(Puppet::DevError)
end
it "should shut down without exiting" do
daemon.argv = %w{foo}
expect(daemon).to receive(:stop).with({:exit => false})
daemon.reexec
end
it "should call 'exec' with the original executable and arguments" do
daemon.argv = %w{foo}
expect(daemon).to receive(:exec).with($0 + " foo")
daemon.reexec
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/property_spec.rb | spec/unit/property_spec.rb | require 'spec_helper'
require 'puppet/property'
Puppet::Type.newtype(:property_test) do
newparam(:name, isnamevar: true)
end
Puppet::Type.type(:property_test).provide(:property_test) do
attr_accessor :foo
end
describe Puppet::Property do
let :resource do
Puppet::Type.type(:property_test).new(:name => "foo")
end
let :subclass do
# We need a completely fresh subclass every time, because we modify both
# class and instance level things inside the tests.
subclass = Class.new(Puppet::Property) do
class << self
attr_accessor :name
end
@name = :foo
end
subclass.initvars
subclass
end
let :property do subclass.new :resource => resource end
it "should be able to look up the modified name for a given value" do
subclass.newvalue(:foo)
expect(subclass.value_name("foo")).to eq(:foo)
end
it "should be able to look up the modified name for a given value matching a regex" do
subclass.newvalue(%r{.})
expect(subclass.value_name("foo")).to eq(%r{.})
end
it "should be able to look up a given value option" do
subclass.newvalue(:foo, :event => :whatever)
expect(subclass.value_option(:foo, :event)).to eq(:whatever)
end
it "should be able to specify required features" do
expect(subclass).to respond_to(:required_features=)
end
{"one" => [:one],:one => [:one],%w{a} => [:a],[:b] => [:b],%w{one two} => [:one,:two],[:a,:b] => [:a,:b]}.each { |in_value,out_value|
it "should always convert required features into an array of symbols (e.g. #{in_value.inspect} --> #{out_value.inspect})" do
subclass.required_features = in_value
expect(subclass.required_features).to eq(out_value)
end
}
it "should return its name as a string when converted to a string" do
expect(property.to_s).to eq(property.name.to_s)
end
describe "when returning the default event name" do
it "should use the current 'should' value to pick the event name" do
expect(property).to receive(:should).and_return("myvalue")
expect(subclass).to receive(:value_option).with('myvalue', :event).and_return(:event_name)
property.event_name
end
it "should return any event defined with the specified value" do
expect(property).to receive(:should).and_return(:myval)
expect(subclass).to receive(:value_option).with(:myval, :event).and_return(:event_name)
expect(property.event_name).to eq(:event_name)
end
describe "and the property is 'ensure'" do
before :each do
allow(property).to receive(:name).and_return(:ensure)
expect(resource).to receive(:type).and_return(:mytype)
end
it "should use <type>_created if the 'should' value is 'present'" do
expect(property).to receive(:should).and_return(:present)
expect(property.event_name).to eq(:mytype_created)
end
it "should use <type>_removed if the 'should' value is 'absent'" do
expect(property).to receive(:should).and_return(:absent)
expect(property.event_name).to eq(:mytype_removed)
end
it "should use <type>_changed if the 'should' value is not 'absent' or 'present'" do
expect(property).to receive(:should).and_return(:foo)
expect(property.event_name).to eq(:mytype_changed)
end
it "should use <type>_changed if the 'should value is nil" do
expect(property).to receive(:should).and_return(nil)
expect(property.event_name).to eq(:mytype_changed)
end
end
it "should use <property>_changed if the property is not 'ensure'" do
allow(property).to receive(:name).and_return(:myparam)
expect(property).to receive(:should).and_return(:foo)
expect(property.event_name).to eq(:myparam_changed)
end
it "should use <property>_changed if no 'should' value is set" do
allow(property).to receive(:name).and_return(:myparam)
expect(property).to receive(:should).and_return(nil)
expect(property.event_name).to eq(:myparam_changed)
end
end
describe "when creating an event" do
before :each do
allow(property).to receive(:should).and_return("myval")
end
it "should use an event from the resource as the base event" do
event = Puppet::Transaction::Event.new
expect(resource).to receive(:event).and_return(event)
expect(property.event).to equal(event)
end
it "should have the default event name" do
expect(property).to receive(:event_name).and_return(:my_event)
expect(property.event.name).to eq(:my_event)
end
it "should have the property's name" do
expect(property.event.property).to eq(property.name.to_s)
end
it "should have the 'should' value set" do
allow(property).to receive(:should).and_return("foo")
expect(property.event.desired_value).to eq("foo")
end
it "should provide its path as the source description" do
allow(property).to receive(:path).and_return("/my/param")
expect(property.event.source_description).to eq("/my/param")
end
it "should have the 'invalidate_refreshes' value set if set on a value" do
allow(property).to receive(:event_name).and_return(:my_event)
allow(property).to receive(:should).and_return("foo")
foo = double()
expect(foo).to receive(:invalidate_refreshes).and_return(true)
collection = double()
expect(collection).to receive(:match?).with("foo").and_return(foo)
allow(property.class).to receive(:value_collection).and_return(collection)
expect(property.event.invalidate_refreshes).to be_truthy
end
it "sets the redacted field on the event when the property is sensitive" do
property.sensitive = true
expect(property.event.redacted).to eq true
end
end
describe "when defining new values" do
it "should define a method for each value created with a block that's not a regex" do
subclass.newvalue(:foo) { }
expect(property).to respond_to(:set_foo)
end
end
describe "when assigning the value" do
it "should just set the 'should' value" do
property.value = "foo"
expect(property.should).to eq("foo")
end
it "should validate each value separately" do
expect(property).to receive(:validate).with("one")
expect(property).to receive(:validate).with("two")
property.value = %w{one two}
end
it "should munge each value separately and use any result as the actual value" do
expect(property).to receive(:munge).with("one").and_return(:one)
expect(property).to receive(:munge).with("two").and_return(:two)
# Do this so we get the whole array back.
subclass.array_matching = :all
property.value = %w{one two}
expect(property.should).to eq([:one, :two])
end
it "should return any set value" do
expect(property.value = :one).to eq(:one)
end
end
describe "when returning the value" do
it "should return nil if no value is set" do
expect(property.should).to be_nil
end
it "should return the first set 'should' value if :array_matching is set to :first" do
subclass.array_matching = :first
property.should = %w{one two}
expect(property.should).to eq("one")
end
it "should return all set 'should' values as an array if :array_matching is set to :all" do
subclass.array_matching = :all
property.should = %w{one two}
expect(property.should).to eq(%w{one two})
end
it "should default to :first array_matching" do
expect(subclass.array_matching).to eq(:first)
end
it "should unmunge the returned value if :array_matching is set to :first" do
property.class.unmunge do |v| v.to_sym end
subclass.array_matching = :first
property.should = %w{one two}
expect(property.should).to eq(:one)
end
it "should unmunge all the returned values if :array_matching is set to :all" do
property.class.unmunge do |v| v.to_sym end
subclass.array_matching = :all
property.should = %w{one two}
expect(property.should).to eq([:one, :two])
end
end
describe "when validating values" do
it "should do nothing if no values or regexes have been defined" do
expect { property.should = "foo" }.not_to raise_error
end
it "should fail if the value is not a defined value or alias and does not match a regex" do
subclass.newvalue(:foo)
expect { property.should = "bar" }.to raise_error(Puppet::Error, /Invalid value "bar"./)
end
it "should succeeed if the value is one of the defined values" do
subclass.newvalue(:foo)
expect { property.should = :foo }.not_to raise_error
end
it "should succeeed if the value is one of the defined values even if the definition uses a symbol and the validation uses a string" do
subclass.newvalue(:foo)
expect { property.should = "foo" }.not_to raise_error
end
it "should succeeed if the value is one of the defined values even if the definition uses a string and the validation uses a symbol" do
subclass.newvalue("foo")
expect { property.should = :foo }.not_to raise_error
end
it "should succeed if the value is one of the defined aliases" do
subclass.newvalue("foo")
subclass.aliasvalue("bar", "foo")
expect { property.should = :bar }.not_to raise_error
end
it "should succeed if the value matches one of the regexes" do
subclass.newvalue(/./)
expect { property.should = "bar" }.not_to raise_error
end
it "should validate that all required features are present" do
subclass.newvalue(:foo, :required_features => [:a, :b])
expect(resource.provider).to receive(:satisfies?).with([:a, :b]).and_return(true)
property.should = :foo
end
it "should fail if required features are missing" do
subclass.newvalue(:foo, :required_features => [:a, :b])
expect(resource.provider).to receive(:satisfies?).with([:a, :b]).and_return(false)
expect { property.should = :foo }.to raise_error(Puppet::Error)
end
it "should internally raise an ArgumentError if required features are missing" do
subclass.newvalue(:foo, :required_features => [:a, :b])
expect(resource.provider).to receive(:satisfies?).with([:a, :b]).and_return(false)
expect { property.validate_features_per_value :foo }.to raise_error(ArgumentError)
end
it "should validate that all required features are present for regexes" do
subclass.newvalue(/./, :required_features => [:a, :b])
expect(resource.provider).to receive(:satisfies?).with([:a, :b]).and_return(true)
property.should = "foo"
end
it "should support specifying an individual required feature" do
subclass.newvalue(/./, :required_features => :a)
expect(resource.provider).to receive(:satisfies?).and_return(true)
property.should = "foo"
end
end
describe "when munging values" do
it "should do nothing if no values or regexes have been defined" do
expect(property.munge("foo")).to eq("foo")
end
it "should return return any matching defined values" do
subclass.newvalue(:foo)
expect(property.munge("foo")).to eq(:foo)
end
it "should return any matching aliases" do
subclass.newvalue(:foo)
subclass.aliasvalue(:bar, :foo)
expect(property.munge("bar")).to eq(:foo)
end
it "should return the value if it matches a regex" do
subclass.newvalue(/./)
expect(property.munge("bar")).to eq("bar")
end
it "should return the value if no other option is matched" do
subclass.newvalue(:foo)
expect(property.munge("bar")).to eq("bar")
end
end
describe "when syncing the 'should' value" do
it "should set the value" do
subclass.newvalue(:foo)
property.should = :foo
expect(property).to receive(:set).with(:foo)
property.sync
end
end
describe "when setting a value" do
it "should catch exceptions and raise Puppet::Error" do
subclass.newvalue(:foo) { raise "eh" }
expect { property.set(:foo) }.to raise_error(Puppet::Error)
end
it "fails when the provider does not handle the attribute" do
subclass.name = "unknown"
expect { property.set(:a_value) }.to raise_error(Puppet::Error)
end
it "propogates the errors about missing methods from the provider" do
provider = resource.provider
def provider.bad_method=(value)
value.this_method_does_not_exist
end
subclass.name = :bad_method
expect { property.set(:a_value) }.to raise_error(NoMethodError, /this_method_does_not_exist/)
end
describe "that was defined without a block" do
it "should call the settor on the provider" do
subclass.newvalue(:bar)
expect(resource.provider).to receive(:foo=).with(:bar)
property.set(:bar)
end
it "should generate setter named from :method argument and propagate call to the provider" do
subclass.newvalue(:bar, :method => 'set_vv')
expect(resource.provider).to receive(:foo=).with(:bar)
property.set_vv(:bar)
end
end
describe "that was defined with a block" do
it "should call the method created for the value if the value is not a regex" do
subclass.newvalue(:bar) {}
expect(property).to receive(:set_bar)
property.set(:bar)
end
it "should call the provided block if the value is a regex" do
thing = double
subclass.newvalue(/./) { thing.test }
expect(thing).to receive(:test)
property.set("foo")
end
end
end
describe "when producing a change log" do
it "should say 'defined' when the current value is 'absent'" do
expect(property.change_to_s(:absent, "foo")).to match(/^defined/)
end
it "should say 'undefined' when the new value is 'absent'" do
expect(property.change_to_s("foo", :absent)).to match(/^undefined/)
end
it "should say 'changed' when neither value is 'absent'" do
expect(property.change_to_s("foo", "bar")).to match(/changed/)
end
end
shared_examples_for "#insync?" do
# We share a lot of behaviour between the all and first matching, so we
# use a shared behaviour set to emulate that. The outside world makes
# sure the class, etc, point to the right content.
[[], [12], [12, 13]].each do |input|
it "should return true if should is empty with is => #{input.inspect}" do
property.should = []
expect(property).to be_insync(input)
expect(property.insync_values?([], input)).to be true
end
end
end
describe "#insync?" do
context "array_matching :all" do
# `@should` is an array of scalar values, and `is` is an array of scalar values.
before :each do
property.class.array_matching = :all
end
it_should_behave_like "#insync?"
context "if the should value is an array" do
let(:input) { [1,2] }
before :each do property.should = input end
it "should match if is exactly matches" do
val = [1, 2]
expect(property).to be_insync val
expect(property.insync_values?(input, val)).to be true
end
it "should match if it matches, but all stringified" do
val = ["1", "2"]
expect(property).to be_insync val
expect(property.insync_values?(input, val)).to be true
end
it "should not match if some-but-not-all values are stringified" do
val = ["1", 2]
expect(property).to_not be_insync val
expect(property.insync_values?(input, val)).to_not be true
val = [1, "2"]
expect(property).to_not be_insync val
expect(property.insync_values?(input, val)).to_not be true
end
it "should not match if order is different but content the same" do
val = [2, 1]
expect(property).to_not be_insync val
expect(property.insync_values?(input, val)).to_not be true
end
it "should not match if there are more items in should than is" do
val = [1]
expect(property).to_not be_insync val
expect(property.insync_values?(input, val)).to_not be true
end
it "should not match if there are less items in should than is" do
val = [1, 2, 3]
expect(property).to_not be_insync val
expect(property.insync_values?(input, val)).to_not be true
end
it "should not match if `is` is empty but `should` isn't" do
val = []
expect(property).to_not be_insync val
expect(property.insync_values?(input, val)).to_not be true
end
end
end
context "array_matching :first" do
# `@should` is an array of scalar values, and `is` is a scalar value.
before :each do
property.class.array_matching = :first
end
it_should_behave_like "#insync?"
[[1], # only the value
[1, 2], # matching value first
[2, 1], # matching value last
[0, 1, 2], # matching value in the middle
].each do |input|
it "should by true if one unmodified should value of #{input.inspect} matches what is" do
val = 1
property.should = input
expect(property).to be_insync val
expect(property.insync_values?(input, val)).to be true
end
it "should be true if one stringified should value of #{input.inspect} matches what is" do
val = "1"
property.should = input
expect(property).to be_insync val
expect(property.insync_values?(input, val)).to be true
end
end
it "should not match if we expect a string but get the non-stringified value" do
property.should = ["1"]
expect(property).to_not be_insync 1
expect(property.insync_values?(["1"], 1)).to_not be true
end
[[0], [0, 2]].each do |input|
it "should not match if no should values match what is" do
property.should = input
expect(property).to_not be_insync 1
expect(property.insync_values?(input, 1)).to_not be true
expect(property).to_not be_insync "1" # shouldn't match either.
expect(property.insync_values?(input, "1")).to_not be true
end
end
end
end
describe "#property_matches?" do
[1, "1", [1], :one].each do |input|
it "should treat two equal objects as equal (#{input.inspect})" do
expect(property.property_matches?(input, input)).to be_truthy
end
end
it "should treat two objects as equal if the first argument is the stringified version of the second" do
expect(property.property_matches?("1", 1)).to be_truthy
end
it "should NOT treat two objects as equal if the first argument is not a string, and the second argument is a string, even if it stringifies to the first" do
expect(property.property_matches?(1, "1")).to be_falsey
end
end
describe "#insync_values?" do
it "should log an exception when insync? throws one" do
expect(property).to receive(:insync?).and_raise(ArgumentError)
expect(property.insync_values?("foo","bar")).to be nil
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/settings_spec.rb | spec/unit/settings_spec.rb | require 'spec_helper'
require 'ostruct'
require 'puppet/settings/errors'
require 'puppet_spec/files'
require 'matchers/resource'
describe Puppet::Settings do
include PuppetSpec::Files
include Matchers::Resource
let(:main_config_file_default_location) do
File.join(Puppet::Util::RunMode[:server].conf_dir, "puppet.conf")
end
let(:user_config_file_default_location) do
File.join(Puppet::Util::RunMode[:user].conf_dir, "puppet.conf")
end
# Return a given object's file metadata.
def metadata(setting)
if setting.is_a?(Puppet::Settings::FileSetting)
{
:owner => setting.owner,
:group => setting.group,
:mode => setting.mode
}.delete_if { |key, value| value.nil? }
else
nil
end
end
def stub_config_with(content)
allow(Puppet.features).to receive(:root?).and_return(false)
expect(Puppet::FileSystem).to receive(:exist?).
with(user_config_file_default_location).
and_return(true).ordered
expect(@settings).to receive(:read_file).
with(user_config_file_default_location).
and_return(content).ordered
@settings.send(:parse_config_files)
end
describe "when specifying defaults" do
before do
@settings = Puppet::Settings.new
end
it "should start with no defined sections or parameters" do
# Note this relies on undocumented side effect that eachsection returns the Settings internal
# configuration on which keys returns all parameters.
expect(@settings.eachsection.keys.length).to eq(0)
end
it "should not allow specification of default values associated with a section as an array" do
expect {
@settings.define_settings(:section, :myvalue => ["defaultval", "my description"])
}.to raise_error(ArgumentError, /setting definition for 'myvalue' is not a hash!/)
end
it "should not allow duplicate parameter specifications" do
@settings.define_settings(:section, :myvalue => { :default => "a", :desc => "b" })
expect { @settings.define_settings(:section, :myvalue => { :default => "c", :desc => "d" }) }.to raise_error(ArgumentError)
end
it "should allow specification of default values associated with a section as a hash" do
@settings.define_settings(:section, :myvalue => {:default => "defaultval", :desc => "my description"})
end
it "should consider defined parameters to be valid" do
@settings.define_settings(:section, :myvalue => { :default => "defaultval", :desc => "my description" })
expect(@settings.valid?(:myvalue)).to be_truthy
end
it "should require a description when defaults are specified with a hash" do
expect { @settings.define_settings(:section, :myvalue => {:default => "a value"}) }.to raise_error(ArgumentError)
end
it "should support specifying owner, group, and mode when specifying files" do
@settings.define_settings(:section, :myvalue => {:type => :file, :default => "/some/file", :owner => "service", :mode => "boo", :group => "service", :desc => "whatever"})
end
it "should support specifying a short name" do
@settings.define_settings(:section, :myvalue => {:default => "w", :desc => "b", :short => "m"})
end
it "should support specifying the setting type" do
@settings.define_settings(:section, :myvalue => {:default => "/w", :desc => "b", :type => :string})
expect(@settings.setting(:myvalue)).to be_instance_of(Puppet::Settings::StringSetting)
end
it "should fail if an invalid setting type is specified" do
expect { @settings.define_settings(:section, :myvalue => {:default => "w", :desc => "b", :type => :foo}) }.to raise_error(ArgumentError)
end
it "should fail when short names conflict" do
@settings.define_settings(:section, :myvalue => {:default => "w", :desc => "b", :short => "m"})
expect { @settings.define_settings(:section, :myvalue => {:default => "w", :desc => "b", :short => "m"}) }.to raise_error(ArgumentError)
end
end
describe "when initializing application defaults do" do
before do
@settings = Puppet::Settings.new
@settings.define_settings(:main, PuppetSpec::Settings::TEST_APP_DEFAULT_DEFINITIONS)
end
it "should fail if the app defaults hash is missing any required values" do
expect {
@settings.initialize_app_defaults(PuppetSpec::Settings::TEST_APP_DEFAULT_VALUES.reject { |key, _| key == :confdir })
}.to raise_error(Puppet::Settings::SettingsError)
end
# ultimately I'd like to stop treating "run_mode" as a normal setting, because it has so many special
# case behaviors / uses. However, until that time... we need to make sure that our private run_mode=
# setter method gets properly called during app initialization.
it "sets the preferred run mode when initializing the app defaults" do
@settings.initialize_app_defaults(PuppetSpec::Settings::TEST_APP_DEFAULT_VALUES.merge(:run_mode => :server))
expect(@settings.preferred_run_mode).to eq(:server)
end
it "creates ancestor directories for all required app settings" do
# initialize_app_defaults is called in spec_helper, before we even
# get here, but call it here to make it explicit what we're trying
# to do.
@settings.initialize_app_defaults(PuppetSpec::Settings::TEST_APP_DEFAULT_VALUES)
Puppet::Settings::REQUIRED_APP_SETTINGS.each do |key|
expect(File).to exist(File.dirname(Puppet[key]))
end
end
end
describe "#call_hooks_deferred_to_application_initialization" do
let(:good_default) { "yay" }
let(:bad_default) { "$doesntexist" }
before(:each) do
@settings = Puppet::Settings.new
end
describe "when ignoring dependency interpolation errors" do
let(:options) { {:ignore_interpolation_dependency_errors => true} }
describe "if interpolation error" do
it "should not raise an error" do
hook_values = []
@settings.define_settings(:section, :badhook => {:default => bad_default, :desc => "boo", :call_hook => :on_initialize_and_write, :hook => lambda { |v| hook_values << v }})
expect do
@settings.send(:call_hooks_deferred_to_application_initialization, options)
end.to_not raise_error
end
end
describe "if no interpolation error" do
it "should not raise an error" do
hook_values = []
@settings.define_settings(:section, :goodhook => {:default => good_default, :desc => "boo", :call_hook => :on_initialize_and_write, :hook => lambda { |v| hook_values << v }})
expect do
@settings.send(:call_hooks_deferred_to_application_initialization, options)
end.to_not raise_error
end
end
end
describe "when not ignoring dependency interpolation errors" do
[ {}, {:ignore_interpolation_dependency_errors => false}].each do |options|
describe "if interpolation error" do
it "should raise an error" do
hook_values = []
@settings.define_settings(
:section,
:badhook => {
:default => bad_default,
:desc => "boo",
:call_hook => :on_initialize_and_write,
:hook => lambda { |v| hook_values << v }
}
)
expect do
@settings.send(:call_hooks_deferred_to_application_initialization, options)
end.to raise_error(Puppet::Settings::InterpolationError)
end
it "should contain the setting name in error message" do
hook_values = []
@settings.define_settings(
:section,
:badhook => {
:default => bad_default,
:desc => "boo",
:call_hook => :on_initialize_and_write,
:hook => lambda { |v| hook_values << v }
}
)
expect do
@settings.send(:call_hooks_deferred_to_application_initialization, options)
end.to raise_error(Puppet::Settings::InterpolationError, /badhook/)
end
end
describe "if no interpolation error" do
it "should not raise an error" do
hook_values = []
@settings.define_settings(
:section,
:goodhook => {
:default => good_default,
:desc => "boo",
:call_hook => :on_initialize_and_write,
:hook => lambda { |v| hook_values << v }
}
)
expect do
@settings.send(:call_hooks_deferred_to_application_initialization, options)
end.to_not raise_error
end
end
end
end
end
describe "when setting values" do
before do
@settings = Puppet::Settings.new
@settings.define_settings :main, :myval => { :default => "val", :desc => "desc" }
@settings.define_settings :main, :bool => { :type => :boolean, :default => true, :desc => "desc" }
end
it "should provide a method for setting values from other objects" do
@settings[:myval] = "something else"
expect(@settings[:myval]).to eq("something else")
end
it "should support a getopt-specific mechanism for setting values" do
@settings.handlearg("--myval", "newval")
expect(@settings[:myval]).to eq("newval")
end
it "should support a getopt-specific mechanism for turning booleans off" do
@settings.override_default(:bool, true)
@settings.handlearg("--no-bool", "")
expect(@settings[:bool]).to eq(false)
end
it "should support a getopt-specific mechanism for turning booleans on" do
# Turn it off first
@settings.override_default(:bool, false)
@settings.handlearg("--bool", "")
expect(@settings[:bool]).to eq(true)
end
it "should consider a cli setting with no argument to be a boolean" do
# Turn it off first
@settings.override_default(:bool, false)
@settings.handlearg("--bool")
expect(@settings[:bool]).to eq(true)
end
it "should consider a cli setting with an empty string as an argument to be an empty argument, if the setting itself is not a boolean" do
@settings.override_default(:myval, "bob")
@settings.handlearg("--myval", "")
expect(@settings[:myval]).to eq("")
end
it "should consider a cli setting with a boolean as an argument to be a boolean" do
# Turn it off first
@settings.override_default(:bool, false)
@settings.handlearg("--bool", "true")
expect(@settings[:bool]).to eq(true)
end
it "should not consider a cli setting of a non boolean with a boolean as an argument to be a boolean" do
@settings.override_default(:myval, "bob")
@settings.handlearg("--no-myval", "")
expect(@settings[:myval]).to eq("")
end
it "should retrieve numeric settings from the CLI" do
@settings.handlearg("--myval", "12")
expect(@settings.set_by_cli(:myval)).to eq("12")
expect(@settings.set_by_cli?(:myval)).to be true
end
it "should retrieve string settings from the CLI" do
@settings.handlearg("--myval", "something")
expect(@settings.set_by_cli(:myval)).to eq("something")
expect(@settings.set_by_cli?(:myval)).to be true
end
it "should retrieve bool settings from the CLI" do
@settings.handlearg("--bool")
expect(@settings.set_by_cli(:bool)).to be true
expect(@settings.set_by_cli?(:bool)).to be true
end
it "should not retrieve settings set in memory as from CLI" do
@settings[:myval] = "12"
expect(@settings.set_by_cli?(:myval)).to be false
end
it "should find no configured settings by default" do
expect(@settings.set_by_config?(:myval)).to be false
end
it "should identify configured settings in memory" do
expect(@settings.instance_variable_get(:@value_sets)[:memory]).to receive(:lookup).with(:myval).and_return('foo')
expect(@settings.set_by_config?(:myval)).to be_truthy
end
it "should identify configured settings from CLI" do
expect(@settings.instance_variable_get(:@value_sets)[:cli]).to receive(:lookup).with(:myval).and_return('foo')
expect(@settings.set_by_config?(:myval)).to be_truthy
end
it "should not identify configured settings from environment by default" do
expect(Puppet.lookup(:environments)).not_to receive(:get_conf).with(Puppet[:environment].to_sym)
expect(@settings.set_by_config?(:manifest)).to be_falsey
end
it "should identify configured settings from environment by when an environment is specified" do
foo = double('environment', :manifest => 'foo')
expect(Puppet.lookup(:environments)).to receive(:get_conf).with(Puppet[:environment].to_sym).and_return(foo)
expect(@settings.set_by_config?(:manifest, Puppet[:environment])).to be_truthy
end
context "when handling puppet.conf" do
describe "#set_by_config?" do
it "should identify configured settings from the preferred run mode" do
stub_config_with(<<~CONFIG)
[#{@settings.preferred_run_mode}]
myval = foo
CONFIG
expect(@settings.set_by_config?(:myval)).to be_truthy
end
it "should identify configured settings from the specified run mode" do
stub_config_with(<<~CONFIG)
[server]
myval = foo
CONFIG
expect(@settings.set_by_config?(:myval, nil, :server)).to be_truthy
end
it "should not identify configured settings from an unspecified run mode" do
stub_config_with(<<~CONFIG)
[zaz]
myval = foo
CONFIG
expect(@settings.set_by_config?(:myval)).to be_falsey
end
it "should identify configured settings from the main section" do
stub_config_with(<<~CONFIG)
[main]
myval = foo
CONFIG
expect(@settings.set_by_config?(:myval)).to be_truthy
end
end
describe "#set_in_section" do
it "should retrieve configured settings from the specified section" do
stub_config_with(<<~CONFIG)
[agent]
myval = foo
CONFIG
expect(@settings.set_in_section(:myval, :agent)).to eq("foo")
expect(@settings.set_in_section?(:myval, :agent)).to be true
end
it "should not retrieve configured settings from a different section" do
stub_config_with(<<~CONFIG)
[main]
myval = foo
CONFIG
expect(@settings.set_in_section(:myval, :agent)).to be nil
expect(@settings.set_in_section?(:myval, :agent)).to be false
end
end
end
it "should clear the cache when setting getopt-specific values" do
@settings.define_settings :mysection,
:one => { :default => "whah", :desc => "yay" },
:two => { :default => "$one yay", :desc => "bah" }
expect(@settings).to receive(:unsafe_flush_cache)
expect(@settings[:two]).to eq("whah yay")
@settings.handlearg("--one", "else")
expect(@settings[:two]).to eq("else yay")
end
it "should clear the cache when the preferred_run_mode is changed" do
expect(@settings).to receive(:flush_cache)
@settings.preferred_run_mode = :server
end
it "should not clear other values when setting getopt-specific values" do
@settings[:myval] = "yay"
@settings.handlearg("--no-bool", "")
expect(@settings[:myval]).to eq("yay")
end
it "should clear the list of used sections" do
expect(@settings).to receive(:clearused)
@settings[:myval] = "yay"
end
describe "call_hook" do
let(:config_file) { tmpfile('config') }
before :each do
# We can't specify the config file to read from using `Puppet[:config] =`
# or pass it as an arg to Puppet.initialize_global_settings, because
# both of those will set the value on the `Puppet.settings` instance
# which is different from the `@settings` instance created in the test.
# Instead, we define a `:config` setting and set its default value to
# the `config_file` temp file, and then access the `config_file` within
# each test.
@settings.define_settings(:main, :config => { :type => :file, :desc => "config file", :default => config_file })
end
Puppet::Settings::StringSetting.available_call_hook_values.each do |val|
describe "when :#{val}" do
describe "and definition invalid" do
it "should raise error if no hook defined" do
expect do
@settings.define_settings(:section, :setting => {:default => "yay", :desc => "boo", :call_hook => val})
end.to raise_error(ArgumentError, /no :hook/)
end
it "should include the setting name in the error message" do
expect do
@settings.define_settings(:section, :setting => {:default => "yay", :desc => "boo", :call_hook => val})
end.to raise_error(ArgumentError, /for :setting/)
end
end
describe "and definition valid" do
before(:each) do
hook_values = []
@settings.define_settings(:section, :setting => {:default => "yay", :desc => "boo", :call_hook => val, :hook => lambda { |v| hook_values << v }})
end
it "should call the hook when value written" do
expect(@settings.setting(:setting)).to receive(:handle).with("something").once
@settings[:setting] = "something"
end
end
end
end
it "should have a default value of :on_write_only" do
@settings.define_settings(:section, :setting => {:default => "yay", :desc => "boo", :hook => lambda { |v| hook_values << v }})
expect(@settings.setting(:setting).call_hook).to eq(:on_write_only)
end
describe "when nil" do
it "should generate a warning" do
expect(Puppet).to receive(:warning)
@settings.define_settings(:section, :setting => {:default => "yay", :desc => "boo", :call_hook => nil, :hook => lambda { |v| hook_values << v }})
end
it "should use default" do
@settings.define_settings(:section, :setting => {:default => "yay", :desc => "boo", :call_hook => nil, :hook => lambda { |v| hook_values << v }})
expect(@settings.setting(:setting).call_hook).to eq(:on_write_only)
end
end
describe "when invalid" do
it "should raise an error" do
expect do
@settings.define_settings(:section, :setting => {:default => "yay", :desc => "boo", :call_hook => :foo, :hook => lambda { |v| hook_values << v }})
end.to raise_error(ArgumentError, /invalid.*call_hook/i)
end
end
describe "when :on_write_only" do
it "returns its hook type" do
@settings.define_settings(:main, :setting => {:default => "yay", :desc => "boo", :hook => lambda { |_| }})
expect(@settings.setting(:setting).call_hook).to eq(:on_write_only)
end
it "should not call the hook at definition" do
hook_values = []
@settings.define_settings(:main, :setting => {:default => "yay", :desc => "boo", :hook => lambda { |v| hook_values << v }})
expect(hook_values).to eq(%w[])
end
it "calls the hook when initializing global defaults with the value from the `main` section" do
hook_values = []
@settings.define_settings(:main, :setting => {:default => "yay", :desc => "boo", :hook => lambda { |v| hook_values << v }})
File.write(config_file, <<~END)
[main]
setting=in_main
END
@settings.initialize_global_settings
expect(@settings[:setting]).to eq('in_main')
expect(hook_values).to eq(%w[in_main])
end
it "doesn't call the hook when initializing app defaults" do
hook_values = []
@settings.define_settings(:main, PuppetSpec::Settings::TEST_APP_DEFAULT_DEFINITIONS)
@settings.define_settings(:main, :setting => {:default => "yay", :desc => "boo", :hook => lambda { |v| hook_values << v }})
File.write(config_file, <<~END)
[main]
setting=in_main
[agent]
setting=in_agent
END
@settings.initialize_global_settings
hook_values.clear
@settings.initialize_app_defaults(PuppetSpec::Settings::TEST_APP_DEFAULT_VALUES)
expect(@settings[:setting]).to eq('in_main')
expect(hook_values).to eq(%w[])
end
it "doesn't call the hook with value from a section that matches the run_mode" do
hook_values = []
@settings.define_settings(:main, PuppetSpec::Settings::TEST_APP_DEFAULT_DEFINITIONS)
@settings.define_settings(:main, :setting => {:default => "yay", :desc => "boo", :hook => lambda { |v| hook_values << v }})
File.write(config_file, <<~END)
[main]
setting=in_main
[agent]
setting=in_agent
END
@settings.initialize_global_settings
hook_values.clear
@settings.initialize_app_defaults(PuppetSpec::Settings::TEST_APP_DEFAULT_VALUES.merge(:run_mode => :agent))
expect(@settings[:setting]).to eq('in_agent')
expect(hook_values).to eq(%w[])
end
end
describe "when :on_define_and_write" do
it "returns its hook type" do
@settings.define_settings(:main, :setting => {:default => "yay", :desc => "boo", :call_hook => :on_define_and_write, :hook => lambda { |_| }})
expect(@settings.setting(:setting).call_hook).to eq(:on_define_and_write)
end
it "should call the hook at definition with the default value" do
hook_values = []
@settings.define_settings(:main, :setting => {:default => "yay", :desc => "boo", :call_hook => :on_define_and_write, :hook => lambda { |v| hook_values << v }})
expect(hook_values).to eq(%w[yay])
end
it "calls the hook when initializing global defaults with the value from the `main` section" do
hook_values = []
@settings.define_settings(:main, :setting => {:default => "yay", :desc => "boo", :call_hook => :on_define_and_write, :hook => lambda { |v| hook_values << v }})
File.write(config_file, <<~END)
[main]
setting=in_main
END
@settings.initialize_global_settings
expect(@settings[:setting]).to eq('in_main')
expect(hook_values).to eq(%w[yay in_main])
end
it "doesn't call the hook when initializing app defaults" do
hook_values = []
@settings.define_settings(:main, PuppetSpec::Settings::TEST_APP_DEFAULT_DEFINITIONS)
@settings.define_settings(:main, :setting => {:default => "yay", :desc => "boo", :call_hook => :on_define_and_write, :hook => lambda { |v| hook_values << v }})
File.write(config_file, <<~END)
[main]
setting=in_main
[agent]
setting=in_agent
END
@settings.initialize_global_settings
hook_values.clear
@settings.initialize_app_defaults(PuppetSpec::Settings::TEST_APP_DEFAULT_VALUES)
expect(@settings[:setting]).to eq('in_main')
expect(hook_values).to eq([])
end
it "doesn't call the hook with value from a section that matches the run_mode" do
hook_values = []
@settings.define_settings(:main, PuppetSpec::Settings::TEST_APP_DEFAULT_DEFINITIONS)
@settings.define_settings(:main, :setting => {:default => "yay", :desc => "boo", :call_hook => :on_define_and_write, :hook => lambda { |v| hook_values << v }})
File.write(config_file, <<~END)
[main]
setting=in_main
[agent]
setting=in_agent
END
@settings.initialize_global_settings
hook_values.clear
@settings.initialize_app_defaults(PuppetSpec::Settings::TEST_APP_DEFAULT_VALUES.merge(:run_mode => :agent))
# The correct value is returned
expect(@settings[:setting]).to eq('in_agent')
# but the hook is never called, seems like a bug!
expect(hook_values).to eq([])
end
end
describe "when :on_initialize_and_write" do
it "returns its hook type" do
@settings.define_settings(:main, :setting => {:default => "yay", :desc => "boo", :call_hook => :on_initialize_and_write, :hook => lambda { |_| }})
expect(@settings.setting(:setting).call_hook).to eq(:on_initialize_and_write)
end
it "should not call the hook at definition" do
hook_values = []
@settings.define_settings(:main, :setting => {:default => "yay", :desc => "boo", :call_hook => :on_initialize_and_write, :hook => lambda { |v| hook_values << v }})
expect(hook_values).to eq([])
end
it "calls the hook when initializing global defaults with the value from the `main` section" do
hook_values = []
@settings.define_settings(:main, :setting => {:default => "yay", :desc => "boo", :call_hook => :on_initialize_and_write, :hook => lambda { |v| hook_values << v }})
File.write(config_file, <<~END)
[main]
setting=in_main
END
@settings.initialize_global_settings
expect(@settings[:setting]).to eq('in_main')
expect(hook_values).to eq(%w[in_main])
end
it "calls the hook when initializing app defaults" do
hook_values = []
@settings.define_settings(:main, PuppetSpec::Settings::TEST_APP_DEFAULT_DEFINITIONS)
@settings.define_settings(:main, :setting => {:default => "yay", :desc => "boo", :call_hook => :on_initialize_and_write, :hook => lambda { |v| hook_values << v }})
File.write(config_file, <<~END)
[main]
setting=in_main
[agent]
setting=in_agent
END
@settings.initialize_global_settings
hook_values.clear
@settings.initialize_app_defaults(PuppetSpec::Settings::TEST_APP_DEFAULT_VALUES)
expect(@settings[:setting]).to eq('in_main')
expect(hook_values).to eq(%w[in_main])
end
it "calls the hook with the overridden value from a section that matches the run_mode" do
hook_values = []
@settings.define_settings(:main, PuppetSpec::Settings::TEST_APP_DEFAULT_DEFINITIONS)
@settings.define_settings(:main, :setting => {:default => "yay", :desc => "boo", :call_hook => :on_initialize_and_write, :hook => lambda { |v| hook_values << v }})
File.write(config_file, <<~END)
[main]
setting=in_main
[agent]
setting=in_agent
END
@settings.initialize_global_settings
hook_values.clear
@settings.initialize_app_defaults(PuppetSpec::Settings::TEST_APP_DEFAULT_VALUES.merge(:run_mode => :agent))
expect(@settings[:setting]).to eq('in_agent')
expect(hook_values).to eq(%w[in_agent])
end
end
end
it "should call passed blocks when values are set" do
values = []
@settings.define_settings(:section, :setting => {:default => "yay", :desc => "boo", :hook => lambda { |v| values << v }})
expect(values).to eq([])
@settings[:setting] = "something"
expect(values).to eq(%w{something})
end
it "should call passed blocks when values are set via the command line" do
values = []
@settings.define_settings(:section, :setting => {:default => "yay", :desc => "boo", :hook => lambda { |v| values << v }})
expect(values).to eq([])
@settings.handlearg("--setting", "yay")
expect(values).to eq(%w{yay})
end
it "should provide an option to call passed blocks during definition" do
values = []
@settings.define_settings(:section, :setting => {:default => "yay", :desc => "boo", :call_hook => :on_define_and_write, :hook => lambda { |v| values << v }})
expect(values).to eq(%w{yay})
end
it "should pass the fully interpolated value to the hook when called on definition" do
values = []
@settings.define_settings(:section, :one => { :default => "test", :desc => "a" })
@settings.define_settings(:section, :setting => {:default => "$one/yay", :desc => "boo", :call_hook => :on_define_and_write, :hook => lambda { |v| values << v }})
expect(values).to eq(%w{test/yay})
end
it "should munge values using the setting-specific methods" do
@settings[:bool] = "false"
expect(@settings[:bool]).to eq(false)
end
it "should prefer values set in ruby to values set on the cli" do
@settings[:myval] = "memarg"
@settings.handlearg("--myval", "cliarg")
expect(@settings[:myval]).to eq("memarg")
end
it "should raise an error if we try to set a setting that hasn't been defined'" do
expect{
@settings[:why_so_serious] = "foo"
}.to raise_error(ArgumentError, /unknown setting/)
end
it "allows overriding cli args based on the cli-set value" do
@settings.handlearg("--myval", "cliarg")
@settings.patch_value(:myval, "modified #{@settings[:myval]}", :cli)
expect(@settings[:myval]).to eq("modified cliarg")
end
end
describe "when returning values" do
before do
@settings = Puppet::Settings.new
@settings.define_settings :section,
:config => { :type => :file, :default => "/my/file", :desc => "eh" },
:one => { :default => "ONE", :desc => "a" },
:two => { :default => "$one TWO", :desc => "b"},
:three => { :default => "$one $two THREE", :desc => "c"},
:four => { :default => "$two $three FOUR", :desc => "d"},
:five => { :default => nil, :desc => "e" },
:code => { :default => "", :desc => "my code"}
allow(Puppet::FileSystem).to receive(:exist?).and_return(true)
end
it "should provide a mechanism for returning set values" do
@settings[:one] = "other"
expect(@settings[:one]).to eq("other")
end
it "setting a value to nil causes it to return to its default" do
@settings.define_settings :main, PuppetSpec::Settings::TEST_APP_DEFAULT_DEFINITIONS
@settings.initialize_app_defaults(PuppetSpec::Settings::TEST_APP_DEFAULT_VALUES.merge(:one => "skipped value"))
@settings[:one] = "value will disappear"
@settings[:one] = nil
expect(@settings[:one]).to eq("ONE")
end
it "should interpolate default values for other parameters into returned parameter values" do
expect(@settings[:one]).to eq("ONE")
expect(@settings[:two]).to eq("ONE TWO")
expect(@settings[:three]).to eq("ONE ONE TWO THREE")
end
it "should interpolate default values that themselves need to be interpolated" do
expect(@settings[:four]).to eq("ONE TWO ONE ONE TWO THREE FOUR")
end
it "should provide a method for returning uninterpolated values" do
@settings[:two] = "$one tw0"
expect(@settings.value(:two, nil, true)).to eq("$one tw0")
expect(@settings.value(:four, nil, true)).to eq("$two $three FOUR")
end
it "should interpolate set values for other parameters into returned parameter values" do
@settings[:one] = "on3"
@settings[:two] = "$one tw0"
@settings[:three] = "$one $two thr33"
@settings[:four] = "$one $two $three f0ur"
expect(@settings[:one]).to eq("on3")
expect(@settings[:two]).to eq("on3 tw0")
expect(@settings[:three]).to eq("on3 on3 tw0 thr33")
expect(@settings[:four]).to eq("on3 on3 tw0 on3 on3 tw0 thr33 f0ur")
end
it "should not cache interpolated values such that stale information is returned" do
expect(@settings[:two]).to eq("ONE TWO")
@settings[:one] = "one"
expect(@settings[:two]).to eq("one TWO")
end
it "should not interpolate the value of the :code setting" do
@code = @settings.setting(:code)
expect(@code).not_to receive(:munge)
expect(@settings[:code]).to eq("")
end
it "should have a run_mode that defaults to user" do
expect(@settings.preferred_run_mode).to eq(:user)
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | true |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/functions4_spec.rb | spec/unit/functions4_spec.rb | require 'spec_helper'
require 'puppet/pops'
require 'puppet/loaders'
require 'puppet_spec/pops'
require 'puppet_spec/scope'
module FunctionAPISpecModule
class TestDuck
end
class TestFunctionLoader < Puppet::Pops::Loader::StaticLoader
def initialize
@constants = {}
end
def add_function(name, function)
set_entry(Puppet::Pops::Loader::TypedName.new(:function, name), function, __FILE__)
end
def add_type(name, type)
set_entry(Puppet::Pops::Loader::TypedName.new(:type, name), type, __FILE__)
end
def set_entry(typed_name, value, origin = nil)
@constants[typed_name] = Puppet::Pops::Loader::Loader::NamedEntry.new(typed_name, value, origin)
end
# override StaticLoader
def load_constant(typed_name)
@constants[typed_name]
end
end
end
describe 'the 4x function api' do
include FunctionAPISpecModule
include PuppetSpec::Pops
include PuppetSpec::Scope
let(:loader) { FunctionAPISpecModule::TestFunctionLoader.new }
def parse_eval(code, here)
if here.respond_to?(:source_location)
eval(code, here, here.source_location[0], here.source_location[1])
else
# this can be removed when ruby < 2.6 is dropped
eval(code, here)
end
end
it 'allows a simple function to be created without dispatch declaration' do
f = Puppet::Functions.create_function('min') do
def min(x,y)
x <= y ? x : y
end
end
# the produced result is a Class inheriting from Function
expect(f.class).to be(Class)
expect(f.superclass).to be(Puppet::Functions::Function)
# and this class had the given name (not a real Ruby class name)
expect(f.name).to eql('min')
end
it 'refuses to create functions that are not based on the Function class' do
expect do
Puppet::Functions.create_function('testing', Object) {}
end.to raise_error(ArgumentError, /function 'testing'.*Functions must be based on Puppet::Pops::Functions::Function. Got Object/)
end
it 'refuses to create functions with parameters that are not named with a symbol' do
expect do
Puppet::Functions.create_function('testing') do
dispatch :test do
param 'Integer', 'not_symbol'
end
def test(x)
end
end
end.to raise_error(ArgumentError, /Parameter name argument must be a Symbol/)
end
it 'a function without arguments can be defined and called without dispatch declaration' do
f = create_noargs_function_class()
func = f.new(:closure_scope, :loader)
expect(func.call({})).to eql(10)
end
it 'an error is raised when calling a no arguments function with arguments' do
f = create_noargs_function_class()
func = f.new(:closure_scope, :loader)
expect{func.call({}, 'surprise')}.to raise_error(ArgumentError, "'test' expects no arguments, got 1")
end
it 'a simple function can be called' do
f = create_min_function_class()
# TODO: Bogus parameters, not yet used
func = f.new(:closure_scope, :loader)
expect(func.is_a?(Puppet::Functions::Function)).to be_truthy
expect(func.call({}, 10,20)).to eql(10)
end
it 'an error is raised if called with too few arguments' do
f = create_min_function_class()
# TODO: Bogus parameters, not yet used
func = f.new(:closure_scope, :loader)
expect(func.is_a?(Puppet::Functions::Function)).to be_truthy
expect do
func.call({}, 10)
end.to raise_error(ArgumentError, "'min' expects 2 arguments, got 1")
end
it 'an error is raised if called with too many arguments' do
f = create_min_function_class()
# TODO: Bogus parameters, not yet used
func = f.new(:closure_scope, :loader)
expect(func.is_a?(Puppet::Functions::Function)).to be_truthy
expect do
func.call({}, 10, 10, 10)
end.to raise_error(ArgumentError, "'min' expects 2 arguments, got 3")
end
it 'correct dispatch is chosen when zero parameter dispatch exists' do
f = create_function_with_no_parameter_dispatch
func = f.new(:closure_scope, :loader)
expect(func.is_a?(Puppet::Functions::Function)).to be_truthy
expect(func.call({}, 1)).to eql(1)
end
it 'an error is raised if simple function-name and method are not matched' do
expect do
create_badly_named_method_function_class()
end.to raise_error(ArgumentError, /Function Creation Error, cannot create a default dispatcher for function 'mix', no method with this name found/)
end
it 'the implementation separates dispatchers for different functions' do
# this tests that meta programming / construction puts class attributes in the correct class
f1 = create_min_function_class()
f2 = create_max_function_class()
d1 = f1.dispatcher
d2 = f2.dispatcher
expect(d1).to_not eql(d2)
expect(d1.dispatchers[0]).to_not eql(d2.dispatchers[0])
end
context 'when using regular dispatch' do
it 'a function can be created using dispatch and called' do
f = create_min_function_class_using_dispatch()
func = f.new(:closure_scope, :loader)
expect(func.call({}, 3,4)).to eql(3)
end
it 'an error is raised with reference to given parameter names when called with mis-matched arguments' do
f = create_min_function_class_using_dispatch()
# TODO: Bogus parameters, not yet used
func = f.new(:closure_scope, :loader)
expect(func.is_a?(Puppet::Functions::Function)).to be_truthy
expect do
func.call({}, 10, 'ten')
end.to raise_error(ArgumentError, "'min' parameter 'b' expects a Numeric value, got String")
end
it 'an error includes optional indicators for last element' do
f = create_function_with_optionals_and_repeated_via_multiple_dispatch()
# TODO: Bogus parameters, not yet used
func = f.new(:closure_scope, :loader)
expect(func.is_a?(Puppet::Functions::Function)).to be_truthy
expect do
func.call({}, 3, 10, 3, "4")
end.to raise_error(ArgumentError, "The function 'min' was called with arguments it does not accept. It expects one of:
(Numeric x, Numeric y, Numeric a?, Numeric b?, Numeric c*)
rejected: parameter 'b' expects a Numeric value, got String
(String x, String y, String a+)
rejected: parameter 'x' expects a String value, got Integer")
end
it 'can create optional repeated parameter' do
f = create_function_with_repeated
func = f.new(:closure_scope, :loader)
expect(func.call({})).to eql(0)
expect(func.call({}, 1)).to eql(1)
expect(func.call({}, 1, 2)).to eql(2)
f = create_function_with_optional_repeated
func = f.new(:closure_scope, :loader)
expect(func.call({})).to eql(0)
expect(func.call({}, 1)).to eql(1)
expect(func.call({}, 1, 2)).to eql(2)
end
it 'can create required repeated parameter' do
f = create_function_with_required_repeated
func = f.new(:closure_scope, :loader)
expect(func.call({}, 1)).to eql(1)
expect(func.call({}, 1, 2)).to eql(2)
expect { func.call({}) }.to raise_error(ArgumentError, "'count_args' expects at least 1 argument, got none")
end
it 'can create scope_param followed by repeated parameter' do
f = create_function_with_scope_param_required_repeat
func = f.new(:closure_scope, :loader)
expect(func.call({}, 'yay', 1,2,3)).to eql([{}, 'yay',1,2,3])
end
it 'a function can use inexact argument mapping' do
f = create_function_with_inexact_dispatch
func = f.new(:closure_scope, :loader)
expect(func.call({}, 3.0,4.0,5.0)).to eql([Float, Float, Float])
expect(func.call({}, 'Apple', 'Banana')).to eql([String, String])
end
it 'a function can be created using dispatch and called' do
f = create_min_function_class_disptaching_to_two_methods()
func = f.new(:closure_scope, :loader)
expect(func.call({}, 3,4)).to eql(3)
expect(func.call({}, 'Apple', 'Banana')).to eql('Apple')
end
it 'a function can not be created with parameters declared after a repeated parameter' do
expect { create_function_with_param_after_repeated }.to raise_error(ArgumentError,
/function 't1'.*Parameters cannot be added after a repeated parameter/)
end
it 'a function can not be created with required parameters declared after optional ones' do
expect { create_function_with_rq_after_opt }.to raise_error(ArgumentError,
/function 't1'.*A required parameter cannot be added after an optional parameter/)
end
it 'a function can not be created with required repeated parameters declared after optional ones' do
expect { create_function_with_rq_repeated_after_opt }.to raise_error(ArgumentError,
/function 't1'.*A required repeated parameter cannot be added after an optional parameter/)
end
it 'an error is raised with reference to multiple methods when called with mis-matched arguments' do
f = create_min_function_class_disptaching_to_two_methods()
# TODO: Bogus parameters, not yet used
func = f.new(:closure_scope, :loader)
expect(func.is_a?(Puppet::Functions::Function)).to be_truthy
expect do
func.call({}, 10, '20')
end.to raise_error(ArgumentError, "The function 'min' was called with arguments it does not accept. It expects one of:
(Numeric a, Numeric b)
rejected: parameter 'b' expects a Numeric value, got String
(String s1, String s2)
rejected: parameter 's1' expects a String value, got Integer")
end
context 'an argument_mismatch handler' do
let(:func) { create_function_with_mismatch_handler.new(:closure_scope, :loader) }
it 'is called on matching arguments' do
expect { func.call({}, '1') }.to raise_error(ArgumentError, "'test' It's not OK to pass a string")
end
it 'is not called unless arguments are matching' do
expect { func.call({}, '1', 3) }.to raise_error(ArgumentError, "'test' expects 1 argument, got 2")
end
it 'is not included in a signature mismatch description' do
expect { func.call({}, 2.3) }.to raise_error { |e| expect(e.message).not_to match(/String/) }
end
end
context 'when requesting a type' do
it 'responds with a Callable for a single signature' do
tf = Puppet::Pops::Types::TypeFactory
fc = create_min_function_class_using_dispatch()
t = fc.dispatcher.to_type
expect(t.class).to be(Puppet::Pops::Types::PCallableType)
expect(t.param_types.class).to be(Puppet::Pops::Types::PTupleType)
expect(t.param_types.types).to eql([tf.numeric(), tf.numeric()])
expect(t.block_type).to be_nil
end
it 'responds with a Variant[Callable...] for multiple signatures' do
tf = Puppet::Pops::Types::TypeFactory
fc = create_min_function_class_disptaching_to_two_methods()
t = fc.dispatcher.to_type
expect(t.class).to be(Puppet::Pops::Types::PVariantType)
expect(t.types.size).to eql(2)
t1 = t.types[0]
expect(t1.param_types.class).to be(Puppet::Pops::Types::PTupleType)
expect(t1.param_types.types).to eql([tf.numeric(), tf.numeric()])
expect(t1.block_type).to be_nil
t2 = t.types[1]
expect(t2.param_types.class).to be(Puppet::Pops::Types::PTupleType)
expect(t2.param_types.types).to eql([tf.string(), tf.string()])
expect(t2.block_type).to be_nil
end
end
context 'supports lambdas' do
it 'such that, a required block can be defined and given as an argument' do
the_function = create_function_with_required_block_all_defaults().new(:closure_scope, :loader)
result = the_function.call({}, 7) { |a,b| a < b ? a : b }
expect(result).to eq(7)
end
it 'such that, a missing required block when called raises an error' do
the_function = create_function_with_required_block_all_defaults().new(:closure_scope, :loader)
expect do
the_function.call({}, 10)
end.to raise_error(ArgumentError, "'test' expects a block")
end
it 'such that, an optional block can be defined and given as an argument' do
the_function = create_function_with_optional_block_all_defaults().new(:closure_scope, :loader)
result = the_function.call({}, 4) { |a,b| a < b ? a : b }
expect(result).to eql(4)
end
it 'such that, an optional block can be omitted when called and gets the value nil' do
the_function = create_function_with_optional_block_all_defaults().new(:closure_scope, :loader)
expect(the_function.call({}, 2)).to be_nil
end
it 'such that, a scope can be injected and a block can be used' do
the_function = create_function_with_scope_required_block_all_defaults().new(:closure_scope, :loader)
expect(the_function.call({}, 1) { |a,b| a < b ? a : b }).to eql(1)
end
end
context 'provides signature information' do
it 'about capture rest (varargs)' do
fc = create_function_with_optionals_and_repeated
signatures = fc.signatures
expect(signatures.size).to eql(1)
signature = signatures[0]
expect(signature.last_captures_rest?).to be_truthy
end
it 'about optional and required parameters' do
fc = create_function_with_optionals_and_repeated
signature = fc.signatures[0]
expect(signature.args_range).to eql( [2, Float::INFINITY ] )
expect(signature.infinity?(signature.args_range[1])).to be_truthy
end
it 'about block not being allowed' do
fc = create_function_with_optionals_and_repeated
signature = fc.signatures[0]
expect(signature.block_range).to eql( [ 0, 0 ] )
expect(signature.block_type).to be_nil
end
it 'about required block' do
fc = create_function_with_required_block_all_defaults
signature = fc.signatures[0]
expect(signature.block_range).to eql( [ 1, 1 ] )
expect(signature.block_type).to_not be_nil
end
it 'about optional block' do
fc = create_function_with_optional_block_all_defaults
signature = fc.signatures[0]
expect(signature.block_range).to eql( [ 0, 1 ] )
expect(signature.block_type).to_not be_nil
end
it 'about the type' do
fc = create_function_with_optional_block_all_defaults
signature = fc.signatures[0]
expect(signature.type.class).to be(Puppet::Pops::Types::PCallableType)
end
it 'about parameter names obtained from ruby introspection' do
fc = create_min_function_class
signature = fc.signatures[0]
expect(signature.parameter_names).to eql(['x', 'y'])
end
it 'about parameter names specified with dispatch' do
fc = create_min_function_class_using_dispatch
signature = fc.signatures[0]
expect(signature.parameter_names).to eql([:a, :b])
end
it 'about block_name when it is *not* given in the definition' do
# neither type, nor name
fc = create_function_with_required_block_all_defaults
signature = fc.signatures[0]
expect(signature.block_name).to eql(:block)
# no name given, only type
fc = create_function_with_required_block_given_type
signature = fc.signatures[0]
expect(signature.block_name).to eql(:block)
end
it 'about block_name when it *is* given in the definition' do
# neither type, nor name
fc = create_function_with_required_block_default_type
signature = fc.signatures[0]
expect(signature.block_name).to eql(:the_block)
# no name given, only type
fc = create_function_with_required_block_fully_specified
signature = fc.signatures[0]
expect(signature.block_name).to eql(:the_block)
end
end
context 'supports calling other functions' do
before(:each) do
Puppet.push_context( {:loaders => Puppet::Pops::Loaders.new(Puppet::Node::Environment.create(:testing, []))})
end
after(:each) do
Puppet.pop_context()
end
it 'such that, other functions are callable by name' do
fc = Puppet::Functions.create_function('test') do
def test()
# Call a function available in the puppet system
call_function('assert_type', 'Integer', 10)
end
end
# initiate the function the same way the loader initiates it
f = fc.new(:closure_scope, Puppet.lookup(:loaders).puppet_system_loader)
expect(f.call({})).to eql(10)
end
it 'such that, calling a non existing function raises an error' do
fc = Puppet::Functions.create_function('test') do
def test()
# Call a function not available in the puppet system
call_function('no_such_function', 'Integer', 'hello')
end
end
# initiate the function the same way the loader initiates it
f = fc.new(:closure_scope, Puppet.lookup(:loaders).puppet_system_loader)
expect{f.call({})}.to raise_error(ArgumentError, "Function test(): Unknown function: 'no_such_function'")
end
end
context 'functions in a context with a compiler' do
before(:each) do
Puppet.push_context( {:loaders => Puppet::Pops::Loaders.new(Puppet::Node::Environment.create(:testing, []))})
end
after(:each) do
Puppet.pop_context()
end
before(:each) do
Puppet[:strict_variables] = true
end
let(:parser) { Puppet::Pops::Parser::EvaluatingParser.new }
let(:node) { 'node.example.com' }
let(:scope) { s = create_test_scope_for_node(node); s }
let(:loader) { Puppet::Pops::Loaders.find_loader(nil) }
context 'supports calling ruby functions with lambda from puppet' do
it 'function with required block can be called' do
# construct ruby function to call
fc = Puppet::Functions.create_function('testing::test') do
dispatch :test do
param 'Integer', :x
# block called 'the_block', and using "all_callables"
required_block_param #(all_callables(), 'the_block')
end
def test(x)
# call the block with x
yield(x)
end
end
# add the function to the loader (as if it had been loaded from somewhere)
the_loader = loader
f = fc.new({}, the_loader)
loader.set_entry(Puppet::Pops::Loader::TypedName.new(:function, 'testing::test'), f)
# evaluate a puppet call
source = "testing::test(10) |$x| { $x+1 }"
program = parser.parse_string(source, __FILE__)
expect(Puppet::Pops::Adapters::LoaderAdapter).to receive(:loader_for_model_object).at_least(:once).and_return(the_loader)
expect(parser.evaluate(scope, program)).to eql(11)
end
end
it 'supports injection of a cache' do
the_function = create_function_with_cache_param.new(:closure_scope, :loader)
expect(the_function.call(scope, 'key', 10)).to eql(nil)
expect(the_function.call(scope, 'key', 20)).to eql(10)
expect(the_function.call(scope, 'key', 30)).to eql(20)
end
end
context 'reports meaningful errors' do
let(:parser) { Puppet::Pops::Parser::EvaluatingParser.new }
it 'syntax error in local type is reported with puppet source, puppet location, and ruby file containing function' do
the_loader = loader()
here = get_binding(the_loader)
expect do
parse_eval(<<-CODE, here)
Puppet::Functions.create_function('testing::test') do
local_types do
type 'MyType += Array[Integer]'
end
dispatch :test do
param 'MyType', :x
end
def test(x)
x
end
end
CODE
end.to raise_error(/MyType \+\= Array.*<Syntax error at '\+\=' \(line: 1, column: [0-9]+\)>.*functions4_spec\.rb.*/m)
# Note that raised error reports this spec file as the function source since the function is defined here
end
it 'syntax error in param type is reported with puppet source, puppet location, and ruby file containing function' do
the_loader = loader()
here = get_binding(the_loader)
expect do
parse_eval(<<-CODE, here)
Puppet::Functions.create_function('testing::test') do
dispatch :test do
param 'Array[1+=1]', :x
end
def test(x)
x
end
end
CODE
end.to raise_error(/Parsing of type string '"Array\[1\+=1\]"' failed with message: <Syntax error at '\]' \(line: 1, column: [0-9]+\)>/m)
end
end
context 'can use a loader when parsing types in function dispatch, and' do
let(:parser) { Puppet::Pops::Parser::EvaluatingParser.new }
it 'uses return_type to validate returned value' do
the_loader = loader()
here = get_binding(the_loader)
fc = parse_eval(<<-CODE, here)
Puppet::Functions.create_function('testing::test') do
dispatch :test do
param 'Integer', :x
return_type 'String'
end
def test(x)
x
end
end
CODE
the_loader.add_function('testing::test', fc.new({}, the_loader))
program = parser.parse_string('testing::test(10)', __FILE__)
expect(Puppet::Pops::Adapters::LoaderAdapter).to receive(:loader_for_model_object).and_return(the_loader)
expect { parser.evaluate({}, program) }.to raise_error(Puppet::Error,
/value returned from function 'test' has wrong type, expects a String value, got Integer/)
end
it 'resolve a referenced Type alias' do
the_loader = loader()
the_loader.add_type('myalias', type_alias_t('MyAlias', 'Integer'))
here = get_binding(the_loader)
fc = parse_eval(<<-CODE, here)
Puppet::Functions.create_function('testing::test') do
dispatch :test do
param 'MyAlias', :x
return_type 'MyAlias'
end
def test(x)
x
end
end
CODE
the_loader.add_function('testing::test', fc.new({}, the_loader))
program = parser.parse_string('testing::test(10)', __FILE__)
expect(Puppet::Pops::Adapters::LoaderAdapter).to receive(:loader_for_model_object).and_return(the_loader)
expect(parser.evaluate({}, program)).to eql(10)
end
it 'reports a reference to an unresolved type' do
the_loader = loader()
here = get_binding(the_loader)
fc = parse_eval(<<-CODE, here)
Puppet::Functions.create_function('testing::test') do
dispatch :test do
param 'MyAlias', :x
end
def test(x)
x
end
end
CODE
the_loader.add_function('testing::test', fc.new({}, the_loader))
program = parser.parse_string('testing::test(10)', __FILE__)
expect(Puppet::Pops::Adapters::LoaderAdapter).to receive(:loader_for_model_object).and_return(the_loader)
expect { parser.evaluate({}, program) }.to raise_error(Puppet::Error, /parameter 'x' references an unresolved type 'MyAlias'/)
end
it 'create local Type aliases' do
the_loader = loader()
here = get_binding(the_loader)
fc = parse_eval(<<-CODE, here)
Puppet::Functions.create_function('testing::test') do
local_types do
type 'MyType = Array[Integer]'
end
dispatch :test do
param 'MyType', :x
end
def test(x)
x
end
end
CODE
the_loader.add_function('testing::test', fc.new({}, the_loader))
program = parser.parse_string('testing::test([10,20])', __FILE__)
expect(Puppet::Pops::Adapters::LoaderAdapter).to receive(:loader_for_model_object).and_return(the_loader)
expect(parser.evaluate({}, program)).to eq([10,20])
end
it 'create nested local Type aliases' do
the_loader = loader()
here = get_binding(the_loader)
fc = parse_eval(<<-CODE, here)
Puppet::Functions.create_function('testing::test') do
local_types do
type 'InnerType = Array[Integer]'
type 'OuterType = Hash[String,InnerType]'
end
dispatch :test do
param 'OuterType', :x
end
def test(x)
x
end
end
CODE
the_loader.add_function('testing::test', fc.new({}, the_loader))
program = parser.parse_string("testing::test({'x' => [10,20]})", __FILE__)
expect(Puppet::Pops::Adapters::LoaderAdapter).to receive(:loader_for_model_object).and_return(the_loader)
expect(parser.evaluate({}, program)).to eq({'x' => [10,20]})
end
it 'create self referencing local Type aliases' do
the_loader = loader()
here = get_binding(the_loader)
fc = parse_eval(<<-CODE, here)
Puppet::Functions.create_function('testing::test') do
local_types do
type 'Tree = Hash[String,Variant[String,Tree]]'
end
dispatch :test do
param 'Tree', :x
end
def test(x)
x
end
end
CODE
the_loader.add_function('testing::test', fc.new({}, the_loader))
program = parser.parse_string("testing::test({'x' => {'y' => 'n'}})", __FILE__)
expect(Puppet::Pops::Adapters::LoaderAdapter).to receive(:loader_for_model_object).and_return(the_loader)
expect(parser.evaluate({}, program)).to eq({'x' => {'y' => 'n'}})
end
end
end
def create_noargs_function_class
Puppet::Functions.create_function('test') do
def test()
10
end
end
end
def create_min_function_class
Puppet::Functions.create_function('min') do
def min(x,y)
x <= y ? x : y
end
end
end
def create_max_function_class
Puppet::Functions.create_function('max') do
def max(x,y)
x >= y ? x : y
end
end
end
def create_badly_named_method_function_class
Puppet::Functions.create_function('mix') do
def mix_up(x,y)
x <= y ? x : y
end
end
end
def create_min_function_class_using_dispatch
Puppet::Functions.create_function('min') do
dispatch :min do
param 'Numeric', :a
param 'Numeric', :b
end
def min(x,y)
x <= y ? x : y
end
end
end
def create_min_function_class_disptaching_to_two_methods
Puppet::Functions.create_function('min') do
dispatch :min do
param 'Numeric', :a
param 'Numeric', :b
end
dispatch :min_s do
param 'String', :s1
param 'String', :s2
end
def min(x,y)
x <= y ? x : y
end
def min_s(x,y)
cmp = (x.downcase <=> y.downcase)
cmp <= 0 ? x : y
end
end
end
def create_function_with_optionals_and_repeated
Puppet::Functions.create_function('min') do
def min(x,y,a=1, b=1, *c)
x <= y ? x : y
end
end
end
def create_function_with_optionals_and_repeated_via_dispatch
Puppet::Functions.create_function('min') do
dispatch :min do
param 'Numeric', :x
param 'Numeric', :y
optional_param 'Numeric', :a
optional_param 'Numeric', :b
repeated_param 'Numeric', :c
end
def min(x,y,a=1, b=1, *c)
x <= y ? x : y
end
end
end
def create_function_with_optionals_and_repeated_via_multiple_dispatch
Puppet::Functions.create_function('min') do
dispatch :min do
param 'Numeric', :x
param 'Numeric', :y
optional_param 'Numeric', :a
optional_param 'Numeric', :b
repeated_param 'Numeric', :c
end
dispatch :min do
param 'String', :x
param 'String', :y
required_repeated_param 'String', :a
end
def min(x,y,a=1, b=1, *c)
x <= y ? x : y
end
end
end
def create_function_with_required_repeated_via_dispatch
Puppet::Functions.create_function('min') do
dispatch :min do
param 'Numeric', :x
param 'Numeric', :y
required_repeated_param 'Numeric', :z
end
def min(x,y, *z)
x <= y ? x : y
end
end
end
def create_function_with_repeated
Puppet::Functions.create_function('count_args') do
dispatch :count_args do
repeated_param 'Any', :c
end
def count_args(*c)
c.size
end
end
end
def create_function_with_optional_repeated
Puppet::Functions.create_function('count_args') do
dispatch :count_args do
optional_repeated_param 'Any', :c
end
def count_args(*c)
c.size
end
end
end
def create_function_with_required_repeated
Puppet::Functions.create_function('count_args') do
dispatch :count_args do
required_repeated_param 'Any', :c
end
def count_args(*c)
c.size
end
end
end
def create_function_with_inexact_dispatch
Puppet::Functions.create_function('t1') do
dispatch :t1 do
param 'Numeric', :x
param 'Numeric', :y
repeated_param 'Numeric', :z
end
dispatch :t1 do
param 'String', :x
param 'String', :y
repeated_param 'String', :z
end
def t1(first, *x)
[first.class, *x.map {|e|e.class}]
end
end
end
def create_function_with_rq_after_opt
Puppet::Functions.create_function('t1') do
dispatch :t1 do
optional_param 'Numeric', :x
param 'Numeric', :y
end
def t1(*x)
x
end
end
end
def create_function_with_rq_repeated_after_opt
Puppet::Functions.create_function('t1') do
dispatch :t1 do
optional_param 'Numeric', :x
required_repeated_param 'Numeric', :y
end
def t1(x, *y)
x
end
end
end
def create_function_with_param_after_repeated
Puppet::Functions.create_function('t1') do
dispatch :t1 do
repeated_param 'Numeric', :x
param 'Numeric', :y
end
def t1(*x)
x
end
end
end
# DEAD TODO REMOVE
# def create_function_with_param_injection_regular
# Puppet::Functions.create_function('test', Puppet::Functions::InternalFunction) do
# attr_injected Puppet::Pops::Types::TypeFactory.type_of(FunctionAPISpecModule::TestDuck), :test_attr
# attr_injected Puppet::Pops::Types::TypeFactory.string(), :test_attr2, "a_string"
# attr_injected_producer Puppet::Pops::Types::TypeFactory.integer(), :serial, "an_int"
#
# dispatch :test do
# injected_param Puppet::Pops::Types::TypeFactory.string, :x, 'a_string'
# injected_producer_param Puppet::Pops::Types::TypeFactory.integer, :y, 'an_int'
# param 'Scalar', :a
# param 'Scalar', :b
# end
#
# def test(x,y,a,b)
# y_produced = y.produce(nil)
# "#{x}! #{a}, and #{b} < #{y_produced} = #{ !!(a < y_produced && b < y_produced)}"
# end
# end
# end
def create_function_with_required_block_all_defaults
Puppet::Functions.create_function('test') do
dispatch :test do
param 'Integer', :x
# use defaults, any callable, name is 'block'
block_param
end
def test(x)
yield(8,x)
end
end
end
def create_function_with_scope_required_block_all_defaults
Puppet::Functions.create_function('test', Puppet::Functions::InternalFunction) do
dispatch :test do
scope_param
param 'Integer', :x
# use defaults, any callable, name is 'block'
required_block_param
end
def test(scope, x)
yield(3,x)
end
end
end
def create_function_with_required_block_default_type
Puppet::Functions.create_function('test') do
dispatch :test do
param 'Integer', :x
# use defaults, any callable, name is 'block'
required_block_param :the_block
end
def test(x)
yield
end
end
end
def create_function_with_scope_param_required_repeat
Puppet::Functions.create_function('test', Puppet::Functions::InternalFunction) do
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | true |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/reports_spec.rb | spec/unit/reports_spec.rb | require 'spec_helper'
require 'puppet/reports'
describe Puppet::Reports do
it "should instance-load report types" do
expect(Puppet::Reports.instance_loader(:report)).to be_instance_of(Puppet::Util::Autoload)
end
it "should have a method for registering report types" do
expect(Puppet::Reports).to respond_to(:register_report)
end
it "should have a method for retrieving report types by name" do
expect(Puppet::Reports).to respond_to(:report)
end
it "should provide a method for returning documentation for all reports" do
expect(Puppet::Reports).to receive(:loaded_instances).with(:report).and_return([:one, :two])
one = double('one', :doc => "onedoc")
two = double('two', :doc => "twodoc")
expect(Puppet::Reports).to receive(:report).with(:one).and_return(one)
expect(Puppet::Reports).to receive(:report).with(:two).and_return(two)
doc = Puppet::Reports.reportdocs
expect(doc.include?("onedoc")).to be_truthy
expect(doc.include?("twodoc")).to be_truthy
end
end
describe Puppet::Reports, " when loading report types" do
it "should use the instance loader to retrieve report types" do
expect(Puppet::Reports).to receive(:loaded_instance).with(:report, :myreporttype)
Puppet::Reports.report(:myreporttype)
end
end
describe Puppet::Reports, " when registering report types" do
it "should evaluate the supplied block as code for a module" do
expect(Puppet::Reports).to receive(:genmodule).and_return(Module.new)
Puppet::Reports.register_report(:testing) { }
end
it "should allow a successful report to be reloaded" do
Puppet::Reports.register_report(:testing) { }
Puppet::Reports.register_report(:testing) { }
end
it "should allow a failed report to be reloaded and show the correct exception both times" do
expect { Puppet::Reports.register_report(:testing) { raise TypeError, 'failed report' } }.to raise_error(TypeError)
expect { Puppet::Reports.register_report(:testing) { raise TypeError, 'failed report' } }.to raise_error(TypeError)
end
it "should extend the report type with the Puppet::Util::Docs module" do
mod = double('module', :define_method => true)
expect(Puppet::Reports).to receive(:genmodule).with(anything, hash_including(extend: Puppet::Util::Docs)).and_return(mod)
Puppet::Reports.register_report(:testing) { }
end
it "should define a :report_name method in the module that returns the name of the report" do
mod = double('module')
expect(mod).to receive(:define_method).with(:report_name)
expect(Puppet::Reports).to receive(:genmodule).and_return(mod)
Puppet::Reports.register_report(:testing) { }
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/data_binding_spec.rb | spec/unit/data_binding_spec.rb | require 'spec_helper'
require 'puppet/data_binding'
describe Puppet::DataBinding do
describe "when indirecting" do
it "should default to the 'hiera' data_binding terminus" do
Puppet::DataBinding.indirection.reset_terminus_class
expect(Puppet::DataBinding.indirection.terminus_class).to eq(:hiera)
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/etc_spec.rb | spec/unit/etc_spec.rb | require 'puppet'
require 'spec_helper'
require 'puppet_spec/character_encoding'
# The Ruby::Etc module is largely non-functional on Windows - many methods
# simply return nil regardless of input, the Etc::Group struct is not defined,
# and Etc::Passwd is missing fields
# We want to test that:
# - We correctly set external encoding values IF they're valid UTF-8 bytes
# - We do not modify non-UTF-8 values if they're NOT valid UTF-8 bytes
describe Puppet::Etc, :if => !Puppet::Util::Platform.windows? do
# http://www.fileformat.info/info/unicode/char/5e0c/index.htm
# 希 Han Character 'rare; hope, expect, strive for'
# In EUC_KR: \xfd \xf1 - 253 241
# In UTF-8: \u5e0c - \xe5 \xb8 \x8c - 229 184 140
let(:euc_kr) { [253, 241].pack('C*').force_encoding(Encoding::EUC_KR) } # valid_encoding? == true
let(:euc_kr_as_binary) { [253, 241].pack('C*') } # valid_encoding? == true
let(:euc_kr_as_utf_8) { [253, 241].pack('C*').force_encoding(Encoding::UTF_8) } # valid_encoding? == false
# characters representing different UTF-8 widths
# 1-byte A
# 2-byte ۿ - http://www.fileformat.info/info/unicode/char/06ff/index.htm - 0xDB 0xBF / 219 191
# 3-byte ᚠ - http://www.fileformat.info/info/unicode/char/16A0/index.htm - 0xE1 0x9A 0xA0 / 225 154 160
# 4-byte 𠜎 - http://www.fileformat.info/info/unicode/char/2070E/index.htm - 0xF0 0xA0 0x9C 0x8E / 240 160 156 142
let(:mixed_utf_8) { "A\u06FF\u16A0\u{2070E}".force_encoding(Encoding::UTF_8) } # Aۿᚠ𠜎
let(:mixed_utf_8_as_binary) { "A\u06FF\u16A0\u{2070E}".force_encoding(Encoding::BINARY) }
let(:mixed_utf_8_as_euc_kr) { "A\u06FF\u16A0\u{2070E}".force_encoding(Encoding::EUC_KR) }
# An uninteresting value that ruby might return in an Etc struct.
let(:root) { 'root' }
# Set up example Etc Group structs with values representative of what we would
# get back in these encodings
let(:utf_8_group_struct) do
group = Etc::Group.new
# In a UTF-8 environment, these values will come back as UTF-8, even if
# they're not valid UTF-8. We do not modify anything about either the
# valid or invalid UTF-8 strings.
# Group member contains a mix of valid and invalid UTF-8-labeled strings
group.mem = [mixed_utf_8, root.dup.force_encoding(Encoding::UTF_8), euc_kr_as_utf_8]
# group name contains same EUC_KR bytes labeled as UTF-8
group.name = euc_kr_as_utf_8
# group passwd field is valid UTF-8
group.passwd = mixed_utf_8
group.gid = 12345
group
end
let(:euc_kr_group_struct) do
# In an EUC_KR environment, values will come back as EUC_KR, even if they're
# not valid in that encoding. For values that are valid in UTF-8 we expect
# their external encoding to be set to UTF-8 by Puppet::Etc. For values that
# are invalid in UTF-8, we expect the string to be kept intact, unmodified,
# as we can't transcode it.
group = Etc::Group.new
group.mem = [euc_kr, root.dup.force_encoding(Encoding::EUC_KR), mixed_utf_8_as_euc_kr]
group.name = euc_kr
group.passwd = mixed_utf_8_as_euc_kr
group.gid = 12345
group
end
let(:ascii_group_struct) do
# In a POSIX environment, any strings containing only values under
# code-point 128 will be returned as ASCII, whereas anything above that
# point will be returned as BINARY. In either case we override the encoding
# to UTF-8 if that would be valid.
group = Etc::Group.new
group.mem = [euc_kr_as_binary, root.dup.force_encoding(Encoding::ASCII), mixed_utf_8_as_binary]
group.name = euc_kr_as_binary
group.passwd = mixed_utf_8_as_binary
group.gid = 12345
group
end
let(:utf_8_user_struct) do
user = Etc::Passwd.new
# user name contains same EUC_KR bytes labeled as UTF-8
user.name = euc_kr_as_utf_8
# group passwd field is valid UTF-8
user.passwd = mixed_utf_8
user.uid = 12345
user
end
let(:euc_kr_user_struct) do
user = Etc::Passwd.new
user.name = euc_kr
user.passwd = mixed_utf_8_as_euc_kr
user.uid = 12345
user
end
let(:ascii_user_struct) do
user = Etc::Passwd.new
user.name = euc_kr_as_binary
user.passwd = mixed_utf_8_as_binary
user.uid = 12345
user
end
shared_examples "methods that return an overridden group struct from Etc" do |param|
it "should return a new Struct object with corresponding canonical_ members" do
group = Etc::Group.new
expect(Etc).to receive(subject).with(param.nil? ? no_args : param).and_return(group)
puppet_group = Puppet::Etc.send(subject, *param)
expect(puppet_group.members).to include(*group.members)
expect(puppet_group.members).to include(*group.members.map { |mem| "canonical_#{mem}".to_sym })
# Confirm we haven't just added the new members to the original struct object, ie this is really a new struct
expect(group.members.any? { |elem| elem.match(/^canonical_/) }).to be_falsey
end
context "when Encoding.default_external is UTF-8" do
before do
expect(Etc).to receive(subject).with(param.nil? ? no_args : param).and_return(utf_8_group_struct)
end
let(:overridden) {
PuppetSpec::CharacterEncoding.with_external_encoding(Encoding::UTF_8) do
Puppet::Etc.send(subject, *param)
end
}
it "should leave the valid UTF-8 values in arrays unmodified" do
expect(overridden.mem[0]).to eq(mixed_utf_8)
expect(overridden.mem[1]).to eq(root)
end
it "should replace invalid characters with replacement characters in invalid UTF-8 values in arrays" do
expect(overridden.mem[2]).to eq("\uFFFD\uFFFD")
end
it "should keep an unmodified version of the invalid UTF-8 values in arrays in the corresponding canonical_ member" do
expect(overridden.canonical_mem[2]).to eq(euc_kr_as_utf_8)
end
it "should leave the valid UTF-8 values unmodified" do
expect(overridden.passwd).to eq(mixed_utf_8)
end
it "should replace invalid characters with '?' characters in invalid UTF-8 values" do
expect(overridden.name).to eq("\uFFFD\uFFFD")
end
it "should keep an unmodified version of the invalid UTF-8 values in the corresponding canonical_ member" do
expect(overridden.canonical_name).to eq(euc_kr_as_utf_8)
end
it "should copy all values to the new struct object" do
# Confirm we've actually copied all the values to the canonical_members
utf_8_group_struct.each_pair do |member, value|
expect(overridden["canonical_#{member}"]).to eq(value)
# Confirm we've reassigned all non-string and array values
if !value.is_a?(String) && !value.is_a?(Array)
expect(overridden[member]).to eq(value)
expect(overridden[member].object_id).to eq(value.object_id)
end
end
end
end
context "when Encoding.default_external is EUC_KR (i.e., neither UTF-8 nor POSIX)" do
before do
expect(Etc).to receive(subject).with(param.nil? ? no_args : param).and_return(euc_kr_group_struct)
end
let(:overridden) {
PuppetSpec::CharacterEncoding.with_external_encoding(Encoding::EUC_KR) do
Puppet::Etc.send(subject, *param)
end
}
it "should override EUC_KR-labeled values in arrays to UTF-8 if that would result in valid UTF-8" do
expect(overridden.mem[2]).to eq(mixed_utf_8)
expect(overridden.mem[1]).to eq(root)
end
it "should leave valid EUC_KR-labeled values that would not be valid UTF-8 in arrays unmodified" do
expect(overridden.mem[0]).to eq(euc_kr)
end
it "should override EUC_KR-labeled values to UTF-8 if that would result in valid UTF-8" do
expect(overridden.passwd).to eq(mixed_utf_8)
end
it "should leave valid EUC_KR-labeled values that would not be valid UTF-8 unmodified" do
expect(overridden.name).to eq(euc_kr)
end
it "should copy all values to the new struct object" do
# Confirm we've actually copied all the values to the canonical_members
euc_kr_group_struct.each_pair do |member, value|
expect(overridden["canonical_#{member}"]).to eq(value)
# Confirm we've reassigned all non-string and array values
if !value.is_a?(String) && !value.is_a?(Array)
expect(overridden[member]).to eq(value)
expect(overridden[member].object_id).to eq(value.object_id)
end
end
end
end
context "when Encoding.default_external is POSIX (ASCII-7bit)" do
before do
expect(Etc).to receive(subject).with(param.nil? ? no_args : param).and_return(ascii_group_struct)
end
let(:overridden) {
PuppetSpec::CharacterEncoding.with_external_encoding(Encoding::ASCII) do
Puppet::Etc.send(subject, *param)
end
}
it "should not modify binary values in arrays that would be invalid UTF-8" do
expect(overridden.mem[0]).to eq(euc_kr_as_binary)
end
it "should set the encoding to UTF-8 on binary values in arrays that would be valid UTF-8" do
expect(overridden.mem[1]).to eq(root.dup.force_encoding(Encoding::UTF_8))
expect(overridden.mem[2]).to eq(mixed_utf_8)
end
it "should not modify binary values that would be invalid UTF-8" do
expect(overridden.name).to eq(euc_kr_as_binary)
end
it "should set the encoding to UTF-8 on binary values that would be valid UTF-8" do
expect(overridden.passwd).to eq(mixed_utf_8)
end
it "should copy all values to the new struct object" do
# Confirm we've actually copied all the values to the canonical_members
ascii_group_struct.each_pair do |member, value|
expect(overridden["canonical_#{member}"]).to eq(value)
# Confirm we've reassigned all non-string and array values
if !value.is_a?(String) && !value.is_a?(Array)
expect(overridden[member]).to eq(value)
expect(overridden[member].object_id).to eq(value.object_id)
end
end
end
end
end
shared_examples "methods that return an overridden user struct from Etc" do |param|
it "should return a new Struct object with corresponding canonical_ members" do
user = Etc::Passwd.new
expect(Etc).to receive(subject).with(param.nil? ? no_args : param).and_return(user)
puppet_user = Puppet::Etc.send(subject, *param)
expect(puppet_user.members).to include(*user.members)
expect(puppet_user.members).to include(*user.members.map { |mem| "canonical_#{mem}".to_sym })
# Confirm we haven't just added the new members to the original struct object, ie this is really a new struct
expect(user.members.any? { |elem| elem.match(/^canonical_/)}).to be_falsey
end
context "when Encoding.default_external is UTF-8" do
before do
expect(Etc).to receive(subject).with(param.nil? ? no_args : param).and_return(utf_8_user_struct)
end
let(:overridden) {
PuppetSpec::CharacterEncoding.with_external_encoding(Encoding::UTF_8) do
Puppet::Etc.send(subject, *param)
end
}
it "should leave the valid UTF-8 values unmodified" do
expect(overridden.passwd).to eq(mixed_utf_8)
end
it "should replace invalid characters with unicode replacement characters in invalid UTF-8 values" do
expect(overridden.name).to eq("\uFFFD\uFFFD")
end
it "should keep an unmodified version of the invalid UTF-8 values in the corresponding canonical_ member" do
expect(overridden.canonical_name).to eq(euc_kr_as_utf_8)
end
it "should copy all values to the new struct object" do
# Confirm we've actually copied all the values to the canonical_members
utf_8_user_struct.each_pair do |member, value|
expect(overridden["canonical_#{member}"]).to eq(value)
# Confirm we've reassigned all non-string and array values
if !value.is_a?(String) && !value.is_a?(Array)
expect(overridden[member]).to eq(value)
expect(overridden[member].object_id).to eq(value.object_id)
end
end
end
end
context "when Encoding.default_external is EUC_KR (i.e., neither UTF-8 nor POSIX)" do
before do
expect(Etc).to receive(subject).with(param.nil? ? no_args : param).and_return(euc_kr_user_struct)
end
let(:overridden) {
PuppetSpec::CharacterEncoding.with_external_encoding(Encoding::EUC_KR) do
Puppet::Etc.send(subject, *param)
end
}
it "should override valid UTF-8 EUC_KR-labeled values to UTF-8" do
expect(overridden.passwd).to eq(mixed_utf_8)
end
it "should leave invalid EUC_KR-labeled values unmodified" do
expect(overridden.name).to eq(euc_kr)
end
it "should copy all values to the new struct object" do
# Confirm we've actually copied all the values to the canonical_members
euc_kr_user_struct.each_pair do |member, value|
expect(overridden["canonical_#{member}"]).to eq(value)
# Confirm we've reassigned all non-string and array values
if !value.is_a?(String) && !value.is_a?(Array)
expect(overridden[member]).to eq(value)
expect(overridden[member].object_id).to eq(value.object_id)
end
end
end
end
context "when Encoding.default_external is POSIX (ASCII-7bit)" do
before do
expect(Etc).to receive(subject).with(param.nil? ? no_args : param).and_return(ascii_user_struct)
end
let(:overridden) {
PuppetSpec::CharacterEncoding.with_external_encoding(Encoding::ASCII) do
Puppet::Etc.send(subject, *param)
end
}
it "should not modify binary values that would be invalid UTF-8" do
expect(overridden.name).to eq(euc_kr_as_binary)
end
it "should set the encoding to UTF-8 on binary values that would be valid UTF-8" do
expect(overridden.passwd).to eq(mixed_utf_8)
end
it "should copy all values to the new struct object" do
# Confirm we've actually copied all the values to the canonical_members
ascii_user_struct.each_pair do |member, value|
expect(overridden["canonical_#{member}"]).to eq(value)
# Confirm we've reassigned all non-string and array values
if !value.is_a?(String) && !value.is_a?(Array)
expect(overridden[member]).to eq(value)
expect(overridden[member].object_id).to eq(value.object_id)
end
end
end
end
end
describe :getgrent do
it_should_behave_like "methods that return an overridden group struct from Etc"
end
describe :getgrnam do
it_should_behave_like "methods that return an overridden group struct from Etc", 'foo'
it "should call Etc.getgrnam with the supplied group name" do
expect(Etc).to receive(:getgrnam).with('foo')
Puppet::Etc.getgrnam('foo')
end
end
describe :getgrgid do
it_should_behave_like "methods that return an overridden group struct from Etc", 0
it "should call Etc.getgrgid with supplied group id" do
expect(Etc).to receive(:getgrgid).with(0)
Puppet::Etc.getgrgid(0)
end
end
describe :getpwent do
it_should_behave_like "methods that return an overridden user struct from Etc"
end
describe :getpwnam do
it_should_behave_like "methods that return an overridden user struct from Etc", 'foo'
it "should call Etc.getpwnam with that username" do
expect(Etc).to receive(:getpwnam).with('foo')
Puppet::Etc.getpwnam('foo')
end
end
describe :getpwuid do
it_should_behave_like "methods that return an overridden user struct from Etc", 2
it "should call Etc.getpwuid with the id" do
expect(Etc).to receive(:getpwuid).with(2)
Puppet::Etc.getpwuid(2)
end
end
describe :group do
it 'should return the next group struct if a block is not provided' do
expect(Puppet::Etc).to receive(:getgrent).and_return(ascii_group_struct)
expect(Puppet::Etc.group).to eql(ascii_group_struct)
end
it 'should iterate over the available groups if a block is provided' do
expected_groups = [
utf_8_group_struct,
euc_kr_group_struct,
ascii_group_struct
]
allow(Puppet::Etc).to receive(:getgrent).and_return(*(expected_groups + [nil]))
expect(Puppet::Etc).to receive(:setgrent)
expect(Puppet::Etc).to receive(:endgrent)
actual_groups = []
Puppet::Etc.group { |group| actual_groups << group }
expect(actual_groups).to eql(expected_groups)
end
end
describe "endgrent" do
it "should call Etc.getgrent" do
expect(Etc).to receive(:getgrent)
Puppet::Etc.getgrent
end
end
describe "setgrent" do
it "should call Etc.setgrent" do
expect(Etc).to receive(:setgrent)
Puppet::Etc.setgrent
end
end
describe "endpwent" do
it "should call Etc.endpwent" do
expect(Etc).to receive(:endpwent)
Puppet::Etc.endpwent
end
end
describe "setpwent" do
it "should call Etc.setpwent" do
expect(Etc).to receive(:setpwent)
Puppet::Etc.setpwent
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/task_spec.rb | spec/unit/task_spec.rb | require 'spec_helper'
require 'puppet_spec/files'
require 'puppet_spec/modules'
require 'puppet/module/task'
describe Puppet::Module::Task do
include PuppetSpec::Files
let(:modpath) { tmpdir('task_modpath') }
let(:mymodpath) { File.join(modpath, 'mymod') }
let(:othermodpath) { File.join(modpath, 'othermod') }
let(:mymod) { Puppet::Module.new('mymod', mymodpath, nil) }
let(:othermod) { Puppet::Module.new('othermod', othermodpath, nil) }
let(:tasks_path) { File.join(mymodpath, 'tasks') }
let(:other_tasks_path) { File.join(othermodpath, 'tasks') }
let(:tasks_glob) { File.join(mymodpath, 'tasks', '*') }
it "cannot construct tasks with illegal names" do
expect { Puppet::Module::Task.new(mymod, "iLegal", []) }
.to raise_error(Puppet::Module::Task::InvalidName,
"Task names must start with a lowercase letter and be composed of only lowercase letters, numbers, and underscores")
end
it "constructs tasks as expected when every task has a metadata file with the same name (besides extension)" do
task_files = %w{task1.json task1 task2.json task2.exe task3.json task3.sh}.map { |bn| "#{tasks_path}/#{bn}" }
expect(Dir).to receive(:glob).with(tasks_glob).and_return(task_files)
task_files.each { |f| expect(File).to receive(:file?).with(f).and_return(true) }
tasks = Puppet::Module::Task.tasks_in_module(mymod)
allow_any_instance_of(Puppet::Module::Task).to receive(:metadata).and_return({})
expect(tasks.count).to eq(3)
expect(tasks.map{|t| t.name}).to eq(%w{mymod::task1 mymod::task2 mymod::task3})
expect(tasks.map{|t| t.metadata_file}).to eq(["#{tasks_path}/task1.json",
"#{tasks_path}/task2.json",
"#{tasks_path}/task3.json"])
expect(tasks.map{|t| t.files.map { |f| f["path"] } }).to eq([["#{tasks_path}/task1"],
["#{tasks_path}/task2.exe"],
["#{tasks_path}/task3.sh"]])
expect(tasks.map{|t| t.files.map { |f| f["name"] } }).to eq([["task1"],
["task2.exe"],
["task3.sh"]])
tasks.map{|t| t.metadata_file}.each do |metadata_file|
expect(metadata_file).to eq(File.absolute_path(metadata_file))
end
tasks.map{|t| t.files}.each do |file_data|
path = file_data[0]['path']
expect(path).to eq(File.absolute_path(path))
end
end
it "constructs tasks as expected when some tasks don't have a metadata file" do
task_files = %w{task1 task2.exe task3.json task3.sh}.map { |bn| "#{tasks_path}/#{bn}" }
expect(Dir).to receive(:glob).with(tasks_glob).and_return(task_files)
task_files.each { |f| expect(File).to receive(:file?).with(f).and_return(true) }
allow_any_instance_of(Puppet::Module::Task).to receive(:metadata).and_return({})
tasks = Puppet::Module::Task.tasks_in_module(mymod)
expect(tasks.count).to eq(3)
expect(tasks.map{|t| t.name}).to eq(%w{mymod::task1 mymod::task2 mymod::task3})
expect(tasks.map{|t| t.metadata_file}).to eq([nil, nil, "#{tasks_path}/task3.json"])
expect(tasks.map{|t| t.files.map { |f| f["path"] } }).to eq([["#{tasks_path}/task1"],
["#{tasks_path}/task2.exe"],
["#{tasks_path}/task3.sh"]])
end
it "constructs a task as expected when a task has implementations" do
task_files = %w{task1.elf task1.sh task1.json}.map { |bn| "#{tasks_path}/#{bn}" }
expect(Dir).to receive(:glob).with(tasks_glob).and_return(task_files)
task_files.each { |f| expect(File).to receive(:file?).with(f).and_return(true) }
tasks = Puppet::Module::Task.tasks_in_module(mymod)
allow_any_instance_of(Puppet::Module::Task).to receive(:metadata).and_return({'implementations' => [{"name" => "task1.sh"}]})
expect(tasks.count).to eq(1)
expect(tasks.map{|t| t.name}).to eq(%w{mymod::task1})
expect(tasks.map{|t| t.metadata_file}).to eq(["#{tasks_path}/task1.json"])
expect(tasks.map{|t| t.files.map{ |f| f["path"] } }).to eq([["#{tasks_path}/task1.sh"]])
end
it "constructs a task as expected when task metadata declares additional files" do
task_files = %w{task1.sh task1.json}.map { |bn| "#{tasks_path}/#{bn}" }
expect(Dir).to receive(:glob).with(tasks_glob).and_return(task_files)
task_files.each { |f| expect(File).to receive(:file?).with(f).and_return(true) }
expect(Puppet::Module::Task).to receive(:find_extra_files).and_return([{'name' => 'mymod/lib/file0.elf', 'path' => "/path/to/file0.elf"}])
tasks = Puppet::Module::Task.tasks_in_module(mymod)
allow_any_instance_of(Puppet::Module::Task).to receive(:metadata).and_return({'files' => ["mymod/lib/file0.elf"]})
expect(tasks.count).to eq(1)
expect(tasks.map{|t| t.name}).to eq(%w{mymod::task1})
expect(tasks.map{|t| t.metadata_file}).to eq(["#{tasks_path}/task1.json"])
expect(tasks.map{|t| t.files.map{ |f| f["path"] } }).to eq([["#{tasks_path}/task1.sh", "/path/to/file0.elf"]])
end
it "constructs a task as expected when a task implementation declares additional files" do
task_files = %w{task1.sh task1.json}.map { |bn| "#{tasks_path}/#{bn}" }
expect(Dir).to receive(:glob).with(tasks_glob).and_return(task_files)
task_files.each { |f| expect(File).to receive(:file?).with(f).and_return(true) }
expect(Puppet::Module::Task).to receive(:find_extra_files).and_return([{'name' => 'mymod/lib/file0.elf', 'path' => "/path/to/file0.elf"}])
tasks = Puppet::Module::Task.tasks_in_module(mymod)
allow_any_instance_of(Puppet::Module::Task).to receive(:metadata).and_return({'implementations' => [{"name" => "task1.sh", "files" => ["mymod/lib/file0.elf"]}]})
expect(tasks.count).to eq(1)
expect(tasks.map{|t| t.name}).to eq(%w{mymod::task1})
expect(tasks.map{|t| t.metadata_file}).to eq(["#{tasks_path}/task1.json"])
expect(tasks.map{|t| t.files.map{ |f| f["path"] } }).to eq([["#{tasks_path}/task1.sh", "/path/to/file0.elf"]])
end
it "constructs a task as expected when task metadata and a task implementation both declare additional files" do
task_files = %w{task1.sh task1.json}.map { |bn| "#{tasks_path}/#{bn}" }
expect(Dir).to receive(:glob).with(tasks_glob).and_return(task_files)
task_files.each { |f| expect(File).to receive(:file?).with(f).and_return(true) }
expect(Puppet::Module::Task).to receive(:find_extra_files).and_return([
{'name' => 'mymod/lib/file0.elf', 'path' => "/path/to/file0.elf"},
{'name' => 'yourmod/files/file1.txt', 'path' => "/other/path/to/file1.txt"}
])
tasks = Puppet::Module::Task.tasks_in_module(mymod)
allow_any_instance_of(Puppet::Module::Task).to receive(:metadata).and_return({'implementations' => [{"name" => "task1.sh", "files" => ["mymod/lib/file0.elf"]}]})
expect(tasks.count).to eq(1)
expect(tasks.map{|t| t.name}).to eq(%w{mymod::task1})
expect(tasks.map{|t| t.metadata_file}).to eq(["#{tasks_path}/task1.json"])
expect(tasks.map{|t| t.files.map{ |f| f["path"] } }).to eq([[
"#{tasks_path}/task1.sh",
"/path/to/file0.elf",
"/other/path/to/file1.txt"
]])
end
it "constructs a task as expected when a task has files" do
og_files = %w{task1.sh task1.json}.map { |bn| "#{tasks_path}/#{bn}" }
expect(Dir).to receive(:glob).with(tasks_glob).and_return(og_files)
og_files.each { |f| expect(File).to receive(:file?).with(f).and_return(true) }
expect(File).to receive(:exist?).with(any_args).and_return(true).at_least(:once)
expect(Puppet::Module).to receive(:find).with(othermod.name, "production").and_return(othermod).at_least(:once)
short_files = %w{other_task.sh other_task.json task_2.sh}.map { |bn| "#{othermod.name}/tasks/#{bn}" }
long_files = %w{other_task.sh other_task.json task_2.sh}.map { |bn| "#{other_tasks_path}/#{bn}" }
tasks = Puppet::Module::Task.tasks_in_module(mymod)
allow_any_instance_of(Puppet::Module::Task).to receive(:metadata).and_return({'files' => short_files})
expect(tasks.count).to eq(1)
expect(tasks.map{|t| t.files.map{ |f| f["path"] } }).to eq([["#{tasks_path}/task1.sh"] + long_files])
end
it "fails to load a task if its metadata specifies a non-existent file" do
og_files = %w{task1.sh task1.json}.map { |bn| "#{tasks_path}/#{bn}" }
allow(Dir).to receive(:glob).with(tasks_glob).and_return(og_files)
og_files.each { |f| expect(File).to receive(:file?).with(f).and_return(true) }
allow(File).to receive(:exist?).with(any_args).and_return(true)
expect(Puppet::Module).to receive(:find).with(othermod.name, "production").and_return(nil).at_least(:once)
tasks = Puppet::Module::Task.tasks_in_module(mymod)
allow_any_instance_of(Puppet::Module::Task).to receive(:metadata).and_return({'files' => ["#{othermod.name}/files/test"]})
expect { tasks.first.files }.to raise_error(Puppet::Module::Task::InvalidMetadata, /Could not find module #{othermod.name} containing task file test/)
end
it "finds files whose names (besides extensions) are valid task names" do
og_files = %w{task task_1 xx_t_a_s_k_2_xx}.map { |bn| "#{tasks_path}/#{bn}" }
expect(Dir).to receive(:glob).with(tasks_glob).and_return(og_files)
og_files.each { |f| expect(File).to receive(:file?).with(f).and_return(true) }
tasks = Puppet::Module::Task.tasks_in_module(mymod)
expect(tasks.count).to eq(3)
expect(tasks.map{|t| t.name}).to eq(%w{mymod::task mymod::task_1 mymod::xx_t_a_s_k_2_xx})
end
it "ignores files that have names (besides extensions) that are not valid task names" do
og_files = %w{.nottask.exe .wat !runme _task 2task2furious def_a_task_PSYCH Fake_task not-a-task realtask}.map { |bn| "#{tasks_path}/#{bn}" }
expect(Dir).to receive(:glob).with(tasks_glob).and_return(og_files)
og_files.each { |f| expect(File).to receive(:file?).with(f).and_return(true) }
tasks = Puppet::Module::Task.tasks_in_module(mymod)
expect(tasks.count).to eq(1)
expect(tasks.map{|t| t.name}).to eq(%w{mymod::realtask})
end
it "ignores files that have names ending in .conf and .md" do
og_files = %w{ginuwine_task task.conf readme.md other_task.md}.map { |bn| "#{tasks_path}/#{bn}" }
expect(Dir).to receive(:glob).with(tasks_glob).and_return(og_files)
og_files.each { |f| expect(File).to receive(:file?).with(f).and_return(true) }
tasks = Puppet::Module::Task.tasks_in_module(mymod)
expect(tasks.count).to eq(1)
expect(tasks.map{|t| t.name}).to eq(%w{mymod::ginuwine_task})
end
it "ignores files which are not regular files" do
og_files = %w{foo}.map { |bn| "#{tasks_path}/#{bn}" }
expect(Dir).to receive(:glob).with(tasks_glob).and_return(og_files)
og_files.each { |f| expect(File).to receive(:file?).with(f).and_return(false) }
tasks = Puppet::Module::Task.tasks_in_module(mymod)
expect(tasks.count).to eq(0)
end
it "gives the 'init' task a name that is just the module's name" do
expect(Puppet::Module::Task.new(mymod, 'init', ["#{tasks_path}/init.sh"]).name).to eq('mymod')
end
describe :metadata do
it "loads metadata for a task" do
metadata = {'desciption': 'some info'}
og_files = %w{task1.exe task1.json}.map { |bn| "#{tasks_path}/#{bn}" }
expect(Dir).to receive(:glob).with(tasks_glob).and_return(og_files)
og_files.each { |f| expect(File).to receive(:file?).with(f).and_return(true) }
allow(Puppet::Module::Task).to receive(:read_metadata).and_return(metadata)
tasks = Puppet::Module::Task.tasks_in_module(mymod)
expect(tasks.count).to eq(1)
expect(tasks[0].metadata).to eq(metadata)
end
it 'returns nil for metadata if no file is present' do
og_files = %w{task1.exe}.map { |bn| "#{tasks_path}/#{bn}" }
expect(Dir).to receive(:glob).with(tasks_glob).and_return(og_files)
og_files.each { |f| expect(File).to receive(:file?).with(f).and_return(true) }
tasks = Puppet::Module::Task.tasks_in_module(mymod)
expect(tasks.count).to eq(1)
expect(tasks[0].metadata).to be_nil
end
it 'raises InvalidMetadata if the json metadata is invalid' do
FileUtils.mkdir_p(tasks_path)
File.open(File.join(tasks_path, 'task.json'), 'w') { |f| f.write '{ "whoops"' }
FileUtils.touch(File.join(tasks_path, 'task'))
tasks = Puppet::Module::Task.tasks_in_module(mymod)
expect(tasks.count).to eq(1)
expect {
tasks[0].metadata
}.to raise_error(Puppet::Module::Task::InvalidMetadata, /whoops/)
end
it 'returns empty hash for metadata when json metadata file is empty' do
FileUtils.mkdir_p(tasks_path)
FileUtils.touch(File.join(tasks_path, 'task.json'))
FileUtils.touch(File.join(tasks_path, 'task'))
tasks = Puppet::Module::Task.tasks_in_module(mymod)
expect(tasks.count).to eq(1)
expect(tasks[0].metadata).to eq({})
end
end
describe :validate do
it "validates when there is no metadata" do
og_files = %w{task1.exe}.map { |bn| "#{tasks_path}/#{bn}" }
expect(Dir).to receive(:glob).with(tasks_glob).and_return(og_files)
og_files.each { |f| expect(File).to receive(:file?).with(f).and_return(true) }
tasks = Puppet::Module::Task.tasks_in_module(mymod)
expect(tasks.count).to eq(1)
expect(tasks[0].validate).to eq(true)
end
it "validates when an implementation isn't used" do
metadata = {'desciption' => 'some info',
'implementations' => [ {"name" => "task1.exe"}, ] }
og_files = %w{task1.exe task1.sh task1.json}.map { |bn| "#{tasks_path}/#{bn}" }
expect(Dir).to receive(:glob).with(tasks_glob).and_return(og_files)
og_files.each { |f| expect(File).to receive(:file?).with(f).and_return(true) }
allow(Puppet::Module::Task).to receive(:read_metadata).and_return(metadata)
tasks = Puppet::Module::Task.tasks_in_module(mymod)
expect(tasks.count).to eq(1)
expect(tasks[0].validate).to be(true)
end
it "validates when an implementation is another task" do
metadata = {'desciption' => 'some info',
'implementations' => [ {"name" => "task2.sh"}, ] }
og_files = %w{task1.exe task2.sh task1.json}.map { |bn| "#{tasks_path}/#{bn}" }
expect(Dir).to receive(:glob).with(tasks_glob).and_return(og_files)
og_files.each { |f| expect(File).to receive(:file?).with(f).and_return(true) }
allow(Puppet::Module::Task).to receive(:read_metadata).and_return(metadata)
tasks = Puppet::Module::Task.tasks_in_module(mymod)
expect(tasks.count).to eq(2)
expect(tasks.map(&:validate)).to eq([true, true])
end
it "fails validation when there is no metadata and multiple task files" do
og_files = %w{task1.elf task1.exe task1.json task2.ps1 task2.sh}.map { |bn| "#{tasks_path}/#{bn}" }
expect(Dir).to receive(:glob).with(tasks_glob).and_return(og_files)
og_files.each { |f| expect(File).to receive(:file?).with(f).and_return(true) }
tasks = Puppet::Module::Task.tasks_in_module(mymod)
allow_any_instance_of(Puppet::Module::Task).to receive(:metadata).and_return({})
tasks.each do |task|
expect {task.validate}.to raise_error(Puppet::Module::Task::InvalidTask)
end
end
it "fails validation when an implementation references a non-existant file" do
og_files = %w{task1.elf task1.exe task1.json}.map { |bn| "#{tasks_path}/#{bn}" }
expect(Dir).to receive(:glob).with(tasks_glob).and_return(og_files)
og_files.each { |f| expect(File).to receive(:file?).with(f).and_return(true) }
tasks = Puppet::Module::Task.tasks_in_module(mymod)
allow_any_instance_of(Puppet::Module::Task).to receive(:metadata).and_return({'implementations' => [ { 'name' => 'task1.sh' } ] })
tasks.each do |task|
expect {task.validate}.to raise_error(Puppet::Module::Task::InvalidTask)
end
end
it 'fails validation when there is metadata but no executable' do
og_files = %w{task1.json task2.sh}.map { |bn| "#{tasks_path}/#{bn}" }
expect(Dir).to receive(:glob).with(tasks_glob).and_return(og_files)
og_files.each { |f| expect(File).to receive(:file?).with(f).and_return(true) }
tasks = Puppet::Module::Task.tasks_in_module(mymod)
allow_any_instance_of(Puppet::Module::Task).to receive(:metadata).and_return({})
expect { tasks.find { |t| t.name == 'mymod::task1' }.validate }.to raise_error(Puppet::Module::Task::InvalidTask)
end
it 'fails validation when the implementations are not an array' do
og_files = %w{task1.json task2.sh}.map { |bn| "#{tasks_path}/#{bn}" }
expect(Dir).to receive(:glob).with(tasks_glob).and_return(og_files)
og_files.each { |f| expect(File).to receive(:file?).with(f).and_return(true) }
tasks = Puppet::Module::Task.tasks_in_module(mymod)
allow_any_instance_of(Puppet::Module::Task).to receive(:metadata).and_return({"implemenations" => {}})
expect { tasks.find { |t| t.name == 'mymod::task1' }.validate }.to raise_error(Puppet::Module::Task::InvalidTask)
end
it 'fails validation when the implementation is json' do
og_files = %w{task1.json task1.sh}.map { |bn| "#{tasks_path}/#{bn}" }
expect(Dir).to receive(:glob).with(tasks_glob).and_return(og_files)
og_files.each { |f| expect(File).to receive(:file?).with(f).and_return(true) }
tasks = Puppet::Module::Task.tasks_in_module(mymod)
allow_any_instance_of(Puppet::Module::Task).to receive(:metadata).and_return({'implementations' => [ { 'name' => 'task1.json' } ] })
expect { tasks.find { |t| t.name == 'mymod::task1' }.validate }.to raise_error(Puppet::Module::Task::InvalidTask)
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/puppet_pal_2pec.rb | spec/unit/puppet_pal_2pec.rb | require 'spec_helper'
require 'puppet_spec/files'
require 'puppet_pal'
describe 'Puppet Pal' do
include PuppetSpec::Files
let(:testing_env) do
{
'pal_env' => {
'functions' => functions,
'lib' => { 'puppet' => lib_puppet },
'manifests' => manifests,
'modules' => modules,
'plans' => plans,
'tasks' => tasks,
'types' => types,
},
'other_env1' => { 'modules' => {} },
'other_env2' => { 'modules' => {} },
}
end
let(:functions) { {} }
let(:manifests) { {} }
let(:modules) { {} }
let(:plans) { {} }
let(:lib_puppet) { {} }
let(:tasks) { {} }
let(:types) { {} }
let(:environments_dir) { Puppet[:environmentpath] }
let(:testing_env_dir) do
dir_contained_in(environments_dir, testing_env)
env_dir = File.join(environments_dir, 'pal_env')
PuppetSpec::Files.record_tmp(env_dir)
PuppetSpec::Files.record_tmp(File.join(environments_dir, 'other_env1'))
PuppetSpec::Files.record_tmp(File.join(environments_dir, 'other_env2'))
env_dir
end
let(:modules_dir) { File.join(testing_env_dir, 'modules') }
# Without any facts - this speeds up the tests that do not require $facts to have any values
let(:node_facts) { Hash.new }
# TODO: to be used in examples for running in an existing env
# let(:env) { Puppet::Node::Environment.create(:testing, [modules_dir]) }
context 'in general - without code in modules or env' do
let(:modulepath) { [] }
context 'deprecated PAL API methods work and' do
it '"evaluate_script_string" evaluates a code string in a given tmp environment' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
ctx.evaluate_script_string('1+2+3')
end
expect(result).to eq(6)
end
it '"evaluate_script_manifest" evaluates a manifest file in a given tmp environment' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
manifest = file_containing('testing.pp', "1+2+3+4")
ctx.evaluate_script_manifest(manifest)
end
expect(result).to eq(10)
end
end
context "with a script compiler" do
it 'errors if given both configured_by_env and manifest_file' do
expect {
Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
ctx.with_script_compiler(configured_by_env: true, manifest_file: 'undef.pp') {|c| }
end
}.to raise_error(/manifest_file or code_string cannot be given when configured_by_env is true/)
end
it 'errors if given both configured_by_env and code_string' do
expect {
Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
ctx.with_script_compiler(configured_by_env: true, code_string: 'undef') {|c| }
end
}.to raise_error(/manifest_file or code_string cannot be given when configured_by_env is true/)
end
context "evaluate_string method" do
it 'evaluates code string in a given tmp environment' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
ctx.with_script_compiler {|c| c.evaluate_string('1+2+3') }
end
expect(result).to eq(6)
end
it 'can be evaluated more than once in a given tmp environment - each in fresh compiler' do
Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
expect( ctx.with_script_compiler {|c| c.evaluate_string('$a = 1+2+3')}).to eq(6)
expect { ctx.with_script_compiler {|c| c.evaluate_string('$a') }}.to raise_error(/Unknown variable: 'a'/)
end
end
it 'instantiates definitions in the given code string' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |pal|
pal.with_script_compiler do |compiler|
compiler.evaluate_string(<<-CODE)
function run_me() { "worked1" }
run_me()
CODE
end
end
expect(result).to eq('worked1')
end
end
context "evaluate_file method" do
it 'evaluates a manifest file in a given tmp environment' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
manifest = file_containing('testing.pp', "1+2+3+4")
ctx.with_script_compiler {|c| c.evaluate_file(manifest) }
end
expect(result).to eq(10)
end
it 'instantiates definitions in the given code string' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |pal|
pal.with_script_compiler do |compiler|
manifest = file_containing('testing.pp', (<<-CODE))
function run_me() { "worked1" }
run_me()
CODE
pal.with_script_compiler {|c| c.evaluate_file(manifest) }
end
end
expect(result).to eq('worked1')
end
end
context "variables are supported such that" do
it 'they can be set in any scope' do
vars = {'a'=> 10, 'x::y' => 20}
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts, variables: vars) do |ctx|
ctx.with_script_compiler {|c| c.evaluate_string("1+2+3+4+$a+$x::y")}
end
expect(result).to eq(40)
end
it 'an error is raised if a variable name is illegal' do
vars = {'_a::b'=> 10}
expect do
Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts, variables: vars) do |ctx|
manifest = file_containing('testing.pp', "ok")
ctx.with_script_compiler {|c| c.evaluate_file(manifest) }
end
end.to raise_error(/has illegal name/)
end
it 'an error is raised if variable value is not RichData compliant' do
vars = {'a'=> ArgumentError.new("not rich data")}
expect do
Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts, variables: vars) do |ctx|
ctx.with_script_compiler {|c| }
end
end.to raise_error(/has illegal type - got: ArgumentError/)
end
it 'variable given to script_compiler overrides those given for environment' do
vars = {'a'=> 10, 'x::y' => 20}
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts, variables: vars) do |ctx|
ctx.with_script_compiler(variables: {'x::y' => 40}) {|c| c.evaluate_string("1+2+3+4+$a+$x::y")}
end
expect(result).to eq(60)
end
end
context "functions are supported such that" do
it '"call_function" calls a function' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
manifest = file_containing('afunc.pp', "function myfunc($a) { $a * 2 } ")
ctx.with_script_compiler(manifest_file: manifest) {|c| c.call_function('myfunc', 6) }
end
expect(result).to eq(12)
end
it '"call_function" accepts a call with a ruby block' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
ctx.with_script_compiler {|c| c.call_function('with', 6) {|x| x * 2} }
end
expect(result).to eq(12)
end
it '"function_signature" returns a signature of a function' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
manifest = file_containing('afunc.pp', "function myfunc(Integer $a) { $a * 2 } ")
ctx.with_script_compiler(manifest_file: manifest) do |c|
c.function_signature('myfunc')
end
end
expect(result.class).to eq(Puppet::Pal::FunctionSignature)
end
it '"FunctionSignature#callable_with?" returns boolean if function is callable with given argument values' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
manifest = file_containing('afunc.pp', "function myfunc(Integer $a) { $a * 2 } ")
ctx.with_script_compiler(manifest_file: manifest) do |c|
signature = c.function_signature('myfunc')
[ signature.callable_with?([10]),
signature.callable_with?(['nope'])
]
end
end
expect(result).to eq([true, false])
end
it '"FunctionSignature#callable_with?" calls a given lambda if there is an error' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
manifest = file_containing('afunc.pp', "function myfunc(Integer $a) { $a * 2 } ")
ctx.with_script_compiler(manifest_file: manifest) do |c|
signature = c.function_signature('myfunc')
local_result = 'not yay'
signature.callable_with?(['nope']) {|error| local_result = error }
local_result
end
end
expect(result).to match(/'myfunc' parameter 'a' expects an Integer value, got String/)
end
it '"FunctionSignature#callable_with?" does not call a given lambda when there is no error' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
manifest = file_containing('afunc.pp', "function myfunc(Integer $a) { $a * 2 } ")
ctx.with_script_compiler(manifest_file: manifest) do |c|
signature = c.function_signature('myfunc')
local_result = 'yay'
signature.callable_with?([10]) {|error| local_result = 'not yay' }
local_result
end
end
expect(result).to eq('yay')
end
it '"function_signature" gets the signatures from a ruby function with multiple dispatch' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
ctx.with_script_compiler {|c| c.function_signature('lookup') }
end
# check two different signatures of the lookup function
expect(result.callable_with?(['key'])).to eq(true)
expect(result.callable_with?(['key'], lambda() {|k| })).to eq(true)
end
it '"function_signature" returns nil if function is not found' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
ctx.with_script_compiler {|c| c.function_signature('no_where_to_be_found') }
end
expect(result).to eq(nil)
end
it '"FunctionSignature#callables" returns an array of callables' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
manifest = file_containing('afunc.pp', "function myfunc(Integer $a) { $a * 2 } ")
ctx.with_script_compiler(manifest_file: manifest) do |c|
c.function_signature('myfunc').callables
end
end
expect(result.class).to eq(Array)
expect(result.all? {|c| c.is_a?(Puppet::Pops::Types::PCallableType)}).to eq(true)
end
it '"list_functions" returns an array with all function names that can be loaded' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
ctx.with_script_compiler {|c| c.list_functions() }
end
expect(result.is_a?(Array)).to eq(true)
expect(result.all? {|s| s.is_a?(Puppet::Pops::Loader::TypedName) }).to eq(true)
# there are certainly more than 30 functions in puppet - (56 when writing this, but some refactoring
# may take place, so don't want an exact number here - jsut make sure it found "all of them"
expect(result.count).to be > 30
end
it '"list_functions" filters on name based on a given regexp' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
ctx.with_script_compiler {|c| c.list_functions(/epp/) }
end
expect(result.is_a?(Array)).to eq(true)
expect(result.all? {|s| s.is_a?(Puppet::Pops::Loader::TypedName) }).to eq(true)
# there are two functions currently that have 'epp' in their name
expect(result.count).to eq(2)
end
end
context 'supports plans such that' do
it '"plan_signature" returns the signatures of a plan' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
manifest = file_containing('afunc.pp', "plan myplan(Integer $a) { } ")
ctx.with_script_compiler(manifest_file: manifest) do |c|
signature = c.plan_signature('myplan')
[ signature.callable_with?({'a' => 10}),
signature.callable_with?({'a' => 'nope'})
]
end
end
expect(result).to eq([true, false])
end
it 'a PlanSignature.callable_with? calls a given lambda with any errors as a formatted string' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
manifest = file_containing('afunc.pp', "plan myplan(Integer $a, Integer $b) { } ")
ctx.with_script_compiler(manifest_file: manifest) do |c|
signature = c.plan_signature('myplan')
local_result = nil
signature.callable_with?({'a' => 'nope'}) {|errors| local_result = errors }
local_result
end
end
# Note that errors are indented one space and on separate lines
#
expect(result).to eq(" parameter 'a' expects an Integer value, got String\n expects a value for parameter 'b'")
end
it 'a PlanSignature.callable_with? does not call a given lambda if there are no errors' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
manifest = file_containing('afunc.pp', "plan myplan(Integer $a) { } ")
ctx.with_script_compiler(manifest_file: manifest) do |c|
signature = c.plan_signature('myplan')
local_result = 'yay'
signature.callable_with?({'a' => 1}) {|errors| local_result = 'not yay' }
local_result
end
end
expect(result).to eq('yay')
end
it '"plan_signature" returns nil if plan is not found' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
ctx.with_script_compiler {|c| c.plan_signature('no_where_to_be_found') }
end
expect(result).to be(nil)
end
it '"PlanSignature#params_type" returns a map of all parameters and their types' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
manifest = file_containing('afunc.pp', "plan myplan(Integer $a, String $b) { } ")
ctx.with_script_compiler(manifest_file: manifest) do |c|
c.plan_signature('myplan').params_type
end
end
expect(result.class).to eq(Puppet::Pops::Types::PStructType)
expect(result.to_s).to eq("Struct[{'a' => Integer, 'b' => String}]")
end
end
context 'supports puppet data types such that' do
it '"type" parses and returns a Type from a string specification' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
manifest = file_containing('main.pp', "type MyType = Float")
ctx.with_script_compiler(manifest_file: manifest) {|c| c.type('Variant[Integer, Boolean, MyType]') }
end
expect(result.is_a?(Puppet::Pops::Types::PVariantType)).to eq(true)
expect(result.types.size).to eq(3)
expect(result.instance?(3.14)).to eq(true)
end
it '"create" creates a new object from a puppet data type and args' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
ctx.with_script_compiler { |c| c.create(Puppet::Pops::Types::PIntegerType::DEFAULT, '0x10') }
end
expect(result).to eq(16)
end
it '"create" creates a new object from puppet data type in string form and args' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
ctx.with_script_compiler { |c| c.create('Integer', '010') }
end
expect(result).to eq(8)
end
end
end
context 'supports parsing such that' do
it '"parse_string" parses a puppet language string' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
ctx.with_script_compiler { |c| c.parse_string('$a = 10') }
end
expect(result.class).to eq(Puppet::Pops::Model::Program)
end
{ nil => Puppet::Error,
'0xWAT' => Puppet::ParseErrorWithIssue,
'$0 = 1' => Puppet::ParseErrorWithIssue,
'else 32' => Puppet::ParseErrorWithIssue,
}.each_pair do |input, error_class|
it "'parse_string' raises an error for invalid input: '#{input}'" do
expect {
Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
ctx.with_script_compiler { |c| c.parse_string(input) }
end
}.to raise_error(error_class)
end
end
it '"parse_file" parses a puppet language string' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
manifest = file_containing('main.pp', "$a = 10")
ctx.with_script_compiler { |c| c.parse_file(manifest) }
end
expect(result.class).to eq(Puppet::Pops::Model::Program)
end
it "'parse_file' raises an error for invalid input: 'else 32'" do
expect {
Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
manifest = file_containing('main.pp', "else 32")
ctx.with_script_compiler { |c| c.parse_file(manifest) }
end
}.to raise_error(Puppet::ParseErrorWithIssue)
end
it "'parse_file' raises an error for invalid input, file is not a string" do
expect {
Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
ctx.with_script_compiler { |c| c.parse_file(42) }
end
}.to raise_error(Puppet::Error)
end
it 'the "evaluate" method evaluates the parsed AST' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
ctx.with_script_compiler { |c| c.evaluate(c.parse_string('10 + 20')) }
end
expect(result).to eq(30)
end
it 'the "evaluate" method instantiates definitions when given a Program' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
ctx.with_script_compiler { |c| c.evaluate(c.parse_string('function foo() { "yay"}; foo()')) }
end
expect(result).to eq('yay')
end
it 'the "evaluate" method does not instantiates definitions when given ast other than Program' do
expect do
Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
ctx.with_script_compiler do |c|
program= c.parse_string('function foo() { "yay"}; foo()')
c.evaluate(program.body)
end
end
end.to raise_error(/Unknown function: 'foo'/)
end
it 'the "evaluate_literal" method evaluates AST being a representation of a literal value' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
ctx.with_script_compiler { |c| c.evaluate_literal(c.parse_string('{10 => "hello"}')) }
end
expect(result).to eq({10 => 'hello'})
end
it 'the "evaluate_literal" method errors if ast is not representing a literal value' do
expect do
Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
ctx.with_script_compiler { |c| c.evaluate_literal(c.parse_string('{10+1 => "hello"}')) }
end
end.to raise_error(/does not represent a literal value/)
end
it 'the "evaluate_literal" method errors if ast contains definitions' do
expect do
Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do | ctx|
ctx.with_script_compiler { |c| c.evaluate_literal(c.parse_string('function foo() { }; 42')) }
end
end.to raise_error(/does not represent a literal value/)
end
end
end
context 'with code in modules and env' do
let(:modulepath) { [modules_dir] }
let(:metadata_json_a) {
{
'name' => 'example/a',
'version' => '0.1.0',
'source' => 'git@github.com/example/example-a.git',
'dependencies' => [{'name' => 'c', 'version_range' => '>=0.1.0'}],
'author' => 'Bob the Builder',
'license' => 'Apache-2.0'
}
}
let(:metadata_json_b) {
{
'name' => 'example/b',
'version' => '0.1.0',
'source' => 'git@github.com/example/example-b.git',
'dependencies' => [{'name' => 'c', 'version_range' => '>=0.1.0'}],
'author' => 'Bob the Builder',
'license' => 'Apache-2.0'
}
}
let(:metadata_json_c) {
{
'name' => 'example/c',
'version' => '0.1.0',
'source' => 'git@github.com/example/example-c.git',
'dependencies' => [],
'author' => 'Bob the Builder',
'license' => 'Apache-2.0'
}
}
# TODO: there is something amiss with the metadata wrt dependencies - when metadata is present there is an error
# that dependencies could not be resolved. Metadata is therefore commented out.
# Dependency based visibility is probably something that we should remove...
let(:modules) {
{
'a' => {
'functions' => a_functions,
'lib' => { 'puppet' => a_lib_puppet },
'plans' => a_plans,
'tasks' => a_tasks,
'types' => a_types,
# 'metadata.json' => metadata_json_a.to_json
},
'b' => {
'functions' => b_functions,
'lib' => b_lib,
'plans' => b_plans,
'tasks' => b_tasks,
'types' => b_types,
# 'metadata.json' => metadata_json_b.to_json
},
'c' => {
'types' => c_types,
# 'metadata.json' => metadata_json_c.to_json
},
}
}
let(:a_plans) {
{
'aplan.pp' => <<-PUPPET.unindent,
plan a::aplan() { 'a::aplan value' }
PUPPET
}
}
let(:a_types) {
{
'atype.pp' => <<-PUPPET.unindent,
type A::Atype = Integer
PUPPET
}
}
let(:a_tasks) {
{
'atask' => '',
}
}
let(:a_functions) {
{
'afunc.pp' => 'function a::afunc() { "a::afunc value" }',
}
}
let(:a_lib_puppet) {
{
'functions' => {
'a' => {
'arubyfunc.rb' => <<-RUBY.unindent,
require 'stuff/something'
Puppet::Functions.create_function(:'a::arubyfunc') do
def arubyfunc
Stuff::SOMETHING
end
end
RUBY
'myscriptcompilerfunc.rb' => <<-RUBY.unindent,
Puppet::Functions.create_function(:'a::myscriptcompilerfunc', Puppet::Functions::InternalFunction) do
dispatch :myscriptcompilerfunc do
script_compiler_param
param 'String',:name
end
def myscriptcompilerfunc(script_compiler, name)
script_compiler.is_a?(Puppet::Pal::ScriptCompiler) ? name : 'no go'
end
end
RUBY
}
}
}
}
let(:b_plans) {
{
'aplan.pp' => <<-PUPPET.unindent,
plan b::aplan() {}
PUPPET
}
}
let(:b_types) {
{
'atype.pp' => <<-PUPPET.unindent,
type B::Atype = Integer
PUPPET
}
}
let(:b_tasks) {
{
'atask' => "# doing exactly nothing\n",
'atask.json' => <<-JSONTEXT.unindent
{
"description": "test task b::atask",
"input_method": "stdin",
"parameters": {
"string_param": {
"description": "A string parameter",
"type": "String[1]"
},
"int_param": {
"description": "An integer parameter",
"type": "Integer"
}
}
}
JSONTEXT
}
}
let(:b_functions) {
{
'afunc.pp' => 'function b::afunc() {}',
}
}
let(:b_lib) {
{
'puppet' => b_lib_puppet,
'stuff' => {
'something.rb' => "module Stuff; SOMETHING = 'something'; end"
}
}
}
let(:b_lib_puppet) {
{
'functions' => {
'b' => {
'arubyfunc.rb' => "Puppet::Functions.create_function(:'b::arubyfunc') { def arubyfunc; 'arubyfunc_value'; end }",
}
}
}
}
let(:c_types) {
{
'atype.pp' => <<-PUPPET.unindent,
type C::Atype = Integer
PUPPET
}
}
context 'configured as temporary environment such that' do
it 'modules are available' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
ctx.with_script_compiler {|c| c.evaluate_string('a::afunc()') }
end
expect(result).to eq("a::afunc value")
end
it 'libs in a given "modulepath" are added to the Ruby $LOAD_PATH' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
ctx.with_script_compiler {|c| c.evaluate_string('a::arubyfunc()') }
end
expect(result).to eql('something')
end
it 'errors if a block is not given to in_tmp_environment' do
expect do
Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts)
end.to raise_error(/A block must be given to 'in_tmp_environment/)
end
it 'errors if an env_name is given and is not a String[1]' do
expect do
Puppet::Pal.in_tmp_environment('', modulepath: modulepath, facts: node_facts) { |ctx| }
end.to raise_error(/temporary environment name has wrong type/)
expect do
Puppet::Pal.in_tmp_environment(32, modulepath: modulepath, facts: node_facts) { |ctx| }
end.to raise_error(/temporary environment name has wrong type/)
end
{ 'a hash' => {'a' => 'hm'},
'an integer' => 32,
'separated strings' => 'dir1;dir2',
'empty string in array' => ['']
}.each_pair do |what, value|
it "errors if modulepath is #{what}" do
expect do
Puppet::Pal.in_tmp_environment('pal_env', modulepath: value, facts: node_facts) { |ctx| }
end.to raise_error(/modulepath has wrong type/)
end
end
context 'facts are supported such that' do
it 'they are obtained if they are not given' do
facts = Puppet::Node::Facts.new(Puppet[:certname], 'puppetversion' => Puppet.version)
Puppet::Node::Facts.indirection.save(facts)
testing_env_dir # creates the structure
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath ) do |ctx|
ctx.with_script_compiler {|c| c.evaluate_string("$facts =~ Hash and $facts[puppetversion] == '#{Puppet.version}'") }
end
expect(result).to eq(true)
end
it 'can be given as a hash when creating the environment' do
testing_env_dir # creates the structure
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: { 'myfact' => 42 }) do |ctx|
ctx.with_script_compiler {|c| c.evaluate_string("$facts =~ Hash and $facts[myfact] == 42") }
end
expect(result).to eq(true)
end
it 'can be overridden with a hash when creating a script compiler' do
testing_env_dir # creates the structure
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: { 'myfact' => 42 }) do |ctx|
ctx.with_script_compiler(facts: { 'myfact' => 43 }) {|c| c.evaluate_string("$facts =~ Hash and $facts[myfact] == 43") }
end
expect(result).to eq(true)
end
it 'can be disabled with the :set_local_facts option' do
Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: { 'myfact' => 42}) do |ctx|
ctx.with_script_compiler(facts: { 'myfact' => 42 }, set_local_facts: false) do |compiler|
expect { compiler.evaluate_string('$facts') }.to raise_error(
Puppet::PreformattedError,
/Unknown variable: 'facts'/
)
end
end
end
end
context 'supports tasks such that' do
it '"task_signature" returns the signatures of a generic task' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
ctx.with_script_compiler do |c|
signature = c.task_signature('a::atask')
[ signature.runnable_with?('whatever' => 10),
signature.runnable_with?('anything_goes' => 'foo')
]
end
end
expect(result).to eq([true, true])
end
it '"TaskSignature#runnable_with?" calls a given lambda if there is an error in a generic task' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
ctx.with_script_compiler do |c|
signature = c.task_signature('a::atask')
local_result = 'not yay'
signature.runnable_with?('string_param' => /not data/) {|error| local_result = error }
local_result
end
end
expect(result).to match(/Task a::atask:\s+entry 'string_param' expects a Data value, got Regexp/m)
end
it '"task_signature" returns the signatures of a task defined with metadata' do
result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: modulepath, facts: node_facts) do |ctx|
ctx.with_script_compiler do |c|
signature = c.task_signature('b::atask')
[ signature.runnable_with?('string_param' => 'foo', 'int_param' => 10),
signature.runnable_with?('anything_goes' => 'foo'),
signature.task_hash['name'],
signature.task_hash['metadata']['parameters']['string_param']['description'],
signature.task_hash['metadata']['description'],
signature.task_hash['metadata']['parameters']['int_param']['type'],
]
end
end
expect(result).to eq([true, false, 'b::atask', 'A string parameter', 'test task b::atask', 'Integer'])
end
it '"TaskSignature#runnable_with?" calls a given lambda if there is an error' do
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | true |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/module_tool_spec.rb | spec/unit/module_tool_spec.rb | # encoding: UTF-8
require 'spec_helper'
require 'puppet/module_tool'
describe Puppet::ModuleTool do
describe '.is_module_root?' do
it 'should return true if directory has a metadata.json file' do
expect(FileTest).to receive(:file?).with(have_attributes(to_s: '/a/b/c/metadata.json')).and_return(true)
expect(subject.is_module_root?(Pathname.new('/a/b/c'))).to be_truthy
end
it 'should return false if directory does not have a metadata.json file' do
expect(FileTest).to receive(:file?).with(have_attributes(to_s: '/a/b/c/metadata.json')).and_return(false)
expect(subject.is_module_root?(Pathname.new('/a/b/c'))).to be_falsey
end
end
describe '.find_module_root' do
let(:sample_path) { Pathname.new('/a/b/c').expand_path }
it 'should return the first path as a pathname when it contains a module file' do
expect(Puppet::ModuleTool).to receive(:is_module_root?).with(sample_path).
and_return(true)
expect(subject.find_module_root(sample_path)).to eq(sample_path)
end
it 'should return a parent path as a pathname when it contains a module file' do
expect(Puppet::ModuleTool).to receive(:is_module_root?).with(have_attributes(to_s: File.expand_path('/a/b/c'))).and_return(false)
expect(Puppet::ModuleTool).to receive(:is_module_root?).with(have_attributes(to_s: File.expand_path('/a/b'))).and_return(true)
expect(subject.find_module_root(sample_path)).to eq(Pathname.new('/a/b').expand_path)
end
it 'should return nil when no module root can be found' do
expect(Puppet::ModuleTool).to receive(:is_module_root?).at_least(:once).and_return(false)
expect(subject.find_module_root(sample_path)).to be_nil
end
end
describe '.format_tree' do
it 'should return an empty tree when given an empty list' do
expect(subject.format_tree([])).to eq('')
end
it 'should return a shallow when given a list without dependencies' do
list = [ { :text => 'first' }, { :text => 'second' }, { :text => 'third' } ]
expect(subject.format_tree(list)).to eq <<-TREE
├── first
├── second
└── third
TREE
end
it 'should return a deeply nested tree when given a list with deep dependencies' do
list = [
{
:text => 'first',
:dependencies => [
{
:text => 'second',
:dependencies => [
{ :text => 'third' }
]
}
]
},
]
expect(subject.format_tree(list)).to eq <<-TREE
└─┬ first
└─┬ second
└── third
TREE
end
it 'should show connectors when deep dependencies are not on the last node of the top level' do
list = [
{
:text => 'first',
:dependencies => [
{
:text => 'second',
:dependencies => [
{ :text => 'third' }
]
}
]
},
{ :text => 'fourth' }
]
expect(subject.format_tree(list)).to eq <<-TREE
├─┬ first
│ └─┬ second
│ └── third
└── fourth
TREE
end
it 'should show connectors when deep dependencies are not on the last node of any level' do
list = [
{
:text => 'first',
:dependencies => [
{
:text => 'second',
:dependencies => [
{ :text => 'third' }
]
},
{ :text => 'fourth' }
]
}
]
expect(subject.format_tree(list)).to eq <<-TREE
└─┬ first
├─┬ second
│ └── third
└── fourth
TREE
end
it 'should show connectors in every case when deep dependencies are not on the last node' do
list = [
{
:text => 'first',
:dependencies => [
{
:text => 'second',
:dependencies => [
{ :text => 'third' }
]
},
{ :text => 'fourth' }
]
},
{ :text => 'fifth' }
]
expect(subject.format_tree(list)).to eq <<-TREE
├─┬ first
│ ├─┬ second
│ │ └── third
│ └── fourth
└── fifth
TREE
end
end
describe '.set_option_defaults' do
let(:options) { {} }
let(:modulepath) { ['/env/module/path', '/global/module/path'] }
let(:environment_name) { :current_environment }
let(:environment) { Puppet::Node::Environment.create(environment_name, modulepath) }
subject do
described_class.set_option_defaults(options)
options
end
around do |example|
envs = Puppet::Environments::Static.new(environment)
Puppet.override(:environments => envs) do
example.run
end
end
describe ':environment' do
context 'as String' do
let(:options) { { :environment => "#{environment_name}" } }
it 'assigns the environment with the given name to :environment_instance' do
expect(subject).to include :environment_instance => environment
end
end
context 'as Symbol' do
let(:options) { { :environment => :"#{environment_name}" } }
it 'assigns the environment with the given name to :environment_instance' do
expect(subject).to include :environment_instance => environment
end
end
context 'as Puppet::Node::Environment' do
let(:env) { Puppet::Node::Environment.create('anonymous', []) }
let(:options) { { :environment => env } }
it 'assigns the given environment to :environment_instance' do
expect(subject).to include :environment_instance => env
end
end
end
describe ':modulepath' do
let(:options) do
{ :modulepath => %w[bar foo baz].join(File::PATH_SEPARATOR) }
end
let(:paths) { options[:modulepath].split(File::PATH_SEPARATOR).map { |dir| File.expand_path(dir) } }
it 'is expanded to an absolute path' do
expect(subject[:environment_instance].full_modulepath).to eql paths
end
it 'is used to compute :target_dir' do
expect(subject).to include :target_dir => paths.first
end
context 'conflicts with :environment' do
let(:options) do
{ :modulepath => %w[bar foo baz].join(File::PATH_SEPARATOR), :environment => environment_name }
end
it 'replaces the modulepath of the :environment_instance' do
expect(subject[:environment_instance].full_modulepath).to eql paths
end
it 'is used to compute :target_dir' do
expect(subject).to include :target_dir => paths.first
end
end
end
describe ':target_dir' do
let(:options) do
{ :target_dir => 'foo' }
end
let(:target) { File.expand_path(options[:target_dir]) }
it 'is expanded to an absolute path' do
expect(subject).to include :target_dir => target
end
it 'is prepended to the modulepath of the :environment_instance' do
expect(subject[:environment_instance].full_modulepath.first).to eql target
end
context 'conflicts with :modulepath' do
let(:options) do
{ :target_dir => 'foo', :modulepath => %w[bar foo baz].join(File::PATH_SEPARATOR) }
end
it 'is prepended to the modulepath of the :environment_instance' do
expect(subject[:environment_instance].full_modulepath.first).to eql target
end
it 'shares the provided :modulepath via the :environment_instance' do
paths = %w[foo] + options[:modulepath].split(File::PATH_SEPARATOR)
paths.map! { |dir| File.expand_path(dir) }
expect(subject[:environment_instance].full_modulepath).to eql paths
end
end
context 'conflicts with :environment' do
let(:options) do
{ :target_dir => 'foo', :environment => environment_name }
end
it 'is prepended to the modulepath of the :environment_instance' do
expect(subject[:environment_instance].full_modulepath.first).to eql target
end
it 'shares the provided :modulepath via the :environment_instance' do
paths = %w[foo] + environment.full_modulepath
paths.map! { |dir| File.expand_path(dir) }
expect(subject[:environment_instance].full_modulepath).to eql paths
end
end
context 'when not passed' do
it 'is populated with the first component of the modulepath' do
expect(subject).to include :target_dir => subject[:environment_instance].full_modulepath.first
end
end
end
end
describe '.parse_module_dependency' do
it 'parses a dependency without a version range expression' do
name, range, expr = subject.parse_module_dependency('source', 'name' => 'foo-bar')
expect(name).to eql('foo-bar')
expect(range).to eql(SemanticPuppet::VersionRange.parse('>= 0.0.0'))
expect(expr).to eql('>= 0.0.0')
end
it 'parses a dependency with a version range expression' do
name, range, expr = subject.parse_module_dependency('source', 'name' => 'foo-bar', 'version_requirement' => '1.2.x')
expect(name).to eql('foo-bar')
expect(range).to eql(SemanticPuppet::VersionRange.parse('1.2.x'))
expect(expr).to eql('1.2.x')
end
it 'does not raise an error on invalid version range expressions' do
name, range, expr = subject.parse_module_dependency('source', 'name' => 'foo-bar', 'version_requirement' => 'nope')
expect(name).to eql('foo-bar')
expect(range).to eql(SemanticPuppet::VersionRange::EMPTY_RANGE)
expect(expr).to eql('nope')
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/application_spec.rb | spec/unit/application_spec.rb | require 'spec_helper'
require 'puppet/application'
require 'puppet'
require 'getoptlong'
require 'timeout'
describe Puppet::Application do
before(:each) do
@appclass = Class.new(Puppet::Application) do
def handle_unknown(opt, arg); end
end
@app = @appclass.new
allow(@app).to receive(:name).and_return("test_app")
end
describe "application commandline" do
it "should not pick up changes to the array of arguments" do
args = %w{subcommand --arg}
command_line = Puppet::Util::CommandLine.new('puppet', args)
app = Puppet::Application.new(command_line)
args[0] = 'different_subcommand'
args[1] = '--other-arg'
expect(app.command_line.subcommand_name).to eq('subcommand')
expect(app.command_line.args).to eq(['--arg'])
end
end
describe "application defaults" do
it "should fail if required app default values are missing" do
allow(@app).to receive(:app_defaults).and_return({ :foo => 'bar' })
expect(Puppet).to receive(:send_log).with(:err, /missing required app default setting/)
expect {
@app.run
}.to exit_with(1)
end
end
describe "finding" do
before do
@klass = Puppet::Application
allow(@klass).to receive(:puts)
end
it "should find classes in the namespace" do
expect(@klass.find("Agent")).to eq(@klass::Agent)
end
it "should not find classes outside the namespace" do
expect { @klass.find("String") }.to raise_error(LoadError)
end
it "should error if it can't find a class" do
expect(Puppet).to receive(:send_log) do |_level, message|
expect(message).to match(/Unable to find application 'ThisShallNeverEverEverExist'/)
expect(message).to match(/puppet\/application\/thisshallneverevereverexist/)
expect(message).to match(/no such file to load|cannot load such file/)
end
expect {
@klass.find("ThisShallNeverEverEverExist")
}.to raise_error(LoadError)
end
end
describe "#available_application_names" do
it 'should be able to find available application names' do
apps = %w{describe filebucket kick queue resource agent cert apply doc master}
expect(Puppet::Util::Autoload).to receive(:files_to_load).and_return(apps)
expect(Puppet::Application.available_application_names).to match_array(apps)
end
it 'should find applications from multiple paths' do
expect(Puppet::Util::Autoload).to receive(:files_to_load).with(
'puppet/application',
be_a(Puppet::Node::Environment)
).and_return(%w{ /a/foo.rb /b/bar.rb })
expect(Puppet::Application.available_application_names).to match_array(%w{ foo bar })
end
it 'should return unique application names' do
expect(Puppet::Util::Autoload).to receive(:files_to_load).with(
'puppet/application',
be_a(Puppet::Node::Environment)
).and_return(%w{ /a/foo.rb /b/foo.rb })
expect(Puppet::Application.available_application_names).to eq(%w{ foo })
end
it 'finds the application using the configured environment' do
Puppet[:environment] = 'production'
expect(Puppet::Util::Autoload).to receive(:files_to_load) do |_, env|
expect(env.name).to eq(:production)
end.and_return(%w{ /a/foo.rb })
expect(Puppet::Application.available_application_names).to eq(%w{ foo })
end
it "falls back to the current environment if the configured environment doesn't exist" do
Puppet[:environment] = 'doesnotexist'
expect(Puppet::Util::Autoload).to receive(:files_to_load) do |_, env|
expect(env.name).to eq(:'*root*')
end.and_return(%w[a/foo.rb])
expect(Puppet::Application.available_application_names).to eq(%w[foo])
end
end
describe ".run_mode" do
it "should default to user" do
expect(@appclass.run_mode.name).to eq(:user)
end
it "should set and get a value" do
@appclass.run_mode :agent
expect(@appclass.run_mode.name).to eq(:agent)
end
it "considers :server to be master" do
@appclass.run_mode :server
expect(@appclass.run_mode).to be_master
end
end
describe ".environment_mode" do
it "should default to :local" do
expect(@appclass.get_environment_mode).to eq(:local)
end
it "should set and get a value" do
@appclass.environment_mode :remote
expect(@appclass.get_environment_mode).to eq(:remote)
end
it "should error if given a random symbol" do
expect{@appclass.environment_mode :foo}.to raise_error(/Invalid environment mode/)
end
it "should error if given a string" do
expect{@appclass.environment_mode 'local'}.to raise_error(/Invalid environment mode/)
end
end
# These tests may look a little weird and repetative in its current state;
# it used to illustrate several ways that the run_mode could be changed
# at run time; there are fewer ways now, but it would still be nice to
# get to a point where it was entirely impossible.
describe "when dealing with run_mode" do
class TestApp < Puppet::Application
run_mode :server
def run_command
# no-op
end
end
it "should sadly and frighteningly allow run_mode to change at runtime via #initialize_app_defaults" do
allow(Puppet.features).to receive(:syslog?).and_return(true)
app = TestApp.new
app.initialize_app_defaults
expect(Puppet.run_mode).to be_server
end
it "should sadly and frighteningly allow run_mode to change at runtime via #run" do
app = TestApp.new
app.run
expect(app.class.run_mode.name).to eq(:server)
expect(Puppet.run_mode).to be_server
end
end
it "should explode when an invalid run mode is set at runtime, for great victory" do
expect {
class InvalidRunModeTestApp < Puppet::Application
run_mode :abracadabra
def run_command
# no-op
end
end
}.to raise_error(Puppet::Settings::ValidationError, /Invalid run mode/)
end
it "should have a run entry-point" do
expect(@app).to respond_to(:run)
end
it "should have a read accessor to options" do
expect(@app).to respond_to(:options)
end
it "should include a default setup method" do
expect(@app).to respond_to(:setup)
end
it "should include a default preinit method" do
expect(@app).to respond_to(:preinit)
end
it "should include a default run_command method" do
expect(@app).to respond_to(:run_command)
end
it "should invoke main as the default" do
expect(@app).to receive(:main)
@app.run_command
end
describe 'when invoking clear!' do
before :each do
Puppet::Application.run_status = :stop_requested
Puppet::Application.clear!
end
it 'should have nil run_status' do
expect(Puppet::Application.run_status).to be_nil
end
it 'should return false for restart_requested?' do
expect(Puppet::Application.restart_requested?).to be_falsey
end
it 'should return false for stop_requested?' do
expect(Puppet::Application.stop_requested?).to be_falsey
end
it 'should return false for interrupted?' do
expect(Puppet::Application.interrupted?).to be_falsey
end
it 'should return true for clear?' do
expect(Puppet::Application.clear?).to be_truthy
end
end
describe 'after invoking stop!' do
before :each do
Puppet::Application.run_status = nil
Puppet::Application.stop!
end
after :each do
Puppet::Application.run_status = nil
end
it 'should have run_status of :stop_requested' do
expect(Puppet::Application.run_status).to eq(:stop_requested)
end
it 'should return true for stop_requested?' do
expect(Puppet::Application.stop_requested?).to be_truthy
end
it 'should return false for restart_requested?' do
expect(Puppet::Application.restart_requested?).to be_falsey
end
it 'should return true for interrupted?' do
expect(Puppet::Application.interrupted?).to be_truthy
end
it 'should return false for clear?' do
expect(Puppet::Application.clear?).to be_falsey
end
end
describe 'when invoking restart!' do
before :each do
Puppet::Application.run_status = nil
Puppet::Application.restart!
end
after :each do
Puppet::Application.run_status = nil
end
it 'should have run_status of :restart_requested' do
expect(Puppet::Application.run_status).to eq(:restart_requested)
end
it 'should return true for restart_requested?' do
expect(Puppet::Application.restart_requested?).to be_truthy
end
it 'should return false for stop_requested?' do
expect(Puppet::Application.stop_requested?).to be_falsey
end
it 'should return true for interrupted?' do
expect(Puppet::Application.interrupted?).to be_truthy
end
it 'should return false for clear?' do
expect(Puppet::Application.clear?).to be_falsey
end
end
describe 'when performing a controlled_run' do
it 'should not execute block if not :clear?' do
Puppet::Application.run_status = :stop_requested
target = double('target')
expect(target).not_to receive(:some_method)
Puppet::Application.controlled_run do
target.some_method
end
end
it 'should execute block if :clear?' do
Puppet::Application.run_status = nil
target = double('target')
expect(target).to receive(:some_method).once
Puppet::Application.controlled_run do
target.some_method
end
end
describe 'on POSIX systems', :if => (Puppet.features.posix? && RUBY_PLATFORM != 'java') do
it 'should signal process with HUP after block if restart requested during block execution' do
Timeout::timeout(3) do # if the signal doesn't fire, this causes failure.
has_run = false
old_handler = trap('HUP') { has_run = true }
begin
Puppet::Application.controlled_run do
Puppet::Application.run_status = :restart_requested
end
# Ruby 1.9 uses a separate OS level thread to run the signal
# handler, so we have to poll - ideally, in a way that will kick
# the OS into running other threads - for a while.
#
# You can't just use the Ruby Thread yield thing either, because
# that is just an OS hint, and Linux ... doesn't take that
# seriously. --daniel 2012-03-22
sleep 0.001 while not has_run
ensure
trap('HUP', old_handler)
end
end
end
end
after :each do
Puppet::Application.run_status = nil
end
end
describe "when parsing command-line options" do
before :each do
allow(@app.command_line).to receive(:args).and_return([])
allow(Puppet.settings).to receive(:optparse_addargs).and_return([])
end
it "should pass the banner to the option parser" do
option_parser = double("option parser")
allow(option_parser).to receive(:on)
allow(option_parser).to receive(:parse!)
@app.class.instance_eval do
banner "banner"
end
expect(OptionParser).to receive(:new).with("banner").and_return(option_parser)
@app.parse_options
end
it "should ask OptionParser to parse the command-line argument" do
allow(@app.command_line).to receive(:args).and_return(%w{ fake args })
expect_any_instance_of(OptionParser).to receive(:parse!).with(%w{ fake args })
@app.parse_options
end
describe "when using --help" do
it "should call exit" do
allow(@app).to receive(:puts)
expect { @app.handle_help(nil) }.to exit_with 0
end
end
describe "when using --version" do
it "should declare a version option" do
expect(@app).to respond_to(:handle_version)
end
it "should exit after printing the version" do
allow(@app).to receive(:puts)
expect { @app.handle_version(nil) }.to exit_with 0
end
end
describe "when dealing with an argument not declared directly by the application" do
it "should pass it to handle_unknown if this method exists" do
allow(Puppet.settings).to receive(:optparse_addargs).and_return([["--not-handled", :REQUIRED]])
expect(@app).to receive(:handle_unknown).with("--not-handled", "value").and_return(true)
allow(@app.command_line).to receive(:args).and_return(["--not-handled", "value"])
@app.parse_options
end
it "should transform boolean option to normal form for Puppet.settings" do
expect(@app).to receive(:handle_unknown).with("--option", true)
@app.send(:handlearg, "--[no-]option", true)
end
it "should transform boolean option to no- form for Puppet.settings" do
expect(@app).to receive(:handle_unknown).with("--no-option", false)
@app.send(:handlearg, "--[no-]option", false)
end
end
end
describe "when calling default setup" do
before :each do
allow(@app.options).to receive(:[])
end
[ :debug, :verbose ].each do |level|
it "should honor option #{level}" do
allow(@app.options).to receive(:[]).with(level).and_return(true)
allow(Puppet::Util::Log).to receive(:newdestination)
@app.setup
expect(Puppet::Util::Log.level).to eq(level == :verbose ? :info : :debug)
end
end
it "should honor setdest option" do
allow(@app.options).to receive(:[]).with(:setdest).and_return(false)
expect(Puppet::Util::Log).to receive(:setup_default)
@app.setup
end
it "sets the log destination if provided via settings" do
allow(@app.options).to receive(:[]).and_call_original
Puppet[:logdest] = "set_via_config"
expect(Puppet::Util::Log).to receive(:newdestination).with("set_via_config")
@app.setup
end
it "does not downgrade the loglevel when --verbose is specified" do
Puppet[:log_level] = :debug
allow(@app.options).to receive(:[]).with(:verbose).and_return(true)
@app.setup_logs
expect(Puppet::Util::Log.level).to eq(:debug)
end
it "allows the loglevel to be specified as an argument" do
@app.set_log_level(:debug => true)
expect(Puppet::Util::Log.level).to eq(:debug)
end
end
describe "when configuring routes" do
include PuppetSpec::Files
before :each do
Puppet::Node.indirection.reset_terminus_class
end
after :each do
Puppet::Node.indirection.reset_terminus_class
end
it "should use the routes specified for only the active application" do
Puppet[:route_file] = tmpfile('routes')
File.open(Puppet[:route_file], 'w') do |f|
f.print <<-ROUTES
test_app:
node:
terminus: exec
other_app:
node:
terminus: plain
catalog:
terminus: invalid
ROUTES
end
@app.configure_indirector_routes
expect(Puppet::Node.indirection.terminus_class).to eq('exec')
end
it "should not fail if the route file doesn't exist" do
Puppet[:route_file] = "/dev/null/non-existent"
expect { @app.configure_indirector_routes }.to_not raise_error
end
it "should raise an error if the routes file is invalid" do
Puppet[:route_file] = tmpfile('routes')
File.open(Puppet[:route_file], 'w') do |f|
f.print <<-ROUTES
invalid : : yaml
ROUTES
end
expect { @app.configure_indirector_routes }.to raise_error(Puppet::Error, /mapping values are not allowed/)
end
it "should treat master routes on server application" do
allow(@app).to receive(:name).and_return("server")
Puppet[:route_file] = tmpfile('routes')
File.open(Puppet[:route_file], 'w') do |f|
f.print <<-ROUTES
master:
node:
terminus: exec
ROUTES
end
@app.configure_indirector_routes
expect(Puppet::Node.indirection.terminus_class).to eq('exec')
end
it "should treat server routes on master application" do
allow(@app).to receive(:name).and_return("master")
Puppet[:route_file] = tmpfile('routes')
File.open(Puppet[:route_file], 'w') do |f|
f.print <<-ROUTES
server:
node:
terminus: exec
ROUTES
end
@app.configure_indirector_routes
expect(Puppet::Node.indirection.terminus_class).to eq('exec')
end
end
describe "when running" do
before :each do
allow(@app).to receive(:preinit)
allow(@app).to receive(:setup)
allow(@app).to receive(:parse_options)
end
it "should call preinit" do
allow(@app).to receive(:run_command)
expect(@app).to receive(:preinit)
@app.run
end
it "should call parse_options" do
allow(@app).to receive(:run_command)
expect(@app).to receive(:parse_options)
@app.run
end
it "should call run_command" do
expect(@app).to receive(:run_command)
@app.run
end
it "should call run_command" do
expect(@app).to receive(:run_command)
@app.run
end
it "should call main as the default command" do
expect(@app).to receive(:main)
@app.run
end
it "should warn and exit if no command can be called" do
expect(Puppet).to receive(:send_log).with(:err, "Could not run: No valid command or main")
expect { @app.run }.to exit_with 1
end
it "should raise an error if dispatch returns no command" do
expect(Puppet).to receive(:send_log).with(:err, "Could not run: No valid command or main")
expect { @app.run }.to exit_with 1
end
end
describe "when metaprogramming" do
describe "when calling option" do
it "should create a new method named after the option" do
@app.class.option("--test1","-t") do
end
expect(@app).to respond_to(:handle_test1)
end
it "should transpose in option name any '-' into '_'" do
@app.class.option("--test-dashes-again","-t") do
end
expect(@app).to respond_to(:handle_test_dashes_again)
end
it "should create a new method called handle_test2 with option(\"--[no-]test2\")" do
@app.class.option("--[no-]test2","-t") do
end
expect(@app).to respond_to(:handle_test2)
end
describe "when a block is passed" do
it "should create a new method with it" do
@app.class.option("--[no-]test2","-t") do
raise "I can't believe it, it works!"
end
expect { @app.handle_test2 }.to raise_error(RuntimeError, /I can't believe it, it works!/)
end
it "should declare the option to OptionParser" do
allow_any_instance_of(OptionParser).to receive(:on)
expect_any_instance_of(OptionParser).to receive(:on).with("--[no-]test3", anything)
@app.class.option("--[no-]test3","-t") do
end
@app.parse_options
end
it "should pass a block that calls our defined method" do
allow_any_instance_of(OptionParser).to receive(:on)
allow_any_instance_of(OptionParser).to receive(:on).with('--test4', '-t').and_yield(nil)
expect(@app).to receive(:send).with(:handle_test4, nil)
@app.class.option("--test4","-t") do
end
@app.parse_options
end
end
describe "when no block is given" do
it "should declare the option to OptionParser" do
allow_any_instance_of(OptionParser).to receive(:on)
expect_any_instance_of(OptionParser).to receive(:on).with("--test4", "-t")
@app.class.option("--test4","-t")
@app.parse_options
end
it "should give to OptionParser a block that adds the value to the options array" do
allow_any_instance_of(OptionParser).to receive(:on)
allow_any_instance_of(OptionParser).to receive(:on).with("--test4", "-t").and_yield(nil)
expect(@app.options).to receive(:[]=).with(:test4, nil)
@app.class.option("--test4","-t")
@app.parse_options
end
end
end
end
describe "#handle_logdest_arg" do
let(:test_arg) { "arg_test_logdest" }
it "should log an exception that is raised" do
our_exception = Puppet::DevError.new("test exception")
expect(Puppet::Util::Log).to receive(:newdestination).with(test_arg).and_raise(our_exception)
expect(Puppet).to receive(:log_and_raise).with(our_exception, anything)
@app.handle_logdest_arg(test_arg)
end
it "should exit when an exception is raised" do
our_exception = Puppet::DevError.new("test exception")
expect(Puppet::Util::Log).to receive(:newdestination).with(test_arg).and_raise(our_exception)
expect(Puppet).to receive(:log_and_raise).with(our_exception, anything).and_raise(our_exception)
expect { @app.handle_logdest_arg(test_arg) }.to raise_error(Puppet::DevError)
end
it "should set the new log destination" do
expect(Puppet::Util::Log).to receive(:newdestination).with(test_arg)
@app.handle_logdest_arg(test_arg)
end
it "should set the flag that a destination is set in the options hash" do
allow(Puppet::Util::Log).to receive(:newdestination).with(test_arg)
@app.handle_logdest_arg(test_arg)
expect(@app.options[:setdest]).to be_truthy
end
it "does not set the log destination if arg is nil" do
expect(Puppet::Util::Log).not_to receive(:newdestination)
@app.handle_logdest_arg(nil)
end
it "accepts multiple destinations as a comma sepparated list" do
dest1 = '/tmp/path1'
dest2 = 'console'
dest3 = '/tmp/path2'
dest_args = [dest1, dest2, dest3].join(' , ')
[dest1, dest2, dest3].each do |dest|
expect(Puppet::Util::Log).to receive(:newdestination).with(dest)
end
@app.handle_logdest_arg(dest_args)
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/transaction_spec.rb | spec/unit/transaction_spec.rb | require 'spec_helper'
require 'matchers/include_in_order'
require 'puppet_spec/compiler'
require 'puppet/transaction'
require 'fileutils'
describe Puppet::Transaction do
include PuppetSpec::Files
include PuppetSpec::Compiler
def catalog_with_resource(resource)
catalog = Puppet::Resource::Catalog.new
catalog.add_resource(resource)
catalog
end
def transaction_with_resource(resource)
transaction = Puppet::Transaction.new(catalog_with_resource(resource), nil, Puppet::Graph::SequentialPrioritizer.new)
transaction
end
before(:all) do
Puppet::Type.newtype(:transaction_generator) do
newparam(:name) { isnamevar }
def generate
end
end
end
after(:all) do
Puppet::Type.rmtype(:transaction_generator)
end
before do
@basepath = make_absolute("/what/ever")
@transaction = Puppet::Transaction.new(Puppet::Resource::Catalog.new, nil, Puppet::Graph::SequentialPrioritizer.new)
end
it "should be able to look resource status up by resource reference" do
resource = Puppet::Type.type(:notify).new :title => "foobar"
transaction = transaction_with_resource(resource)
transaction.evaluate
expect(transaction.resource_status(resource.to_s)).to be_changed
end
# This will basically only ever be used during testing.
it "should automatically create resource statuses if asked for a non-existent status" do
resource = Puppet::Type.type(:notify).new :title => "foobar"
transaction = transaction_with_resource(resource)
expect(transaction.resource_status(resource)).to be_instance_of(Puppet::Resource::Status)
end
it "should add provided resource statuses to its report" do
resource = Puppet::Type.type(:notify).new :title => "foobar"
transaction = transaction_with_resource(resource)
transaction.evaluate
status = transaction.resource_status(resource)
expect(transaction.report.resource_statuses[resource.to_s]).to equal(status)
end
it "should not consider there to be failed or failed_to_restart resources if no statuses are marked failed" do
resource = Puppet::Type.type(:notify).new :title => "foobar"
transaction = transaction_with_resource(resource)
transaction.evaluate
expect(transaction).not_to be_any_failed
end
it "should use the provided report object" do
report = Puppet::Transaction::Report.new
transaction = Puppet::Transaction.new(Puppet::Resource::Catalog.new, report, nil)
expect(transaction.report).to eq(report)
end
it "should create a report if none is provided" do
transaction = Puppet::Transaction.new(Puppet::Resource::Catalog.new, nil, nil)
expect(transaction.report).to be_kind_of Puppet::Transaction::Report
end
describe "when initializing" do
it "should create an event manager" do
transaction = Puppet::Transaction.new(Puppet::Resource::Catalog.new, nil, nil)
expect(transaction.event_manager).to be_instance_of(Puppet::Transaction::EventManager)
expect(transaction.event_manager.transaction).to equal(transaction)
end
it "should create a resource harness" do
transaction = Puppet::Transaction.new(Puppet::Resource::Catalog.new, nil, nil)
expect(transaction.resource_harness).to be_instance_of(Puppet::Transaction::ResourceHarness)
expect(transaction.resource_harness.transaction).to equal(transaction)
end
it "should set retrieval time on the report" do
catalog = Puppet::Resource::Catalog.new
report = Puppet::Transaction::Report.new
catalog.retrieval_duration = 5
expect(report).to receive(:add_times).with(:config_retrieval, 5)
Puppet::Transaction.new(catalog, report, nil)
end
end
describe "when evaluating a resource" do
let(:resource) { Puppet::Type.type(:file).new :path => @basepath }
it "should process events" do
transaction = transaction_with_resource(resource)
expect(transaction).to receive(:skip?).with(resource).and_return(false)
expect(transaction.event_manager).to receive(:process_events).with(resource)
transaction.evaluate
end
describe "and the resource should be skipped" do
it "should mark the resource's status as skipped" do
transaction = transaction_with_resource(resource)
expect(transaction).to receive(:skip?).with(resource).and_return(true)
transaction.evaluate
expect(transaction.resource_status(resource)).to be_skipped
end
it "does not process any scheduled events" do
transaction = transaction_with_resource(resource)
expect(transaction).to receive(:skip?).with(resource).and_return(true)
expect(transaction.event_manager).not_to receive(:process_events).with(resource)
transaction.evaluate
end
it "dequeues all events scheduled on that resource" do
transaction = transaction_with_resource(resource)
expect(transaction).to receive(:skip?).with(resource).and_return(true)
expect(transaction.event_manager).to receive(:dequeue_all_events_for_resource).with(resource)
transaction.evaluate
end
end
end
describe "when evaluating a skipped resource for corrective change it" do
before :each do
# Enable persistence during tests
allow_any_instance_of(Puppet::Transaction::Persistence).to receive(:enabled?).and_return(true)
end
it "should persist in the transactionstore" do
Puppet[:transactionstorefile] = tmpfile('persistence_test')
resource = Puppet::Type.type(:notify).new :title => "foobar"
transaction = transaction_with_resource(resource)
transaction.evaluate
expect(transaction.resource_status(resource)).to be_changed
transaction = transaction_with_resource(resource)
expect(transaction).to receive(:skip?).with(resource).and_return(true)
expect(transaction.event_manager).not_to receive(:process_events).with(resource)
transaction.evaluate
expect(transaction.resource_status(resource)).to be_skipped
persistence = Puppet::Transaction::Persistence.new
persistence.load
expect(persistence.get_system_value(resource.ref, "message")).to eq(["foobar"])
end
end
describe "when applying a resource" do
before do
@catalog = Puppet::Resource::Catalog.new
@resource = Puppet::Type.type(:file).new :path => @basepath
@catalog.add_resource(@resource)
@status = Puppet::Resource::Status.new(@resource)
@transaction = Puppet::Transaction.new(@catalog, nil, Puppet::Graph::SequentialPrioritizer.new)
allow(@transaction.event_manager).to receive(:queue_events)
end
it "should use its resource harness to apply the resource" do
expect(@transaction.resource_harness).to receive(:evaluate).with(@resource)
@transaction.evaluate
end
it "should add the resulting resource status to its status list" do
allow(@transaction.resource_harness).to receive(:evaluate).and_return(@status)
@transaction.evaluate
expect(@transaction.resource_status(@resource)).to be_instance_of(Puppet::Resource::Status)
end
it "should queue any events added to the resource status" do
allow(@transaction.resource_harness).to receive(:evaluate).and_return(@status)
expect(@status).to receive(:events).and_return(%w{a b})
expect(@transaction.event_manager).to receive(:queue_events).with(@resource, ["a", "b"])
@transaction.evaluate
end
it "should log and skip any resources that cannot be applied" do
expect(@resource).to receive(:properties).and_raise(ArgumentError)
@transaction.evaluate
expect(@transaction.report.resource_statuses[@resource.to_s]).to be_failed
end
it "should report any_failed if any resources failed" do
expect(@resource).to receive(:properties).and_raise(ArgumentError)
@transaction.evaluate
expect(@transaction).to be_any_failed
end
it "should report any_failed if any resources failed to restart" do
@transaction.evaluate
@transaction.report.resource_statuses[@resource.to_s].failed_to_restart = true
expect(@transaction).to be_any_failed
end
end
describe "#unblock" do
let(:graph) { @transaction.relationship_graph }
let(:resource) { Puppet::Type.type(:notify).new(:name => 'foo') }
it "should calculate the number of blockers if it's not known" do
graph.add_vertex(resource)
3.times do |i|
other = Puppet::Type.type(:notify).new(:name => i.to_s)
graph.add_vertex(other)
graph.add_edge(other, resource)
end
graph.unblock(resource)
expect(graph.blockers[resource]).to eq(2)
end
it "should decrement the number of blockers if there are any" do
graph.blockers[resource] = 40
graph.unblock(resource)
expect(graph.blockers[resource]).to eq(39)
end
it "should warn if there are no blockers" do
vertex = double('vertex')
expect(vertex).to receive(:warning).with("appears to have a negative number of dependencies")
graph.blockers[vertex] = 0
graph.unblock(vertex)
end
it "should return true if the resource is now unblocked" do
graph.blockers[resource] = 1
expect(graph.unblock(resource)).to eq(true)
end
it "should return false if the resource is still blocked" do
graph.blockers[resource] = 2
expect(graph.unblock(resource)).to eq(false)
end
end
describe "when traversing" do
let(:path) { tmpdir('eval_generate') }
let(:resource) { Puppet::Type.type(:file).new(:path => path, :recurse => true) }
before :each do
@transaction.catalog.add_resource(resource)
end
it "should yield the resource even if eval_generate is called" do
expect_any_instance_of(Puppet::Transaction::AdditionalResourceGenerator).to receive(:eval_generate).with(resource).and_return(true)
yielded = false
@transaction.evaluate do |res|
yielded = true if res == resource
end
expect(yielded).to eq(true)
end
it "should prefetch the provider if necessary" do
expect(@transaction).to receive(:prefetch_if_necessary).with(resource)
@transaction.evaluate {}
end
it "traverses independent resources before dependent resources" do
dependent = Puppet::Type.type(:notify).new(:name => "hello", :require => resource)
@transaction.catalog.add_resource(dependent)
seen = []
@transaction.evaluate do |res|
seen << res
end
expect(seen).to include_in_order(resource, dependent)
end
it "traverses completely independent resources in the order they appear in the catalog" do
independent = Puppet::Type.type(:notify).new(:name => "hello", :require => resource)
@transaction.catalog.add_resource(independent)
seen = []
@transaction.evaluate do |res|
seen << res
end
expect(seen).to include_in_order(resource, independent)
end
it "should fail unsuitable resources and go on if it gets blocked" do
dependent = Puppet::Type.type(:notify).new(:name => "hello", :require => resource)
@transaction.catalog.add_resource(dependent)
allow(resource).to receive(:suitable?).and_return(false)
evaluated = []
@transaction.evaluate do |res|
evaluated << res
end
# We should have gone on to evaluate the children
expect(evaluated).to eq([dependent])
expect(@transaction.resource_status(resource)).to be_failed
end
end
describe "when generating resources before traversal" do
let(:catalog) { Puppet::Resource::Catalog.new }
let(:transaction) { Puppet::Transaction.new(catalog, nil, Puppet::Graph::SequentialPrioritizer.new) }
let(:generator) { Puppet::Type.type(:transaction_generator).new :title => "generator" }
let(:generated) do
%w[a b c].map { |name| Puppet::Type.type(:transaction_generator).new(:name => name) }
end
before :each do
catalog.add_resource generator
allow(generator).to receive(:generate).and_return(generated)
# avoid crude failures because of nil resources that result
# from implicit containment and lacking containers
allow(catalog).to receive(:container_of).and_return(generator)
end
it "should call 'generate' on all created resources" do
generated.each { |res| expect(res).to receive(:generate) }
transaction.evaluate
end
it "should finish all resources" do
generated.each { |res| expect(res).to receive(:finish) }
transaction.evaluate
end
it "should copy all tags to the newly generated resources" do
generator.tag('one', 'two')
transaction.evaluate
generated.each do |res|
expect(res).to be_tagged(*generator.tags)
end
end
end
describe "after resource traversal" do
let(:catalog) { Puppet::Resource::Catalog.new }
let(:prioritizer) { Puppet::Graph::SequentialPrioritizer.new }
let(:report) { Puppet::Transaction::Report.new }
let(:transaction) { Puppet::Transaction.new(catalog, report, prioritizer) }
let(:generator) { Puppet::Transaction::AdditionalResourceGenerator.new(catalog, nil, prioritizer) }
before :each do
generator = Puppet::Transaction::AdditionalResourceGenerator.new(catalog, nil, prioritizer)
allow(Puppet::Transaction::AdditionalResourceGenerator).to receive(:new).and_return(generator)
end
it "should should query the generator for whether resources failed to generate" do
relationship_graph = Puppet::Graph::RelationshipGraph.new(prioritizer)
allow(catalog).to receive(:relationship_graph).and_return(relationship_graph)
expect(relationship_graph).to receive(:traverse).ordered
expect(generator).to receive(:resources_failed_to_generate).ordered
transaction.evaluate
end
it "should report that resources failed to generate" do
expect(generator).to receive(:resources_failed_to_generate).and_return(true)
expect(report).to receive(:resources_failed_to_generate=).with(true)
transaction.evaluate
end
it "should not report that resources failed to generate if none did" do
expect(generator).to receive(:resources_failed_to_generate).and_return(false)
expect(report).not_to receive(:resources_failed_to_generate=)
transaction.evaluate
end
end
describe "when performing pre-run checks" do
let(:resource) { Puppet::Type.type(:notify).new(:title => "spec") }
let(:transaction) { transaction_with_resource(resource) }
let(:spec_exception) { 'spec-exception' }
it "should invoke each resource's hook and apply the catalog after no failures" do
expect(resource).to receive(:pre_run_check)
transaction.evaluate
end
it "should abort the transaction on failure" do
expect(resource).to receive(:pre_run_check).and_raise(Puppet::Error, spec_exception)
expect { transaction.evaluate }.to raise_error(Puppet::Error, /Some pre-run checks failed/)
end
it "should log the resource-specific exception" do
expect(resource).to receive(:pre_run_check).and_raise(Puppet::Error, spec_exception)
expect(resource).to receive(:log_exception).with(have_attributes(message: match(/#{spec_exception}/)))
expect { transaction.evaluate }.to raise_error(Puppet::Error)
end
end
describe "when skipping a resource" do
before :each do
@resource = Puppet::Type.type(:notify).new :name => "foo"
@catalog = Puppet::Resource::Catalog.new
@resource.catalog = @catalog
@transaction = Puppet::Transaction.new(@catalog, nil, nil)
end
it "should skip resource with missing tags" do
allow(@transaction).to receive(:missing_tags?).and_return(true)
expect(@transaction).to be_skip(@resource)
end
it "should skip resources tagged with the skip tags" do
allow(@transaction).to receive(:skip_tags?).and_return(true)
expect(@transaction).to be_skip(@resource)
end
it "should skip unscheduled resources" do
allow(@transaction).to receive(:scheduled?).and_return(false)
expect(@transaction).to be_skip(@resource)
end
it "should skip resources with failed dependencies" do
allow(@transaction).to receive(:failed_dependencies?).and_return(true)
expect(@transaction).to be_skip(@resource)
end
it "should skip virtual resource" do
allow(@resource).to receive(:virtual?).and_return(true)
expect(@transaction).to be_skip(@resource)
end
it "should skip device only resouce on normal host" do
allow(@resource).to receive(:appliable_to_host?).and_return(false)
allow(@resource).to receive(:appliable_to_device?).and_return(true)
@transaction.for_network_device = false
expect(@transaction).to be_skip(@resource)
end
it "should not skip device only resouce on remote device" do
allow(@resource).to receive(:appliable_to_host?).and_return(false)
allow(@resource).to receive(:appliable_to_device?).and_return(true)
@transaction.for_network_device = true
expect(@transaction).not_to be_skip(@resource)
end
it "should skip host resouce on device" do
allow(@resource).to receive(:appliable_to_host?).and_return(true)
allow(@resource).to receive(:appliable_to_device?).and_return(false)
@transaction.for_network_device = true
expect(@transaction).to be_skip(@resource)
end
it "should not skip resouce available on both device and host when on device" do
allow(@resource).to receive(:appliable_to_host?).and_return(true)
allow(@resource).to receive(:appliable_to_device?).and_return(true)
@transaction.for_network_device = true
expect(@transaction).not_to be_skip(@resource)
end
it "should not skip resouce available on both device and host when on host" do
allow(@resource).to receive(:appliable_to_host?).and_return(true)
allow(@resource).to receive(:appliable_to_device?).and_return(true)
@transaction.for_network_device = false
expect(@transaction).not_to be_skip(@resource)
end
end
describe "when determining if tags are missing" do
before :each do
@resource = Puppet::Type.type(:notify).new :name => "foo"
@catalog = Puppet::Resource::Catalog.new
@resource.catalog = @catalog
@transaction = Puppet::Transaction.new(@catalog, nil, nil)
allow(@transaction).to receive(:ignore_tags?).and_return(false)
end
it "should not be missing tags if tags are being ignored" do
expect(@transaction).to receive(:ignore_tags?).and_return(true)
expect(@resource).not_to receive(:tagged?)
expect(@transaction).not_to be_missing_tags(@resource)
end
it "should not be missing tags if the transaction tags are empty" do
@transaction.tags = []
expect(@resource).not_to receive(:tagged?)
expect(@transaction).not_to be_missing_tags(@resource)
end
it "should otherwise let the resource determine if it is missing tags" do
tags = ['one', 'two']
@transaction.tags = tags
expect(@transaction).to be_missing_tags(@resource)
end
end
describe "when determining if a resource should be scheduled" do
before :each do
@resource = Puppet::Type.type(:notify).new :name => "foo"
@catalog = Puppet::Resource::Catalog.new
@catalog.add_resource(@resource)
@transaction = Puppet::Transaction.new(@catalog, nil, Puppet::Graph::SequentialPrioritizer.new)
end
it "should always schedule resources if 'ignoreschedules' is set" do
@transaction.ignoreschedules = true
expect(@transaction.resource_harness).not_to receive(:scheduled?)
@transaction.evaluate
expect(@transaction.resource_status(@resource)).to be_changed
end
it "should let the resource harness determine whether the resource should be scheduled" do
expect(@transaction.resource_harness).to receive(:scheduled?).with(@resource).and_return("feh")
@transaction.evaluate
end
end
describe "when prefetching" do
let(:catalog) { Puppet::Resource::Catalog.new }
let(:transaction) { Puppet::Transaction.new(catalog, nil, nil) }
let(:resource) { Puppet::Type.type(:package).new :title => "foo", :name => "bar", :provider => :pkgng }
let(:resource2) { Puppet::Type.type(:package).new :title => "blah", :provider => :apt }
before :each do
allow(resource).to receive(:suitable?).and_return(true)
catalog.add_resource resource
catalog.add_resource resource2
end
it "should match resources by name, not title" do
expect(resource.provider.class).to receive(:prefetch).with({"bar" => resource})
transaction.prefetch_if_necessary(resource)
end
it "should not prefetch a provider which has already been prefetched" do
transaction.prefetched_providers[:package][:pkgng] = true
expect(resource.provider.class).not_to receive(:prefetch)
transaction.prefetch_if_necessary(resource)
end
it "should mark the provider prefetched" do
allow(resource.provider.class).to receive(:prefetch)
transaction.prefetch_if_necessary(resource)
expect(transaction.prefetched_providers[:package][:pkgng]).to be_truthy
end
it "should prefetch resources without a provider if prefetching the default provider" do
other = Puppet::Type.type(:package).new :name => "other"
other.instance_variable_set(:@provider, nil)
catalog.add_resource other
allow(resource.class).to receive(:defaultprovider).and_return(resource.provider.class)
expect(resource.provider.class).to receive(:prefetch).with({'bar' => resource, 'other' => other})
transaction.prefetch_if_necessary(resource)
end
it "should not prefetch a provider which has failed" do
transaction.prefetch_failed_providers[:package][:pkgng] = true
expect(resource.provider.class).not_to receive(:prefetch)
transaction.prefetch_if_necessary(resource)
end
it "should not rescue SystemExit" do
expect(resource.provider.class).to receive(:prefetch).and_raise(SystemExit, "SystemMessage")
expect { transaction.prefetch_if_necessary(resource) }.to raise_error(SystemExit, "SystemMessage")
end
it "should mark resources as failed when prefetching raises LoadError" do
expect(resource.provider.class).to receive(:prefetch).and_raise(LoadError, "LoadMessage")
transaction.prefetch_if_necessary(resource)
expect(transaction.prefetched_providers[:package][:pkgng]).to be_truthy
end
describe "and prefetching raises Puppet::Error" do
before :each do
expect(resource.provider.class).to receive(:prefetch).and_raise(Puppet::Error, "message")
end
it "should rescue prefetch executions" do
transaction.prefetch_if_necessary(resource)
expect(transaction.prefetched_providers[:package][:pkgng]).to be_truthy
end
it "should mark resources as failed", :unless => RUBY_PLATFORM == 'java' do
transaction.evaluate
expect(transaction.resource_status(resource).failed?).to be_truthy
end
it "should mark a provider that has failed prefetch" do
transaction.prefetch_if_necessary(resource)
expect(transaction.prefetch_failed_providers[:package][:pkgng]).to be_truthy
end
describe "and new resources are generated" do
let(:generator) { Puppet::Type.type(:transaction_generator).new :title => "generator" }
let(:generated) do
%w[a b c].map { |name| Puppet::Type.type(:package).new :title => "foo", :name => name, :provider => :apt }
end
before :each do
catalog.add_resource generator
allow(generator).to receive(:generate).and_return(generated)
allow(catalog).to receive(:container_of).and_return(generator)
end
it "should not evaluate resources with a failed provider, even if the prefetch is rescued" do
#Only the generator resource should be applied, all the other resources are failed, and skipped.
catalog.remove_resource resource2
expect(transaction).to receive(:apply).once
transaction.evaluate
end
it "should not fail other resources added after the failing resource", :unless => RUBY_PLATFORM == 'java' do
new_resource = Puppet::Type.type(:notify).new :name => "baz"
catalog.add_resource(new_resource)
transaction.evaluate
expect(transaction.resource_status(new_resource).failed?).to be_falsey
end
it "should fail other resources that require the failing resource" do
new_resource = Puppet::Type.type(:notify).new(:name => "baz", :require => resource)
catalog.add_resource(new_resource)
catalog.remove_resource resource2
expect(transaction).to receive(:apply).once
transaction.evaluate
expect(transaction.resource_status(resource).failed?).to be_truthy
expect(transaction.resource_status(new_resource).dependency_failed?).to be_truthy
expect(transaction.skip?(new_resource)).to be_truthy
end
end
end
end
describe "during teardown" do
let(:catalog) { Puppet::Resource::Catalog.new }
let(:transaction) do
Puppet::Transaction.new(catalog, nil, Puppet::Graph::SequentialPrioritizer.new)
end
let(:teardown_type) do
Puppet::Type.newtype(:teardown_test) do
newparam(:name) {}
end
end
before :each do
teardown_type.provide(:teardown_provider) do
class << self
attr_reader :result
def post_resource_eval
@result = 'passed'
end
end
end
end
it "should call ::post_resource_eval on provider classes that support it" do
resource = teardown_type.new(:title => "foo", :provider => :teardown_provider)
transaction = transaction_with_resource(resource)
transaction.evaluate
expect(resource.provider.class.result).to eq('passed')
end
it "should call ::post_resource_eval even if other providers' ::post_resource_eval fails" do
teardown_type.provide(:always_fails) do
class << self
attr_reader :result
def post_resource_eval
@result = 'failed'
raise Puppet::Error, "This provider always fails"
end
end
end
good_resource = teardown_type.new(:title => "bloo", :provider => :teardown_provider)
bad_resource = teardown_type.new(:title => "blob", :provider => :always_fails)
catalog.add_resource(bad_resource)
catalog.add_resource(good_resource)
transaction.evaluate
expect(good_resource.provider.class.result).to eq('passed')
expect(bad_resource.provider.class.result).to eq('failed')
end
it "should call ::post_resource_eval even if one of the resources fails" do
resource = teardown_type.new(:title => "foo", :provider => :teardown_provider)
allow(resource).to receive(:retrieve_resource).and_raise
catalog.add_resource resource
expect(resource.provider.class).to receive(:post_resource_eval)
transaction.evaluate
end
it "should call Selinux.selabel_close in case Selinux is enabled", :if => Puppet.features.posix? do
handle = double('selinux_handle')
selinux = class_double('selinux', is_selinux_enabled: 1, selabel_close: nil, selabel_open: handle, selabel_lookup: -1)
stub_const('Selinux', selinux)
stub_const('Selinux::SELABEL_CTX_FILE', 0)
resource = Puppet::Type.type(:file).new(:path => make_absolute("/tmp/foo"))
transaction = transaction_with_resource(resource)
expect(Selinux).to receive(:selabel_close).with(handle)
transaction.evaluate
end
end
describe 'when checking application run state' do
before do
@catalog = Puppet::Resource::Catalog.new
@transaction = Puppet::Transaction.new(@catalog, nil, Puppet::Graph::SequentialPrioritizer.new)
end
context "when stop is requested" do
before :each do
allow(Puppet::Application).to receive(:stop_requested?).and_return(true)
end
it 'should return true for :stop_processing?' do
expect(@transaction).to be_stop_processing
end
it 'always evaluates non-host_config catalogs' do
@catalog.host_config = false
expect(@transaction).not_to be_stop_processing
end
end
it 'should return false for :stop_processing? if Puppet::Application.stop_requested? is false' do
allow(Puppet::Application).to receive(:stop_requested?).and_return(false)
expect(@transaction.stop_processing?).to be_falsey
end
describe 'within an evaluate call' do
before do
@resource = Puppet::Type.type(:notify).new :title => "foobar"
@catalog.add_resource @resource
end
it 'should stop processing if :stop_processing? is true' do
allow(@transaction).to receive(:stop_processing?).and_return(true)
expect(@transaction).not_to receive(:eval_resource)
@transaction.evaluate
end
it 'should continue processing if :stop_processing? is false' do
allow(@transaction).to receive(:stop_processing?).and_return(false)
expect(@transaction).to receive(:eval_resource).and_return(nil)
@transaction.evaluate
end
end
end
it "errors with a dependency cycle for a resource that requires itself" do
expect(Puppet).to receive(:err).with(/Found 1 dependency cycle:.*\(Notify\[cycle\] => Notify\[cycle\]\)/m)
expect do
apply_compiled_manifest(<<-MANIFEST)
notify { cycle: require => Notify[cycle] }
MANIFEST
end.to raise_error(Puppet::Error, 'One or more resource dependency cycles detected in graph')
end
it "errors with a dependency cycle for a self-requiring resource also required by another resource" do
expect(Puppet).to receive(:err).with(/Found 1 dependency cycle:.*\(Notify\[cycle\] => Notify\[cycle\]\)/m)
expect do
apply_compiled_manifest(<<-MANIFEST)
notify { cycle: require => Notify[cycle] }
notify { other: require => Notify[cycle] }
MANIFEST
end.to raise_error(Puppet::Error, 'One or more resource dependency cycles detected in graph')
end
it "errors with a dependency cycle for a resource that requires itself and another resource" do
expect(Puppet).to receive(:err).with(/Found 1 dependency cycle:.*\(Notify\[cycle\] => Notify\[cycle\]\)/m)
expect do
apply_compiled_manifest(<<-MANIFEST)
notify { cycle:
require => [Notify[other], Notify[cycle]]
}
notify { other: }
MANIFEST
end.to raise_error(Puppet::Error, 'One or more resource dependency cycles detected in graph')
end
it "errors with a dependency cycle for a resource that is later modified to require itself" do
expect(Puppet).to receive(:err).with(/Found 1 dependency cycle:.*\(Notify\[cycle\] => Notify\[cycle\]\)/m)
expect do
apply_compiled_manifest(<<-MANIFEST)
notify { cycle: }
Notify <| title == 'cycle' |> {
require => Notify[cycle]
}
MANIFEST
end.to raise_error(Puppet::Error, 'One or more resource dependency cycles detected in graph')
end
context "when generating a report for a transaction with a dependency cycle" do
let(:catalog) do
compile_to_ral(<<-MANIFEST)
notify { foo: require => Notify[bar] }
notify { bar: require => Notify[foo] }
MANIFEST
end
let(:prioritizer) { Puppet::Graph::SequentialPrioritizer.new }
let(:transaction) { Puppet::Transaction.new(catalog,
Puppet::Transaction::Report.new("apply"),
prioritizer) }
before(:each) do
expect { transaction.evaluate }.to raise_error(Puppet::Error)
transaction.report.finalize_report
end
it "should report resources involved in a dependency cycle as failed" do
expect(transaction.report.resource_statuses['Notify[foo]']).to be_failed
expect(transaction.report.resource_statuses['Notify[bar]']).to be_failed
end
it "should generate a failure event for a resource in a dependency cycle" do
status = transaction.report.resource_statuses['Notify[foo]']
expect(status.events.first.status).to eq('failure')
expect(status.events.first.message).to eq('resource is part of a dependency cycle')
end
it "should report that the transaction is failed" do
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | true |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/defaults_spec.rb | spec/unit/defaults_spec.rb | require 'spec_helper'
require 'puppet/settings'
describe "Defaults" do
describe ".default_diffargs" do
it "should be '-u'" do
expect(Puppet.default_diffargs).to eq("-u")
end
end
describe 'strict' do
it 'should accept the valid value :off' do
expect {Puppet.settings[:strict] = 'off'}.to_not raise_exception
end
it 'should accept the valid value :warning' do
expect {Puppet.settings[:strict] = 'warning'}.to_not raise_exception
end
it 'should accept the valid value :error' do
expect {Puppet.settings[:strict] = 'error'}.to_not raise_exception
end
it 'should fail if given an invalid value' do
expect {Puppet.settings[:strict] = 'ignore'}.to raise_exception(/Invalid value 'ignore' for parameter strict\./)
end
end
describe '.default_digest_algorithm' do
it 'defaults to sha256 when FIPS is not enabled' do
allow(Puppet::Util::Platform).to receive(:fips_enabled?).and_return(false)
expect(Puppet.default_digest_algorithm).to eq('sha256')
end
it 'defaults to sha256 when FIPS is enabled' do
allow(Puppet::Util::Platform).to receive(:fips_enabled?).and_return(true)
expect(Puppet.default_digest_algorithm).to eq('sha256')
end
end
describe '.supported_checksum_types' do
it 'defaults to sha256, sha384, sha512, sha224, md5 when FIPS is not enabled' do
allow(Puppet::Util::Platform).to receive(:fips_enabled?).and_return(false)
expect(Puppet.default_file_checksum_types).to eq(%w[sha256 sha384 sha512 sha224 md5])
end
it 'defaults to sha256, sha384, sha512, sha224 when FIPS is enabled' do
allow(Puppet::Util::Platform).to receive(:fips_enabled?).and_return(true)
expect(Puppet.default_file_checksum_types).to eq(%w[sha256 sha384 sha512 sha224])
end
end
describe 'Puppet[:supported_checksum_types]' do
it 'defaults to sha256, sha512, sha384, sha224, md5' do
expect(Puppet.settings[:supported_checksum_types]).to eq(%w[sha256 sha384 sha512 sha224 md5])
end
it 'should raise an error on an unsupported checksum type' do
expect {
Puppet.settings[:supported_checksum_types] = %w[md5 foo]
}.to raise_exception ArgumentError,
/Invalid value 'foo' for parameter supported_checksum_types. Allowed values are/
end
it 'should not raise an error on setting a valid list of checksum types' do
Puppet.settings[:supported_checksum_types] = %w[sha256 md5lite mtime]
expect(Puppet.settings[:supported_checksum_types]).to eq(%w[sha256 md5lite mtime])
end
it 'raises when setting md5 in FIPS mode' do
allow(Puppet::Util::Platform).to receive(:fips_enabled?).and_return(true)
expect {
Puppet.settings[:supported_checksum_types] = %w[md5]
}.to raise_error(ArgumentError,
/Invalid value 'md5' for parameter supported_checksum_types. Allowed values are 'sha256'/)
end
end
describe 'manage_internal_file_permissions' do
describe 'on windows', :if => Puppet::Util::Platform.windows? do
it 'should default to false' do
expect(Puppet.settings[:manage_internal_file_permissions]).to be false
end
end
describe 'on non-windows', :if => ! Puppet::Util::Platform.windows? do
it 'should default to true' do
expect(Puppet.settings[:manage_internal_file_permissions]).to be true
end
end
end
describe 'basemodulepath' do
it 'includes the user and system modules', :unless => Puppet::Util::Platform.windows? do
expect(
Puppet[:basemodulepath]
).to match(%r{.*/code/modules:/opt/puppetlabs/puppet/modules$})
end
describe 'on windows', :if => Puppet::Util::Platform.windows? do
let(:installdir) { 'C:\Program Files\Puppet Labs\Puppet' }
it 'includes user and system modules' do
allow(ENV).to receive(:fetch).with("FACTER_env_windows_installdir", anything).and_return(installdir)
expect(
Puppet.default_basemodulepath
).to eq('$codedir/modules;C:\Program Files\Puppet Labs\Puppet/puppet/modules')
end
it 'includes user modules if installdir fact is missing' do
allow(ENV).to receive(:[]).with("FACTER_env_windows_installdir").and_return(nil)
expect(
Puppet.default_basemodulepath
).to eq('$codedir/modules')
end
end
end
describe 'vendormoduledir' do
it 'includes the default vendormoduledir', :unless => Puppet::Util::Platform.windows? do
expect(
Puppet[:vendormoduledir]
).to eq('/opt/puppetlabs/puppet/vendor_modules')
end
describe 'on windows', :if => Puppet::Util::Platform.windows? do
let(:installdir) { 'C:\Program Files\Puppet Labs\Puppet' }
it 'includes the default vendormoduledir' do
allow(ENV).to receive(:fetch).with("FACTER_env_windows_installdir", anything).and_return(installdir)
expect(
Puppet.default_vendormoduledir
).to eq('C:\Program Files\Puppet Labs\Puppet\puppet\vendor_modules')
end
it 'is nil if installdir fact is missing' do
allow(ENV).to receive(:[]).with("FACTER_env_windows_installdir").and_return(nil)
expect(Puppet.default_vendormoduledir).to be_nil
end
end
end
describe "deprecated settings" do
it 'does not issue a deprecation warning by default' do
expect(Puppet).to receive(:deprecation_warning).never
Puppet.initialize_settings
end
end
describe "the default cadir", :unless => Puppet::Util::Platform.windows? do
it 'defaults to the puppetserver confdir when no cadir is found' do
Puppet.initialize_settings
expect(Puppet[:cadir]).to eq('/etc/puppetlabs/puppetserver/ca')
end
it 'returns an empty string for Windows platforms', :if => Puppet::Util::Platform.windows? do
Puppet.initialize_settings
expect(Puppet[:cadir]).to eq("")
end
end
describe '#default_cadir', :unless => Puppet::Util::Platform.windows? do
it 'warns when a CA dir exists in the current ssldir' do
cadir = File.join(Puppet[:ssldir], 'ca')
FileUtils.mkdir_p(cadir)
expect(Puppet.default_cadir).to eq(cadir)
end
end
describe "#preferred_serialization_format" do
it 'raises if PSON is not available', unless: Puppet.features.pson? do
expect {
Puppet.settings[:preferred_serialization_format] = "pson"
}.to raise_error(Puppet::Settings::ValidationError, "The 'puppet-pson' gem must be installed to use the PSON serialization format.")
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/puppet_pal_spec.rb | spec/unit/puppet_pal_spec.rb | require 'spec_helper'
require 'puppet_spec/files'
require_relative 'puppet_pal_2pec'
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/datatypes_spec.rb | spec/unit/datatypes_spec.rb | require 'spec_helper'
require 'puppet_spec/compiler'
require 'puppet_spec/files'
require 'puppet/pops'
module PuppetSpec::DataTypes
describe "Puppet::DataTypes" do
include PuppetSpec::Compiler
include PuppetSpec::Files
let(:modules) { { 'mytest' => mytest } }
let(:datatypes) { {} }
let(:environments_dir) { Puppet[:environmentpath] }
let(:mytest) {{
'lib' => {
'puppet' => {
'datatypes' => mytest_datatypes,
'functions' => mytest_functions },
'puppetx' => { 'mytest' => mytest_classes },
}
}}
let(:mytest_datatypes) { {} }
let(:mytest_classes) { {} }
let(:mytest_functions) { {
'mytest' => {
'to_data.rb' => <<-RUBY.unindent,
Puppet::Functions.create_function('mytest::to_data') do
def to_data(data)
Puppet::Pops::Serialization::ToDataConverter.convert(data, {
:rich_data => true,
:symbol_as_string => true,
:type_by_reference => true,
:message_prefix => 'test'
})
end
end
RUBY
'from_data.rb' => <<-RUBY.unindent,
Puppet::Functions.create_function('mytest::from_data') do
def from_data(data)
Puppet::Pops::Serialization::FromDataConverter.convert(data)
end
end
RUBY
'serialize.rb' => <<-RUBY.unindent,
Puppet::Functions.create_function('mytest::serialize') do
def serialize(data)
buffer = ''
serializer = Puppet::Pops::Serialization::Serializer.new(
Puppet::Pops::Serialization::JSON::Writer.new(buffer))
serializer.write(data)
serializer.finish
buffer
end
end
RUBY
'deserialize.rb' => <<-RUBY.unindent,
Puppet::Functions.create_function('mytest::deserialize') do
def deserialize(data)
deserializer = Puppet::Pops::Serialization::Deserializer.new(
Puppet::Pops::Serialization::JSON::Reader.new(data), Puppet::Pops::Loaders.find_loader(nil))
deserializer.read
end
end
RUBY
}
} }
let(:testing_env_dir) do
dir_contained_in(environments_dir, testing_env)
env_dir = File.join(environments_dir, 'testing')
PuppetSpec::Files.record_tmp(env_dir)
env_dir
end
let(:modules_dir) { File.join(testing_env_dir, 'modules') }
let(:env) { Puppet::Node::Environment.create(:testing, [modules_dir]) }
let(:node) { Puppet::Node.new('test', :environment => env) }
let(:testing_env) do
{
'testing' => {
'lib' => { 'puppet' => { 'datatypes' => datatypes } },
'modules' => modules,
}
}
end
before(:each) do
Puppet[:environment] = 'testing'
end
context 'when creating type with derived attributes using implementation' do
let(:datatypes) {
{
'mytype.rb' => <<-RUBY.unindent,
Puppet::DataTypes.create_type('Mytype') do
interface <<-PUPPET
attributes => {
name => { type => String },
year_of_birth => { type => Integer },
age => { type => Integer, kind => derived },
}
PUPPET
implementation do
def age
DateTime.now.year - @year_of_birth
end
end
end
RUBY
}
}
it 'loads and returns value of attribute' do
expect(eval_and_collect_notices('notice(Mytype("Bob", 1984).age)', node)).to eql(["#{DateTime.now.year - 1984}"])
end
it 'can convert value to and from data' do
expect(eval_and_collect_notices(<<-PUPPET.unindent, node)).to eql(['false', 'true', 'true', "#{DateTime.now.year - 1984}"])
$m = Mytype("Bob", 1984)
$d = $m.mytest::to_data
notice($m == $d)
notice($d =~ Data)
$m2 = $d.mytest::from_data
notice($m == $m2)
notice($m2.age)
PUPPET
end
end
context 'when creating type for an already implemented class' do
let(:datatypes) {
{
'mytest.rb' => <<-RUBY.unindent,
Puppet::DataTypes.create_type('Mytest') do
interface <<-PUPPET
attributes => {
name => { type => String },
year_of_birth => { type => Integer },
age => { type => Integer, kind => derived },
},
functions => {
'[]' => Callable[[String[1]], Variant[String, Integer]]
}
PUPPET
implementation_class PuppetSpec::DataTypes::MyTest
end
RUBY
}
}
before(:each) do
class ::PuppetSpec::DataTypes::MyTest
attr_reader :name, :year_of_birth
def initialize(name, year_of_birth)
@name = name
@year_of_birth = year_of_birth
end
def age
DateTime.now.year - @year_of_birth
end
def [](key)
case key
when 'name'
@name
when 'year_of_birth'
@year_of_birth
when 'age'
age
else
nil
end
end
def ==(o)
self.class == o.class && @name == o.name && @year_of_birth == o.year_of_birth
end
end
end
after(:each) do
::PuppetSpec::DataTypes.send(:remove_const, :MyTest)
end
it 'loads and returns value of attribute' do
expect(eval_and_collect_notices('notice(Mytest("Bob", 1984).age)', node)).to eql(["#{DateTime.now.year - 1984}"])
end
it 'can convert value to and from data' do
expect(eval_and_collect_notices(<<-PUPPET.unindent, node)).to eql(['true', 'true', "#{DateTime.now.year - 1984}"])
$m = Mytest("Bob", 1984)
$d = $m.mytest::to_data
notice($d =~ Data)
$m2 = $d.mytest::from_data
notice($m == $m2)
notice($m2.age)
PUPPET
end
it 'can access using implemented [] method' do
expect(eval_and_collect_notices(<<-PUPPET.unindent, node)).to eql(['Bob', "#{DateTime.now.year - 1984}"])
$m = Mytest("Bob", 1984)
notice($m['name'])
notice($m['age'])
PUPPET
end
it 'can serialize and deserialize data' do
expect(eval_and_collect_notices(<<-PUPPET.unindent, node)).to eql(['true', 'true', "#{DateTime.now.year - 1984}"])
$m = Mytest("Bob", 1984)
$d = $m.mytest::serialize
notice($d =~ String)
$m2 = $d.mytest::deserialize
notice($m == $m2)
notice($m2.age)
PUPPET
end
end
context 'when creating type with custom new_function' do
let(:datatypes) {
{
'mytest.rb' => <<-RUBY.unindent,
Puppet::DataTypes.create_type('Mytest') do
interface <<-PUPPET
attributes => {
strings => { type => Array[String] },
ints => { type => Array[Integer] },
}
PUPPET
implementation_class PuppetSpec::DataTypes::MyTest
end
RUBY
}
}
before(:each) do
class ::PuppetSpec::DataTypes::MyTest
def self.create_new_function(t)
Puppet::Functions.create_function('new_%s' % t.name) do
dispatch :create do
repeated_param 'Variant[String,Integer]', :args
end
def create(*args)
::PuppetSpec::DataTypes::MyTest.new(*args.partition { |arg| arg.is_a?(String) })
end
end
end
attr_reader :strings, :ints
def initialize(strings, ints)
@strings = strings
@ints = ints
end
end
end
after(:each) do
::PuppetSpec::DataTypes.send(:remove_const, :MyTest)
end
it 'loads and calls custom new function' do
expect(eval_and_collect_notices('notice(Mytest("A", 32, "B", 20).ints)', node)).to eql(['[32, 20]'])
end
end
context 'with data type and class defined in a module' do
let(:mytest_classes) {
{
'position.rb' => <<-RUBY
module PuppetX; module Mytest; class Position
attr_reader :x, :y
def initialize(x, y)
@x = x
@y = y
end
end; end; end
RUBY
}
}
after(:each) do
::PuppetX.send(:remove_const, :Mytest)
end
context 'in module namespace' do
let(:mytest_datatypes) {
{
'mytest' => { 'position.rb' => <<-RUBY
Puppet::DataTypes.create_type('Mytest::Position') do
interface <<-PUPPET
attributes => {
x => Integer,
y => Integer
}
PUPPET
load_file('puppetx/mytest/position')
implementation_class PuppetX::Mytest::Position
end
RUBY
}
}
}
it 'loads and returns value of attribute' do
expect(eval_and_collect_notices('notice(Mytest::Position(23, 12).x)', node)).to eql(['23'])
end
end
context 'in top namespace' do
let(:mytest_datatypes) {
{
'position.rb' => <<-RUBY
Puppet::DataTypes.create_type('Position') do
interface <<-PUPPET
attributes => {
x => Integer,
y => Integer
}
PUPPET
load_file('puppetx/mytest/position')
implementation_class PuppetX::Mytest::Position
end
RUBY
}
}
it 'loads and returns value of attribute' do
expect(eval_and_collect_notices('notice(Position(23, 12).x)', node)).to eql(['23'])
end
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/parameter_spec.rb | spec/unit/parameter_spec.rb | require 'spec_helper'
require 'puppet/parameter'
describe Puppet::Parameter do
before do
@class = Class.new(Puppet::Parameter) do
@name = :foo
end
@class.initvars
@resource = double('resource')
allow(@resource).to receive(:expects)
allow(@resource).to receive(:pathbuilder)
@parameter = @class.new :resource => @resource
end
it "should create a value collection" do
@class = Class.new(Puppet::Parameter)
expect(@class.value_collection).to be_nil
@class.initvars
expect(@class.value_collection).to be_instance_of(Puppet::Parameter::ValueCollection)
end
it "should return its name as a string when converted to a string" do
expect(@parameter.to_s).to eq(@parameter.name.to_s)
end
[:line, :file, :version].each do |data|
it "should return its resource's #{data} as its #{data}" do
expect(@resource).to receive(data).and_return("foo")
expect(@parameter.send(data)).to eq("foo")
end
end
it "should return the resource's tags plus its name as its tags" do
expect(@resource).to receive(:tags).and_return(%w{one two})
expect(@parameter.tags).to eq(%w{one two foo})
end
it "should have a path" do
expect(@parameter.path).to eq("//foo")
end
describe "when returning the value" do
it "should return nil if no value is set" do
expect(@parameter.value).to be_nil
end
it "should validate the value" do
expect(@parameter).to receive(:validate).with("foo")
@parameter.value = "foo"
end
it "should munge the value and use any result as the actual value" do
expect(@parameter).to receive(:munge).with("foo").and_return("bar")
@parameter.value = "foo"
expect(@parameter.value).to eq("bar")
end
it "should unmunge the value when accessing the actual value" do
@parameter.class.unmunge do |value| value.to_sym end
@parameter.value = "foo"
expect(@parameter.value).to eq(:foo)
end
it "should return the actual value by default when unmunging" do
expect(@parameter.unmunge("bar")).to eq("bar")
end
it "should return any set value" do
@parameter.value = "foo"
expect(@parameter.value).to eq("foo")
end
end
describe "when validating values" do
it "should do nothing if no values or regexes have been defined" do
@parameter.validate("foo")
end
it "should catch abnormal failures thrown during validation" do
@class.validate { |v| raise "This is broken" }
expect { @parameter.validate("eh") }.to raise_error(Puppet::DevError)
end
it "should fail if the value is not a defined value or alias and does not match a regex" do
@class.newvalues :foo
expect { @parameter.validate("bar") }.to raise_error(Puppet::Error)
end
it "should succeed if the value is one of the defined values" do
@class.newvalues :foo
expect { @parameter.validate(:foo) }.to_not raise_error
end
it "should succeed if the value is one of the defined values even if the definition uses a symbol and the validation uses a string" do
@class.newvalues :foo
expect { @parameter.validate("foo") }.to_not raise_error
end
it "should succeed if the value is one of the defined values even if the definition uses a string and the validation uses a symbol" do
@class.newvalues "foo"
expect { @parameter.validate(:foo) }.to_not raise_error
end
it "should succeed if the value is one of the defined aliases" do
@class.newvalues :foo
@class.aliasvalue :bar, :foo
expect { @parameter.validate("bar") }.to_not raise_error
end
it "should succeed if the value matches one of the regexes" do
@class.newvalues %r{\d}
expect { @parameter.validate("10") }.to_not raise_error
end
end
describe "when munging values" do
it "should do nothing if no values or regexes have been defined" do
expect(@parameter.munge("foo")).to eq("foo")
end
it "should catch abnormal failures thrown during munging" do
@class.munge { |v| raise "This is broken" }
expect { @parameter.munge("eh") }.to raise_error(Puppet::DevError)
end
it "should return return any matching defined values" do
@class.newvalues :foo, :bar
expect(@parameter.munge("foo")).to eq(:foo)
end
it "should return any matching aliases" do
@class.newvalues :foo
@class.aliasvalue :bar, :foo
expect(@parameter.munge("bar")).to eq(:foo)
end
it "should return the value if it matches a regex" do
@class.newvalues %r{\w}
expect(@parameter.munge("bar")).to eq("bar")
end
it "should return the value if no other option is matched" do
@class.newvalues :foo
expect(@parameter.munge("bar")).to eq("bar")
end
end
describe "when logging" do
it "should use its resource's log level and the provided message" do
expect(@resource).to receive(:[]).with(:loglevel).and_return(:notice)
expect(@parameter).to receive(:send_log).with(:notice, "mymessage")
@parameter.log "mymessage"
end
end
describe ".format_value_for_display" do
it 'should format strings appropriately' do
expect(described_class.format_value_for_display('foo')).to eq("'foo'")
end
it 'should format numbers appropriately' do
expect(described_class.format_value_for_display(1)).to eq('1')
end
it 'should format symbols appropriately' do
expect(described_class.format_value_for_display(:bar)).to eq("'bar'")
end
it 'should format arrays appropriately' do
expect(described_class.format_value_for_display([1, 'foo', :bar])).to eq("[1, 'foo', 'bar']")
end
it 'should format hashes appropriately' do
expect(described_class.format_value_for_display(
{1 => 'foo', :bar => 2, 'baz' => :qux}
)).to eq(<<-RUBY.unindent.sub(/\n$/, ''))
{
1 => 'foo',
'bar' => 2,
'baz' => 'qux'
}
RUBY
end
it 'should format arrays with nested data appropriately' do
expect(described_class.format_value_for_display(
[1, 'foo', :bar, [1, 2, 3], {1 => 2, 3 => 4}]
)).to eq(<<-RUBY.unindent.sub(/\n$/, ''))
[1, 'foo', 'bar',
[1, 2, 3],
{
1 => 2,
3 => 4
}]
RUBY
end
it 'should format hashes with nested data appropriately' do
expect(described_class.format_value_for_display(
{1 => 'foo', :bar => [2, 3, 4], 'baz' => {:qux => 1, :quux => 'two'}}
)).to eq(<<-RUBY.unindent.sub(/\n$/, ''))
{
1 => 'foo',
'bar' => [2, 3, 4],
'baz' => {
'qux' => 1,
'quux' => 'two'
}
}
RUBY
end
it 'should format hashes with nested Objects appropriately' do
tf = Puppet::Pops::Types::TypeFactory
type = tf.object({'name' => 'MyType', 'attributes' => { 'qux' => tf.integer, 'quux' => tf.string }})
expect(described_class.format_value_for_display(
{1 => 'foo', 'bar' => type.create(1, 'one'), 'baz' => type.create(2, 'two')}
)).to eq(<<-RUBY.unindent.sub(/\n$/, ''))
{
1 => 'foo',
'bar' => MyType({
'qux' => 1,
'quux' => 'one'
}),
'baz' => MyType({
'qux' => 2,
'quux' => 'two'
})
}
RUBY
end
it 'should format Objects with nested Objects appropriately' do
tf = Puppet::Pops::Types::TypeFactory
inner_type = tf.object({'name' => 'MyInnerType', 'attributes' => { 'qux' => tf.integer, 'quux' => tf.string }})
outer_type = tf.object({'name' => 'MyOuterType', 'attributes' => { 'x' => tf.string, 'inner' => inner_type }})
expect(described_class.format_value_for_display(
{'bar' => outer_type.create('a', inner_type.create(1, 'one')), 'baz' => outer_type.create('b', inner_type.create(2, 'two'))}
)).to eq(<<-RUBY.unindent.sub(/\n$/, ''))
{
'bar' => MyOuterType({
'x' => 'a',
'inner' => MyInnerType({
'qux' => 1,
'quux' => 'one'
})
}),
'baz' => MyOuterType({
'x' => 'b',
'inner' => MyInnerType({
'qux' => 2,
'quux' => 'two'
})
})
}
RUBY
end
end
describe 'formatting messages' do
it "formats messages as-is when the parameter is not sensitive" do
expect(@parameter.format("hello %s", "world")).to eq("hello world")
end
it "formats messages with redacted values when the parameter is not sensitive" do
@parameter.sensitive = true
expect(@parameter.format("hello %s", "world")).to eq("hello [redacted]")
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/resource_spec.rb | spec/unit/resource_spec.rb | require 'spec_helper'
require 'puppet/resource'
describe Puppet::Resource do
include PuppetSpec::Files
let(:basepath) { make_absolute("/somepath") }
let(:environment) { Puppet::Node::Environment.create(:testing, []) }
def expect_lookup(key, options = {})
expectation = receive(:unchecked_key_lookup).with(Puppet::Pops::Lookup::LookupKey.new(key), any_args)
expectation = expectation.and_throw(options[:throws]) if options[:throws]
expectation = expectation.and_raise(*options[:raises]) if options[:raises]
expectation = expectation.and_return(options[:returns]) if options[:returns]
expect_any_instance_of(Puppet::Pops::Lookup::GlobalDataProvider).to expectation
end
[:catalog, :file, :line].each do |attr|
it "should have an #{attr} attribute" do
resource = Puppet::Resource.new("file", "/my/file")
expect(resource).to respond_to(attr)
expect(resource).to respond_to(attr.to_s + "=")
end
end
it "should have a :title attribute" do
expect(Puppet::Resource.new(:user, "foo").title).to eq("foo")
end
it "should require the type and title" do
expect { Puppet::Resource.new }.to raise_error(ArgumentError)
end
it "should canonize types to capitalized strings" do
expect(Puppet::Resource.new(:user, "foo").type).to eq("User")
end
it "should canonize qualified types so all strings are capitalized" do
expect(Puppet::Resource.new("foo::bar", "foo").type).to eq("Foo::Bar")
end
it "should tag itself with its type" do
expect(Puppet::Resource.new("file", "/f")).to be_tagged("file")
end
it "should tag itself with its title if the title is a valid tag" do
expect(Puppet::Resource.new("user", "bar")).to be_tagged("bar")
end
it "should not tag itself with its title if the title is a not valid tag" do
expect(Puppet::Resource.new("file", "/bar")).not_to be_tagged("/bar")
end
it "should allow setting of attributes" do
expect(Puppet::Resource.new("file", "/bar", :file => "/foo").file).to eq("/foo")
expect(Puppet::Resource.new("file", "/bar", :exported => true)).to be_exported
end
it "should set its type to 'Class' and its title to the passed title if the passed type is :component and the title has no square brackets in it" do
ref = Puppet::Resource.new(:component, "foo")
expect(ref.type).to eq("Class")
expect(ref.title).to eq("Foo")
end
it "should interpret the title as a reference and assign appropriately if the type is :component and the title contains square brackets" do
ref = Puppet::Resource.new(:component, "foo::bar[yay]")
expect(ref.type).to eq("Foo::Bar")
expect(ref.title).to eq("yay")
end
it "should set the type to 'Class' if it is nil and the title contains no square brackets" do
ref = Puppet::Resource.new(nil, "yay")
expect(ref.type).to eq("Class")
expect(ref.title).to eq("Yay")
end
it "should interpret the title as a reference and assign appropriately if the type is nil and the title contains square brackets" do
ref = Puppet::Resource.new(nil, "foo::bar[yay]")
expect(ref.type).to eq("Foo::Bar")
expect(ref.title).to eq("yay")
end
it "should interpret the title as a reference and assign appropriately if the type is nil and the title contains nested square brackets" do
ref = Puppet::Resource.new(nil, "foo::bar[baz[yay]]")
expect(ref.type).to eq("Foo::Bar")
expect(ref.title).to eq("baz[yay]")
end
it "should interpret the type as a reference and assign appropriately if the title is nil and the type contains square brackets" do
ref = Puppet::Resource.new("foo::bar[baz]")
expect(ref.type).to eq("Foo::Bar")
expect(ref.title).to eq("baz")
end
it "should not interpret the title as a reference if the type is a non component or whit reference" do
ref = Puppet::Resource.new("Notify", "foo::bar[baz]")
expect(ref.type).to eq("Notify")
expect(ref.title).to eq("foo::bar[baz]")
end
it "should be able to extract its information from a Puppet::Type instance" do
ral = Puppet::Type.type(:file).new :path => basepath+"/foo"
ref = Puppet::Resource.new(ral)
expect(ref.type).to eq("File")
expect(ref.title).to eq(basepath+"/foo")
end
it "should fail if the title is nil and the type is not a valid resource reference string" do
expect { Puppet::Resource.new("resource-spec-foo") }.to raise_error(ArgumentError)
end
it 'should fail if strict is set and type does not exist' do
expect { Puppet::Resource.new('resource-spec-foo', 'title', {:strict=>true}) }.to raise_error(ArgumentError, 'Invalid resource type resource-spec-foo')
end
it 'should fail if strict is set and class does not exist' do
expect { Puppet::Resource.new('Class', 'resource-spec-foo', {:strict=>true}) }.to raise_error(ArgumentError, 'Could not find declared class resource-spec-foo')
end
it "should fail if the title is a hash and the type is not a valid resource reference string" do
expect { Puppet::Resource.new({:type => "resource-spec-foo", :title => "bar"}) }.
to raise_error ArgumentError, /Puppet::Resource.new does not take a hash/
end
it "should be taggable" do
expect(Puppet::Resource.ancestors).to be_include(Puppet::Util::Tagging)
end
it "should have an 'exported' attribute" do
resource = Puppet::Resource.new("file", "/f")
resource.exported = true
expect(resource.exported).to eq(true)
expect(resource).to be_exported
end
describe "and munging its type and title" do
describe "when modeling a builtin resource" do
it "should be able to find the resource type" do
expect(Puppet::Resource.new("file", "/my/file").resource_type).to equal(Puppet::Type.type(:file))
end
it "should set its type to the capitalized type name" do
expect(Puppet::Resource.new("file", "/my/file").type).to eq("File")
end
end
describe "when modeling a defined resource" do
describe "that exists" do
before do
@type = Puppet::Resource::Type.new(:definition, "foo::bar")
environment.known_resource_types.add @type
end
it "should set its type to the capitalized type name" do
expect(Puppet::Resource.new("foo::bar", "/my/file", :environment => environment).type).to eq("Foo::Bar")
end
it "should be able to find the resource type" do
expect(Puppet::Resource.new("foo::bar", "/my/file", :environment => environment).resource_type).to equal(@type)
end
it "should set its title to the provided title" do
expect(Puppet::Resource.new("foo::bar", "/my/file", :environment => environment).title).to eq("/my/file")
end
end
describe "that does not exist" do
it "should set its resource type to the capitalized resource type name" do
expect(Puppet::Resource.new("foo::bar", "/my/file").type).to eq("Foo::Bar")
end
end
end
describe "when modeling a node" do
# Life's easier with nodes, because they can't be qualified.
it "should set its type to 'Node' and its title to the provided title" do
node = Puppet::Resource.new("node", "foo")
expect(node.type).to eq("Node")
expect(node.title).to eq("foo")
end
end
describe "when modeling a class" do
it "should set its type to 'Class'" do
expect(Puppet::Resource.new("class", "foo").type).to eq("Class")
end
describe "that exists" do
before do
@type = Puppet::Resource::Type.new(:hostclass, "foo::bar")
environment.known_resource_types.add @type
end
it "should set its title to the capitalized, fully qualified resource type" do
expect(Puppet::Resource.new("class", "foo::bar", :environment => environment).title).to eq("Foo::Bar")
end
it "should be able to find the resource type" do
expect(Puppet::Resource.new("class", "foo::bar", :environment => environment).resource_type).to equal(@type)
end
end
describe "that does not exist" do
it "should set its type to 'Class' and its title to the capitalized provided name" do
klass = Puppet::Resource.new("class", "foo::bar")
expect(klass.type).to eq("Class")
expect(klass.title).to eq("Foo::Bar")
end
end
describe "and its name is set to the empty string" do
it "should set its title to :main" do
expect(Puppet::Resource.new("class", "").title).to eq(:main)
end
describe "and a class exists whose name is the empty string" do # this was a bit tough to track down
it "should set its title to :main" do
@type = Puppet::Resource::Type.new(:hostclass, "")
environment.known_resource_types.add @type
expect(Puppet::Resource.new("class", "", :environment => environment).title).to eq(:main)
end
end
end
describe "and its name is set to :main" do
it "should set its title to :main" do
expect(Puppet::Resource.new("class", :main).title).to eq(:main)
end
describe "and a class exists whose name is the empty string" do # this was a bit tough to track down
it "should set its title to :main" do
@type = Puppet::Resource::Type.new(:hostclass, "")
environment.known_resource_types.add @type
expect(Puppet::Resource.new("class", :main, :environment => environment).title).to eq(:main)
end
end
end
end
end
it "should return nil when looking up resource types that don't exist" do
expect(Puppet::Resource.new("foobar", "bar").resource_type).to be_nil
end
it "should not fail when an invalid parameter is used and strict mode is disabled" do
type = Puppet::Resource::Type.new(:definition, "foobar")
environment.known_resource_types.add type
resource = Puppet::Resource.new("foobar", "/my/file", :environment => environment)
resource[:yay] = true
end
it "should be considered equivalent to another resource if their type and title match and no parameters are set" do
expect(Puppet::Resource.new("file", "/f")).to eq(Puppet::Resource.new("file", "/f"))
end
it "should be considered equivalent to another resource if their type, title, and parameters are equal" do
expect(Puppet::Resource.new("file", "/f", :parameters => {:foo => "bar"})).to eq(Puppet::Resource.new("file", "/f", :parameters => {:foo => "bar"}))
end
it "should not be considered equivalent to another resource if their type and title match but parameters are different" do
expect(Puppet::Resource.new("file", "/f", :parameters => {:fee => "baz"})).not_to eq(Puppet::Resource.new("file", "/f", :parameters => {:foo => "bar"}))
end
it "should not be considered equivalent to a non-resource" do
expect(Puppet::Resource.new("file", "/f")).not_to eq("foo")
end
it "should not be considered equivalent to another resource if their types do not match" do
expect(Puppet::Resource.new("file", "/f")).not_to eq(Puppet::Resource.new("exec", "/f"))
end
it "should not be considered equivalent to another resource if their titles do not match" do
expect(Puppet::Resource.new("file", "/foo")).not_to eq(Puppet::Resource.new("file", "/f"))
end
describe "when setting default parameters" do
let(:foo_node) { Puppet::Node.new('foo', :environment => environment) }
let(:compiler) { Puppet::Parser::Compiler.new(foo_node) }
let(:scope) { Puppet::Parser::Scope.new(compiler) }
def ast_leaf(value)
Puppet::Parser::AST::Leaf.new(value: value)
end
describe "when the resource type is :hostclass" do
let(:environment_name) { "testing env" }
let(:fact_values) { { 'a' => 1 } }
let(:port) { Puppet::Parser::AST::Leaf.new(:value => '80') }
def inject_and_set_defaults(resource, scope)
resource.resource_type.set_resource_parameters(resource, scope)
end
before do
environment.known_resource_types.add(apache)
scope.set_facts(fact_values)
end
context 'with a default value expression' do
let(:apache) { Puppet::Resource::Type.new(:hostclass, 'apache', :arguments => { 'port' => port }) }
context "when no value is provided" do
let(:resource) do
Puppet::Parser::Resource.new("class", "apache", :scope => scope)
end
it "should query the data_binding terminus using a namespaced key" do
expect_lookup('lookup_options', throws: :no_such_key)
expect_lookup('apache::port')
inject_and_set_defaults(resource, scope)
end
it "should use the value from the data_binding terminus" do
expect_lookup('lookup_options', throws: :no_such_key)
expect_lookup('apache::port', returns: '443')
inject_and_set_defaults(resource, scope)
expect(resource[:port]).to eq('443')
end
it 'should use the default value if no value is found using the data_binding terminus' do
expect_lookup('lookup_options', throws: :no_such_key)
expect_lookup('apache::port', throws: :no_such_key)
inject_and_set_defaults(resource, scope)
expect(resource[:port]).to eq('80')
end
it 'should use the default value if an undef value is found using the data_binding terminus' do
expect_lookup('lookup_options', throws: :no_such_key)
expect_lookup('apache::port', returns: nil)
inject_and_set_defaults(resource, scope)
expect(resource[:port]).to eq('80')
end
it "should fail with error message about data binding on a hiera failure" do
expect_lookup('lookup_options', throws: :no_such_key)
expect_lookup('apache::port', raises: [Puppet::DataBinding::LookupError, 'Forgettabotit'])
expect {
inject_and_set_defaults(resource, scope)
}.to raise_error(Puppet::Error, /Lookup of key 'apache::port' failed: Forgettabotit/)
end
end
context "when a value is provided" do
let(:port_parameter) do
Puppet::Parser::Resource::Param.new(
name: 'port', value: '8080'
)
end
let(:resource) do
Puppet::Parser::Resource.new("class", "apache", :scope => scope,
:parameters => [port_parameter])
end
it "should not query the data_binding terminus" do
expect(Puppet::DataBinding.indirection).not_to receive(:find)
inject_and_set_defaults(resource, scope)
end
it "should use the value provided" do
expect(Puppet::DataBinding.indirection).not_to receive(:find)
expect(resource[:port]).to eq('8080')
end
it "should use the value from the data_binding terminus when provided value is undef" do
expect_lookup('lookup_options', throws: :no_such_key)
expect_lookup('apache::port', returns: '443')
rs = Puppet::Parser::Resource.new("class", "apache", :scope => scope,
:parameters => [Puppet::Parser::Resource::Param.new(name: 'port', value: nil)])
rs.resource_type.set_resource_parameters(rs, scope)
expect(rs[:port]).to eq('443')
end
end
end
context 'without a default value expression' do
let(:apache) { Puppet::Resource::Type.new(:hostclass, 'apache', :arguments => { 'port' => nil }) }
let(:resource) { Puppet::Parser::Resource.new("class", "apache", :scope => scope) }
it "should use the value from the data_binding terminus" do
expect_lookup('lookup_options', throws: :no_such_key)
expect_lookup('apache::port', returns: '443')
inject_and_set_defaults(resource, scope)
expect(resource[:port]).to eq('443')
end
it "should use an undef value from the data_binding terminus" do
expect_lookup('lookup_options', throws: :no_such_key)
expect_lookup('apache::port', returns: nil)
inject_and_set_defaults(resource, scope)
expect(resource[:port]).to be_nil
end
end
end
end
describe "when referring to a resource with name canonicalization" do
it "should canonicalize its own name" do
res = Puppet::Resource.new("file", "/path/")
expect(res.uniqueness_key).to eq(["/path"])
expect(res.ref).to eq("File[/path/]")
end
end
describe "when running in strict mode" do
it "should be strict" do
expect(Puppet::Resource.new("file", "/path", :strict => true)).to be_strict
end
it "should fail if invalid parameters are used" do
expect { Puppet::Resource.new("file", "/path", :strict => true, :parameters => {:nosuchparam => "bar"}) }.to raise_error(Puppet::Error, /no parameter named 'nosuchparam'/)
end
it "should fail if the resource type cannot be resolved" do
expect { Puppet::Resource.new("nosuchtype", "/path", :strict => true) }.to raise_error(ArgumentError, /Invalid resource type/)
end
end
describe "when managing parameters" do
before do
@resource = Puppet::Resource.new("file", "/my/file")
end
it "should correctly detect when provided parameters are not valid for builtin types" do
expect(Puppet::Resource.new("file", "/my/file")).not_to be_valid_parameter("foobar")
end
it "should correctly detect when provided parameters are valid for builtin types" do
expect(Puppet::Resource.new("file", "/my/file")).to be_valid_parameter("mode")
end
it "should correctly detect when provided parameters are not valid for defined resource types" do
type = Puppet::Resource::Type.new(:definition, "foobar")
environment.known_resource_types.add type
expect(Puppet::Resource.new("foobar", "/my/file", :environment => environment)).not_to be_valid_parameter("myparam")
end
it "should correctly detect when provided parameters are valid for defined resource types" do
type = Puppet::Resource::Type.new(:definition, "foobar", :arguments => {"myparam" => nil})
environment.known_resource_types.add type
expect(Puppet::Resource.new("foobar", "/my/file", :environment => environment)).to be_valid_parameter("myparam")
end
it "should allow setting and retrieving of parameters" do
@resource[:foo] = "bar"
expect(@resource[:foo]).to eq("bar")
end
it "should allow setting of parameters at initialization" do
expect(Puppet::Resource.new("file", "/my/file", :parameters => {:foo => "bar"})[:foo]).to eq("bar")
end
it "should canonicalize retrieved parameter names to treat symbols and strings equivalently" do
@resource[:foo] = "bar"
expect(@resource["foo"]).to eq("bar")
end
it "should canonicalize set parameter names to treat symbols and strings equivalently" do
@resource["foo"] = "bar"
expect(@resource[:foo]).to eq("bar")
end
it "should set the namevar when asked to set the name" do
resource = Puppet::Resource.new("user", "bob")
allow(Puppet::Type.type(:user)).to receive(:key_attributes).and_return([:myvar])
resource[:name] = "bob"
expect(resource[:myvar]).to eq("bob")
end
it "should return the namevar when asked to return the name" do
resource = Puppet::Resource.new("user", "bob")
allow(Puppet::Type.type(:user)).to receive(:key_attributes).and_return([:myvar])
resource[:myvar] = "test"
expect(resource[:name]).to eq("test")
end
it "should be able to set the name for non-builtin types" do
resource = Puppet::Resource.new(:foo, "bar")
resource[:name] = "eh"
expect { resource[:name] = "eh" }.to_not raise_error
end
it "should be able to return the name for non-builtin types" do
resource = Puppet::Resource.new(:foo, "bar")
resource[:name] = "eh"
expect(resource[:name]).to eq("eh")
end
it "should be able to iterate over parameters" do
@resource[:foo] = "bar"
@resource[:fee] = "bare"
params = {}
@resource.each do |key, value|
params[key] = value
end
expect(params).to eq({:foo => "bar", :fee => "bare"})
end
it "should include Enumerable" do
expect(@resource.class.ancestors).to be_include(Enumerable)
end
it "should have a method for testing whether a parameter is included" do
@resource[:foo] = "bar"
expect(@resource).to be_has_key(:foo)
expect(@resource).not_to be_has_key(:eh)
end
it "should have a method for providing the list of parameters" do
@resource[:foo] = "bar"
@resource[:bar] = "foo"
keys = @resource.keys
expect(keys).to be_include(:foo)
expect(keys).to be_include(:bar)
end
it "should have a method for providing the number of parameters" do
@resource[:foo] = "bar"
expect(@resource.length).to eq(1)
end
it "should have a method for deleting parameters" do
@resource[:foo] = "bar"
@resource.delete(:foo)
expect(@resource[:foo]).to be_nil
end
it "should have a method for testing whether the parameter list is empty" do
expect(@resource).to be_empty
@resource[:foo] = "bar"
expect(@resource).not_to be_empty
end
it "should be able to produce a hash of all existing parameters" do
@resource[:foo] = "bar"
@resource[:fee] = "yay"
hash = @resource.to_hash
expect(hash[:foo]).to eq("bar")
expect(hash[:fee]).to eq("yay")
end
it "should not provide direct access to the internal parameters hash when producing a hash" do
hash = @resource.to_hash
hash[:foo] = "bar"
expect(@resource[:foo]).to be_nil
end
it "should use the title as the namevar to the hash if no namevar is present" do
resource = Puppet::Resource.new("user", "bob")
allow(Puppet::Type.type(:user)).to receive(:key_attributes).and_return([:myvar])
expect(resource.to_hash[:myvar]).to eq("bob")
end
it "should set :name to the title if :name is not present for non-existent types" do
resource = Puppet::Resource.new :doesnotexist, "bar"
expect(resource.to_hash[:name]).to eq("bar")
end
it "should set :name to the title if :name is not present for a definition" do
type = Puppet::Resource::Type.new(:definition, :foo)
environment.known_resource_types.add(type)
resource = Puppet::Resource.new :foo, "bar", :environment => environment
expect(resource.to_hash[:name]).to eq("bar")
end
end
describe "when serializing a native type" do
before do
@resource = Puppet::Resource.new("file", "/my/file")
@resource["one"] = "test"
@resource["two"] = "other"
end
# PUP-3272, needs to work becuse serialization is not only to network
#
it "should produce an equivalent yaml object" do
text = @resource.render('yaml')
newresource = Puppet::Resource.convert_from('yaml', text)
expect(newresource).to equal_resource_attributes_of(@resource)
end
# PUP-3272, since serialization to network is done in json, not yaml
it "should produce an equivalent json object" do
text = @resource.render('json')
newresource = Puppet::Resource.convert_from('json', text)
expect(newresource).to equal_resource_attributes_of(@resource)
end
end
describe "when serializing a defined type" do
before do
type = Puppet::Resource::Type.new(:definition, "foo::bar")
environment.known_resource_types.add type
@resource = Puppet::Resource.new('foo::bar', 'xyzzy', :environment => environment)
@resource['one'] = 'test'
@resource['two'] = 'other'
@resource.resource_type
end
it "doesn't include transient instance variables (#4506)" do
expect(@resource.to_data_hash.keys).to_not include('rstype')
end
it "produces an equivalent json object" do
text = @resource.render('json')
newresource = Puppet::Resource.convert_from('json', text)
expect(newresource).to equal_resource_attributes_of(@resource)
end
it 'to_data_hash returns value that is instance of Data' do
Puppet::Pops::Types::TypeAsserter.assert_instance_of('', Puppet::Pops::Types::TypeFactory.data, @resource.to_data_hash)
expect(Puppet::Pops::Types::TypeFactory.data.instance?(@resource.to_data_hash)).to be_truthy
end
end
describe "when converting to a RAL resource" do
it "should use the resource type's :new method to create the resource if the resource is of a builtin type" do
resource = Puppet::Resource.new("file", basepath+"/my/file")
result = resource.to_ral
expect(result).to be_instance_of(Puppet::Type.type(:file))
expect(result[:path]).to eq(basepath+"/my/file")
end
it "should convert to a component instance if the resource is not a compilable_type" do
resource = Puppet::Resource.new("foobar", "somename")
result = resource.to_ral
expect(result).to be_instance_of(Puppet::Type.type(:component))
expect(result.title).to eq("Foobar[somename]")
end
it "should convert to a component instance if the resource is a class" do
resource = Puppet::Resource.new("Class", "somename")
result = resource.to_ral
expect(result).to be_instance_of(Puppet::Type.type(:component))
expect(result.title).to eq("Class[Somename]")
end
it "should convert to component when the resource is a defined_type" do
resource = Puppet::Resource.new("Unknown", "type", :kind => 'defined_type')
result = resource.to_ral
expect(result).to be_instance_of(Puppet::Type.type(:component))
end
it "should raise if a resource type is a compilable_type and it wasn't found" do
resource = Puppet::Resource.new("Unknown", "type", :kind => 'compilable_type')
expect { resource.to_ral }.to raise_error(Puppet::Error, "Resource type 'Unknown' was not found")
end
it "should use the old behaviour when the catalog_format is equal to 1" do
resource = Puppet::Resource.new("Unknown", "type")
catalog = Puppet::Resource::Catalog.new("mynode")
resource.catalog = catalog
resource.catalog.catalog_format = 1
result = resource.to_ral
expect(result).to be_instance_of(Puppet::Type.type(:component))
end
it "should use the new behaviour and fail when the catalog_format is greater than 1" do
resource = Puppet::Resource.new("Unknown", "type", :kind => 'compilable_type')
catalog = Puppet::Resource::Catalog.new("mynode")
resource.catalog = catalog
resource.catalog.catalog_format = 2
expect { resource.to_ral }.to raise_error(Puppet::Error, "Resource type 'Unknown' was not found")
end
it "should use the resource type when the resource doesn't respond to kind and the resource type can be found" do
resource = Puppet::Resource.new("file", basepath+"/my/file")
result = resource.to_ral
expect(result).to be_instance_of(Puppet::Type.type(:file))
end
end
describe "when converting to puppet code" do
before do
@resource = Puppet::Resource.new("one::two", "/my/file",
:parameters => {
:noop => true,
:foo => %w{one two},
:ensure => 'present',
}
)
end
it "should escape internal single quotes in a title" do
singlequote_resource = Puppet::Resource.new("one::two", "/my/file'b'a'r",
:parameters => {
:ensure => 'present',
}
)
expect(singlequote_resource.to_manifest).to eq(<<-HEREDOC.gsub(/^\s{8}/, '').gsub(/\n$/, ''))
one::two { '/my/file\\'b\\'a\\'r':
ensure => 'present',
}
HEREDOC
end
it "should align, sort and add trailing commas to attributes with ensure first" do
expect(@resource.to_manifest).to eq(<<-HEREDOC.gsub(/^\s{8}/, '').gsub(/\n$/, ''))
one::two { '/my/file':
ensure => 'present',
foo => ['one', 'two'],
noop => true,
}
HEREDOC
end
end
describe "when converting to Yaml for Hiera" do
before do
@resource = Puppet::Resource.new("one::two", "/my/file",
:parameters => {
:noop => true,
:foo => [:one, "two"],
:bar => 'a\'b',
:ensure => 'present',
}
)
end
it "should align and sort to attributes with ensure first" do
expect(@resource.to_hierayaml).to eq(<<-HEREDOC.gsub(/^\s{8}/, ''))
/my/file:
ensure: 'present'
bar : 'a\\'b'
foo : ['one', 'two']
noop : true
HEREDOC
end
it "should convert some types to String" do
expect(@resource.to_hiera_hash).to eq(
"/my/file" => {
'ensure' => "present",
'bar' => "a'b",
'foo' => ["one", "two"],
'noop' => true
}
)
end
it "accepts symbolic titles" do
res = Puppet::Resource.new(:file, "/my/file", :parameters => { 'ensure' => "present" })
expect(res.to_hiera_hash.keys).to eq(["/my/file"])
end
it "emits an empty parameters hash" do
res = Puppet::Resource.new(:file, "/my/file")
expect(res.to_hiera_hash).to eq({"/my/file" => {}})
end
end
describe "when converting to json" do
# LAK:NOTE For all of these tests, we convert back to the resource so we can
# trap the actual data structure then.
it "should set its type to the provided type" do
expect(Puppet::Resource.from_data_hash(JSON.parse(Puppet::Resource.new("File", "/foo").to_json)).type).to eq("File")
end
it "should set its title to the provided title" do
expect(Puppet::Resource.from_data_hash(JSON.parse(Puppet::Resource.new("File", "/foo").to_json)).title).to eq("/foo")
end
it "should include all tags from the resource" do
resource = Puppet::Resource.new("File", "/foo")
resource.tag("yay")
expect(Puppet::Resource.from_data_hash(JSON.parse(resource.to_json)).tags).to eq(resource.tags)
end
it "should include the file if one is set" do
resource = Puppet::Resource.new("File", "/foo")
resource.file = "/my/file"
expect(Puppet::Resource.from_data_hash(JSON.parse(resource.to_json)).file).to eq("/my/file")
end
it "should include the line if one is set" do
resource = Puppet::Resource.new("File", "/foo")
resource.line = 50
expect(Puppet::Resource.from_data_hash(JSON.parse(resource.to_json)).line).to eq(50)
end
it "should include the kind if one is set" do
resource = Puppet::Resource.new("File", "/foo")
resource.kind = 'im_a_file'
expect(Puppet::Resource.from_data_hash(JSON.parse(resource.to_json)).kind).to eq('im_a_file')
end
it "should include the 'exported' value if one is set" do
resource = Puppet::Resource.new("File", "/foo")
resource.exported = true
expect(Puppet::Resource.from_data_hash(JSON.parse(resource.to_json)).exported?).to be_truthy
end
it "should set 'exported' to false if no value is set" do
resource = Puppet::Resource.new("File", "/foo")
expect(Puppet::Resource.from_data_hash(JSON.parse(resource.to_json)).exported?).to be_falsey
end
it "should set all of its parameters as the 'parameters' entry" do
resource = Puppet::Resource.new("File", "/foo")
resource[:foo] = %w{bar eh}
resource[:fee] = %w{baz}
result = Puppet::Resource.from_data_hash(JSON.parse(resource.to_json))
expect(result["foo"]).to eq(%w{bar eh})
expect(result["fee"]).to eq(%w{baz})
end
it "should set sensitive parameters as an array of strings" do
resource = Puppet::Resource.new("File", "/foo", :sensitive_parameters => [:foo, :fee])
result = JSON.parse(resource.to_json)
expect(result["sensitive_parameters"]).to eq(["foo", "fee"])
end
it "should serialize relationships as reference strings" do
resource = Puppet::Resource.new("File", "/foo")
resource[:requires] = Puppet::Resource.new("File", "/bar")
result = Puppet::Resource.from_data_hash(JSON.parse(resource.to_json))
expect(result[:requires]).to eq("File[/bar]")
end
it "should serialize multiple relationships as arrays of reference strings" do
resource = Puppet::Resource.new("File", "/foo")
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | true |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/node_spec.rb | spec/unit/node_spec.rb | require 'spec_helper'
require 'matchers/json'
require 'puppet_spec/files'
describe Puppet::Node do
include JSONMatchers
include PuppetSpec::Files
let(:environment) { Puppet::Node::Environment.create(:bar, []) }
let(:env_loader) { Puppet::Environments::Static.new(environment) }
describe "when managing its environment" do
it "provides an environment instance" do
expect(Puppet::Node.new("foo", :environment => environment).environment.name).to eq(:bar)
end
context "present in a loader" do
around do |example|
Puppet.override(:environments => env_loader) do
example.run
end
end
it "uses any set environment" do
expect(Puppet::Node.new("foo", :environment => "bar").environment).to eq(environment)
end
it "determines its environment from its parameters if no environment is set" do
expect(Puppet::Node.new("foo", :parameters => {"environment" => :bar}).environment).to eq(environment)
end
it "uses the configured environment if no environment is provided" do
Puppet[:environment] = environment.name.to_s
expect(Puppet::Node.new("foo").environment).to eq(environment)
end
it "allows the environment to be set after initialization" do
node = Puppet::Node.new("foo")
node.environment = :bar
expect(node.environment.name).to eq(:bar)
end
it "sets environment_name with the correct environment name" do
node = Puppet::Node.new("foo")
node.environment = Puppet::Node::Environment.remote('www123')
expect(node.environment_name).to eq(:www123)
end
it "allows its environment to be set by parameters after initialization" do
node = Puppet::Node.new("foo")
node.parameters["environment"] = :bar
expect(node.environment.name).to eq(:bar)
end
end
end
describe "serialization" do
around do |example|
Puppet.override(:environments => env_loader) do
example.run
end
end
it "can round-trip through json" do
Puppet::Node::Facts.new("hello", "one" => "c", "two" => "b")
node = Puppet::Node.new("hello",
:environment => 'bar',
:classes => ['erth', 'aiu'],
:parameters => {"hostname"=>"food"}
)
new_node = Puppet::Node.convert_from('json', node.render('json'))
expect(new_node.environment).to eq(node.environment)
expect(new_node.parameters).to eq(node.parameters)
expect(new_node.classes).to eq(node.classes)
expect(new_node.name).to eq(node.name)
end
it "validates against the node json schema" do
Puppet::Node::Facts.new("hello", "one" => "c", "two" => "b")
node = Puppet::Node.new("hello",
:environment => 'bar',
:classes => ['erth', 'aiu'],
:parameters => {"hostname"=>"food"}
)
expect(node.to_json).to validate_against('api/schemas/node.json')
end
it "when missing optional parameters validates against the node json schema" do
Puppet::Node::Facts.new("hello", "one" => "c", "two" => "b")
node = Puppet::Node.new("hello",
:environment => 'bar'
)
expect(node.to_json).to validate_against('api/schemas/node.json')
end
it "should allow its environment parameter to be set by attribute after initialization" do
node = Puppet::Node.new("foo", { :parameters => { 'environment' => :foo } })
node.environment_name = :foo
node.environment = :bar
expect(node.environment_name).to eq(:bar)
expect(node.parameters['environment']).to eq('bar')
end
it 'to_data_hash returns value that is instance of to Data' do
node = Puppet::Node.new("hello",
:environment => 'bar',
:classes => ['erth', 'aiu'],
:parameters => {"hostname"=>"food"}
)
expect(Puppet::Pops::Types::TypeFactory.data.instance?(node.to_data_hash)).to be_truthy
end
end
describe "when serializing using yaml" do
before do
@node = Puppet::Node.new("mynode")
end
it "a node can roundtrip" do
expect(Puppet::Util::Yaml.safe_load(@node.to_yaml, [Puppet::Node]).name).to eql("mynode")
end
it "limits the serialization of environment to be just the name" do
yaml_file = file_containing("temp_yaml", @node.to_yaml)
expect(File.read(yaml_file)).to eq(<<~NODE)
--- !ruby/object:Puppet::Node
name: mynode
environment: production
NODE
end
end
describe "when serializing using yaml and values classes and parameters are missing in deserialized hash" do
it "a node can roundtrip" do
@node = Puppet::Node.from_data_hash({'name' => "mynode"})
expect(Puppet::Util::Yaml.safe_load(@node.to_yaml, [Puppet::Node]).name).to eql("mynode")
end
it "errors if name is nil" do
expect { Puppet::Node.from_data_hash({ })}.to raise_error(ArgumentError, /No name provided in serialized data/)
end
end
describe "when converting to json" do
before do
@node = Puppet::Node.new("mynode")
end
it "provide its name" do
expect(@node).to set_json_attribute('name').to("mynode")
end
it "includes the classes if set" do
@node.classes = %w{a b c}
expect(@node).to set_json_attribute("classes").to(%w{a b c})
end
it "does not include the classes if there are none" do
expect(@node).to_not set_json_attribute('classes')
end
it "includes parameters if set" do
@node.parameters = {"a" => "b", "c" => "d"}
expect(@node).to set_json_attribute('parameters').to({"a" => "b", "c" => "d"})
end
it "does not include the environment parameter in the json" do
@node.parameters = {"a" => "b", "c" => "d"}
@node.environment = environment
expect(@node.parameters).to eq({"a"=>"b", "c"=>"d", "environment"=>"bar"})
expect(@node).to set_json_attribute('parameters').to({"a" => "b", "c" => "d"})
end
it "does not include the parameters if there are none" do
expect(@node).to_not set_json_attribute('parameters')
end
it "includes the environment" do
@node.environment = "production"
expect(@node).to set_json_attribute('environment').to('production')
end
end
describe "when converting from json" do
before do
@node = Puppet::Node.new("mynode")
@format = Puppet::Network::FormatHandler.format('json')
end
def from_json(json)
@format.intern(Puppet::Node, json)
end
it "sets its name" do
expect(Puppet::Node).to read_json_attribute('name').from(@node.to_json).as("mynode")
end
it "includes the classes if set" do
@node.classes = %w{a b c}
expect(Puppet::Node).to read_json_attribute('classes').from(@node.to_json).as(%w{a b c})
end
it "includes parameters if set" do
@node.parameters = {"a" => "b", "c" => "d"}
expect(Puppet::Node).to read_json_attribute('parameters').from(@node.to_json).as({"a" => "b", "c" => "d", "environment" => "production"})
end
it "deserializes environment to environment_name as a symbol" do
Puppet.override(:environments => env_loader) do
@node.environment = environment
expect(Puppet::Node).to read_json_attribute('environment_name').from(@node.to_json).as(:bar)
end
end
it "does not immediately populate the environment instance" do
node = described_class.from_data_hash("name" => "foo", "environment" => "production")
expect(node.environment_name).to eq(:production)
expect(node).not_to be_has_environment_instance
node.environment
expect(node).to be_has_environment_instance
end
end
end
describe Puppet::Node, "when initializing" do
before do
@node = Puppet::Node.new("testnode")
end
it "sets the node name" do
expect(@node.name).to eq("testnode")
end
it "does not allow nil node names" do
expect { Puppet::Node.new(nil) }.to raise_error(ArgumentError)
end
it "defaults to an empty parameter hash" do
expect(@node.parameters).to eq({})
end
it "defaults to an empty class array" do
expect(@node.classes).to eq([])
end
it "notes its creation time" do
expect(@node.time).to be_instance_of(Time)
end
it "accepts parameters passed in during initialization" do
params = {"a" => "b"}
@node = Puppet::Node.new("testing", :parameters => params)
expect(@node.parameters).to eq(params)
end
it "accepts classes passed in during initialization" do
classes = %w{one two}
@node = Puppet::Node.new("testing", :classes => classes)
expect(@node.classes).to eq(classes)
end
it "always returns classes as an array" do
@node = Puppet::Node.new("testing", :classes => "myclass")
expect(@node.classes).to eq(["myclass"])
end
end
describe Puppet::Node, "when merging facts" do
before do
@node = Puppet::Node.new("testnode")
Puppet[:facts_terminus] = :memory
Puppet::Node::Facts.indirection.save(Puppet::Node::Facts.new(@node.name, "one" => "c", "two" => "b"))
end
context "when supplied facts as a parameter" do
let(:facts) { Puppet::Node::Facts.new(@node.name, "foo" => "bar") }
it "accepts facts to merge with the node" do
expect(@node).to receive(:merge).with({ 'foo' => 'bar' })
@node.fact_merge(facts)
end
it "will not query the facts indirection if facts are supplied" do
expect(Puppet::Node::Facts.indirection).not_to receive(:find)
@node.fact_merge(facts)
end
end
it "recovers with a Puppet::Error if something is thrown from the facts indirection" do
expect(Puppet::Node::Facts.indirection).to receive(:find).and_raise("something bad happened in the indirector")
expect { @node.fact_merge }.to raise_error(Puppet::Error, /Could not retrieve facts for testnode: something bad happened in the indirector/)
end
it "prefers parameters already set on the node over facts from the node" do
@node = Puppet::Node.new("testnode", :parameters => {"one" => "a"})
@node.fact_merge
expect(@node.parameters["one"]).to eq("a")
end
it "adds passed parameters to the parameter list" do
@node = Puppet::Node.new("testnode", :parameters => {"one" => "a"})
@node.fact_merge
expect(@node.parameters["two"]).to eq("b")
end
it "warns when a parameter value is not updated" do
@node = Puppet::Node.new("testnode", :parameters => {"one" => "a"})
expect(Puppet).to receive(:warning).with('The node parameter \'one\' for node \'testnode\' was already set to \'a\'. It could not be set to \'b\'')
@node.merge "one" => "b"
end
it "accepts arbitrary parameters to merge into its parameters" do
@node = Puppet::Node.new("testnode", :parameters => {"one" => "a"})
@node.merge "two" => "three"
expect(@node.parameters["two"]).to eq("three")
end
context "with an env loader" do
let(:environment) { Puppet::Node::Environment.create(:one, []) }
let(:environment_two) { Puppet::Node::Environment.create(:two, []) }
let(:environment_three) { Puppet::Node::Environment.create(:three, []) }
let(:environment_prod) { Puppet::Node::Environment.create(:production, []) }
let(:env_loader) { Puppet::Environments::Static.new(environment, environment_two, environment_three, environment_prod) }
around do |example|
Puppet.override(:environments => env_loader) do
example.run
end
end
context "when a node is initialized from a data hash" do
context "when a node is initialzed with an environment" do
it "uses 'environment' when provided" do
my_node = Puppet::Node.from_data_hash("environment" => "one", "name" => "my_node")
expect(my_node.environment.name).to eq(:one)
end
it "uses the environment parameter when provided" do
my_node = Puppet::Node.from_data_hash("parameters" => {"environment" => "one"}, "name" => "my_node")
expect(my_node.environment.name).to eq(:one)
end
it "uses the environment when also given an environment parameter" do
my_node = Puppet::Node.from_data_hash("parameters" => {"environment" => "one"}, "name" => "my_node", "environment" => "two")
expect(my_node.environment.name).to eq(:two)
end
it "uses 'environment' when an environment fact has been merged" do
my_node = Puppet::Node.from_data_hash("environment" => "one", "name" => "my_node")
my_node.fact_merge Puppet::Node::Facts.new "my_node", "environment" => "two"
expect(my_node.environment.name).to eq(:one)
end
it "uses an environment parameter when an environment fact has been merged" do
my_node = Puppet::Node.from_data_hash("parameters" => {"environment" => "one"}, "name" => "my_node")
my_node.fact_merge Puppet::Node::Facts.new "my_node", "environment" => "two"
expect(my_node.environment.name).to eq(:one)
end
it "uses an environment when an environment parameter has been given and an environment fact has been merged" do
my_node = Puppet::Node.from_data_hash("parameters" => {"environment" => "two"}, "name" => "my_node", "environment" => "one")
my_node.fact_merge Puppet::Node::Facts.new "my_node", "environment" => "three"
expect(my_node.environment.name).to eq(:one)
end
end
context "when a node is initialized without an environment" do
it "should use the server's default environment" do
my_node = Puppet::Node.from_data_hash("name" => "my_node")
expect(my_node.environment.name).to eq(:production)
end
it "should use the server's default when an environment fact has been merged" do
my_node = Puppet::Node.from_data_hash("name" => "my_node")
my_node.fact_merge Puppet::Node::Facts.new "my_node", "environment" => "two"
expect(my_node.environment.name).to eq(:production)
end
end
end
context "when a node is initialized from new" do
context "when a node is initialzed with an environment" do
it "adds the environment to the list of parameters" do
Puppet[:environment] = "one"
@node = Puppet::Node.new("testnode", :environment => "one")
@node.merge "two" => "three"
expect(@node.parameters["environment"]).to eq("one")
end
it "when merging, syncs the environment parameter to a node's existing environment" do
@node = Puppet::Node.new("testnode", :environment => "one")
@node.merge "environment" => "two"
expect(@node.parameters["environment"]).to eq("one")
end
it "merging facts does not override that environment" do
@node = Puppet::Node.new("testnode", :environment => "one")
@node.fact_merge Puppet::Node::Facts.new "testnode", "environment" => "two"
expect(@node.environment.name.to_s).to eq("one")
end
end
context "when a node is initialized without an environment" do
it "it perfers an environment name to an environment fact" do
@node = Puppet::Node.new("testnode")
@node.environment_name = "one"
@node.fact_merge Puppet::Node::Facts.new "testnode", "environment" => "two"
expect(@node.environment.name.to_s).to eq("one")
end
end
end
end
end
describe Puppet::Node, "when indirecting" do
it "defaults to the 'plain' node terminus" do
Puppet::Node.indirection.reset_terminus_class
expect(Puppet::Node.indirection.terminus_class).to eq(:plain)
end
end
describe Puppet::Node, "when generating the list of names to search through" do
before do
@node = Puppet::Node.new("foo.domain.com",
:parameters => {"hostname" => "yay", "domain" => "domain.com"})
end
it "returns an array of one name" do
expect(@node.names).to be_instance_of(Array)
expect(@node.names).to eq ["foo.domain.com"]
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/x509/pem_store_spec.rb | spec/unit/x509/pem_store_spec.rb | # coding: utf-8
require 'spec_helper'
require 'puppet/x509'
class Puppet::X509::TestPemStore
include Puppet::X509::PemStore
end
describe Puppet::X509::PemStore do
include PuppetSpec::Files
let(:subject) { Puppet::X509::TestPemStore.new }
def with_unreadable_file
path = tmpfile('pem_store')
Puppet::FileSystem.touch(path)
Puppet::FileSystem.chmod(0, path)
yield path
ensure
Puppet::FileSystem.chmod(0600, path)
end
def with_unwritable_file(&block)
if Puppet::Util::Platform.windows?
with_unwritable_file_win32(&block)
else
with_unwritable_file_posix(&block)
end
end
def with_unwritable_file_win32
dir = tmpdir('pem_store')
path = File.join(dir, 'unwritable')
# if file handle is open, then file can't be written by other processes
File.open(path, 'w') do |f|
yield path
end
end
def with_unwritable_file_posix
dir = tmpdir('pem_store')
path = File.join(dir, 'unwritable')
# if directory is not executable/traverseable, then file can't be written to
Puppet::FileSystem.chmod(0, dir)
begin
yield path
ensure
Puppet::FileSystem.chmod(0700, dir)
end
end
let(:cert_path) { File.join(PuppetSpec::FIXTURE_DIR, 'ssl', 'netlock-arany-utf8.pem') }
context 'loading' do
it 'returns nil if it does not exist' do
expect(subject.load_pem('/does/not/exist')).to be_nil
end
it 'returns the file content as UTF-8' do
expect(
subject.load_pem(cert_path)
).to match(/\ANetLock Arany \(Class Gold\) Főtanúsítvány/)
end
it 'raises EACCES if the file is unreadable' do
with_unreadable_file do |path|
expect {
subject.load_pem(path)
}.to raise_error(Errno::EACCES, /Permission denied/)
end
end
end
context 'saving' do
let(:path) { tmpfile('pem_store') }
it 'writes the file content as UTF-8' do
# read the file directly to preserve the comments
utf8 = File.read(cert_path, encoding: 'UTF-8')
subject.save_pem(utf8, path)
expect(
File.read(path, :encoding => 'UTF-8')
).to match(/\ANetLock Arany \(Class Gold\) Főtanúsítvány/)
end
it 'never changes the owner and group on Windows', if: Puppet::Util::Platform.windows? do
expect(FileUtils).not_to receive(:chown)
subject.save_pem('PEM', path, owner: 'Administrator', group: 'None')
end
it 'changes the owner and group when running as root', unless: Puppet::Util::Platform.windows? do
allow(Puppet.features).to receive(:root?).and_return(true)
expect(FileUtils).to receive(:chown).with('root', 'root', path)
subject.save_pem('PEM', path, owner: 'root', group: 'root')
end
it 'does not change owner and group when running not as roo', unless: Puppet::Util::Platform.windows? do
allow(Puppet.features).to receive(:root?).and_return(false)
expect(FileUtils).not_to receive(:chown)
subject.save_pem('PEM', path, owner: 'root', group: 'root')
end
it 'allows a mode of 0600 to be specified', unless: Puppet::Util::Platform.windows? do
subject.save_pem('PEM', path, mode: 0600)
expect(File.stat(path).mode & 0777).to eq(0600)
end
it 'defaults the mode to 0644' do
subject.save_pem('PEM', path)
expect(File.stat(path).mode & 0777).to eq(0644)
end
it 'raises EACCES if the file is unwritable' do
with_unwritable_file do |path|
expect {
subject.save_pem('', path)
}.to raise_error(Errno::EACCES, /Permission denied/)
end
end
it 'raises if the directory does not exist' do
dir = tmpdir('pem_store')
Dir.unlink(dir)
expect {
subject.save_pem('', File.join(dir, 'something'))
}.to raise_error(Errno::ENOENT, /No such file or directory/)
end
end
context 'deleting' do
it 'returns false if the file does not exist' do
expect(subject.delete_pem('/does/not/exist')).to eq(false)
end
it 'returns true if the file exists' do
path = tmpfile('pem_store')
FileUtils.touch(path)
expect(subject.delete_pem(path)).to eq(true)
expect(File).to_not be_exist(path)
end
it 'raises EACCES if the file is undeletable' do
with_unwritable_file do |path|
expect {
subject.delete_pem(path)
}.to raise_error(Errno::EACCES, /Permission denied/)
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/x509/cert_provider_spec.rb | spec/unit/x509/cert_provider_spec.rb | require 'spec_helper'
require 'puppet/x509'
describe Puppet::X509::CertProvider do
include PuppetSpec::Files
def create_provider(options)
described_class.new(**options)
end
def expects_public_file(path)
if Puppet::Util::Platform.windows?
current_sid = Puppet::Util::Windows::SID.name_to_sid(Puppet::Util::Windows::ADSI::User.current_user_name)
sd = Puppet::Util::Windows::Security.get_security_descriptor(path)
expect(sd.dacl).to contain_exactly(
an_object_having_attributes(sid: Puppet::Util::Windows::SID::LocalSystem, mask: 0x1f01ff),
an_object_having_attributes(sid: Puppet::Util::Windows::SID::BuiltinAdministrators, mask: 0x1f01ff),
an_object_having_attributes(sid: current_sid, mask: 0x1f01ff),
an_object_having_attributes(sid: Puppet::Util::Windows::SID::BuiltinUsers, mask: 0x120089)
)
else
expect(File.stat(path).mode & 07777).to eq(0644)
end
end
def expects_private_file(path)
if Puppet::Util::Platform.windows?
current_sid = Puppet::Util::Windows::SID.name_to_sid(Puppet::Util::Windows::ADSI::User.current_user_name)
sd = Puppet::Util::Windows::Security.get_security_descriptor(path)
expect(sd.dacl).to contain_exactly(
an_object_having_attributes(sid: Puppet::Util::Windows::SID::LocalSystem, mask: 0x1f01ff),
an_object_having_attributes(sid: Puppet::Util::Windows::SID::BuiltinAdministrators, mask: 0x1f01ff),
an_object_having_attributes(sid: current_sid, mask: 0x1f01ff)
)
else
expect(File.stat(path).mode & 07777).to eq(0640)
end
end
let(:fixture_dir) { File.join(PuppetSpec::FIXTURE_DIR, 'ssl') }
context 'when loading' do
context 'cacerts' do
it 'returns nil if it does not exist' do
provider = create_provider(capath: '/does/not/exist')
expect(provider.load_cacerts).to be_nil
end
it 'raises if cacerts are required' do
provider = create_provider(capath: '/does/not/exist')
expect {
provider.load_cacerts(required: true)
}.to raise_error(Puppet::Error, %r{The CA certificates are missing from '/does/not/exist'})
end
it 'returns an array of certificates' do
subject = OpenSSL::X509::Name.new([['CN', 'Test CA']])
certs = create_provider(capath: File.join(fixture_dir, 'ca.pem')).load_cacerts
expect(certs).to contain_exactly(an_object_having_attributes(subject: subject))
end
context 'and input is invalid' do
it 'raises when invalid input is inside BEGIN-END block' do
ca_path = file_containing('invalid_ca', <<~END)
-----BEGIN CERTIFICATE-----
whoops
-----END CERTIFICATE-----
END
expect {
create_provider(capath: ca_path).load_cacerts
}.to raise_error(OpenSSL::X509::CertificateError)
end
it 'raises if the input is empty' do
expect {
create_provider(capath: file_containing('empty_ca', '')).load_cacerts
}.to raise_error(OpenSSL::X509::CertificateError)
end
it 'raises if the input is malformed' do
ca_path = file_containing('malformed_ca', <<~END)
-----BEGIN CERTIFICATE-----
MIIBpDCCAQ2gAwIBAgIBAjANBgkqhkiG9w0BAQsFADAfMR0wGwYDVQQDDBRUZXN0
END
expect {
create_provider(capath: ca_path).load_cacerts
}.to raise_error(OpenSSL::X509::CertificateError)
end
end
it 'raises if the cacerts are unreadable' do
capath = File.join(fixture_dir, 'ca.pem')
provider = create_provider(capath: capath)
allow(provider).to receive(:load_pem).and_raise(Errno::EACCES, 'Permission denied')
expect {
provider.load_cacerts
}.to raise_error(Puppet::Error, "Failed to load CA certificates from '#{capath}'")
end
end
context 'crls' do
it 'returns nil if it does not exist' do
provider = create_provider(crlpath: '/does/not/exist')
expect(provider.load_crls).to be_nil
end
it 'raises if CRLs are required' do
provider = create_provider(crlpath: '/does/not/exist')
expect {
provider.load_crls(required: true)
}.to raise_error(Puppet::Error, %r{The CRL is missing from '/does/not/exist'})
end
it 'returns an array of CRLs' do
issuer = OpenSSL::X509::Name.new([['CN', 'Test CA']])
crls = create_provider(crlpath: File.join(fixture_dir, 'crl.pem')).load_crls
expect(crls).to contain_exactly(an_object_having_attributes(issuer: issuer))
end
context 'and input is invalid' do
it 'raises when invalid input is inside BEGIN-END block' do
pending('jruby bug: https://github.com/jruby/jruby/issues/5619') if Puppet::Util::Platform.jruby?
crl_path = file_containing('invalid_crls', <<~END)
-----BEGIN X509 CRL-----
whoops
-----END X509 CRL-----
END
expect {
create_provider(crlpath: crl_path).load_crls
}.to raise_error(OpenSSL::X509::CRLError, /(PEM_read_bio_X509_CRL: bad base64 decode|nested asn1 error)/)
end
it 'raises if the input is empty' do
expect {
create_provider(crlpath: file_containing('empty_crl', '')).load_crls
}.to raise_error(OpenSSL::X509::CRLError, 'Failed to parse CRLs as PEM')
end
it 'raises if the input is malformed' do
crl_path = file_containing('malformed_crl', <<~END)
-----BEGIN X509 CRL-----
MIIBCjB1AgEBMA0GCSqGSIb3DQEBCwUAMBIxEDAOBgNVBAMMB1Rlc3QgQ0EXDTcw
END
expect {
create_provider(crlpath: crl_path).load_crls
}.to raise_error(OpenSSL::X509::CRLError, 'Failed to parse CRLs as PEM')
end
end
it 'raises if the CRLs are unreadable' do
crlpath = File.join(fixture_dir, 'crl.pem')
provider = create_provider(crlpath: crlpath)
allow(provider).to receive(:load_pem).and_raise(Errno::EACCES, 'Permission denied')
expect {
provider.load_crls
}.to raise_error(Puppet::Error, "Failed to load CRLs from '#{crlpath}'")
end
end
end
context 'when saving' do
context 'cacerts' do
let(:ca_path) { tmpfile('pem_cacerts') }
let(:ca_cert) { cert_fixture('ca.pem') }
it 'writes PEM encoded certs' do
create_provider(capath: ca_path).save_cacerts([ca_cert])
expect(File.read(ca_path)).to match(/\A-----BEGIN CERTIFICATE-----.*?-----END CERTIFICATE-----\Z/m)
end
it 'sets mode to 644' do
create_provider(capath: ca_path).save_cacerts([ca_cert])
expects_public_file(ca_path)
end
it 'raises if the CA certs are unwritable' do
provider = create_provider(capath: ca_path)
allow(provider).to receive(:save_pem).and_raise(Errno::EACCES, 'Permission denied')
expect {
provider.save_cacerts([ca_cert])
}.to raise_error(Puppet::Error, "Failed to save CA certificates to '#{ca_path}'")
end
end
context 'crls' do
let(:crl_path) { tmpfile('pem_crls') }
let(:ca_crl) { crl_fixture('crl.pem') }
it 'writes PEM encoded CRLs' do
create_provider(crlpath: crl_path).save_crls([ca_crl])
expect(File.read(crl_path)).to match(/\A-----BEGIN X509 CRL-----.*?-----END X509 CRL-----\Z/m)
end
it 'sets mode to 644' do
create_provider(crlpath: crl_path).save_crls([ca_crl])
expects_public_file(crl_path)
end
it 'raises if the CRLs are unwritable' do
provider = create_provider(crlpath: crl_path)
allow(provider).to receive(:save_pem).and_raise(Errno::EACCES, 'Permission denied')
expect {
provider.save_crls([ca_crl])
}.to raise_error(Puppet::Error, "Failed to save CRLs to '#{crl_path}'")
end
end
end
context 'when loading' do
context 'private keys', unless: RUBY_PLATFORM == 'java' do
let(:provider) { create_provider(privatekeydir: fixture_dir) }
let(:password) { '74695716c8b6' }
it 'returns nil if it does not exist' do
provider = create_provider(privatekeydir: '/does/not/exist')
expect(provider.load_private_key('whatever')).to be_nil
end
it 'raises if it is required' do
provider = create_provider(privatekeydir: '/does/not/exist')
expect {
provider.load_private_key('whatever', required: true)
}.to raise_error(Puppet::Error, %r{The private key is missing from '/does/not/exist/whatever.pem'})
end
it 'downcases name' do
expect(provider.load_private_key('SIGNED-KEY')).to be_a(OpenSSL::PKey::RSA)
end
it 'raises if name is invalid' do
expect {
provider.load_private_key('signed/../key')
}.to raise_error(RuntimeError, 'Certname "signed/../key" must not contain unprintable or non-ASCII characters')
end
it 'prefers `hostprivkey` if set' do
Puppet[:certname] = 'foo'
Puppet[:hostprivkey] = File.join(fixture_dir, "signed-key.pem")
expect(provider.load_private_key('foo')).to be_a(OpenSSL::PKey::RSA)
end
it 'raises if the private key is unreadable' do
allow(provider).to receive(:load_pem).and_raise(Errno::EACCES, 'Permission denied')
expect {
provider.load_private_key('signed')
}.to raise_error(Puppet::Error, "Failed to load private key for 'signed'")
end
context 'using RSA' do
it 'returns an RSA key' do
expect(provider.load_private_key('signed-key')).to be_a(OpenSSL::PKey::RSA)
end
it 'decrypts an RSA key using the password' do
rsa = provider.load_private_key('encrypted-key', password: password)
expect(rsa).to be_a(OpenSSL::PKey::RSA)
end
it 'raises without a password' do
# password is 74695716c8b6
expect {
provider.load_private_key('encrypted-key')
}.to raise_error(OpenSSL::PKey::PKeyError, /Could not parse PKey/)
end
it 'decrypts an RSA key previously saved using 3DES' do
key = key_fixture('signed-key.pem')
cipher = OpenSSL::Cipher::DES.new(:EDE3, :CBC)
privatekeydir = dir_containing('private_keys', {'oldkey.pem' => key.export(cipher, password)})
provider = create_provider(privatekeydir: privatekeydir)
expect(provider.load_private_key('oldkey', password: password).to_der).to eq(key.to_der)
end
end
context 'using EC' do
it 'returns an EC key' do
expect(provider.load_private_key('ec-key')).to be_a(OpenSSL::PKey::EC)
end
it 'returns an EC key from PKCS#8 format' do
expect(provider.load_private_key('ec-key-pk8')).to be_a(OpenSSL::PKey::EC)
end
it 'returns an EC key from openssl format' do
expect(provider.load_private_key('ec-key-openssl')).to be_a(OpenSSL::PKey::EC)
end
it 'decrypts an EC key using the password' do
ec = provider.load_private_key('encrypted-ec-key', password: password)
expect(ec).to be_a(OpenSSL::PKey::EC)
end
it 'raises without a password' do
# password is 74695716c8b6
expect {
provider.load_private_key('encrypted-ec-key')
}.to raise_error(OpenSSL::PKey::PKeyError, /(unknown|invalid) curve name|Could not parse PKey/)
end
end
end
context 'certs' do
let(:provider) { create_provider(certdir: fixture_dir) }
it 'returns nil if it does not exist' do
provider = create_provider(certdir: '/does/not/exist')
expect(provider.load_client_cert('nonexistent')).to be_nil
end
it 'raises if it is required' do
provider = create_provider(certdir: '/does/not/exist')
expect {
provider.load_client_cert('nonexistent', required: true)
}.to raise_error(Puppet::Error, %r{The client certificate is missing from '/does/not/exist/nonexistent.pem'})
end
it 'returns a certificate' do
cert = provider.load_client_cert('signed')
expect(cert.subject.to_utf8).to eq('CN=signed')
end
it 'downcases name' do
cert = provider.load_client_cert('SIGNED')
expect(cert.subject.to_utf8).to eq('CN=signed')
end
it 'raises if name is invalid' do
expect {
provider.load_client_cert('tom/../key')
}.to raise_error(RuntimeError, 'Certname "tom/../key" must not contain unprintable or non-ASCII characters')
end
it 'prefers `hostcert` if set' do
Puppet[:certname] = 'foo'
Puppet[:hostcert] = File.join(fixture_dir, "signed.pem")
expect(provider.load_client_cert('foo')).to be_a(OpenSSL::X509::Certificate)
end
it 'raises if the certificate is unreadable' do
allow(provider).to receive(:load_pem).and_raise(Errno::EACCES, 'Permission denied')
expect {
provider.load_client_cert('signed')
}.to raise_error(Puppet::Error, "Failed to load client certificate for 'signed'")
end
end
context 'requests' do
let(:request) { request_fixture('request.pem') }
let(:provider) { create_provider(requestdir: fixture_dir) }
it 'returns nil if it does not exist' do
expect(provider.load_request('whatever')).to be_nil
end
it 'returns a request' do
expect(provider.load_request('request')).to be_a(OpenSSL::X509::Request)
end
it 'downcases name' do
csr = provider.load_request('REQUEST')
expect(csr.subject.to_utf8).to eq('CN=pending')
end
it 'raises if name is invalid' do
expect {
provider.load_request('tom/../key')
}.to raise_error(RuntimeError, 'Certname "tom/../key" must not contain unprintable or non-ASCII characters')
end
it 'ignores `hostcsr`' do
Puppet[:hostcsr] = File.join(fixture_dir, "doesnotexist.pem")
expect(provider.load_request('request')).to be_a(OpenSSL::X509::Request)
end
it 'raises if the certificate is unreadable' do
allow(provider).to receive(:load_pem).and_raise(Errno::EACCES, 'Permission denied')
expect {
provider.load_request('pending')
}.to raise_error(Puppet::Error, "Failed to load certificate request for 'pending'")
end
end
end
context 'when saving' do
let(:name) { 'tom' }
context 'private keys' do
let(:privatekeydir) { tmpdir('privatekeydir') }
let(:private_key) { key_fixture('signed-key.pem') }
let(:path) { File.join(privatekeydir, 'tom.pem') }
let(:provider) { create_provider(privatekeydir: privatekeydir) }
it 'writes PEM encoded private key' do
provider.save_private_key(name, private_key)
expect(File.read(path)).to match(/\A-----BEGIN RSA PRIVATE KEY-----.*?-----END RSA PRIVATE KEY-----\Z/m)
end
it 'encrypts the private key using AES128-CBC' do
provider.save_private_key(name, private_key, password: Random.new.bytes(8))
expect(File.read(path)).to match(/Proc-Type: 4,ENCRYPTED.*DEK-Info: AES-128-CBC/m)
end
it 'sets mode to 640' do
provider.save_private_key(name, private_key)
expects_private_file(path)
end
it 'downcases name' do
provider.save_private_key('TOM', private_key)
expect(File).to be_exist(path)
end
it 'raises if name is invalid' do
expect {
provider.save_private_key('tom/../key', private_key)
}.to raise_error(RuntimeError, 'Certname "tom/../key" must not contain unprintable or non-ASCII characters')
end
it 'raises if the private key is unwritable' do
allow(provider).to receive(:save_pem).and_raise(Errno::EACCES, 'Permission denied')
expect {
provider.save_private_key(name, private_key)
}.to raise_error(Puppet::Error, "Failed to save private key for '#{name}'")
end
it 'prefers `hostprivkey` if set' do
overridden_path = tmpfile('hostprivkey')
Puppet[:hostprivkey] = overridden_path
provider.save_private_key(name, private_key)
expect(File).to_not exist(path)
expect(File).to exist(overridden_path)
end
end
context 'certs' do
let(:certdir) { tmpdir('certdir') }
let(:client_cert) { cert_fixture('signed.pem') }
let(:path) { File.join(certdir, 'tom.pem') }
let(:provider) { create_provider(certdir: certdir) }
it 'writes PEM encoded cert' do
provider.save_client_cert(name, client_cert)
expect(File.read(path)).to match(/\A-----BEGIN CERTIFICATE-----.*?-----END CERTIFICATE-----\Z/m)
end
it 'sets mode to 644' do
provider.save_client_cert(name, client_cert)
expects_public_file(path)
end
it 'downcases name' do
provider.save_client_cert('TOM', client_cert)
expect(File).to be_exist(path)
end
it 'raises if name is invalid' do
expect {
provider.save_client_cert('tom/../key', client_cert)
}.to raise_error(RuntimeError, 'Certname "tom/../key" must not contain unprintable or non-ASCII characters')
end
it 'raises if the cert is unwritable' do
allow(provider).to receive(:save_pem).and_raise(Errno::EACCES, 'Permission denied')
expect {
provider.save_client_cert(name, client_cert)
}.to raise_error(Puppet::Error, "Failed to save client certificate for '#{name}'")
end
it 'prefers `hostcert` if set' do
overridden_path = tmpfile('hostcert')
Puppet[:hostcert] = overridden_path
provider.save_client_cert(name, client_cert)
expect(File).to_not exist(path)
expect(File).to exist(overridden_path)
end
end
context 'requests' do
let(:requestdir) { tmpdir('requestdir') }
let(:csr) { request_fixture('request.pem') }
let(:path) { File.join(requestdir, 'tom.pem') }
let(:provider) { create_provider(requestdir: requestdir) }
it 'writes PEM encoded request' do
provider.save_request(name, csr)
expect(File.read(path)).to match(/\A-----BEGIN CERTIFICATE REQUEST-----.*?-----END CERTIFICATE REQUEST-----\Z/m)
end
it 'sets mode to 644' do
provider.save_request(name, csr)
expects_public_file(path)
end
it 'downcases name' do
provider.save_request('TOM', csr)
expect(File).to be_exist(path)
end
it 'raises if name is invalid' do
expect {
provider.save_request('tom/../key', csr)
}.to raise_error(RuntimeError, 'Certname "tom/../key" must not contain unprintable or non-ASCII characters')
end
it 'raises if the request is unwritable' do
allow(provider).to receive(:save_pem).and_raise(Errno::EACCES, 'Permission denied')
expect {
provider.save_request(name, csr)
}.to raise_error(Puppet::Error, "Failed to save certificate request for '#{name}'")
end
end
end
context 'when deleting' do
context 'requests' do
let(:name) { 'jerry' }
let(:requestdir) { tmpdir('cert_provider') }
let(:provider) { create_provider(requestdir: requestdir) }
it 'returns true if request was deleted' do
path = File.join(requestdir, "#{name}.pem")
File.write(path, "PEM")
expect(provider.delete_request(name)).to eq(true)
expect(File).not_to be_exist(path)
end
it 'returns false if the request is non-existent' do
path = File.join(requestdir, "#{name}.pem")
expect(provider.delete_request(name)).to eq(false)
expect(File).to_not be_exist(path)
end
it 'raises if the file is undeletable' do
allow(provider).to receive(:delete_pem).and_raise(Errno::EACCES, 'Permission denied')
expect {
provider.delete_request(name)
}.to raise_error(Puppet::Error, "Failed to delete certificate request for '#{name}'")
end
end
end
context 'when creating', :unless => RUBY_PLATFORM == 'java' do
context 'requests' do
let(:name) { 'tom' }
let(:requestdir) { tmpdir('cert_provider') }
let(:provider) { create_provider(requestdir: requestdir) }
let(:key) { OpenSSL::PKey::RSA.new(Puppet[:keylength]) }
it 'has the auto-renew attribute by default for agents that support automatic renewal' do
csr = provider.create_request(name, key)
# need to create CertificateRequest instance from csr in order to view CSR attributes
wrapped_csr = Puppet::SSL::CertificateRequest.from_instance csr
expect(wrapped_csr.custom_attributes).to include('oid' => 'pp_auth_auto_renew', 'value' => 'true')
end
it 'does not have the auto-renew attribute for agents that do not support automatic renewal' do
Puppet[:hostcert_renewal_interval] = 0
csr = provider.create_request(name, key)
wrapped_csr = Puppet::SSL::CertificateRequest.from_instance csr
expect(wrapped_csr.custom_attributes.length).to eq(0)
end
end
end
context 'CA last update time' do
let(:ca_path) { tmpfile('pem_ca') }
it 'returns nil if the CA does not exist' do
provider = create_provider(capath: '/does/not/exist')
expect(provider.ca_last_update).to be_nil
end
it 'returns the last update time' do
time = Time.now - 30
Puppet::FileSystem.touch(ca_path, mtime: time)
provider = create_provider(capath: ca_path)
expect(provider.ca_last_update).to be_within(1).of(time)
end
it 'sets the last update time' do
time = Time.now - 30
provider = create_provider(capath: ca_path)
provider.ca_last_update = time
expect(Puppet::FileSystem.stat(ca_path).mtime).to be_within(1).of(time)
end
end
context 'CRL last update time' do
let(:crl_path) { tmpfile('pem_crls') }
it 'returns nil if the CRL does not exist' do
provider = create_provider(crlpath: '/does/not/exist')
expect(provider.crl_last_update).to be_nil
end
it 'returns the last update time' do
time = Time.now - 30
Puppet::FileSystem.touch(crl_path, mtime: time)
provider = create_provider(crlpath: crl_path)
expect(provider.crl_last_update).to be_within(1).of(time)
end
it 'sets the last update time' do
time = Time.now - 30
provider = create_provider(crlpath: crl_path)
provider.crl_last_update = time
expect(Puppet::FileSystem.stat(crl_path).mtime).to be_within(1).of(time)
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/profiler_spec.rb | spec/unit/util/profiler_spec.rb | require 'spec_helper'
require 'puppet/util/profiler'
describe Puppet::Util::Profiler do
let(:profiler) { TestProfiler.new() }
it "supports adding profilers" do
subject.add_profiler(profiler)
expect(subject.current[0]).to eq(profiler)
end
it "supports removing profilers" do
subject.add_profiler(profiler)
subject.remove_profiler(profiler)
expect(subject.current.length).to eq(0)
end
it "supports clearing profiler list" do
subject.add_profiler(profiler)
subject.clear
expect(subject.current.length).to eq(0)
end
it "supports profiling" do
subject.add_profiler(profiler)
subject.profile("hi", ["mymetric"]) {}
expect(profiler.context[:metric_id]).to eq(["mymetric"])
expect(profiler.context[:description]).to eq("hi")
expect(profiler.description).to eq("hi")
end
class TestProfiler
attr_accessor :context, :metric, :description
def start(description, metric_id)
{:metric_id => metric_id,
:description => description}
end
def finish(context, description, metric_id)
@context = context
@metric_id = metric_id
@description = description
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/splayer_spec.rb | spec/unit/util/splayer_spec.rb | require 'spec_helper'
require 'puppet/util/splayer'
describe Puppet::Util::Splayer do
include Puppet::Util::Splayer
let (:subject) { self }
before do
Puppet[:splay] = true
Puppet[:splaylimit] = "10"
end
it "should do nothing if splay is disabled" do
Puppet[:splay] = false
expect(subject).not_to receive(:sleep)
subject.splay
end
it "should do nothing if it has already splayed" do
expect(subject).to receive(:splayed?).and_return(true)
expect(subject).not_to receive(:sleep)
subject.splay
end
it "should log that it is splaying" do
allow(subject).to receive(:sleep)
expect(Puppet).to receive(:info)
subject.splay
end
it "should sleep for a random portion of the splaylimit plus 1" do
Puppet[:splaylimit] = "50"
expect(subject).to receive(:rand).with(51).and_return(10)
expect(subject).to receive(:sleep).with(10)
subject.splay
end
it "should mark that it has splayed" do
allow(subject).to receive(:sleep)
subject.splay
expect(subject).to be_splayed
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/monkey_patches_spec.rb | spec/unit/util/monkey_patches_spec.rb | require 'spec_helper'
require 'puppet/util/monkey_patches'
describe Dir do
describe '.exists?' do
it 'returns false if the directory does not exist' do
expect(Dir.exists?('/madeupdirectory')).to be false
end
it 'returns true if the directory exists' do
expect(Dir.exists?(__dir__)).to be true
end
if RUBY_VERSION >= '3.2'
it 'logs a warning message' do
expect(Dir).to receive(:warn).with("Dir.exists?('#{__dir__}') is deprecated, use Dir.exist? instead")
with_verbose_enabled do
Dir.exists?(__dir__)
end
end
end
end
end
describe File do
describe '.exists?' do
it 'returns false if the directory does not exist' do
expect(File.exists?('spec/unit/util/made_up_file')).to be false
end
it 'returns true if the file exists' do
expect(File.exists?(__FILE__)).to be true
end
if RUBY_VERSION >= '3.2'
it 'logs a warning message' do
expect(File).to receive(:warn).with("File.exists?('#{__FILE__}') is deprecated, use File.exist? instead")
with_verbose_enabled do
File.exists?(__FILE__)
end
end
end
end
end
describe Symbol do
after :all do
$unique_warnings.delete('symbol_comparison') if $unique_warnings
end
it 'should have an equal? that is not true for a string with same letters' do
symbol = :undef
expect(symbol).to_not equal('undef')
end
it "should have an eql? that is not true for a string with same letters" do
symbol = :undef
expect(symbol).to_not eql('undef')
end
it "should have an == that is not true for a string with same letters" do
symbol = :undef
expect(symbol == 'undef').to_not be(true)
end
it "should return self from #intern" do
symbol = :foo
expect(symbol).to equal symbol.intern
end
end
describe OpenSSL::SSL::SSLContext do
it 'disables SSLv3 via the SSLContext#options bitmask' do
expect(subject.options & OpenSSL::SSL::OP_NO_SSLv3).to eq(OpenSSL::SSL::OP_NO_SSLv3)
end
it 'does not exclude SSLv3 ciphers shared with TLSv1' do
cipher_str = OpenSSL::SSL::SSLContext::DEFAULT_PARAMS[:ciphers]
if cipher_str
expect(cipher_str.split(':')).not_to include('!SSLv3')
end
end
it 'sets parameters on initialization' do
expect_any_instance_of(described_class).to receive(:set_params)
subject
end
end
describe OpenSSL::X509::Store, :if => Puppet::Util::Platform.windows? do
let(:store) { described_class.new }
let(:cert) { OpenSSL::X509::Certificate.new(File.read(my_fixture('x509.pem'))) }
let(:samecert) { cert.dup() }
def with_root_certs(certs)
expect(Puppet::Util::Windows::RootCerts).to receive(:instance).and_return(certs)
end
it "adds a root cert to the store" do
with_root_certs([cert])
store.set_default_paths
end
it "doesn't warn when calling set_default_paths multiple times" do
with_root_certs([cert])
expect(store).not_to receive(:warn)
store.set_default_paths
store.set_default_paths
end
it "ignores duplicate root certs" do
# prove that even though certs have identical contents, their hashes differ
expect(cert.hash).to_not eq(samecert.hash)
with_root_certs([cert, samecert])
expect(store).to receive(:add_cert).with(cert).once
expect(store).not_to receive(:add_cert).with(samecert)
store.set_default_paths
end
# openssl 1.1.1 ignores duplicate certs
# https://github.com/openssl/openssl/commit/c0452248ea1a59a41023a4765ef7d9825e80a62b
if OpenSSL::OPENSSL_VERSION_NUMBER < 0x10101000
it "warns when adding a certificate that already exists" do
with_root_certs([cert])
store.add_cert(cert)
expect(store).to receive(:warn).with('Failed to add CN=Microsoft Root Certificate Authority,DC=microsoft,DC=com')
store.set_default_paths
end
else
it "doesn't warn when adding a duplicate cert" do
with_root_certs([cert])
store.add_cert(cert)
expect(store).not_to receive(:warn)
store.set_default_paths
end
end
it "raises when adding an invalid certificate" do
with_root_certs(['notacert'])
expect {
store.set_default_paths
}.to raise_error(TypeError)
end
end
describe SecureRandom do
it 'generates a properly formatted uuid' do
expect(SecureRandom.uuid).to match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/rpm_compare_spec.rb | spec/unit/util/rpm_compare_spec.rb | # frozen_string_literal: true
require 'spec_helper'
require 'puppet/util/rpm_compare'
describe Puppet::Util::RpmCompare do
class RpmTest
extend Puppet::Util::RpmCompare
end
describe '.rpmvercmp' do
# test cases munged directly from rpm's own
# tests/rpmvercmp.at
it { expect(RpmTest.rpmvercmp('1.0', '1.0')).to eq(0) }
it { expect(RpmTest.rpmvercmp('1.0', '2.0')).to eq(-1) }
it { expect(RpmTest.rpmvercmp('2.0', '1.0')).to eq(1) }
it { expect(RpmTest.rpmvercmp('2.0.1', '2.0.1')).to eq(0) }
it { expect(RpmTest.rpmvercmp('2.0', '2.0.1')).to eq(-1) }
it { expect(RpmTest.rpmvercmp('2.0.1', '2.0')).to eq(1) }
it { expect(RpmTest.rpmvercmp('2.0.1a', '2.0.1a')).to eq(0) }
it { expect(RpmTest.rpmvercmp('2.0.1a', '2.0.1')).to eq(1) }
it { expect(RpmTest.rpmvercmp('2.0.1', '2.0.1a')).to eq(-1) }
it { expect(RpmTest.rpmvercmp('5.5p1', '5.5p1')).to eq(0) }
it { expect(RpmTest.rpmvercmp('5.5p1', '5.5p2')).to eq(-1) }
it { expect(RpmTest.rpmvercmp('5.5p2', '5.5p1')).to eq(1) }
it { expect(RpmTest.rpmvercmp('5.5p10', '5.5p10')).to eq(0) }
it { expect(RpmTest.rpmvercmp('5.5p1', '5.5p10')).to eq(-1) }
it { expect(RpmTest.rpmvercmp('5.5p10', '5.5p1')).to eq(1) }
it { expect(RpmTest.rpmvercmp('10xyz', '10.1xyz')).to eq(-1) }
it { expect(RpmTest.rpmvercmp('10.1xyz', '10xyz')).to eq(1) }
it { expect(RpmTest.rpmvercmp('xyz10', 'xyz10')).to eq(0) }
it { expect(RpmTest.rpmvercmp('xyz10', 'xyz10.1')).to eq(-1) }
it { expect(RpmTest.rpmvercmp('xyz10.1', 'xyz10')).to eq(1) }
it { expect(RpmTest.rpmvercmp('xyz.4', 'xyz.4')).to eq(0) }
it { expect(RpmTest.rpmvercmp('xyz.4', '8')).to eq(-1) }
it { expect(RpmTest.rpmvercmp('8', 'xyz.4')).to eq(1) }
it { expect(RpmTest.rpmvercmp('xyz.4', '2')).to eq(-1) }
it { expect(RpmTest.rpmvercmp('2', 'xyz.4')).to eq(1) }
it { expect(RpmTest.rpmvercmp('5.5p2', '5.6p1')).to eq(-1) }
it { expect(RpmTest.rpmvercmp('5.6p1', '5.5p2')).to eq(1) }
it { expect(RpmTest.rpmvercmp('5.6p1', '6.5p1')).to eq(-1) }
it { expect(RpmTest.rpmvercmp('6.5p1', '5.6p1')).to eq(1) }
it { expect(RpmTest.rpmvercmp('6.0.rc1', '6.0')).to eq(1) }
it { expect(RpmTest.rpmvercmp('6.0', '6.0.rc1')).to eq(-1) }
it { expect(RpmTest.rpmvercmp('10b2', '10a1')).to eq(1) }
it { expect(RpmTest.rpmvercmp('10a2', '10b2')).to eq(-1) }
it { expect(RpmTest.rpmvercmp('1.0aa', '1.0aa')).to eq(0) }
it { expect(RpmTest.rpmvercmp('1.0a', '1.0aa')).to eq(-1) }
it { expect(RpmTest.rpmvercmp('1.0aa', '1.0a')).to eq(1) }
it { expect(RpmTest.rpmvercmp('10.0001', '10.0001')).to eq(0) }
it { expect(RpmTest.rpmvercmp('10.0001', '10.1')).to eq(0) }
it { expect(RpmTest.rpmvercmp('10.1', '10.0001')).to eq(0) }
it { expect(RpmTest.rpmvercmp('10.0001', '10.0039')).to eq(-1) }
it { expect(RpmTest.rpmvercmp('10.0039', '10.0001')).to eq(1) }
it { expect(RpmTest.rpmvercmp('4.999.9', '5.0')).to eq(-1) }
it { expect(RpmTest.rpmvercmp('5.0', '4.999.9')).to eq(1) }
it { expect(RpmTest.rpmvercmp('20101121', '20101121')).to eq(0) }
it { expect(RpmTest.rpmvercmp('20101121', '20101122')).to eq(-1) }
it { expect(RpmTest.rpmvercmp('20101122', '20101121')).to eq(1) }
it { expect(RpmTest.rpmvercmp('2_0', '2_0')).to eq(0) }
it { expect(RpmTest.rpmvercmp('2.0', '2_0')).to eq(0) }
it { expect(RpmTest.rpmvercmp('2_0', '2.0')).to eq(0) }
it { expect(RpmTest.rpmvercmp('a', 'a')).to eq(0) }
it { expect(RpmTest.rpmvercmp('a+', 'a+')).to eq(0) }
it { expect(RpmTest.rpmvercmp('a+', 'a_')).to eq(0) }
it { expect(RpmTest.rpmvercmp('a_', 'a+')).to eq(0) }
it { expect(RpmTest.rpmvercmp('+a', '+a')).to eq(0) }
it { expect(RpmTest.rpmvercmp('+a', '_a')).to eq(0) }
it { expect(RpmTest.rpmvercmp('_a', '+a')).to eq(0) }
it { expect(RpmTest.rpmvercmp('+_', '+_')).to eq(0) }
it { expect(RpmTest.rpmvercmp('_+', '+_')).to eq(0) }
it { expect(RpmTest.rpmvercmp('_+', '_+')).to eq(0) }
it { expect(RpmTest.rpmvercmp('+', '_')).to eq(0) }
it { expect(RpmTest.rpmvercmp('_', '+')).to eq(0) }
it { expect(RpmTest.rpmvercmp('1.0~rc1', '1.0~rc1')).to eq(0) }
it { expect(RpmTest.rpmvercmp('1.0~rc1', '1.0')).to eq(-1) }
it { expect(RpmTest.rpmvercmp('1.0', '1.0~rc1')).to eq(1) }
it { expect(RpmTest.rpmvercmp('1.0~rc1', '1.0~rc2')).to eq(-1) }
it { expect(RpmTest.rpmvercmp('1.0~rc2', '1.0~rc1')).to eq(1) }
it { expect(RpmTest.rpmvercmp('1.0~rc1~git123', '1.0~rc1~git123')).to eq(0) }
it { expect(RpmTest.rpmvercmp('1.0~rc1~git123', '1.0~rc1')).to eq(-1) }
it { expect(RpmTest.rpmvercmp('1.0~rc1', '1.0~rc1~git123')).to eq(1) }
it { expect(RpmTest.rpmvercmp('1.0~rc1', '1.0arc1')).to eq(-1) }
it { expect(RpmTest.rpmvercmp('', '~')).to eq(1) }
it { expect(RpmTest.rpmvercmp('~', '~~')).to eq(1) }
it { expect(RpmTest.rpmvercmp('~', '~+~')).to eq(1) }
it { expect(RpmTest.rpmvercmp('~', '~a')).to eq(-1) }
# non-upstream test cases
it { expect(RpmTest.rpmvercmp('405', '406')).to eq(-1) }
it { expect(RpmTest.rpmvercmp('1', '0')).to eq(1) }
end
describe '.rpm_compare_evr' do
it 'evaluates identical version-release as equal' do
expect(RpmTest.rpm_compare_evr('1.2.3-1.el5', '1.2.3-1.el5')).to eq(0)
end
it 'evaluates identical version as equal' do
expect(RpmTest.rpm_compare_evr('1.2.3', '1.2.3')).to eq(0)
end
it 'evaluates identical version but older release as less' do
expect(RpmTest.rpm_compare_evr('1.2.3-1.el5', '1.2.3-2.el5')).to eq(-1)
end
it 'evaluates identical version but newer release as greater' do
expect(RpmTest.rpm_compare_evr('1.2.3-3.el5', '1.2.3-2.el5')).to eq(1)
end
it 'evaluates a newer epoch as greater' do
expect(RpmTest.rpm_compare_evr('1:1.2.3-4.5', '1.2.3-4.5')).to eq(1)
end
# these tests describe PUP-1244 logic yet to be implemented
it 'evaluates any version as equal to the same version followed by release' do
expect(RpmTest.rpm_compare_evr('1.2.3', '1.2.3-2.el5')).to eq(0)
end
# test cases for PUP-682
it 'evaluates same-length numeric revisions numerically' do
expect(RpmTest.rpm_compare_evr('2.2-405', '2.2-406')).to eq(-1)
end
end
describe '.rpm_parse_evr' do
it 'parses full simple evr' do
version = RpmTest.rpm_parse_evr('0:1.2.3-4.el5')
expect([version[:epoch], version[:version], version[:release]]).to \
eq(['0', '1.2.3', '4.el5'])
end
it 'parses version only' do
version = RpmTest.rpm_parse_evr('1.2.3')
expect([version[:epoch], version[:version], version[:release]]).to \
eq([nil, '1.2.3', nil])
end
it 'parses version-release' do
version = RpmTest.rpm_parse_evr('1.2.3-4.5.el6')
expect([version[:epoch], version[:version], version[:release]]).to \
eq([nil, '1.2.3', '4.5.el6'])
end
it 'parses release with git hash' do
version = RpmTest.rpm_parse_evr('1.2.3-4.1234aefd')
expect([version[:epoch], version[:version], version[:release]]).to \
eq([nil, '1.2.3', '4.1234aefd'])
end
it 'parses single integer versions' do
version = RpmTest.rpm_parse_evr('12345')
expect([version[:epoch], version[:version], version[:release]]).to \
eq([nil, '12345', nil])
end
it 'parses text in the epoch to 0' do
version = RpmTest.rpm_parse_evr('foo0:1.2.3-4')
expect([version[:epoch], version[:version], version[:release]]).to \
eq([nil, '1.2.3', '4'])
end
it 'parses revisions with text' do
version = RpmTest.rpm_parse_evr('1.2.3-SNAPSHOT20140107')
expect([version[:epoch], version[:version], version[:release]]).to \
eq([nil, '1.2.3', 'SNAPSHOT20140107'])
end
# test cases for PUP-682
it 'parses revisions with text and numbers' do
version = RpmTest.rpm_parse_evr('2.2-SNAPSHOT20121119105647')
expect([version[:epoch], version[:version], version[:release]]).to \
eq([nil, '2.2', 'SNAPSHOT20121119105647'])
end
it 'parses .noarch' do
version = RpmTest.rpm_parse_evr('3.0.12-1.el5.centos.noarch')
expect(version[:arch]).to eq('noarch')
end
end
describe '.compare_values' do
it 'treats two nil values as equal' do
expect(RpmTest.compare_values(nil, nil)).to eq(0)
end
it 'treats a nil value as less than a non-nil value' do
expect(RpmTest.compare_values(nil, '0')).to eq(-1)
end
it 'treats a non-nil value as greater than a nil value' do
expect(RpmTest.compare_values('0', nil)).to eq(1)
end
it 'passes two non-nil values on to rpmvercmp' do
allow(RpmTest).to receive(:rpmvercmp).and_return(0)
expect(RpmTest).to receive(:rpmvercmp).with('s1', 's2')
RpmTest.compare_values('s1', 's2')
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/terminal_spec.rb | spec/unit/util/terminal_spec.rb | require 'spec_helper'
require 'puppet/util/terminal'
describe Puppet::Util::Terminal do
describe '.width' do
before { allow(Puppet.features).to receive(:posix?).and_return(true) }
it 'should invoke `stty` and return the width' do
height, width = 100, 200
expect(subject).to receive(:`).with('stty size 2>/dev/null').and_return("#{height} #{width}\n")
expect(subject.width).to eq(width)
end
it 'should use `tput` if `stty` is unavailable' do
width = 200
expect(subject).to receive(:`).with('stty size 2>/dev/null').and_return("\n")
expect(subject).to receive(:`).with('tput cols 2>/dev/null').and_return("#{width}\n")
expect(subject.width).to eq(width)
end
it 'should default to 80 columns if `tput` and `stty` are unavailable' do
width = 80
expect(subject).to receive(:`).with('stty size 2>/dev/null').and_return("\n")
expect(subject).to receive(:`).with('tput cols 2>/dev/null').and_return("\n")
expect(subject.width).to eq(width)
end
it 'should default to 80 columns if `tput` or `stty` raise exceptions' do
width = 80
expect(subject).to receive(:`).with('stty size 2>/dev/null').and_raise()
allow(subject).to receive(:`).with('tput cols 2>/dev/null').and_return("#{width + 1000}\n")
expect(subject.width).to eq(width)
end
it 'should default to 80 columns if not in a POSIX environment' do
width = 80
allow(Puppet.features).to receive(:posix?).and_return(false)
expect(subject.width).to eq(width)
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/at_fork_spec.rb | spec/unit/util/at_fork_spec.rb | require 'spec_helper'
describe 'Puppet::Util::AtFork' do
EXPECTED_HANDLER_METHODS = [:prepare, :parent, :child]
before :each do
Puppet::Util.class_exec do
remove_const(:AtFork) if defined?(Puppet::Util::AtFork)
const_set(:AtFork, Module.new)
end
end
after :each do
Puppet::Util.class_exec do
remove_const(:AtFork)
end
end
describe '.get_handler' do
context 'when on Solaris' do
before :each do
expect(Puppet::Util::Platform).to receive(:solaris?).and_return(true)
end
after :each do
Object.class_exec do
remove_const(:Fiddle) if const_defined?(:Fiddle)
end
end
def stub_solaris_handler(stub_noop_too = false)
allow(Puppet::Util::AtFork).to receive(:require_relative).with(anything) do |lib|
if lib == 'at_fork/solaris'
load 'puppet/util/at_fork/solaris.rb'
true
elsif stub_noop_too && lib == 'at_fork/noop'
Puppet::Util::AtFork.class_exec do
const_set(:Noop, Class.new)
end
true
else
false
end
end.and_return(true)
unless stub_noop_too
Object.class_exec do
const_set(:Fiddle, Module.new do
const_set(:TYPE_VOIDP, nil)
const_set(:TYPE_VOID, nil)
const_set(:TYPE_INT, nil)
const_set(:DLError, Class.new(StandardError))
const_set(:Handle, Class.new { def initialize(library = nil, flags = 0); end })
const_set(:Function, Class.new { def initialize(ptr, args, ret_type, abi = 0); end })
end)
end
end
allow(TOPLEVEL_BINDING.eval('self')).to receive(:require).with(anything) do |lib|
if lib == 'fiddle'
raise LoadError, 'no fiddle' if stub_noop_too
else
Kernel.require lib
end
true
end.and_return(true)
end
it %q(should return the Solaris specific AtFork handler) do
allow(Puppet::Util::AtFork).to receive(:require_relative).with(anything) do |lib|
if lib == 'at_fork/solaris'
Puppet::Util::AtFork.class_exec do
const_set(:Solaris, Class.new)
end
true
else
false
end
end.and_return(true)
load 'puppet/util/at_fork.rb'
expect(Puppet::Util::AtFork.get_handler.class).to eq(Puppet::Util::AtFork::Solaris)
end
it %q(should return the Noop handler when Fiddle could not be loaded) do
stub_solaris_handler(true)
load 'puppet/util/at_fork.rb'
expect(Puppet::Util::AtFork.get_handler.class).to eq(Puppet::Util::AtFork::Noop)
end
it %q(should fail when libcontract cannot be loaded) do
stub_solaris_handler
expect(Fiddle::Handle).to receive(:new).with(/^libcontract.so.*/).and_raise(Fiddle::DLError, 'no such library')
expect { load 'puppet/util/at_fork.rb' }.to raise_error(Fiddle::DLError, 'no such library')
end
it %q(should fail when libcontract doesn't define all the necessary functions) do
stub_solaris_handler
handle = double('Fiddle::Handle')
expect(Fiddle::Handle).to receive(:new).with(/^libcontract.so.*/).and_return(handle)
expect(handle).to receive(:[]).and_raise(Fiddle::DLError, 'no such method')
expect { load 'puppet/util/at_fork.rb' }.to raise_error(Fiddle::DLError, 'no such method')
end
it %q(the returned Solaris specific handler should respond to the expected methods) do
stub_solaris_handler
handle = double('Fiddle::Handle')
expect(Fiddle::Handle).to receive(:new).with(/^libcontract.so.*/).and_return(handle)
allow(handle).to receive(:[]).and_return(nil)
allow(Fiddle::Function).to receive(:new).and_return(Proc.new {})
load 'puppet/util/at_fork.rb'
expect(Puppet::Util::AtFork.get_handler.public_methods).to include(*EXPECTED_HANDLER_METHODS)
end
end
context 'when NOT on Solaris' do
before :each do
expect(Puppet::Util::Platform).to receive(:solaris?).and_return(false)
end
def stub_noop_handler(namespace_only = false)
allow(Puppet::Util::AtFork).to receive(:require_relative).with(anything) do |lib|
if lib == 'at_fork/noop'
if namespace_only
Puppet::Util::AtFork.class_exec do
const_set(:Noop, Class.new)
end
else
load 'puppet/util/at_fork/noop.rb'
end
true
else
false
end
end.and_return(true)
end
it %q(should return the Noop AtFork handler) do
stub_noop_handler(true)
load 'puppet/util/at_fork.rb'
expect(Puppet::Util::AtFork.get_handler.class).to eq(Puppet::Util::AtFork::Noop)
end
it %q(the returned Noop handler should respond to the expected methods) do
stub_noop_handler
load 'puppet/util/at_fork.rb'
expect(Puppet::Util::AtFork.get_handler.public_methods).to include(*EXPECTED_HANDLER_METHODS)
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/retry_action_spec.rb | spec/unit/util/retry_action_spec.rb | require 'spec_helper'
require 'puppet/util/retry_action'
describe Puppet::Util::RetryAction do
let (:exceptions) { [ Puppet::Error, NameError ] }
it "doesn't retry SystemExit" do
expect do
Puppet::Util::RetryAction.retry_action( :retries => 0 ) do
raise SystemExit
end
end.to exit_with(0)
end
it "doesn't retry NoMemoryError" do
expect do
Puppet::Util::RetryAction.retry_action( :retries => 0 ) do
raise NoMemoryError, "OOM"
end
end.to raise_error(NoMemoryError, /OOM/)
end
it 'should retry on any exception if no acceptable exceptions given' do
expect(Puppet::Util::RetryAction).to receive(:sleep).with( (((2 ** 1) -1) * 0.1) )
expect(Puppet::Util::RetryAction).to receive(:sleep).with( (((2 ** 2) -1) * 0.1) )
expect do
Puppet::Util::RetryAction.retry_action( :retries => 2 ) do
raise ArgumentError, 'Fake Failure'
end
end.to raise_exception(Puppet::Util::RetryAction::RetryException::RetriesExceeded)
end
it 'should retry on acceptable exceptions' do
expect(Puppet::Util::RetryAction).to receive(:sleep).with( (((2 ** 1) -1) * 0.1) )
expect(Puppet::Util::RetryAction).to receive(:sleep).with( (((2 ** 2) -1) * 0.1) )
expect do
Puppet::Util::RetryAction.retry_action( :retries => 2, :retry_exceptions => exceptions) do
raise Puppet::Error, 'Fake Failure'
end
end.to raise_exception(Puppet::Util::RetryAction::RetryException::RetriesExceeded)
end
it 'should not retry on unacceptable exceptions' do
expect(Puppet::Util::RetryAction).not_to receive(:sleep)
expect do
Puppet::Util::RetryAction.retry_action( :retries => 2, :retry_exceptions => exceptions) do
raise ArgumentError
end
end.to raise_exception(ArgumentError)
end
it 'should succeed if nothing is raised' do
expect(Puppet::Util::RetryAction).not_to receive(:sleep)
Puppet::Util::RetryAction.retry_action( :retries => 2) do
true
end
end
it 'should succeed if an expected exception is raised retried and succeeds' do
should_retry = nil
expect(Puppet::Util::RetryAction).to receive(:sleep).once
Puppet::Util::RetryAction.retry_action( :retries => 2, :retry_exceptions => exceptions) do
if should_retry
true
else
should_retry = true
raise Puppet::Error, 'Fake error'
end
end
end
it "doesn't mutate caller's arguments" do
options = { :retries => 1 }.freeze
Puppet::Util::RetryAction.retry_action(options) do
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/suidmanager_spec.rb | spec/unit/util/suidmanager_spec.rb | require 'spec_helper'
describe Puppet::Util::SUIDManager do
let :user do
Puppet::Type.type(:user).new(:name => 'name', :uid => 42, :gid => 42)
end
let :xids do
Hash.new {|h,k| 0}
end
before :each do
allow(Puppet::Util::SUIDManager).to receive(:convert_xid).and_return(42)
pwent = double('pwent', :name => 'fred', :uid => 42, :gid => 42)
allow(Etc).to receive(:getpwuid).with(42).and_return(pwent)
unless Puppet::Util::Platform.windows?
[:euid, :egid, :uid, :gid, :groups].each do |id|
allow(Process).to receive("#{id}=") {|value| xids[id] = value}
end
end
end
describe "#initgroups", unless: Puppet::Util::Platform.windows? do
it "should use the primary group of the user as the 'basegid'" do
expect(Process).to receive(:initgroups).with('fred', 42)
described_class.initgroups(42)
end
end
describe "#uid" do
it "should allow setting euid/egid", unless: Puppet::Util::Platform.windows? do
Puppet::Util::SUIDManager.egid = user[:gid]
Puppet::Util::SUIDManager.euid = user[:uid]
expect(xids[:egid]).to eq(user[:gid])
expect(xids[:euid]).to eq(user[:uid])
end
end
describe "#asuser" do
it "should not get or set euid/egid when not root", unless: Puppet::Util::Platform.windows? do
allow(Process).to receive(:uid).and_return(1)
allow(Process).to receive(:egid).and_return(51)
allow(Process).to receive(:euid).and_return(50)
Puppet::Util::SUIDManager.asuser(user[:uid], user[:gid]) {}
expect(xids).to be_empty
end
context "when root and not Windows" do
before :each do
allow(Process).to receive(:uid).and_return(0)
end
it "should set euid/egid", unless: Puppet::Util::Platform.windows? do
allow(Process).to receive(:egid).and_return(51, 51, user[:gid])
allow(Process).to receive(:euid).and_return(50, 50, user[:uid])
allow(Puppet::Util::SUIDManager).to receive(:convert_xid).with(:gid, 51).and_return(51)
allow(Puppet::Util::SUIDManager).to receive(:convert_xid).with(:uid, 50).and_return(50)
allow(Puppet::Util::SUIDManager).to receive(:initgroups).and_return([])
yielded = false
Puppet::Util::SUIDManager.asuser(user[:uid], user[:gid]) do
expect(xids[:egid]).to eq(user[:gid])
expect(xids[:euid]).to eq(user[:uid])
yielded = true
end
expect(xids[:egid]).to eq(51)
expect(xids[:euid]).to eq(50)
# It's possible asuser could simply not yield, so the assertions in the
# block wouldn't fail. So verify those actually got checked.
expect(yielded).to be_truthy
end
it "should just yield if user and group are nil" do
expect { |b| Puppet::Util::SUIDManager.asuser(nil, nil, &b) }.to yield_control
expect(xids).to eq({})
end
it "should just change group if only group is given", unless: Puppet::Util::Platform.windows? do
expect { |b| Puppet::Util::SUIDManager.asuser(nil, 42, &b) }.to yield_control
expect(xids).to eq({ :egid => 42 })
end
it "should change gid to the primary group of uid by default", unless: Puppet::Util::Platform.windows? do
allow(Process).to receive(:initgroups)
expect { |b| Puppet::Util::SUIDManager.asuser(42, nil, &b) }.to yield_control
expect(xids).to eq({ :euid => 42, :egid => 42 })
end
it "should change both uid and gid if given", unless: Puppet::Util::Platform.windows? do
# I don't like the sequence, but it is the only way to assert on the
# internal behaviour in a reliable fashion, given we need multiple
# sequenced calls to the same methods. --daniel 2012-02-05
expect(Puppet::Util::SUIDManager).to receive(:change_group).with(43, false).ordered()
expect(Puppet::Util::SUIDManager).to receive(:change_user).with(42, false).ordered()
expect(Puppet::Util::SUIDManager).to receive(:change_group).with(Puppet::Util::SUIDManager.egid, false).ordered()
expect(Puppet::Util::SUIDManager).to receive(:change_user).with(Puppet::Util::SUIDManager.euid, false).ordered()
expect { |b| Puppet::Util::SUIDManager.asuser(42, 43, &b) }.to yield_control
end
end
it "should just yield on Windows", if: Puppet::Util::Platform.windows? do
expect { |b| Puppet::Util::SUIDManager.asuser(1, 2, &b) }.to yield_control
end
end
describe "#change_group" do
it "raises on Windows", if: Puppet::Util::Platform.windows? do
expect {
Puppet::Util::SUIDManager.change_group(42, true)
}.to raise_error(NotImplementedError, /change_privilege\(\) function is unimplemented/)
end
describe "when changing permanently", unless: Puppet::Util::Platform.windows? do
it "should change_privilege" do
expect(Process::GID).to receive(:change_privilege) do |gid|
Process.gid = gid
Process.egid = gid
end
Puppet::Util::SUIDManager.change_group(42, true)
expect(xids[:egid]).to eq(42)
expect(xids[:gid]).to eq(42)
end
it "should not change_privilege when gid already matches" do
expect(Process::GID).to receive(:change_privilege) do |gid|
Process.gid = 42
Process.egid = 42
end
Puppet::Util::SUIDManager.change_group(42, true)
expect(xids[:egid]).to eq(42)
expect(xids[:gid]).to eq(42)
end
end
describe "when changing temporarily", unless: Puppet::Util::Platform.windows? do
it "should change only egid" do
Puppet::Util::SUIDManager.change_group(42, false)
expect(xids[:egid]).to eq(42)
expect(xids[:gid]).to eq(0)
end
end
end
describe "#change_user" do
it "raises on Windows", if: Puppet::Util::Platform.windows? do
expect {
Puppet::Util::SUIDManager.change_user(42, true)
}.to raise_error(NotImplementedError, /initgroups\(\) function is unimplemented/)
end
describe "when changing permanently", unless: Puppet::Util::Platform.windows? do
it "should change_privilege" do
expect(Process::UID).to receive(:change_privilege) do |uid|
Process.uid = uid
Process.euid = uid
end
expect(Puppet::Util::SUIDManager).to receive(:initgroups).with(42)
Puppet::Util::SUIDManager.change_user(42, true)
expect(xids[:euid]).to eq(42)
expect(xids[:uid]).to eq(42)
end
it "should not change_privilege when uid already matches" do
expect(Process::UID).to receive(:change_privilege) do |uid|
Process.uid = 42
Process.euid = 42
end
expect(Puppet::Util::SUIDManager).to receive(:initgroups).with(42)
Puppet::Util::SUIDManager.change_user(42, true)
expect(xids[:euid]).to eq(42)
expect(xids[:uid]).to eq(42)
end
end
describe "when changing temporarily", unless: Puppet::Util::Platform.windows? do
it "should change only euid and groups" do
allow(Puppet::Util::SUIDManager).to receive(:initgroups).and_return([])
Puppet::Util::SUIDManager.change_user(42, false)
expect(xids[:euid]).to eq(42)
expect(xids[:uid]).to eq(0)
end
it "should set euid before groups if changing to root" do
allow(Process).to receive(:euid).and_return(50)
expect(Process).to receive(:euid=).ordered()
expect(Puppet::Util::SUIDManager).to receive(:initgroups).ordered()
Puppet::Util::SUIDManager.change_user(0, false)
end
it "should set groups before euid if changing from root" do
allow(Process).to receive(:euid).and_return(0)
expect(Puppet::Util::SUIDManager).to receive(:initgroups).ordered()
expect(Process).to receive(:euid=).ordered()
Puppet::Util::SUIDManager.change_user(50, false)
end
end
end
describe "#root?" do
describe "on POSIX systems", unless: Puppet::Util::Platform.windows? do
it "should be root if uid is 0" do
allow(Process).to receive(:uid).and_return(0)
expect(Puppet::Util::SUIDManager).to be_root
end
it "should not be root if uid is not 0" do
allow(Process).to receive(:uid).and_return(1)
expect(Puppet::Util::SUIDManager).not_to be_root
end
end
describe "on Windows", :if => Puppet::Util::Platform.windows? do
it "should be root if user is privileged" do
allow(Puppet::Util::Windows::User).to receive(:admin?).and_return(true)
expect(Puppet::Util::SUIDManager).to be_root
end
it "should not be root if user is not privileged" do
allow(Puppet::Util::Windows::User).to receive(:admin?).and_return(false)
expect(Puppet::Util::SUIDManager).not_to be_root
end
end
end
end
describe 'Puppet::Util::SUIDManager#groups=' do
subject do
Puppet::Util::SUIDManager
end
it "raises on Windows", if: Puppet::Util::Platform.windows? do
expect {
subject.groups = []
}.to raise_error(NotImplementedError, /groups=\(\) function is unimplemented/)
end
it "(#3419) should rescue Errno::EINVAL on OS X", unless: Puppet::Util::Platform.windows? do
expect(Process).to receive(:groups=).and_raise(Errno::EINVAL, 'blew up')
expect(subject).to receive(:osx_maj_ver).and_return('10.7').twice
subject.groups = ['list', 'of', 'groups']
end
it "(#3419) should fail if an Errno::EINVAL is raised NOT on OS X", unless: Puppet::Util::Platform.windows? do
expect(Process).to receive(:groups=).and_raise(Errno::EINVAL, 'blew up')
expect(subject).to receive(:osx_maj_ver).and_return(false)
expect { subject.groups = ['list', 'of', 'groups'] }.to raise_error(Errno::EINVAL)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/inifile_spec.rb | spec/unit/util/inifile_spec.rb | require 'spec_helper'
require 'puppet/util/inifile'
describe Puppet::Util::IniConfig::Section do
subject { described_class.new('testsection', '/some/imaginary/file') }
describe "determining if the section is dirty" do
it "is not dirty on creation" do
expect(subject).to_not be_dirty
end
it "is dirty if a key is changed" do
subject['hello'] = 'world'
expect(subject).to be_dirty
end
it "is dirty if the section has been explicitly marked as dirty" do
subject.mark_dirty
expect(subject).to be_dirty
end
it "is dirty if the section is marked for deletion" do
subject.destroy = true
expect(subject).to be_dirty
end
it "is clean if the section has been explicitly marked as clean" do
subject['hello'] = 'world'
subject.mark_clean
expect(subject).to_not be_dirty
end
end
describe "reading an entry" do
it "returns nil if the key is not present" do
expect(subject['hello']).to be_nil
end
it "returns the value if the key is specified" do
subject.entries << ['hello', 'world']
expect(subject['hello']).to eq 'world'
end
it "ignores comments when looking for a match" do
subject.entries << '#this = comment'
expect(subject['#this']).to be_nil
end
end
describe "formatting the section" do
it "prefixes the output with the section header" do
expect(subject.format).to eq "[testsection]\n"
end
it "restores comments and blank lines" do
subject.entries << "#comment\n"
subject.entries << " "
expect(subject.format).to eq(
"[testsection]\n" +
"#comment\n" +
" "
)
end
it "adds all keys that have values" do
subject.entries << ['somekey', 'somevalue']
expect(subject.format).to eq("[testsection]\nsomekey=somevalue\n")
end
it "excludes keys that have a value of nil" do
subject.entries << ['empty', nil]
expect(subject.format).to eq("[testsection]\n")
end
it "preserves the order of the section" do
subject.entries << ['firstkey', 'firstval']
subject.entries << "# I am a comment, hear me roar\n"
subject.entries << ['secondkey', 'secondval']
expect(subject.format).to eq(
"[testsection]\n" +
"firstkey=firstval\n" +
"# I am a comment, hear me roar\n" +
"secondkey=secondval\n"
)
end
it "is empty if the section is marked for deletion" do
subject.entries << ['firstkey', 'firstval']
subject.destroy = true
expect(subject.format).to eq('')
end
end
end
describe Puppet::Util::IniConfig::PhysicalFile do
subject { described_class.new('/some/nonexistent/file') }
let(:first_sect) do
sect = Puppet::Util::IniConfig::Section.new('firstsection', '/some/imaginary/file')
sect.entries << "# comment\n" << ['onefish', 'redfish'] << "\n"
sect
end
let(:second_sect) do
sect = Puppet::Util::IniConfig::Section.new('secondsection', '/some/imaginary/file')
sect.entries << ['twofish', 'bluefish']
sect
end
describe "when reading a file" do
it "raises an error if the file does not exist" do
allow(subject.filetype).to receive(:read)
expect {
subject.read
}.to raise_error(%r[Cannot read nonexistent file .*/some/nonexistent/file])
end
it "passes the contents of the file to #parse" do
allow(subject.filetype).to receive(:read).and_return("[section]")
expect(subject).to receive(:parse).with("[section]")
subject.read
end
end
describe "when parsing a file" do
describe "parsing sections" do
it "creates new sections the first time that the section is found" do
text = "[mysect]\n"
subject.parse(text)
expect(subject.contents.count).to eq 1
sect = subject.contents[0]
expect(sect.name).to eq "mysect"
end
it "raises an error if a section is redefined in the file" do
text = "[mysect]\n[mysect]\n"
expect {
subject.parse(text)
}.to raise_error(Puppet::Util::IniConfig::IniParseError,
/Section "mysect" is already defined, cannot redefine/)
end
it "raises an error if a section is redefined in the file collection" do
subject.file_collection = double('file collection', :get_section => true)
text = "[mysect]\n[mysect]\n"
expect {
subject.parse(text)
}.to raise_error(Puppet::Util::IniConfig::IniParseError,
/Section "mysect" is already defined, cannot redefine/)
end
end
describe 'parsing properties' do
it 'raises an error if the property is not within a section' do
text = "key=val\n"
expect {
subject.parse(text)
}.to raise_error(Puppet::Util::IniConfig::IniParseError,
/Property with key "key" outside of a section/)
end
it 'adds the property to the current section' do
text = "[main]\nkey=val\n"
subject.parse(text)
expect(subject.contents.count).to eq 1
sect = subject.contents[0]
expect(sect['key']).to eq 'val'
end
context 'with white space' do
let(:section) do
text = <<-INIFILE
[main]
leading_white_space=value1
white_space_after_key =value2
white_space_after_equals= value3
white_space_after_value=value4\t
INIFILE
subject.parse(text)
expect(subject.contents.count).to eq 1
subject.contents[0]
end
it 'allows and ignores white space before the key' do
expect(section['leading_white_space']).to eq('value1')
end
it 'allows and ignores white space before the equals' do
expect(section['white_space_after_key']).to eq('value2')
end
it 'allows and ignores white space after the equals' do
expect(section['white_space_after_equals']).to eq('value3')
end
it 'allows and ignores white spaces after the value' do
expect(section['white_space_after_value']).to eq('value4')
end
end
end
describe "parsing line continuations" do
it "adds the continued line to the last parsed property" do
text = "[main]\nkey=val\n moreval"
subject.parse(text)
expect(subject.contents.count).to eq 1
sect = subject.contents[0]
expect(sect['key']).to eq "val\n moreval"
end
end
describe "parsing comments and whitespace" do
it "treats # as a comment leader" do
text = "# octothorpe comment"
subject.parse(text)
expect(subject.contents).to eq ["# octothorpe comment"]
end
it "treats ; as a comment leader" do
text = "; semicolon comment"
subject.parse(text)
expect(subject.contents).to eq ["; semicolon comment"]
end
it "treates 'rem' as a comment leader" do
text = "rem rapid eye movement comment"
subject.parse(text)
expect(subject.contents).to eq ["rem rapid eye movement comment"]
end
it "stores comments and whitespace in a section in the correct section" do
text = "[main]\n; main section comment"
subject.parse(text)
sect = subject.get_section("main")
expect(sect.entries).to eq ["; main section comment"]
end
end
end
it "can return all sections" do
text = "[first]\n" +
"; comment\n" +
"[second]\n" +
"key=value"
subject.parse(text)
sections = subject.sections
expect(sections.count).to eq 2
expect(sections[0].name).to eq "first"
expect(sections[1].name).to eq "second"
end
it "can retrieve a specific section" do
text = "[first]\n" +
"; comment\n" +
"[second]\n" +
"key=value"
subject.parse(text)
section = subject.get_section("second")
expect(section.name).to eq "second"
expect(section["key"]).to eq "value"
end
describe "formatting" do
it "concatenates each formatted section in order" do
subject.contents << first_sect << second_sect
expected = "[firstsection]\n" +
"# comment\n" +
"onefish=redfish\n" +
"\n" +
"[secondsection]\n" +
"twofish=bluefish\n"
expect(subject.format).to eq expected
end
it "includes comments that are not within a section" do
subject.contents << "# This comment is not in a section\n" << first_sect << second_sect
expected = "# This comment is not in a section\n" +
"[firstsection]\n" +
"# comment\n" +
"onefish=redfish\n" +
"\n" +
"[secondsection]\n" +
"twofish=bluefish\n"
expect(subject.format).to eq expected
end
it "excludes sections that are marked to be destroyed" do
subject.contents << first_sect << second_sect
first_sect.destroy = true
expected = "[secondsection]\n" + "twofish=bluefish\n"
expect(subject.format).to eq expected
end
end
describe "storing the file" do
describe "with empty contents" do
describe "and destroy_empty is true" do
before { subject.destroy_empty = true }
it "removes the file if there are no sections" do
expect(File).to receive(:unlink)
subject.store
end
it "removes the file if all sections are marked to be destroyed" do
subject.contents << first_sect << second_sect
first_sect.destroy = true
second_sect.destroy = true
expect(File).to receive(:unlink)
subject.store
end
it "doesn't remove the file if not all sections are marked to be destroyed" do
subject.contents << first_sect << second_sect
first_sect.destroy = true
second_sect.destroy = false
expect(File).not_to receive(:unlink)
allow(subject.filetype).to receive(:write)
subject.store
end
end
it "rewrites the file if destroy_empty is false" do
subject.contents << first_sect << second_sect
first_sect.destroy = true
second_sect.destroy = true
expect(File).not_to receive(:unlink)
allow(subject).to receive(:format).and_return("formatted")
expect(subject.filetype).to receive(:write).with("formatted")
subject.store
end
end
it "rewrites the file if any section is dirty" do
subject.contents << first_sect << second_sect
first_sect.mark_dirty
second_sect.mark_clean
allow(subject).to receive(:format).and_return("formatted")
expect(subject.filetype).to receive(:write).with("formatted")
subject.store
end
it "doesn't modify the file if all sections are clean" do
subject.contents << first_sect << second_sect
first_sect.mark_clean
second_sect.mark_clean
allow(subject).to receive(:format).and_return("formatted")
expect(subject.filetype).not_to receive(:write)
subject.store
end
end
end
describe Puppet::Util::IniConfig::FileCollection do
let(:path_a) { '/some/nonexistent/file/a' }
let(:path_b) { '/some/nonexistent/file/b' }
let(:file_a) { Puppet::Util::IniConfig::PhysicalFile.new(path_a) }
let(:file_b) { Puppet::Util::IniConfig::PhysicalFile.new(path_b) }
let(:sect_a1) { Puppet::Util::IniConfig::Section.new('sect_a1', path_a) }
let(:sect_a2) { Puppet::Util::IniConfig::Section.new('sect_a2', path_a) }
let(:sect_b1) { Puppet::Util::IniConfig::Section.new('sect_b1', path_b) }
let(:sect_b2) { Puppet::Util::IniConfig::Section.new('sect_b2', path_b) }
before do
file_a.contents << sect_a1 << sect_a2
file_b.contents << sect_b1 << sect_b2
end
describe "reading a file" do
let(:stub_file) { double('Physical file') }
it "creates a new PhysicalFile and uses that to read the file" do
expect(stub_file).to receive(:read)
expect(stub_file).to receive(:file_collection=)
expect(Puppet::Util::IniConfig::PhysicalFile).to receive(:new).with(path_a).and_return(stub_file)
subject.read(path_a)
end
it "stores the PhysicalFile and the path to the file" do
allow(stub_file).to receive(:read)
allow(stub_file).to receive(:file_collection=)
allow(Puppet::Util::IniConfig::PhysicalFile).to receive(:new).with(path_a).and_return(stub_file)
subject.read(path_a)
path, physical_file = subject.files.first
expect(path).to eq(path_a)
expect(physical_file).to eq stub_file
end
end
describe "storing all files" do
before do
subject.files[path_a] = file_a
subject.files[path_b] = file_b
end
it "stores all files in the collection" do
expect(file_a).to receive(:store).once
expect(file_b).to receive(:store).once
subject.store
end
end
describe "iterating over sections" do
before do
subject.files[path_a] = file_a
subject.files[path_b] = file_b
end
it "yields every section from every file" do
expect { |b|
subject.each_section(&b)
}.to yield_successive_args(sect_a1, sect_a2, sect_b1, sect_b2)
end
end
describe "iterating over files" do
before do
subject.files[path_a] = file_a
subject.files[path_b] = file_b
end
it "yields the path to every file in the collection" do
expect { |b|
subject.each_file(&b)
}.to yield_successive_args(path_a, path_b)
end
end
describe "retrieving a specific section" do
before do
subject.files[path_a] = file_a
subject.files[path_b] = file_b
end
it "retrieves the first section defined" do
expect(subject.get_section('sect_b1')).to eq sect_b1
end
it "returns nil if there was no section with the given name" do
expect(subject.get_section('nope')).to be_nil
end
it "allows #[] to be used as an alias to #get_section" do
expect(subject['b2']).to eq subject.get_section('b2')
end
end
describe "checking if a section has been defined" do
before do
subject.files[path_a] = file_a
subject.files[path_b] = file_b
end
it "is true if a section with the given name is defined" do
expect(subject.include?('sect_a1')).to be_truthy
end
it "is false if a section with the given name can't be found" do
expect(subject.include?('nonexistent')).to be_falsey
end
end
describe "adding a new section" do
before do
subject.files[path_a] = file_a
subject.files[path_b] = file_b
end
it "adds the section to the appropriate file" do
expect(file_a).to receive(:add_section).with('newsect')
subject.add_section('newsect', path_a)
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/reference_spec.rb | spec/unit/util/reference_spec.rb | require 'spec_helper'
require 'puppet/util/reference'
describe Puppet::Util::Reference do
it "should create valid Markdown extension definition lists" do
my_fragment = nil
Puppet::Util::Reference.newreference :testreference, :doc => "A peer of the type and configuration references, but with no useful information" do
my_term = "A term"
my_definition = <<-EOT
The definition of this term, marked by a colon and a space.
We should be able to handle multi-line definitions. Each subsequent
line should left-align with the first word character after the colon
used as the definition marker.
We should be able to handle multi-paragraph definitions.
Leading indentation should be stripped from the definition, which allows
us to indent the source string for cosmetic purposes.
EOT
my_fragment = markdown_definitionlist(my_term, my_definition)
end
Puppet::Util::Reference.reference(:testreference).send(:to_markdown, true)
expect(my_fragment).to eq <<-EOT
A term
: The definition of this term, marked by a colon and a space.
We should be able to handle multi-line definitions. Each subsequent
line should left-align with the first word character after the colon
used as the definition marker.
We should be able to handle multi-paragraph definitions.
Leading indentation should be stripped from the definition, which allows
us to indent the source string for cosmetic purposes.
EOT
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/posix_spec.rb | spec/unit/util/posix_spec.rb | require 'spec_helper'
require 'puppet/ffi/posix'
require 'puppet/util/posix'
class PosixTest
include Puppet::Util::POSIX
end
describe Puppet::Util::POSIX do
before do
@posix = PosixTest.new
end
describe '.groups_of' do
let(:mock_user_data) { double(user, :gid => 1000) }
let(:ngroups_ptr) { double('FFI::MemoryPointer', :address => 0x0001, :size => 4) }
let(:groups_ptr) { double('FFI::MemoryPointer', :address => 0x0002, :size => Puppet::FFI::POSIX::Constants::MAXIMUM_NUMBER_OF_GROUPS) }
let(:mock_groups) do
[
['root', ['root'], 0],
['nomembers', [], 5 ],
['group1', ['user1', 'user2'], 1001],
['group2', ['user2'], 2002],
['group1', ['user1', 'user2'], 1001],
['group3', ['user1'], 3003],
['group4', ['user2'], 4004],
['user1', [], 1111],
['user2', [], 2222]
].map do |(name, members, gid)|
group_struct = double("Group #{name}")
allow(group_struct).to receive(:name).and_return(name)
allow(group_struct).to receive(:mem).and_return(members)
allow(group_struct).to receive(:gid).and_return(gid)
group_struct
end
end
def prepare_user_and_groups_env(user, groups)
groups_gids = []
groups_and_user = []
groups_and_user.replace(groups)
groups_and_user.push(user)
groups_and_user.each do |group|
mock_group = mock_groups.find { |m| m.name == group }
groups_gids.push(mock_group.gid)
allow(Puppet::Etc).to receive(:getgrgid).with(mock_group.gid).and_return(mock_group)
end
if groups_and_user.size > Puppet::FFI::POSIX::Constants::MAXIMUM_NUMBER_OF_GROUPS
allow(ngroups_ptr).to receive(:read_int).and_return(Puppet::FFI::POSIX::Constants::MAXIMUM_NUMBER_OF_GROUPS, groups_and_user.size)
else
allow(ngroups_ptr).to receive(:read_int).and_return(groups_and_user.size)
end
allow(groups_ptr).to receive(:get_array_of_uint).with(0, groups_and_user.size).and_return(groups_gids)
allow(Puppet::Etc).to receive(:getpwnam).with(user).and_return(mock_user_data)
end
before(:each) do
allow(Puppet::FFI::POSIX::Functions).to receive(:respond_to?).with(:getgrouplist, any_args).and_return(true)
end
describe 'when it uses FFI function getgrouplist' do
before(:each) do
allow(FFI::MemoryPointer).to receive(:new).with(:int).and_yield(ngroups_ptr)
allow(FFI::MemoryPointer).to receive(:new).with(:uint, Puppet::FFI::POSIX::Constants::MAXIMUM_NUMBER_OF_GROUPS).and_yield(groups_ptr)
allow(ngroups_ptr).to receive(:write_int).with(Puppet::FFI::POSIX::Constants::MAXIMUM_NUMBER_OF_GROUPS).and_return(ngroups_ptr)
end
describe 'when there are groups' do
context 'for user1' do
let(:user) { 'user1' }
let(:expected_groups) { ['group1', 'group3'] }
before(:each) do
prepare_user_and_groups_env(user, expected_groups)
allow(Puppet::FFI::POSIX::Functions).to receive(:getgrouplist).and_return(1)
end
it "should return the groups for given user" do
expect(Puppet::Util::POSIX.groups_of(user)).to eql(expected_groups)
end
it 'should not print any debug message about falling back to Puppet::Etc.group' do
expect(Puppet).not_to receive(:debug).with(/Falling back to Puppet::Etc.group:/)
Puppet::Util::POSIX.groups_of(user)
end
end
context 'for user2' do
let(:user) { 'user2' }
let(:expected_groups) { ['group1', 'group2', 'group4'] }
before(:each) do
prepare_user_and_groups_env(user, expected_groups)
allow(Puppet::FFI::POSIX::Functions).to receive(:respond_to?).with(:getgrouplist, any_args).and_return(true)
allow(Puppet::FFI::POSIX::Functions).to receive(:getgrouplist).and_return(1)
end
it "should return the groups for given user" do
expect(Puppet::Util::POSIX.groups_of(user)).to eql(expected_groups)
end
it 'should not print any debug message about falling back to Puppet::Etc.group' do
expect(Puppet).not_to receive(:debug).with(/Falling back to Puppet::Etc.group:/)
Puppet::Util::POSIX.groups_of(user)
end
end
end
describe 'when there are no groups' do
let(:user) { 'nomembers' }
let(:expected_groups) { [] }
before(:each) do
prepare_user_and_groups_env(user, expected_groups)
allow(Puppet::FFI::POSIX::Functions).to receive(:respond_to?).with(:getgrouplist, any_args).and_return(true)
allow(Puppet::FFI::POSIX::Functions).to receive(:getgrouplist).and_return(1)
end
it "should return no groups for given user" do
expect(Puppet::Util::POSIX.groups_of(user)).to eql(expected_groups)
end
it 'should not print any debug message about falling back to Puppet::Etc.group' do
expect(Puppet).not_to receive(:debug).with(/Falling back to Puppet::Etc.group:/)
Puppet::Util::POSIX.groups_of(user)
end
end
describe 'when primary group explicitly contains user' do
let(:user) { 'root' }
let(:expected_groups) { ['root'] }
before(:each) do
prepare_user_and_groups_env(user, expected_groups)
allow(Puppet::FFI::POSIX::Functions).to receive(:respond_to?).with(:getgrouplist, any_args).and_return(true)
allow(Puppet::FFI::POSIX::Functions).to receive(:getgrouplist).and_return(1)
end
it "should return the groups, including primary group, for given user" do
expect(Puppet::Util::POSIX.groups_of(user)).to eql(expected_groups)
end
it 'should not print any debug message about falling back to Puppet::Etc.group' do
expect(Puppet).not_to receive(:debug).with(/Falling back to Puppet::Etc.group:/)
Puppet::Util::POSIX.groups_of(user)
end
end
describe 'when primary group does not explicitly contain user' do
let(:user) { 'user1' }
let(:expected_groups) { ['group1', 'group3'] }
before(:each) do
prepare_user_and_groups_env(user, expected_groups)
allow(Puppet::FFI::POSIX::Functions).to receive(:respond_to?).with(:getgrouplist, any_args).and_return(true)
allow(Puppet::FFI::POSIX::Functions).to receive(:getgrouplist).and_return(1)
end
it "should not return primary group for given user" do
expect(Puppet::Util::POSIX.groups_of(user)).not_to include(user)
end
it 'should not print any debug message about falling back to Puppet::Etc.group' do
expect(Puppet).not_to receive(:debug).with(/Falling back to Puppet::Etc.group:/)
Puppet::Util::POSIX.groups_of(user)
end
end
context 'number of groups' do
before(:each) do
stub_const("Puppet::FFI::POSIX::Constants::MAXIMUM_NUMBER_OF_GROUPS", 2)
prepare_user_and_groups_env(user, expected_groups)
allow(FFI::MemoryPointer).to receive(:new).with(:uint, Puppet::FFI::POSIX::Constants::MAXIMUM_NUMBER_OF_GROUPS).and_yield(groups_ptr)
allow(ngroups_ptr).to receive(:write_int).with(Puppet::FFI::POSIX::Constants::MAXIMUM_NUMBER_OF_GROUPS).and_return(ngroups_ptr)
end
describe 'when there are less than maximum expected number of groups' do
let(:user) { 'root' }
let(:expected_groups) { ['root'] }
before(:each) do
allow(Puppet::FFI::POSIX::Functions).to receive(:respond_to?).with(:getgrouplist, any_args).and_return(true)
allow(Puppet::FFI::POSIX::Functions).to receive(:getgrouplist).and_return(1)
end
it "should return the groups for given user, after one 'getgrouplist' call" do
expect(Puppet::FFI::POSIX::Functions).to receive(:getgrouplist).once
expect(Puppet::Util::POSIX.groups_of(user)).to eql(expected_groups)
end
it 'should not print any debug message about falling back to Puppet::Etc.group' do
expect(Puppet).not_to receive(:debug).with(/Falling back to Puppet::Etc.group:/)
Puppet::Util::POSIX.groups_of(user)
end
end
describe 'when there are more than maximum expected number of groups' do
let(:user) { 'user1' }
let(:expected_groups) { ['group1', 'group3'] }
before(:each) do
allow(FFI::MemoryPointer).to receive(:new).with(:uint, Puppet::FFI::POSIX::Constants::MAXIMUM_NUMBER_OF_GROUPS * 2).and_yield(groups_ptr)
allow(ngroups_ptr).to receive(:write_int).with(Puppet::FFI::POSIX::Constants::MAXIMUM_NUMBER_OF_GROUPS * 2).and_return(ngroups_ptr)
allow(Puppet::FFI::POSIX::Functions).to receive(:respond_to?).with(:getgrouplist, any_args).and_return(true)
allow(Puppet::FFI::POSIX::Functions).to receive(:getgrouplist).and_return(-1, 1)
end
it "should return the groups for given user, after two 'getgrouplist' calls" do
expect(Puppet::FFI::POSIX::Functions).to receive(:getgrouplist).twice
expect(Puppet::Util::POSIX.groups_of(user)).to eql(expected_groups)
end
it 'should not print any debug message about falling back to Puppet::Etc.group' do
expect(Puppet).not_to receive(:debug).with(/Falling back to Puppet::Etc.group:/)
Puppet::Util::POSIX.groups_of(user)
end
end
end
end
describe 'when it falls back to Puppet::Etc.group method' do
before(:each) do
etc_stub = receive(:group)
mock_groups.each do |mock_group|
etc_stub = etc_stub.and_yield(mock_group)
end
allow(Puppet::Etc).to etc_stub
allow(Puppet::Etc).to receive(:getpwnam).with(user).and_raise(ArgumentError, "can't find user for #{user}")
allow(Puppet).to receive(:debug)
allow(Puppet::FFI::POSIX::Functions).to receive(:respond_to?).with(:getgrouplist, any_args).and_return(false)
end
describe 'when there are groups' do
context 'for user1' do
let(:user) { 'user1' }
let(:expected_groups) { ['group1', 'group3'] }
it "should return the groups for given user" do
expect(Puppet::Util::POSIX.groups_of(user)).to eql(expected_groups)
end
it 'logs a debug message' do
expect(Puppet).to receive(:debug).with("Falling back to Puppet::Etc.group: The 'getgrouplist' method is not available")
Puppet::Util::POSIX.groups_of(user)
end
end
context 'for user2' do
let(:user) { 'user2' }
let(:expected_groups) { ['group1', 'group2', 'group4'] }
it "should return the groups for given user" do
expect(Puppet::Util::POSIX.groups_of(user)).to eql(expected_groups)
end
it 'logs a debug message' do
expect(Puppet).to receive(:debug).with("Falling back to Puppet::Etc.group: The 'getgrouplist' method is not available")
Puppet::Util::POSIX.groups_of(user)
end
end
end
describe 'when there are no groups' do
let(:user) { 'nomembers' }
let(:expected_groups) { [] }
it "should return no groups for given user" do
expect(Puppet::Util::POSIX.groups_of(user)).to eql(expected_groups)
end
it 'logs a debug message' do
expect(Puppet).to receive(:debug).with("Falling back to Puppet::Etc.group: The 'getgrouplist' method is not available")
Puppet::Util::POSIX.groups_of(user)
end
end
describe 'when primary group explicitly contains user' do
let(:user) { 'root' }
let(:expected_groups) { ['root'] }
it "should return the groups, including primary group, for given user" do
expect(Puppet::Util::POSIX.groups_of(user)).to eql(expected_groups)
end
it 'logs a debug message' do
expect(Puppet).to receive(:debug).with("Falling back to Puppet::Etc.group: The 'getgrouplist' method is not available")
Puppet::Util::POSIX.groups_of(user)
end
end
describe 'when primary group does not explicitly contain user' do
let(:user) { 'user1' }
let(:expected_groups) { ['group1', 'group3'] }
it "should not return primary group for given user" do
expect(Puppet::Util::POSIX.groups_of(user)).not_to include(user)
end
it 'logs a debug message' do
expect(Puppet).to receive(:debug).with("Falling back to Puppet::Etc.group: The 'getgrouplist' method is not available")
Puppet::Util::POSIX.groups_of(user)
end
end
describe "when the 'getgrouplist' method is not available" do
let(:user) { 'user1' }
let(:expected_groups) { ['group1', 'group3'] }
before(:each) do
allow(Puppet::FFI::POSIX::Functions).to receive(:respond_to?).with(:getgrouplist).and_return(false)
end
it "should return the groups" do
expect(Puppet::Util::POSIX.groups_of(user)).to eql(expected_groups)
end
it 'logs a debug message' do
expect(Puppet).to receive(:debug).with("Falling back to Puppet::Etc.group: The 'getgrouplist' method is not available")
Puppet::Util::POSIX.groups_of(user)
end
end
describe "when ffi is not available on the machine" do
let(:user) { 'user1' }
let(:expected_groups) { ['group1', 'group3'] }
before(:each) do
allow(Puppet::Util::POSIX).to receive(:require_relative).with('../../puppet/ffi/posix').and_raise(LoadError, 'cannot load such file -- ffi')
end
it "should return the groups" do
expect(Puppet::Util::POSIX.groups_of(user)).to eql(expected_groups)
end
it 'logs a debug message' do
expect(Puppet).to receive(:debug).with("Falling back to Puppet::Etc.group: cannot load such file -- ffi")
Puppet::Util::POSIX.groups_of(user)
end
end
end
end
[:group, :gr].each do |name|
it "should return :gid as the field for #{name}" do
expect(@posix.idfield(name)).to eq(:gid)
end
it "should return :getgrgid as the id method for #{name}" do
expect(@posix.methodbyid(name)).to eq(:getgrgid)
end
it "should return :getgrnam as the name method for #{name}" do
expect(@posix.methodbyname(name)).to eq(:getgrnam)
end
end
[:user, :pw, :passwd].each do |name|
it "should return :uid as the field for #{name}" do
expect(@posix.idfield(name)).to eq(:uid)
end
it "should return :getpwuid as the id method for #{name}" do
expect(@posix.methodbyid(name)).to eq(:getpwuid)
end
it "should return :getpwnam as the name method for #{name}" do
expect(@posix.methodbyname(name)).to eq(:getpwnam)
end
end
describe "when retrieving a posix field" do
before do
@thing = double('thing', :field => "asdf")
end
it "should fail if no id was passed" do
expect { @posix.get_posix_field("asdf", "bar", nil) }.to raise_error(Puppet::DevError)
end
describe "and the id is an integer" do
it "should log an error and return nil if the specified id is greater than the maximum allowed ID" do
Puppet[:maximum_uid] = 100
expect(Puppet).to receive(:err)
expect(@posix.get_posix_field("asdf", "bar", 200)).to be_nil
end
it "should use the method return by :methodbyid and return the specified field" do
expect(Etc).to receive(:getgrgid).and_return(@thing)
expect(@thing).to receive(:field).and_return("myval")
expect(@posix.get_posix_field(:gr, :field, 200)).to eq("myval")
end
it "should return nil if the method throws an exception" do
expect(Etc).to receive(:getgrgid).and_raise(ArgumentError)
expect(@thing).not_to receive(:field)
expect(@posix.get_posix_field(:gr, :field, 200)).to be_nil
end
end
describe "and the id is not an integer" do
it "should use the method return by :methodbyid and return the specified field" do
expect(Etc).to receive(:getgrnam).and_return(@thing)
expect(@thing).to receive(:field).and_return("myval")
expect(@posix.get_posix_field(:gr, :field, "asdf")).to eq("myval")
end
it "should return nil if the method throws an exception" do
expect(Etc).to receive(:getgrnam).and_raise(ArgumentError)
expect(@thing).not_to receive(:field)
expect(@posix.get_posix_field(:gr, :field, "asdf")).to be_nil
end
end
end
describe "when returning the gid" do
before do
allow(@posix).to receive(:get_posix_field)
end
describe "and the group is an integer" do
it "should convert integers specified as a string into an integer" do
expect(@posix).to receive(:get_posix_field).with(:group, :name, 100)
@posix.gid("100")
end
it "should look up the name for the group" do
expect(@posix).to receive(:get_posix_field).with(:group, :name, 100)
@posix.gid(100)
end
it "should return nil if the group cannot be found" do
expect(@posix).to receive(:get_posix_field).once.and_return(nil)
expect(@posix).not_to receive(:search_posix_field)
expect(@posix.gid(100)).to be_nil
end
it "should use the found name to look up the id" do
expect(@posix).to receive(:get_posix_field).with(:group, :name, 100).and_return("asdf")
expect(@posix).to receive(:get_posix_field).with(:group, :gid, "asdf").and_return(100)
expect(@posix.gid(100)).to eq(100)
end
# LAK: This is because some platforms have a broken Etc module that always return
# the same group.
it "should use :search_posix_field if the discovered id does not match the passed-in id" do
expect(@posix).to receive(:get_posix_field).with(:group, :name, 100).and_return("asdf")
expect(@posix).to receive(:get_posix_field).with(:group, :gid, "asdf").and_return(50)
expect(@posix).to receive(:search_posix_field).with(:group, :gid, 100).and_return("asdf")
expect(@posix.gid(100)).to eq("asdf")
end
end
describe "and the group is a string" do
it "should look up the gid for the group" do
expect(@posix).to receive(:get_posix_field).with(:group, :gid, "asdf")
@posix.gid("asdf")
end
it "should return nil if the group cannot be found" do
expect(@posix).to receive(:get_posix_field).once.and_return(nil)
expect(@posix).not_to receive(:search_posix_field)
expect(@posix.gid("asdf")).to be_nil
end
it "should use the found gid to look up the nam" do
expect(@posix).to receive(:get_posix_field).with(:group, :gid, "asdf").and_return(100)
expect(@posix).to receive(:get_posix_field).with(:group, :name, 100).and_return("asdf")
expect(@posix.gid("asdf")).to eq(100)
end
it "returns the id without full groups query if multiple groups have the same id" do
expect(@posix).to receive(:get_posix_field).with(:group, :gid, "asdf").and_return(100)
expect(@posix).to receive(:get_posix_field).with(:group, :name, 100).and_return("boo")
expect(@posix).to receive(:get_posix_field).with(:group, :gid, "boo").and_return(100)
expect(@posix).not_to receive(:search_posix_field)
expect(@posix.gid("asdf")).to eq(100)
end
it "returns the id with full groups query if name is nil" do
expect(@posix).to receive(:get_posix_field).with(:group, :gid, "asdf").and_return(100)
expect(@posix).to receive(:get_posix_field).with(:group, :name, 100).and_return(nil)
expect(@posix).not_to receive(:get_posix_field).with(:group, :gid, nil)
expect(@posix).to receive(:search_posix_field).with(:group, :gid, "asdf").and_return(100)
expect(@posix.gid("asdf")).to eq(100)
end
it "should use :search_posix_field if the discovered name does not match the passed-in name" do
expect(@posix).to receive(:get_posix_field).with(:group, :gid, "asdf").and_return(100)
expect(@posix).to receive(:get_posix_field).with(:group, :name, 100).and_return("boo")
expect(@posix).to receive(:search_posix_field).with(:group, :gid, "asdf").and_return("asdf")
expect(@posix.gid("asdf")).to eq("asdf")
end
end
end
describe "when returning the uid" do
before do
allow(@posix).to receive(:get_posix_field)
end
describe "and the group is an integer" do
it "should convert integers specified as a string into an integer" do
expect(@posix).to receive(:get_posix_field).with(:passwd, :name, 100)
@posix.uid("100")
end
it "should look up the name for the group" do
expect(@posix).to receive(:get_posix_field).with(:passwd, :name, 100)
@posix.uid(100)
end
it "should return nil if the group cannot be found" do
expect(@posix).to receive(:get_posix_field).once.and_return(nil)
expect(@posix).not_to receive(:search_posix_field)
expect(@posix.uid(100)).to be_nil
end
it "should use the found name to look up the id" do
expect(@posix).to receive(:get_posix_field).with(:passwd, :name, 100).and_return("asdf")
expect(@posix).to receive(:get_posix_field).with(:passwd, :uid, "asdf").and_return(100)
expect(@posix.uid(100)).to eq(100)
end
# LAK: This is because some platforms have a broken Etc module that always return
# the same group.
it "should use :search_posix_field if the discovered id does not match the passed-in id" do
expect(@posix).to receive(:get_posix_field).with(:passwd, :name, 100).and_return("asdf")
expect(@posix).to receive(:get_posix_field).with(:passwd, :uid, "asdf").and_return(50)
expect(@posix).to receive(:search_posix_field).with(:passwd, :uid, 100).and_return("asdf")
expect(@posix.uid(100)).to eq("asdf")
end
end
describe "and the group is a string" do
it "should look up the uid for the group" do
expect(@posix).to receive(:get_posix_field).with(:passwd, :uid, "asdf")
@posix.uid("asdf")
end
it "should return nil if the group cannot be found" do
expect(@posix).to receive(:get_posix_field).once.and_return(nil)
expect(@posix).not_to receive(:search_posix_field)
expect(@posix.uid("asdf")).to be_nil
end
it "should use the found uid to look up the nam" do
expect(@posix).to receive(:get_posix_field).with(:passwd, :uid, "asdf").and_return(100)
expect(@posix).to receive(:get_posix_field).with(:passwd, :name, 100).and_return("asdf")
expect(@posix.uid("asdf")).to eq(100)
end
it "returns the id without full users query if multiple users have the same id" do
expect(@posix).to receive(:get_posix_field).with(:passwd, :uid, "asdf").and_return(100)
expect(@posix).to receive(:get_posix_field).with(:passwd, :name, 100).and_return("boo")
expect(@posix).to receive(:get_posix_field).with(:passwd, :uid, "boo").and_return(100)
expect(@posix).not_to receive(:search_posix_field)
expect(@posix.uid("asdf")).to eq(100)
end
it "returns the id with full users query if name is nil" do
expect(@posix).to receive(:get_posix_field).with(:passwd, :uid, "asdf").and_return(100)
expect(@posix).to receive(:get_posix_field).with(:passwd, :name, 100).and_return(nil)
expect(@posix).not_to receive(:get_posix_field).with(:passwd, :uid, nil)
expect(@posix).to receive(:search_posix_field).with(:passwd, :uid, "asdf").and_return(100)
expect(@posix.uid("asdf")).to eq(100)
end
it "should use :search_posix_field if the discovered name does not match the passed-in name" do
expect(@posix).to receive(:get_posix_field).with(:passwd, :uid, "asdf").and_return(100)
expect(@posix).to receive(:get_posix_field).with(:passwd, :name, 100).and_return("boo")
expect(@posix).to receive(:search_posix_field).with(:passwd, :uid, "asdf").and_return("asdf")
expect(@posix.uid("asdf")).to eq("asdf")
end
end
end
it "should be able to iteratively search for posix values" do
expect(@posix).to respond_to(:search_posix_field)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/watcher_spec.rb | spec/unit/util/watcher_spec.rb | require 'spec_helper'
require 'puppet/util/watcher'
describe Puppet::Util::Watcher do
describe "the common file ctime watcher" do
FakeStat = Struct.new(:ctime)
def ctime(time)
FakeStat.new(time)
end
let(:filename) { "fake" }
it "is initially unchanged" do
expect(Puppet::FileSystem).to receive(:stat).with(filename).and_return(ctime(20)).at_least(:once)
watcher = Puppet::Util::Watcher::Common.file_ctime_change_watcher(filename)
expect(watcher).to_not be_changed
end
it "has not changed if a section of the file path continues to not exist" do
expect(Puppet::FileSystem).to receive(:stat).with(filename).and_raise(Errno::ENOTDIR).at_least(:once)
watcher = Puppet::Util::Watcher::Common.file_ctime_change_watcher(filename)
watcher = watcher.next_reading
expect(watcher).to_not be_changed
end
it "has not changed if the file continues to not exist" do
expect(Puppet::FileSystem).to receive(:stat).with(filename).and_raise(Errno::ENOENT).at_least(:once)
watcher = Puppet::Util::Watcher::Common.file_ctime_change_watcher(filename)
watcher = watcher.next_reading
expect(watcher).to_not be_changed
end
it "has changed if the file is created" do
times_stat_called = 0
expect(Puppet::FileSystem).to receive(:stat).with(filename) do
times_stat_called += 1
raise Errno::ENOENT if times_stat_called == 1
ctime(20)
end.at_least(:once)
watcher = Puppet::Util::Watcher::Common.file_ctime_change_watcher(filename)
watcher = watcher.next_reading
expect(watcher).to be_changed
end
it "is marked as changed if the file is deleted" do
times_stat_called = 0
expect(Puppet::FileSystem).to receive(:stat).with(filename) do
times_stat_called += 1
raise Errno::ENOENT if times_stat_called > 1
ctime(20)
end.at_least(:once)
watcher = Puppet::Util::Watcher::Common.file_ctime_change_watcher(filename)
watcher = watcher.next_reading
expect(watcher).to be_changed
end
it "is marked as changed if the file modified" do
times_stat_called = 0
expect(Puppet::FileSystem).to receive(:stat).with(filename) do
times_stat_called += 1
if times_stat_called == 1
ctime(20)
else
ctime(21)
end
end.at_least(:once)
watcher = Puppet::Util::Watcher::Common.file_ctime_change_watcher(filename)
watcher = watcher.next_reading
expect(watcher).to be_changed
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/package_spec.rb | spec/unit/util/package_spec.rb | require 'spec_helper'
require 'puppet/util/package'
describe Puppet::Util::Package, " versioncmp" do
it "should be able to be used as a module function" do
expect(Puppet::Util::Package).to respond_to(:versioncmp)
end
it "should be able to sort a long set of various unordered versions" do
ary = %w{ 1.1.6 2.3 1.1a 3.0 1.5 1 2.4 1.1-4 2.3.1 1.2 2.3.0 1.1-3 2.4b 2.4 2.40.2 2.3a.1 3.1 0002 1.1-5 1.1.a 1.06}
newary = ary.sort { |a, b| Puppet::Util::Package.versioncmp(a,b) }
expect(newary).to eq(["0002", "1", "1.06", "1.1-3", "1.1-4", "1.1-5", "1.1.6", "1.1.a", "1.1a", "1.2", "1.5", "2.3", "2.3.0", "2.3.1", "2.3a.1", "2.4", "2.4", "2.4b", "2.40.2", "3.0", "3.1"])
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/colors_spec.rb | spec/unit/util/colors_spec.rb | require 'spec_helper'
describe Puppet::Util::Colors do
include Puppet::Util::Colors
let (:message) { 'a message' }
let (:color) { :black }
let (:subject) { self }
describe ".console_color" do
it { is_expected.to respond_to :console_color }
it "should generate ANSI escape sequences" do
expect(subject.console_color(color, message)).to eq("\e[0;30m#{message}\e[0m")
end
end
describe ".html_color" do
it { is_expected.to respond_to :html_color }
it "should generate an HTML span element and style attribute" do
expect(subject.html_color(color, message)).to match(/<span style=\"color: #FFA0A0\">#{message}<\/span>/)
end
end
describe ".colorize" do
it { is_expected.to respond_to :colorize }
context "ansicolor supported" do
it "should colorize console output" do
Puppet[:color] = true
expect(subject).to receive(:console_color).with(color, message)
subject.colorize(:black, message)
end
it "should not colorize unknown color schemes" do
Puppet[:color] = :thisisanunknownscheme
expect(subject.colorize(:black, message)).to eq(message)
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/tag_set_spec.rb | spec/unit/util/tag_set_spec.rb | require 'spec_helper'
require 'puppet/util/tag_set'
RSpec::Matchers.define :be_one_of do |*expected|
match do |actual|
expected.include? actual
end
failure_message do |actual|
"expected #{actual.inspect} to be one of #{expected.map(&:inspect).join(' or ')}"
end
end
describe Puppet::Util::TagSet do
let(:set) { Puppet::Util::TagSet.new }
it 'serializes to yaml as an array' do
array = ['a', :b, 1, 5.4]
set.merge(array)
expect(Set.new(Puppet::Util::Yaml.safe_load(set.to_yaml, [Symbol, Puppet::Util::TagSet]))).to eq(Set.new(array))
end
it 'deserializes from a yaml array' do
array = ['a', :b, 1, 5.4]
expect(Puppet::Util::TagSet.from_yaml(array.to_yaml)).to eq(Puppet::Util::TagSet.new(array))
end
it 'round trips through json' do
array = ['a', 'b', 1, 5.4]
set.merge(array)
tes = Puppet::Util::TagSet.from_data_hash(JSON.parse(set.to_json))
expect(tes).to eq(set)
end
it 'can join its elements with a string separator' do
array = ['a', 'b']
set.merge(array)
expect(set.join(', ')).to be_one_of('a, b', 'b, a')
end
it 'raises when deserializing unacceptable objects' do
yaml = [Object.new].to_yaml
expect {
Puppet::Util::TagSet.from_yaml(yaml)
}.to raise_error(Puppet::Util::Yaml::YamlLoadError, /Tried to load unspecified class: Object/)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/selinux_spec.rb | spec/unit/util/selinux_spec.rb | require 'spec_helper'
require 'pathname'
require 'puppet/util/selinux'
describe Puppet::Util::SELinux do
include Puppet::Util::SELinux
let(:selinux) { double('selinux', is_selinux_enabled: 0) }
before :each do
stub_const('Selinux', selinux)
end
describe "selinux_support?" do
it "should return true if this system has SELinux enabled" do
expect(Selinux).to receive(:is_selinux_enabled).and_return(1)
expect(selinux_support?).to eq(true)
end
it "should return false if this system has SELinux disabled" do
expect(Selinux).to receive(:is_selinux_enabled).and_return(0)
expect(selinux_support?).to eq(false)
end
it "should return false if this system lacks SELinux" do
hide_const('Selinux')
expect(selinux_support?).to eq(false)
end
it "should return nil if /proc/mounts does not exist" do
allow(File).to receive(:new).with("/proc/mounts").and_raise("No such file or directory - /proc/mounts")
expect(read_mounts).to eq(nil)
end
end
describe "read_mounts" do
before :each do
fh = double('fh', :close => nil)
allow(File).to receive(:new).and_call_original()
allow(File).to receive(:new).with("/proc/mounts").and_return(fh)
times_fh_called = 0
expect(fh).to receive(:read_nonblock) do
times_fh_called += 1
raise EOFError if times_fh_called > 1
"rootfs / rootfs rw 0 0\n/dev/root / ext3 rw,relatime,errors=continue,user_xattr,acl,data=ordered 0 0\n/dev /dev tmpfs rw,relatime,mode=755 0 0\n/proc /proc proc rw,relatime 0 0\n/sys /sys sysfs rw,relatime 0 0\n192.168.1.1:/var/export /mnt/nfs nfs rw,relatime,vers=3,rsize=32768,wsize=32768,namlen=255,hard,nointr,proto=tcp,timeo=600,retrans=2,sec=sys,mountaddr=192.168.1.1,mountvers=3,mountproto=udp,addr=192.168.1.1 0 0\n"
end.twice()
end
it "should parse the contents of /proc/mounts" do
result = read_mounts
expect(result).to eq({
'/' => 'ext3',
'/sys' => 'sysfs',
'/mnt/nfs' => 'nfs',
'/proc' => 'proc',
'/dev' => 'tmpfs' })
end
end
describe "filesystem detection" do
before :each do
allow(self).to receive(:read_mounts).and_return({
'/' => 'ext3',
'/sys' => 'sysfs',
'/mnt/nfs' => 'nfs',
'/mnt/zfs' => 'zfs',
'/proc' => 'proc',
'/dev' => 'tmpfs' })
end
it "should match a path on / to ext3" do
expect(find_fs('/etc/puppetlabs/puppet/testfile')).to eq("ext3")
end
it "should match a path on /mnt/nfs to nfs" do
expect(find_fs('/mnt/nfs/testfile/foobar')).to eq("nfs")
end
it "should return true for a capable filesystem" do
expect(selinux_label_support?('/etc/puppetlabs/puppet/testfile')).to be_truthy
end
it "should return true if tmpfs" do
expect(selinux_label_support?('/dev/shm/testfile')).to be_truthy
end
it "should return true if zfs" do
expect(selinux_label_support?('/mnt/zfs/testfile')).to be_truthy
end
it "should return false for a noncapable filesystem" do
expect(selinux_label_support?('/mnt/nfs/testfile')).to be_falsey
end
it "(#8714) don't follow symlinks when determining file systems", :unless => Puppet::Util::Platform.windows? do
scratch = Pathname(PuppetSpec::Files.tmpdir('selinux'))
allow(self).to receive(:read_mounts).and_return({
'/' => 'ext3',
scratch + 'nfs' => 'nfs',
})
(scratch + 'foo').make_symlink('nfs/bar')
expect(selinux_label_support?(scratch + 'foo')).to be_truthy
end
it "should handle files that don't exist" do
scratch = Pathname(PuppetSpec::Files.tmpdir('selinux'))
expect(selinux_label_support?(scratch + 'nonesuch')).to be_truthy
end
end
describe "get_selinux_current_context" do
it "should return nil if no SELinux support" do
expect(self).to receive(:selinux_support?).and_return(false)
expect(get_selinux_current_context("/foo")).to be_nil
end
it "should return a context" do
without_partial_double_verification do
expect(self).to receive(:selinux_support?).and_return(true)
expect(Selinux).to receive(:lgetfilecon).with("/foo").and_return([0, "user_u:role_r:type_t:s0"])
expect(get_selinux_current_context("/foo")).to eq("user_u:role_r:type_t:s0")
end
end
it "should return nil if lgetfilecon fails" do
without_partial_double_verification do
expect(self).to receive(:selinux_support?).and_return(true)
expect(Selinux).to receive(:lgetfilecon).with("/foo").and_return(-1)
expect(get_selinux_current_context("/foo")).to be_nil
end
end
end
describe "get_selinux_default_context" do
it "should return nil if no SELinux support" do
expect(self).to receive(:selinux_support?).and_return(false)
expect(get_selinux_default_context("/foo")).to be_nil
end
it "should return a context if a default context exists" do
without_partial_double_verification do
expect(self).to receive(:selinux_support?).and_return(true)
fstat = double('File::Stat', :mode => 0)
expect(Puppet::FileSystem).to receive(:lstat).with('/foo').and_return(fstat)
expect(self).to receive(:find_fs).with("/foo").and_return("ext3")
expect(Selinux).to receive(:matchpathcon).with("/foo", 0).and_return([0, "user_u:role_r:type_t:s0"])
expect(get_selinux_default_context("/foo")).to eq("user_u:role_r:type_t:s0")
end
end
it "handles permission denied errors by issuing a warning" do
without_partial_double_verification do
allow(self).to receive(:selinux_support?).and_return(true)
allow(self).to receive(:selinux_label_support?).and_return(true)
allow(Selinux).to receive(:matchpathcon).with("/root/chuj", 0).and_return(-1)
allow(self).to receive(:file_lstat).with("/root/chuj").and_raise(Errno::EACCES, "/root/chuj")
expect(get_selinux_default_context("/root/chuj")).to be_nil
end
end
it "backward compatibly handles no such file or directory errors by issuing a warning when resource_ensure not set" do
without_partial_double_verification do
allow(self).to receive(:selinux_support?).and_return(true)
allow(self).to receive(:selinux_label_support?).and_return(true)
allow(Selinux).to receive(:matchpathcon).with("/root/chuj", 0).and_return(-1)
allow(self).to receive(:file_lstat).with("/root/chuj").and_raise(Errno::ENOENT, "/root/chuj")
expect(get_selinux_default_context("/root/chuj")).to be_nil
end
end
it "should determine mode based on resource ensure when set to file" do
without_partial_double_verification do
allow(self).to receive(:selinux_support?).and_return(true)
allow(self).to receive(:selinux_label_support?).and_return(true)
allow(Selinux).to receive(:matchpathcon).with("/root/chuj", 32768).and_return(-1)
allow(self).to receive(:file_lstat).with("/root/chuj").and_raise(Errno::ENOENT, "/root/chuj")
expect(get_selinux_default_context("/root/chuj", :present)).to be_nil
expect(get_selinux_default_context("/root/chuj", :file)).to be_nil
end
end
it "should determine mode based on resource ensure when set to dir" do
without_partial_double_verification do
allow(self).to receive(:selinux_support?).and_return(true)
allow(self).to receive(:selinux_label_support?).and_return(true)
allow(Selinux).to receive(:matchpathcon).with("/root/chuj", 16384).and_return(-1)
allow(self).to receive(:file_lstat).with("/root/chuj").and_raise(Errno::ENOENT, "/root/chuj")
expect(get_selinux_default_context("/root/chuj", :directory)).to be_nil
end
end
it "should determine mode based on resource ensure when set to link" do
without_partial_double_verification do
allow(self).to receive(:selinux_support?).and_return(true)
allow(self).to receive(:selinux_label_support?).and_return(true)
allow(Selinux).to receive(:matchpathcon).with("/root/chuj", 40960).and_return(-1)
allow(self).to receive(:file_lstat).with("/root/chuj").and_raise(Errno::ENOENT, "/root/chuj")
expect(get_selinux_default_context("/root/chuj", :link)).to be_nil
end
end
it "should determine mode based on resource ensure when set to unknown" do
without_partial_double_verification do
allow(self).to receive(:selinux_support?).and_return(true)
allow(self).to receive(:selinux_label_support?).and_return(true)
allow(Selinux).to receive(:matchpathcon).with("/root/chuj", 0).and_return(-1)
allow(self).to receive(:file_lstat).with("/root/chuj").and_raise(Errno::ENOENT, "/root/chuj")
expect(get_selinux_default_context("/root/chuj", "unknown")).to be_nil
end
end
it "should return nil if matchpathcon returns failure" do
without_partial_double_verification do
expect(self).to receive(:selinux_support?).and_return(true)
fstat = double('File::Stat', :mode => 0)
expect(Puppet::FileSystem).to receive(:lstat).with('/foo').and_return(fstat)
expect(self).to receive(:find_fs).with("/foo").and_return("ext3")
expect(Selinux).to receive(:matchpathcon).with("/foo", 0).and_return(-1)
expect(get_selinux_default_context("/foo")).to be_nil
end
end
it "should return nil if selinux_label_support returns false" do
without_partial_double_verification do
expect(self).to receive(:selinux_support?).and_return(true)
expect(self).to receive(:find_fs).with("/foo").and_return("nfs")
expect(get_selinux_default_context("/foo")).to be_nil
end
end
end
describe "get_selinux_default_context_with_handle" do
it "should return a context if a default context exists" do
without_partial_double_verification do
expect(self).to receive(:selinux_support?).and_return(true)
expect(self).to receive(:find_fs).with("/foo").and_return("ext3")
hnd = double("SWIG::TYPE_p_selabel_handle")
expect(Selinux).to receive(:selabel_lookup).with(hnd, '/foo', 0).and_return([0, "user_u:role_r:type_t:s0"])
expect(get_selinux_default_context_with_handle("/foo", hnd)).to eq("user_u:role_r:type_t:s0")
end
end
it "should return nil when permission denied errors are encountered" do
without_partial_double_verification do
expect(self).to receive(:selinux_support?).and_return(true)
expect(self).to receive(:selinux_label_support?).and_return(true)
hnd = double("SWIG::TYPE_p_selabel_handle")
expect(Selinux).to receive(:selabel_lookup).with(hnd, "/root/chuj", 0).and_return(-1)
expect(self).to receive(:file_lstat).with("/root/chuj").and_raise(Errno::EACCES, "/root/chuj")
expect(get_selinux_default_context_with_handle("/root/chuj", hnd)).to be_nil
end
end
it "should return nil when no such file or directory errors are encountered and resource_ensure is unset" do
without_partial_double_verification do
expect(self).to receive(:selinux_support?).and_return(true)
expect(self).to receive(:selinux_label_support?).and_return(true)
hnd = double("SWIG::TYPE_p_selabel_handle")
expect(Selinux).to receive(:selabel_lookup).with(hnd, "/root/chuj", 0).and_return(-1)
expect(self).to receive(:file_lstat).with("/root/chuj").and_raise(Errno::ENOENT, "/root/chuj")
expect(get_selinux_default_context_with_handle("/root/chuj", hnd)).to be_nil
end
end
it "should pass through lstat mode when file exists" do
without_partial_double_verification do
expect(self).to receive(:selinux_support?).and_return(true).twice
expect(self).to receive(:selinux_label_support?).and_return(true).twice
hnd = double("SWIG::TYPE_p_selabel_handle")
fstat = double("File::Stat", :mode => 16384)
expect(Selinux).to receive(:selabel_lookup).with(hnd, "/root/chuj", fstat.mode).and_return([0, "user_u:role_r:type_t:s0"]).twice
expect(self).to receive(:file_lstat).with("/root/chuj").and_return(fstat).twice
expect(get_selinux_default_context_with_handle("/root/chuj", hnd)).to eq("user_u:role_r:type_t:s0")
expect(get_selinux_default_context_with_handle("/root/chuj", hnd, :file)).to eq("user_u:role_r:type_t:s0")
end
end
it "should determine mode based on resource ensure when set to file" do
without_partial_double_verification do
expect(self).to receive(:selinux_support?).and_return(true).twice
expect(self).to receive(:selinux_label_support?).and_return(true).twice
hnd = double("SWIG::TYPE_p_selabel_handle")
expect(Selinux).to receive(:selabel_lookup).with(hnd, "/root/chuj", 32768).and_return(-1).twice
expect(self).to receive(:file_lstat).with("/root/chuj").and_raise(Errno::ENOENT, "/root/chuj").twice
expect(get_selinux_default_context_with_handle("/root/chuj", hnd, :present)).to be_nil
expect(get_selinux_default_context_with_handle("/root/chuj", hnd, :file)).to be_nil
end
end
it "should determine mode based on resource ensure when set to dir" do
without_partial_double_verification do
expect(self).to receive(:selinux_support?).and_return(true)
expect(self).to receive(:selinux_label_support?).and_return(true)
hnd = double("SWIG::TYPE_p_selabel_handle")
expect(Selinux).to receive(:selabel_lookup).with(hnd, "/root/chuj", 16384).and_return(-1)
expect(self).to receive(:file_lstat).with("/root/chuj").and_raise(Errno::ENOENT, "/root/chuj")
expect(get_selinux_default_context_with_handle("/root/chuj", hnd, :directory)).to be_nil
end
end
it "should determine mode based on resource ensure when set to link" do
without_partial_double_verification do
expect(self).to receive(:selinux_support?).and_return(true)
expect(self).to receive(:selinux_label_support?).and_return(true)
hnd = double("SWIG::TYPE_p_selabel_handle")
expect(Selinux).to receive(:selabel_lookup).with(hnd, "/root/chuj", 40960).and_return(-1)
expect(self).to receive(:file_lstat).with("/root/chuj").and_raise(Errno::ENOENT, "/root/chuj")
expect(get_selinux_default_context_with_handle("/root/chuj", hnd, :link)).to be_nil
end
end
it "should determine mode based on resource ensure when set to unknown" do
without_partial_double_verification do
expect(self).to receive(:selinux_support?).and_return(true)
expect(self).to receive(:selinux_label_support?).and_return(true)
hnd = double("SWIG::TYPE_p_selabel_handle")
expect(Selinux).to receive(:selabel_lookup).with(hnd, "/root/chuj", 0).and_return(-1)
expect(self).to receive(:file_lstat).with("/root/chuj").and_raise(Errno::ENOENT, "/root/chuj")
expect(get_selinux_default_context_with_handle("/root/chuj", hnd, "unknown")).to be_nil
end
end
it "should raise an ArgumentError when handle is nil" do
allow(self).to receive(:selinux_support?).and_return(true)
allow(self).to receive(:selinux_label_support?).and_return(true)
expect{get_selinux_default_context_with_handle("/foo", nil)}.to raise_error(ArgumentError, /Cannot get default context with nil handle/)
end
it "should return nil if there is no SELinux support" do
expect(self).to receive(:selinux_support?).and_return(false)
expect(get_selinux_default_context_with_handle("/foo", nil)).to be_nil
end
it "should return nil if selinux_label_support returns false" do
expect(self).to receive(:selinux_support?).and_return(true)
expect(self).to receive(:find_fs).with("/foo").and_return("nfs")
expect(get_selinux_default_context_with_handle("/foo", nil)).to be_nil
end
end
describe "parse_selinux_context" do
it "should return nil if no context is passed" do
expect(parse_selinux_context(:seluser, nil)).to be_nil
end
it "should return nil if the context is 'unlabeled'" do
expect(parse_selinux_context(:seluser, "unlabeled")).to be_nil
end
it "should return the user type when called with :seluser" do
expect(parse_selinux_context(:seluser, "user_u:role_r:type_t:s0")).to eq("user_u")
expect(parse_selinux_context(:seluser, "user-withdash_u:role_r:type_t:s0")).to eq("user-withdash_u")
end
it "should return the role type when called with :selrole" do
expect(parse_selinux_context(:selrole, "user_u:role_r:type_t:s0")).to eq("role_r")
expect(parse_selinux_context(:selrole, "user_u:role-withdash_r:type_t:s0")).to eq("role-withdash_r")
end
it "should return the type type when called with :seltype" do
expect(parse_selinux_context(:seltype, "user_u:role_r:type_t:s0")).to eq("type_t")
expect(parse_selinux_context(:seltype, "user_u:role_r:type-withdash_t:s0")).to eq("type-withdash_t")
end
describe "with spaces in the components" do
it "should raise when user contains a space" do
expect{parse_selinux_context(:seluser, "user with space_u:role_r:type_t:s0")}.to raise_error Puppet::Error
end
it "should raise when role contains a space" do
expect{parse_selinux_context(:selrole, "user_u:role with space_r:type_t:s0")}.to raise_error Puppet::Error
end
it "should raise when type contains a space" do
expect{parse_selinux_context(:seltype, "user_u:role_r:type with space_t:s0")}.to raise_error Puppet::Error
end
it "should return the range when range contains a space" do
expect(parse_selinux_context(:selrange, "user_u:role_r:type_t:s0 s1")).to eq("s0 s1")
end
end
it "should return nil for :selrange when no range is returned" do
expect(parse_selinux_context(:selrange, "user_u:role_r:type_t")).to be_nil
end
it "should return the range type when called with :selrange" do
expect(parse_selinux_context(:selrange, "user_u:role_r:type_t:s0")).to eq("s0")
expect(parse_selinux_context(:selrange, "user_u:role_r:type-withdash_t:s0")).to eq("s0")
end
describe "with a variety of SELinux range formats" do
['s0', 's0:c3', 's0:c3.c123', 's0:c3,c5,c8', 'TopSecret', 'TopSecret,Classified', 'Patient_Record'].each do |range|
it "should parse range '#{range}'" do
expect(parse_selinux_context(:selrange, "user_u:role_r:type_t:#{range}")).to eq(range)
end
end
end
end
describe "set_selinux_context" do
before :each do
fh = double('fh', :close => nil)
allow(File).to receive(:new).with("/proc/mounts").and_return(fh)
times_fh_called = 0
allow(fh).to receive(:read_nonblock) do
times_fh_called += 1
raise EOFError if times_fh_called > 1
"rootfs / rootfs rw 0 0\n/dev/root / ext3 rw,relatime,errors=continue,user_xattr,acl,data=ordered 0 0\n"+
"/dev /dev tmpfs rw,relatime,mode=755 0 0\n/proc /proc proc rw,relatime 0 0\n"+
"/sys /sys sysfs rw,relatime 0 0\n"
end
end
it "should return nil if there is no SELinux support" do
expect(self).to receive(:selinux_support?).and_return(false)
expect(set_selinux_context("/foo", "user_u:role_r:type_t:s0")).to be_nil
end
it "should return nil if selinux_label_support returns false" do
expect(self).to receive(:selinux_support?).and_return(true)
expect(self).to receive(:selinux_label_support?).with("/foo").and_return(false)
expect(set_selinux_context("/foo", "user_u:role_r:type_t:s0")).to be_nil
end
it "should use lsetfilecon to set a context" do
without_partial_double_verification do
expect(self).to receive(:selinux_support?).and_return(true)
expect(Selinux).to receive(:lsetfilecon).with("/foo", "user_u:role_r:type_t:s0").and_return(0)
expect(set_selinux_context("/foo", "user_u:role_r:type_t:s0")).to be_truthy
end
end
it "should use lsetfilecon to set user_u user context" do
without_partial_double_verification do
expect(self).to receive(:selinux_support?).and_return(true)
expect(Selinux).to receive(:lgetfilecon).with("/foo").and_return([0, "foo:role_r:type_t:s0"])
expect(Selinux).to receive(:lsetfilecon).with("/foo", "user_u:role_r:type_t:s0").and_return(0)
expect(set_selinux_context("/foo", "user_u", :seluser)).to be_truthy
end
end
it "should use lsetfilecon to set role_r role context" do
without_partial_double_verification do
expect(self).to receive(:selinux_support?).and_return(true)
expect(Selinux).to receive(:lgetfilecon).with("/foo").and_return([0, "user_u:foo:type_t:s0"])
expect(Selinux).to receive(:lsetfilecon).with("/foo", "user_u:role_r:type_t:s0").and_return(0)
expect(set_selinux_context("/foo", "role_r", :selrole)).to be_truthy
end
end
it "should use lsetfilecon to set type_t type context" do
without_partial_double_verification do
expect(self).to receive(:selinux_support?).and_return(true)
expect(Selinux).to receive(:lgetfilecon).with("/foo").and_return([0, "user_u:role_r:foo:s0"])
expect(Selinux).to receive(:lsetfilecon).with("/foo", "user_u:role_r:type_t:s0").and_return(0)
expect(set_selinux_context("/foo", "type_t", :seltype)).to be_truthy
end
end
it "should use lsetfilecon to set s0:c3,c5 range context" do
without_partial_double_verification do
expect(self).to receive(:selinux_support?).and_return(true)
expect(Selinux).to receive(:lgetfilecon).with("/foo").and_return([0, "user_u:role_r:type_t:s0"])
expect(Selinux).to receive(:lsetfilecon).with("/foo", "user_u:role_r:type_t:s0:c3,c5").and_return(0)
expect(set_selinux_context("/foo", "s0:c3,c5", :selrange)).to be_truthy
end
end
end
describe "set_selinux_default_context" do
it "should return nil if there is no SELinux support" do
expect(self).to receive(:selinux_support?).and_return(false)
expect(set_selinux_default_context("/foo")).to be_nil
end
it "should return nil if no default context exists" do
expect(self).to receive(:get_selinux_default_context).with("/foo", nil).and_return(nil)
expect(set_selinux_default_context("/foo")).to be_nil
end
it "should do nothing and return nil if the current context matches the default context" do
expect(self).to receive(:get_selinux_default_context).with("/foo", nil).and_return("user_u:role_r:type_t")
expect(self).to receive(:get_selinux_current_context).with("/foo").and_return("user_u:role_r:type_t")
expect(set_selinux_default_context("/foo")).to be_nil
end
it "should set and return the default context if current and default do not match" do
expect(self).to receive(:get_selinux_default_context).with("/foo", nil).and_return("user_u:role_r:type_t")
expect(self).to receive(:get_selinux_current_context).with("/foo").and_return("olduser_u:role_r:type_t")
expect(self).to receive(:set_selinux_context).with("/foo", "user_u:role_r:type_t").and_return(true)
expect(set_selinux_default_context("/foo")).to eq("user_u:role_r:type_t")
end
end
describe "get_create_mode" do
it "should return 0 if the resource is absent" do
expect(get_create_mode(:absent)).to eq(0)
end
it "should return mode with file type set to S_IFREG when resource is file" do
expect(get_create_mode(:present)).to eq(32768)
expect(get_create_mode(:file)).to eq(32768)
end
it "should return mode with file type set to S_IFDIR when resource is dir" do
expect(get_create_mode(:directory)).to eq(16384)
end
it "should return mode with file type set to S_IFLNK when resource is link" do
expect(get_create_mode(:link)).to eq(40960)
end
it "should return 0 for everything else" do
expect(get_create_mode("unknown")).to eq(0)
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/plist_spec.rb | spec/unit/util/plist_spec.rb | # coding: utf-8
require 'spec_helper'
require 'puppet/util/plist'
require 'puppet_spec/files'
describe Puppet::Util::Plist, :if => Puppet.features.cfpropertylist? do
include PuppetSpec::Files
let(:valid_xml_plist) do
'<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>LastUsedPrinters</key>
<array>
<dict>
<key>Network</key>
<string>10.85.132.1</string>
<key>PrinterID</key>
<string>baskerville_corp_puppetlabs_net</string>
</dict>
<dict>
<key>Network</key>
<string>10.14.96.1</string>
<key>PrinterID</key>
<string>Statler</string>
</dict>
</array>
</dict>
</plist>'
end
let(:invalid_xml_plist) do
'<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>LastUsedPrinters</key>
<array>
<dict>
<!-- this comment is --terrible -->
<key>Network</key>
<string>10.85.132.1</string>
<key>PrinterID</key>
<string>baskerville_corp_puppetlabs_net</string>
</dict>
<dict>
<key>Network</key>
<string>10.14.96.1</string>
<key>PrinterID</key>
<string>Statler</string>
</dict>
</array>
</dict>
</plist>'
end
let(:ascii_xml_plist) do
'<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>RecordName</key>
<array>
<string>Timișoara</string>
<string>Tōkyō</string>
</array>
</dict>
</plist>'.force_encoding(Encoding::US_ASCII)
end
let(:non_plist_data) do
"Take my love, take my land
Take me where I cannot stand
I don't care, I'm still free
You can't take the sky from me."
end
let(:binary_data) do
"\xCF\xFA\xED\xFE\a\u0000\u0000\u0001\u0003\u0000\u0000\x80\u0002\u0000\u0000\u0000\u0012\u0000\u0000\u0000\b"
end
let(:valid_xml_plist_hash) { {"LastUsedPrinters"=>[{"Network"=>"10.85.132.1", "PrinterID"=>"baskerville_corp_puppetlabs_net"}, {"Network"=>"10.14.96.1", "PrinterID"=>"Statler"}]} }
let(:ascii_xml_plist_hash) { {"RecordName"=>["Timișoara", "Tōkyō"]} }
let(:plist_path) { file_containing('sample.plist', valid_xml_plist) }
let(:binary_plist_magic_number) { 'bplist00' }
let(:bad_xml_doctype) { '<!DOCTYPE plist PUBLIC -//Apple Computer' }
let(:good_xml_doctype) { '<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">' }
describe "#read_plist_file" do
it "calls #convert_cfpropertylist_to_native_types on a plist object when a valid binary plist is read" do
allow(subject).to receive(:read_file_with_offset).with(plist_path, 8).and_return(binary_plist_magic_number)
allow(subject).to receive(:new_cfpropertylist).with({:file => plist_path}).and_return('plist_object')
expect(subject).to receive(:convert_cfpropertylist_to_native_types).with('plist_object').and_return('plist_hash')
expect(subject.read_plist_file(plist_path)).to eq('plist_hash')
end
it "returns a valid hash when a valid XML plist is read" do
allow(subject).to receive(:read_file_with_offset).with(plist_path, 8).and_return('notbinary')
allow(subject).to receive(:open_file_with_args).with(plist_path, 'r:UTF-8').and_return(valid_xml_plist)
expect(subject.read_plist_file(plist_path)).to eq(valid_xml_plist_hash)
end
it "raises a debug message and replaces a bad XML plist doctype should one be encountered" do
allow(subject).to receive(:read_file_with_offset).with(plist_path, 8).and_return('notbinary')
allow(subject).to receive(:open_file_with_args).with(plist_path, 'r:UTF-8').and_return(bad_xml_doctype)
expect(subject).to receive(:new_cfpropertylist).with({:data => good_xml_doctype}).and_return('plist_object')
allow(subject).to receive(:convert_cfpropertylist_to_native_types).with('plist_object').and_return('plist_hash')
expect(Puppet).to receive(:debug).with("Had to fix plist with incorrect DOCTYPE declaration: #{plist_path}")
expect(subject.read_plist_file(plist_path)).to eq('plist_hash')
end
it "attempts to read pure xml using plutil when reading an improperly formatted service plist" do
allow(subject).to receive(:read_file_with_offset).with(plist_path, 8).and_return('notbinary')
allow(subject).to receive(:open_file_with_args).with(plist_path, 'r:UTF-8').and_return(invalid_xml_plist)
expect(Puppet).to receive(:debug).with(/^Failed with CFFormatError/)
expect(Puppet).to receive(:debug).with("Plist #{plist_path} ill-formatted, converting with plutil")
expect(Puppet::Util::Execution).to receive(:execute)
.with(['/usr/bin/plutil', '-convert', 'xml1', '-o', '-', plist_path],
{:failonfail => true, :combine => true})
.and_return(Puppet::Util::Execution::ProcessOutput.new(valid_xml_plist, 0))
expect(subject.read_plist_file(plist_path)).to eq(valid_xml_plist_hash)
end
it "returns nil when direct parsing and plutil conversion both fail" do
allow(subject).to receive(:read_file_with_offset).with(plist_path, 8).and_return('notbinary')
allow(subject).to receive(:open_file_with_args).with(plist_path, 'r:UTF-8').and_return(non_plist_data)
expect(Puppet).to receive(:debug).with(/^Failed with (CFFormatError|NoMethodError)/)
expect(Puppet).to receive(:debug).with("Plist #{plist_path} ill-formatted, converting with plutil")
expect(Puppet::Util::Execution).to receive(:execute)
.with(['/usr/bin/plutil', '-convert', 'xml1', '-o', '-', plist_path],
{:failonfail => true, :combine => true})
.and_raise(Puppet::ExecutionFailure, 'boom')
expect(subject.read_plist_file(plist_path)).to eq(nil)
end
it "returns nil when file is a non-plist binary blob" do
allow(subject).to receive(:read_file_with_offset).with(plist_path, 8).and_return('notbinary')
allow(subject).to receive(:open_file_with_args).with(plist_path, 'r:UTF-8').and_return(binary_data)
expect(Puppet).to receive(:debug).with(/^Failed with (CFFormatError|ArgumentError)/)
expect(Puppet).to receive(:debug).with("Plist #{plist_path} ill-formatted, converting with plutil")
expect(Puppet::Util::Execution).to receive(:execute)
.with(['/usr/bin/plutil', '-convert', 'xml1', '-o', '-', plist_path],
{:failonfail => true, :combine => true})
.and_raise(Puppet::ExecutionFailure, 'boom')
expect(subject.read_plist_file(plist_path)).to eq(nil)
end
end
describe "#parse_plist" do
it "returns a valid hash when a valid XML plist is provided" do
expect(subject.parse_plist(valid_xml_plist)).to eq(valid_xml_plist_hash)
end
it "returns a valid hash when an ASCII XML plist is provided" do
expect(subject.parse_plist(ascii_xml_plist)).to eq(ascii_xml_plist_hash)
end
it "raises a debug message and replaces a bad XML plist doctype should one be encountered" do
expect(subject).to receive(:new_cfpropertylist).with({:data => good_xml_doctype}).and_return('plist_object')
allow(subject).to receive(:convert_cfpropertylist_to_native_types).with('plist_object')
expect(Puppet).to receive(:debug).with("Had to fix plist with incorrect DOCTYPE declaration: #{plist_path}")
subject.parse_plist(bad_xml_doctype, plist_path)
end
it "raises a debug message with malformed plist" do
allow(subject).to receive(:convert_cfpropertylist_to_native_types).with('plist_object')
expect(Puppet).to receive(:debug).with(/^Failed with CFFormatError/)
subject.parse_plist("<plist><dict><key>Foo</key>")
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/network_device_spec.rb | spec/unit/util/network_device_spec.rb | require 'spec_helper'
require 'ostruct'
require 'puppet/util/network_device'
describe Puppet::Util::NetworkDevice do
before(:each) do
@device = OpenStruct.new(:name => "name", :provider => "test", :url => "telnet://admin:password@127.0.0.1", :options => { :debug => false })
end
after(:each) do
Puppet::Util::NetworkDevice.teardown
end
class Puppet::Util::NetworkDevice::Test
class Device
def initialize(device, options)
end
end
end
describe "when initializing the remote network device singleton" do
it "should create a network device instance" do
allow(Puppet::Util::NetworkDevice).to receive(:require)
expect(Puppet::Util::NetworkDevice::Test::Device).to receive(:new).with("telnet://admin:password@127.0.0.1", {:debug => false})
Puppet::Util::NetworkDevice.init(@device)
end
it "should raise an error if the remote device instance can't be created" do
allow(Puppet::Util::NetworkDevice).to receive(:require).and_raise("error")
expect { Puppet::Util::NetworkDevice.init(@device) }.to raise_error(RuntimeError, /Can't load test for name/)
end
it "should let caller to access the singleton device" do
device = double('device')
allow(Puppet::Util::NetworkDevice).to receive(:require)
expect(Puppet::Util::NetworkDevice::Test::Device).to receive(:new).and_return(device)
Puppet::Util::NetworkDevice.init(@device)
expect(Puppet::Util::NetworkDevice.current).to eq(device)
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/symbolic_file_mode_spec.rb | spec/unit/util/symbolic_file_mode_spec.rb | require 'spec_helper'
require 'puppet/util/symbolic_file_mode'
describe Puppet::Util::SymbolicFileMode do
include Puppet::Util::SymbolicFileMode
describe "#valid_symbolic_mode?" do
%w{
0 0000 1 1 7 11 77 111 777 11
0 00000 01 01 07 011 077 0111 0777 011
= - + u= g= o= a= u+ g+ o+ a+ u- g- o- a- ugo= ugoa= ugugug=
a=,u=,g= a=,g+
=rwx +rwx -rwx
644 go-w =rw,+X +X 755 u=rwx,go=rx u=rwx,go=u-w go= g=u-w
755 0755
}.each do |input|
it "should treat #{input.inspect} as valid" do
expect(valid_symbolic_mode?(input)).to be_truthy
end
end
[0000, 0111, 0640, 0755, 0777].each do |input|
it "should treat the int #{input.to_s(8)} as value" do
expect(valid_symbolic_mode?(input)).to be_truthy
end
end
%w{
-1 -8 8 9 18 19 91 81 000000 11111 77777
0-1 0-8 08 09 018 019 091 081 0000000 011111 077777
u g o a ug uo ua ag
}.each do |input|
it "should treat #{input.inspect} as invalid" do
expect(valid_symbolic_mode?(input)).to be_falsey
end
end
end
describe "#normalize_symbolic_mode" do
it "should turn an int into a string" do
expect(normalize_symbolic_mode(12)).to be_an_instance_of String
end
it "should not add a leading zero to an int" do
expect(normalize_symbolic_mode(12)).not_to match(/^0/)
end
it "should not add a leading zero to a string with a number" do
expect(normalize_symbolic_mode("12")).not_to match(/^0/)
end
it "should string a leading zero from a number" do
expect(normalize_symbolic_mode("012")).to eq('12')
end
it "should pass through any other string" do
expect(normalize_symbolic_mode("u=rwx")).to eq('u=rwx')
end
end
describe "#symbolic_mode_to_int" do
{
"0654" => 00654,
"u+r" => 00400,
"g+r" => 00040,
"a+r" => 00444,
"a+x" => 00111,
"o+t" => 01000,
["o-t", 07777] => 06777,
["a-x", 07777] => 07666,
["a-rwx", 07777] => 07000,
["ug-rwx", 07777] => 07007,
"a+x,ug-rwx" => 00001,
# My experimentation on debian suggests that +g ignores the sgid flag
["a+g", 02060] => 02666,
# My experimentation on debian suggests that -g ignores the sgid flag
["a-g", 02666] => 02000,
"g+x,a+g" => 00111,
# +X without exec set in the original should not set anything
"u+x,g+X" => 00100,
"g+X" => 00000,
# +X only refers to the original, *unmodified* file mode!
["u+x,a+X", 0600] => 00700,
# Examples from the MacOS chmod(1) manpage
"0644" => 00644,
["go-w", 07777] => 07755,
["=rw,+X", 07777] => 07777,
["=rw,+X", 07766] => 07777,
["=rw,+X", 07676] => 07777,
["=rw,+X", 07667] => 07777,
["=rw,+X", 07666] => 07666,
"0755" => 00755,
"u=rwx,go=rx" => 00755,
"u=rwx,go=u-w" => 00755,
["go=", 07777] => 07700,
["g=u-w", 07777] => 07757,
["g=u-w", 00700] => 00750,
["g=u-w", 00600] => 00640,
["g=u-w", 00500] => 00550,
["g=u-w", 00400] => 00440,
["g=u-w", 00300] => 00310,
["g=u-w", 00200] => 00200,
["g=u-w", 00100] => 00110,
["g=u-w", 00000] => 00000,
# Cruel, but legal, use of the action set.
["g=u+r-w", 0300] => 00350,
# Empty assignments.
["u=", 00000] => 00000,
["u=", 00600] => 00000,
["ug=", 00000] => 00000,
["ug=", 00600] => 00000,
["ug=", 00660] => 00000,
["ug=", 00666] => 00006,
["=", 00000] => 00000,
["=", 00666] => 00000,
["+", 00000] => 00000,
["+", 00124] => 00124,
["-", 00000] => 00000,
["-", 00124] => 00124,
}.each do |input, result|
from = input.is_a?(Array) ? "#{input[0]}, 0#{input[1].to_s(8)}" : input
it "should map #{from.inspect} to #{result.inspect}" do
expect(symbolic_mode_to_int(*input)).to eq(result)
end
end
# Now, test some failure modes.
it "should fail if no mode is given" do
expect { symbolic_mode_to_int('') }.
to raise_error Puppet::Error, /empty mode string/
end
%w{u g o ug uo go ugo a uu u/x u!x u=r,,g=r}.each do |input|
it "should fail if no (valid) action is given: #{input.inspect}" do
expect { symbolic_mode_to_int(input) }.
to raise_error Puppet::Error, /Missing action/
end
end
%w{u+q u-rwF u+rw,g+rw,o+RW}.each do |input|
it "should fail with unknown op #{input.inspect}" do
expect { symbolic_mode_to_int(input) }.
to raise_error Puppet::Error, /Unknown operation/
end
end
it "should refuse to subtract the conditional execute op" do
expect { symbolic_mode_to_int("o-rwX") }.
to raise_error Puppet::Error, /only works with/
end
it "should refuse to set to the conditional execute op" do
expect { symbolic_mode_to_int("o=rwX") }.
to raise_error Puppet::Error, /only works with/
end
%w{8 08 9 09 118 119}.each do |input|
it "should fail for decimal modes: #{input.inspect}" do
expect { symbolic_mode_to_int(input) }.
to raise_error Puppet::Error, /octal/
end
end
it "should set the execute bit on a directory, without exec in original" do
expect(symbolic_mode_to_int("u+X", 0444, true).to_s(8)).to eq("544")
expect(symbolic_mode_to_int("g+X", 0444, true).to_s(8)).to eq("454")
expect(symbolic_mode_to_int("o+X", 0444, true).to_s(8)).to eq("445")
expect(symbolic_mode_to_int("+X", 0444, true).to_s(8)).to eq("555")
end
it "should set the execute bit on a file with exec in the original" do
expect(symbolic_mode_to_int("+X", 0544).to_s(8)).to eq("555")
end
it "should not set the execute bit on a file without exec on the original even if set by earlier DSL" do
expect(symbolic_mode_to_int("u+x,go+X", 0444).to_s(8)).to eq("544")
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/logging_spec.rb | spec/unit/util/logging_spec.rb | require 'spec_helper'
require 'puppet/util/logging'
Puppet::Type.newtype(:logging_test) do
newparam(:name, isnamevar: true)
newproperty(:path)
end
Puppet::Type.type(:logging_test).provide(:logging_test) do
end
class LoggingTester
include Puppet::Util::Logging
end
class PuppetStackCreator
def raise_error(exception_class)
case exception_class
when Puppet::ParseErrorWithIssue
raise exception_class.new('Oops', '/tmp/test.pp', 30, 15, nil, :SYNTAX_ERROR)
when Puppet::ParseError
raise exception_class.new('Oops', '/tmp/test.pp', 30, 15)
else
raise exception_class.new('Oops')
end
end
def call_raiser(exception_class)
Puppet::Pops::PuppetStack.stack('/tmp/test2.pp', 20, self, :raise_error, [exception_class])
end
def two_frames_and_a_raise(exception_class)
Puppet::Pops::PuppetStack.stack('/tmp/test3.pp', 15, self, :call_raiser, [exception_class])
end
def outer_rescue(exception_class)
begin
two_frames_and_a_raise(exception_class)
rescue Puppet::Error => e
Puppet.log_exception(e)
end
end
def run(exception_class)
Puppet::Pops::PuppetStack.stack('/tmp/test4.pp', 10, self, :outer_rescue, [exception_class])
end
end
describe Puppet::Util::Logging do
before do
@logger = LoggingTester.new
end
Puppet::Util::Log.eachlevel do |level|
it "should have a method for sending '#{level}' logs" do
expect(@logger).to respond_to(level)
end
end
it "should have a method for sending a log with a specified log level" do
expect(@logger).to receive(:to_s).and_return("I'm a string!")
expect(Puppet::Util::Log).to receive(:create).with(hash_including(source: "I'm a string!", level: "loglevel", message: "mymessage"))
@logger.send_log "loglevel", "mymessage"
end
describe "when sending a log" do
it "should use the Log's 'create' entrance method" do
expect(Puppet::Util::Log).to receive(:create)
@logger.notice "foo"
end
it "should send itself converted to a string as the log source" do
expect(@logger).to receive(:to_s).and_return("I'm a string!")
expect(Puppet::Util::Log).to receive(:create).with(hash_including(source: "I'm a string!"))
@logger.notice "foo"
end
it "should queue logs sent without a specified destination" do
Puppet::Util::Log.close_all
expect(Puppet::Util::Log).to receive(:queuemessage)
@logger.notice "foo"
end
it "should use the path of any provided resource type" do
resource = Puppet::Type.type(:logging_test).new :name => "foo"
expect(resource).to receive(:path).and_return("/path/to/host".to_sym)
expect(Puppet::Util::Log).to receive(:create).with(hash_including(source: "/path/to/host"))
resource.notice "foo"
end
it "should use the path of any provided resource parameter" do
resource = Puppet::Type.type(:logging_test).new :name => "foo"
param = resource.parameter(:name)
expect(param).to receive(:path).and_return("/path/to/param".to_sym)
expect(Puppet::Util::Log).to receive(:create).with(hash_including(source: "/path/to/param"))
param.notice "foo"
end
it "should send the provided argument as the log message" do
expect(Puppet::Util::Log).to receive(:create).with(hash_including(message: "foo"))
@logger.notice "foo"
end
it "should join any provided arguments into a single string for the message" do
expect(Puppet::Util::Log).to receive(:create).with(hash_including(message: "foo bar baz"))
@logger.notice ["foo", "bar", "baz"]
end
[:file, :line, :tags].each do |attr|
it "should include #{attr} if available" do
@logger.singleton_class.send(:attr_accessor, attr)
@logger.send(attr.to_s + "=", "myval")
expect(Puppet::Util::Log).to receive(:create).with(hash_including(attr => "myval"))
@logger.notice "foo"
end
end
end
describe "log_exception" do
context "when requesting a debug level it is logged at debug" do
it "the exception is a ParseErrorWithIssue and message is :default" do
expect(Puppet::Util::Log).to receive(:create) do |args|
expect(args[:message]).to eq("Test")
expect(args[:level]).to eq(:debug)
end
begin
raise Puppet::ParseErrorWithIssue, "Test"
rescue Puppet::ParseErrorWithIssue => err
Puppet.log_exception(err, :default, level: :debug)
end
end
it "the exception is something else" do
expect(Puppet::Util::Log).to receive(:create) do |args|
expect(args[:message]).to eq("Test")
expect(args[:level]).to eq(:debug)
end
begin
raise Puppet::Error, "Test"
rescue Puppet::Error => err
Puppet.log_exception(err, :default, level: :debug)
end
end
end
context "no log level is requested it defaults to err" do
it "the exception is a ParseErrorWithIssue and message is :default" do
expect(Puppet::Util::Log).to receive(:create) do |args|
expect(args[:message]).to eq("Test")
expect(args[:level]).to eq(:err)
end
begin
raise Puppet::ParseErrorWithIssue, "Test"
rescue Puppet::ParseErrorWithIssue => err
Puppet.log_exception(err)
end
end
it "the exception is something else" do
expect(Puppet::Util::Log).to receive(:create) do |args|
expect(args[:message]).to eq("Test")
expect(args[:level]).to eq(:err)
end
begin
raise Puppet::Error, "Test"
rescue Puppet::Error => err
Puppet.log_exception(err)
end
end
end
end
describe "when sending a deprecation warning" do
it "does not log a message when deprecation warnings are disabled" do
expect(Puppet).to receive(:[]).with(:disable_warnings).and_return(%w[deprecations])
expect(@logger).not_to receive(:warning)
@logger.deprecation_warning 'foo'
end
it "logs the message with warn" do
expect(@logger).to receive(:warning).with(/^foo\n/)
@logger.deprecation_warning 'foo'
end
it "only logs each offending line once" do
expect(@logger).to receive(:warning).with(/^foo\n/).once
5.times { @logger.deprecation_warning 'foo' }
end
it "ensures that deprecations from same origin are logged if their keys differ" do
expect(@logger).to receive(:warning).with(/deprecated foo/).exactly(5).times()
5.times { |i| @logger.deprecation_warning('deprecated foo', :key => "foo#{i}") }
end
it "does not duplicate deprecations for a given key" do
expect(@logger).to receive(:warning).with(/deprecated foo/).once
5.times { @logger.deprecation_warning('deprecated foo', :key => 'foo-msg') }
end
it "only logs the first 100 messages" do
(1..100).each { |i|
expect(@logger).to receive(:warning).with(/^#{i}\n/).once
# since the deprecation warning will only log each offending line once, we have to do some tomfoolery
# here in order to make it think each of these calls is coming from a unique call stack; we're basically
# mocking the method that it would normally use to find the call stack.
expect(@logger).to receive(:get_deprecation_offender).and_return(["deprecation log count test ##{i}"])
@logger.deprecation_warning i
}
expect(@logger).not_to receive(:warning).with(101)
@logger.deprecation_warning 101
end
end
describe "when sending a puppet_deprecation_warning" do
it "requires file and line or key options" do
expect do
@logger.puppet_deprecation_warning("foo")
end.to raise_error(Puppet::DevError, /Need either :file and :line, or :key/)
expect do
@logger.puppet_deprecation_warning("foo", :file => 'bar')
end.to raise_error(Puppet::DevError, /Need either :file and :line, or :key/)
expect do
@logger.puppet_deprecation_warning("foo", :key => 'akey')
@logger.puppet_deprecation_warning("foo", :file => 'afile', :line => 1)
end.to_not raise_error
end
it "warns with file and line" do
expect(@logger).to receive(:warning).with(/deprecated foo.*\(file: afile, line: 5\)/m)
@logger.puppet_deprecation_warning("deprecated foo", :file => 'afile', :line => 5)
end
it "warns keyed from file and line" do
expect(@logger).to receive(:warning).with(/deprecated foo.*\(file: afile, line: 5\)/m).once
5.times do
@logger.puppet_deprecation_warning("deprecated foo", :file => 'afile', :line => 5)
end
end
it "warns with separate key only once regardless of file and line" do
expect(@logger).to receive(:warning).with(/deprecated foo.*\(file: afile, line: 5\)/m).once
@logger.puppet_deprecation_warning("deprecated foo", :key => 'some_key', :file => 'afile', :line => 5)
@logger.puppet_deprecation_warning("deprecated foo", :key => 'some_key', :file => 'bfile', :line => 3)
end
it "warns with key but no file and line" do
expect(@logger).to receive(:warning).with(/deprecated foo.*\(file: unknown, line: unknown\)/m)
@logger.puppet_deprecation_warning("deprecated foo", :key => 'some_key')
end
end
describe "when sending a warn_once" do
before(:each) {
@logger.clear_deprecation_warnings
}
it "warns with file when only file is given" do
expect(@logger).to receive(:send_log).with(:warning, /wet paint.*\(file: aFile\)/m)
@logger.warn_once('kind', 'wp', "wet paint", 'aFile')
end
it "warns with unknown file and line when only line is given" do
expect(@logger).to receive(:send_log).with(:warning, /wet paint.*\(line: 5\)/m)
@logger.warn_once('kind', 'wp', "wet paint", nil, 5)
end
it "warns with file and line when both are given" do
expect(@logger).to receive(:send_log).with(:warning, /wet paint.*\(file: aFile, line: 5\)/m)
@logger.warn_once('kind', 'wp', "wet paint",'aFile', 5)
end
it "warns once per key" do
expect(@logger).to receive(:send_log).with(:warning, /wet paint.*/m).once
5.times do
@logger.warn_once('kind', 'wp', "wet paint")
end
end
Puppet::Util::Log.eachlevel do |level|
it "can use log level #{level}" do
expect(@logger).to receive(:send_log).with(level, /wet paint.*/m).once
5.times do
@logger.warn_once('kind', 'wp', "wet paint", nil, nil, level)
end
end
end
end
describe "does not warn about undefined variables when disabled_warnings says so" do
let(:logger) { LoggingTester.new }
before(:each) do
Puppet.settings.initialize_global_settings
logger.clear_deprecation_warnings
Puppet[:disable_warnings] = ['undefined_variables']
end
after(:each) do
Puppet[:disable_warnings] = []
allow(logger).to receive(:send_log).and_call_original()
allow(Facter).to receive(:respond_to?).and_call_original()
allow(Facter).to receive(:debugging).and_call_original()
end
it "does not produce warning if kind is disabled" do
expect(logger).not_to receive(:send_log)
logger.warn_once('undefined_variables', 'wp', "wet paint")
end
end
describe "warns about undefined variables when deprecations are in disabled_warnings" do
let(:logger) { LoggingTester.new }
before(:each) do
Puppet.settings.initialize_global_settings
logger.clear_deprecation_warnings
Puppet[:disable_warnings] = ['deprecations']
end
after(:each) do
Puppet[:disable_warnings] = []
allow(logger).to receive(:send_log).and_call_original()
allow(Facter).to receive(:respond_to?).and_call_original()
allow(Facter).to receive(:debugging).and_call_original()
end
it "produces warning even if deprecation warnings are disabled " do
expect(logger).to receive(:send_log).with(:warning, /wet paint/).once
logger.warn_once('undefined_variables', 'wp', "wet paint")
end
end
describe "when formatting exceptions" do
it "should be able to format a chain of exceptions" do
exc3 = Puppet::Error.new("original")
exc3.set_backtrace(["1.rb:4:in `a'","2.rb:2:in `b'","3.rb:1"])
exc2 = Puppet::Error.new("second", exc3)
exc2.set_backtrace(["4.rb:8:in `c'","5.rb:1:in `d'","6.rb:3"])
exc1 = Puppet::Error.new("third", exc2)
exc1.set_backtrace(["7.rb:31:in `e'","8.rb:22:in `f'","9.rb:9"])
# whoa ugly
expect(@logger.format_exception(exc1)).to match(/third
.*7\.rb:31:in `e'
.*8\.rb:22:in `f'
.*9\.rb:9
Wrapped exception:
second
.*4\.rb:8:in `c'
.*5\.rb:1:in `d'
.*6\.rb:3
Wrapped exception:
original
.*1\.rb:4:in `a'
.*2\.rb:2:in `b'
.*3\.rb:1/)
end
describe "when trace is disabled" do
it 'excludes backtrace for RuntimeError in log message' do
begin
raise RuntimeError, 'Oops'
rescue RuntimeError => e
Puppet.log_exception(e)
end
expect(@logs.size).to eq(1)
log = @logs[0]
expect(log.message).to_not match('/logging_spec.rb')
expect(log.backtrace).to be_nil
end
it "backtrace member is unset when logging ParseErrorWithIssue" do
begin
raise Puppet::ParseErrorWithIssue.new('Oops', '/tmp/test.pp', 30, 15, nil, :SYNTAX_ERROR)
rescue RuntimeError => e
Puppet.log_exception(e)
end
expect(@logs.size).to eq(1)
log = @logs[0]
expect(log.message).to_not match('/logging_spec.rb')
expect(log.backtrace).to be_nil
end
end
describe "when trace is enabled" do
it 'includes backtrace for RuntimeError in log message when enabled globally' do
Puppet[:trace] = true
begin
raise RuntimeError, 'Oops'
rescue RuntimeError => e
Puppet.log_exception(e, :default)
end
Puppet[:trace] = false
expect(@logs.size).to eq(1)
log = @logs[0]
expect(log.message).to match('/logging_spec.rb')
expect(log.backtrace).to be_nil
end
it 'includes backtrace for RuntimeError in log message when enabled via option' do
begin
raise RuntimeError, 'Oops'
rescue RuntimeError => e
Puppet.log_exception(e, :default, :trace => true)
end
expect(@logs.size).to eq(1)
log = @logs[0]
expect(log.message).to match('/logging_spec.rb')
expect(log.backtrace).to be_nil
end
it "backtrace member is set when logging ParseErrorWithIssue" do
begin
raise Puppet::ParseErrorWithIssue.new('Oops', '/tmp/test.pp', 30, 15, nil, :SYNTAX_ERROR)
rescue RuntimeError => e
Puppet.log_exception(e, :default, :trace => true)
end
expect(@logs.size).to eq(1)
log = @logs[0]
expect(log.message).to_not match('/logging_spec.rb')
expect(log.backtrace).to be_a(Array)
expect(log.backtrace[0]).to match('/logging_spec.rb')
end
it "backtrace has interleaved PuppetStack when logging ParseErrorWithIssue" do
Puppet[:trace] = true
PuppetStackCreator.new.run(Puppet::ParseErrorWithIssue)
Puppet[:trace] = false
expect(@logs.size).to eq(1)
log = @logs[0]
expect(log.message).to_not match('/logging_spec.rb')
expect(log.backtrace[0]).to match('/logging_spec.rb')
expect(log.backtrace[1]).to match('/tmp/test2.pp:20')
puppetstack = log.backtrace.select { |l| l =~ /tmp\/test\d\.pp/ }
expect(puppetstack.length).to equal 3
end
it "message has interleaved PuppetStack when logging ParseError" do
Puppet[:trace] = true
PuppetStackCreator.new.run(Puppet::ParseError)
Puppet[:trace] = false
expect(@logs.size).to eq(1)
log = @logs[0]
log_lines = log.message.split("\n")
expect(log_lines[1]).to match('/logging_spec.rb')
expect(log_lines[2]).to match('/tmp/test2.pp:20')
puppetstack = log_lines.select { |l| l =~ /tmp\/test\d\.pp/ }
expect(puppetstack.length).to equal 3
end
end
describe "when trace is disabled but puppet_trace is enabled" do
it "includes only PuppetStack as backtrace member with ParseErrorWithIssue" do
Puppet[:trace] = false
Puppet[:puppet_trace] = true
PuppetStackCreator.new.run(Puppet::ParseErrorWithIssue)
Puppet[:trace] = false
Puppet[:puppet_trace] = false
expect(@logs.size).to eq(1)
log = @logs[0]
expect(log.backtrace[0]).to match('/tmp/test2.pp:20')
expect(log.backtrace.length).to equal 3
end
it "includes only PuppetStack in message with ParseError" do
Puppet[:trace] = false
Puppet[:puppet_trace] = true
PuppetStackCreator.new.run(Puppet::ParseError)
Puppet[:trace] = false
Puppet[:puppet_trace] = false
expect(@logs.size).to eq(1)
log = @logs[0]
log_lines = log.message.split("\n")
expect(log_lines[1]).to match('/tmp/test2.pp:20')
puppetstack = log_lines.select { |l| l =~ /tmp\/test\d\.pp/ }
expect(puppetstack.length).to equal 3
end
end
it 'includes position details for ParseError in log message' do
begin
raise Puppet::ParseError.new('Oops', '/tmp/test.pp', 30, 15)
rescue RuntimeError => e
Puppet.log_exception(e)
end
expect(@logs.size).to eq(1)
log = @logs[0]
expect(log.message).to match(/ \(file: \/tmp\/test\.pp, line: 30, column: 15\)/)
expect(log.message).to be(log.to_s)
end
it 'excludes position details for ParseErrorWithIssue from log message' do
begin
raise Puppet::ParseErrorWithIssue.new('Oops', '/tmp/test.pp', 30, 15, nil, :SYNTAX_ERROR)
rescue RuntimeError => e
Puppet.log_exception(e)
end
expect(@logs.size).to eq(1)
log = @logs[0]
expect(log.message).to_not match(/ \(file: \/tmp\/test\.pp, line: 30, column: 15\)/)
expect(log.to_s).to match(/ \(file: \/tmp\/test\.pp, line: 30, column: 15\)/)
expect(log.issue_code).to eq(:SYNTAX_ERROR)
expect(log.file).to eq('/tmp/test.pp')
expect(log.line).to eq(30)
expect(log.pos).to eq(15)
end
end
describe 'when Facter' do
after :each do
# Unstub these calls as there is global code run after
# each spec that may reset the log level to debug
allow(Facter).to receive(:respond_to?).and_call_original()
allow(Facter).to receive(:debugging).and_call_original()
end
describe 'does support debugging' do
before :each do
allow(Facter).to receive(:respond_to?).with(:on_message).and_return(true)
allow(Facter).to receive(:respond_to?).with(:debugging, any_args).and_return(true)
end
it 'enables Facter debugging when debug level' do
allow(Facter).to receive(:debugging).with(true)
Puppet::Util::Log.level = :debug
end
it 'disables Facter debugging when not debug level' do
allow(Facter).to receive(:debugging).with(false)
Puppet::Util::Log.level = :info
end
end
describe 'does support trace' do
before :each do
allow(Facter).to receive(:respond_to?).with(:on_message)
allow(Facter).to receive(:respond_to?).with(:trace, any_args).and_return(true)
end
it 'enables Facter trace when enabled' do
allow(Facter).to receive(:trace).with(true)
Puppet[:trace] = true
end
it 'disables Facter trace when disabled' do
allow(Facter).to receive(:trace).with(false)
Puppet[:trace] = false
end
end
describe 'does support on_message' do
before :each do
allow(Facter).to receive(:respond_to?).with(:on_message, any_args).and_return(true)
end
def setup(level, message)
allow(Facter).to receive(:on_message).and_yield(level, message)
# Transform from Facter level to Puppet level
case level
when :trace
level = :debug
when :warn
level = :warning
when :error
level = :err
when :fatal
level = :crit
end
allow(Puppet::Util::Log).to receive(:create).with(hash_including(level: level, message: message, source: 'Facter')).once
end
[:trace, :debug, :info, :warn, :error, :fatal].each do |level|
it "calls Facter.on_message and handles #{level} messages" do
setup(level, "#{level} message")
expect(Puppet::Util::Logging::setup_facter_logging!).to be_truthy
end
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/autoload_spec.rb | spec/unit/util/autoload_spec.rb | require 'spec_helper'
require 'fileutils'
require 'puppet/util/autoload'
describe Puppet::Util::Autoload do
include PuppetSpec::Files
let(:env) { Puppet::Node::Environment.create(:foo, []) }
before do
@autoload = Puppet::Util::Autoload.new("foo", "tmp")
@loaded = {}
allow(@autoload.class).to receive(:loaded).and_return(@loaded)
end
describe "when building the search path" do
before :each do
## modulepath/libdir can't be used until after app settings are initialized, so we need to simulate that:
allow(Puppet.settings).to receive(:app_defaults_initialized?).and_return(true)
end
def with_libdir(libdir)
begin
old_loadpath = $LOAD_PATH.dup
old_libdir = Puppet[:libdir]
Puppet[:libdir] = libdir
$LOAD_PATH.unshift(libdir)
yield
ensure
Puppet[:libdir] = old_libdir
$LOAD_PATH.clear
$LOAD_PATH.concat(old_loadpath)
end
end
it "should collect all of the lib directories that exist in the current environment's module path" do
dira = dir_containing('dir_a', {
"one" => {},
"two" => { "lib" => {} }
})
dirb = dir_containing('dir_a', {
"one" => {},
"two" => { "lib" => {} }
})
environment = Puppet::Node::Environment.create(:foo, [dira, dirb])
expect(@autoload.class.module_directories(environment)).to eq(["#{dira}/two/lib", "#{dirb}/two/lib"])
end
it "ignores missing module directories" do
environment = Puppet::Node::Environment.create(:foo, [File.expand_path('does/not/exist')])
expect(@autoload.class.module_directories(environment)).to be_empty
end
it "ignores the configured environment when it doesn't exist" do
Puppet[:environment] = 'nonexistent'
env = Puppet::Node::Environment.create(:dev, [])
Puppet.override(environments: Puppet::Environments::Static.new(env)) do
expect(@autoload.class.module_directories(Puppet.lookup(:current_environment))).to be_empty
end
end
it "raises when no environment is given" do
Puppet[:environment] = 'nonexistent'
Puppet.override(environments: Puppet::Environments::Static.new) do
expect {
@autoload.class.module_directories(nil)
}.to raise_error(ArgumentError, /Autoloader requires an environment/)
end
end
it "should include the module directories, the Puppet libdir, Ruby load directories, and vendored modules" do
vendor_dir = tmpdir('vendor_modules')
module_libdir = File.join(vendor_dir, 'amodule_core', 'lib')
FileUtils.mkdir_p(module_libdir)
libdir = File.expand_path('/libdir1')
Puppet[:vendormoduledir] = vendor_dir
Puppet.initialize_settings
with_libdir(libdir) do
expect(@autoload.class).to receive(:gem_directories).and_return(%w{/one /two})
expect(@autoload.class).to receive(:module_directories).and_return(%w{/three /four})
dirs = @autoload.class.search_directories(nil)
expect(dirs[0..4]).to eq(%w{/one /two /three /four} + [libdir])
expect(dirs.last).to eq(module_libdir)
end
end
it "does not split the Puppet[:libdir]" do
dir = File.expand_path("/libdir1#{File::PATH_SEPARATOR}/libdir2")
with_libdir(dir) do
expect(@autoload.class).to receive(:gem_directories).and_return(%w{/one /two})
expect(@autoload.class).to receive(:module_directories).and_return(%w{/three /four})
dirs = @autoload.class.search_directories(nil)
expect(dirs).to include(dir)
end
end
end
describe "when loading a file" do
before do
allow(@autoload.class).to receive(:search_directories).and_return([make_absolute("/a")])
allow(FileTest).to receive(:directory?).and_return(true)
@time_a = Time.utc(2010, 'jan', 1, 6, 30)
allow(File).to receive(:mtime).and_return(@time_a)
end
after(:each) do
$LOADED_FEATURES.delete("/a/tmp/myfile.rb")
end
[RuntimeError, LoadError, SyntaxError].each do |error|
it "should die with Puppet::Error if a #{error.to_s} exception is thrown" do
allow(Puppet::FileSystem).to receive(:exist?).and_return(true)
expect(Kernel).to receive(:load).and_raise(error)
expect { @autoload.load("foo", env) }.to raise_error(Puppet::Error)
end
end
it "should not raise an error if the file is missing" do
expect(@autoload.load("foo", env)).to eq(false)
end
it "should register loaded files with the autoloader" do
allow(Puppet::FileSystem).to receive(:exist?).and_return(true)
allow(Kernel).to receive(:load)
@autoload.load("myfile", env)
expect(@autoload.class.loaded?("tmp/myfile.rb")).to be
end
it "should be seen by loaded? on the instance using the short name" do
allow(Puppet::FileSystem).to receive(:exist?).and_return(true)
allow(Kernel).to receive(:load)
@autoload.load("myfile", env)
expect(@autoload.loaded?("myfile.rb")).to be
end
it "should register loaded files with the main loaded file list so they are not reloaded by ruby" do
allow(Puppet::FileSystem).to receive(:exist?).and_return(true)
allow(Kernel).to receive(:load)
@autoload.load("myfile", env)
expect($LOADED_FEATURES).to be_include(make_absolute("/a/tmp/myfile.rb"))
end
it "should load the first file in the searchpath" do
allow(@autoload.class).to receive(:search_directories).and_return([make_absolute("/a"), make_absolute("/b")])
allow(FileTest).to receive(:directory?).and_return(true)
allow(Puppet::FileSystem).to receive(:exist?).and_return(true)
expect(Kernel).to receive(:load).with(make_absolute("/a/tmp/myfile.rb"), any_args)
@autoload.load("myfile", env)
end
it "should treat equivalent paths to a loaded file as loaded" do
allow(Puppet::FileSystem).to receive(:exist?).and_return(true)
allow(Kernel).to receive(:load)
@autoload.load("myfile", env)
expect(@autoload.class.loaded?("tmp/myfile")).to be
expect(@autoload.class.loaded?("tmp/./myfile.rb")).to be
expect(@autoload.class.loaded?("./tmp/myfile.rb")).to be
expect(@autoload.class.loaded?("tmp/../tmp/myfile.rb")).to be
end
end
describe "when loading all files" do
let(:basedir) { tmpdir('autoloader') }
let(:path) { File.join(basedir, @autoload.path, 'file.rb') }
before do
FileUtils.mkdir_p(File.dirname(path))
FileUtils.touch(path)
allow(@autoload.class).to receive(:search_directories).and_return([basedir])
end
[RuntimeError, LoadError, SyntaxError].each do |error|
it "should die an if a #{error.to_s} exception is thrown" do
expect(Kernel).to receive(:load).and_raise(error)
expect { @autoload.loadall(env) }.to raise_error(Puppet::Error)
end
end
it "should require the full path to the file" do
expect(Kernel).to receive(:load).with(path, any_args)
@autoload.loadall(env)
end
it "autoloads from a directory whose ancestor is Windows 8.3", if: Puppet::Util::Platform.windows? do
pending("GH runners seem to have disabled 8.3 support")
# File.expand_path will expand ~ in the last directory component only(!)
# so create an ancestor directory with a long path
dir = File.join(tmpdir('longpath'), 'short')
path = File.join(dir, @autoload.path, 'file.rb')
FileUtils.mkdir_p(File.dirname(path))
FileUtils.touch(path)
dir83 = File.join(File.dirname(basedir), 'longpa~1', 'short')
path83 = File.join(dir83, @autoload.path, 'file.rb')
allow(@autoload.class).to receive(:search_directories).and_return([dir83])
expect(Kernel).to receive(:load).with(path83, any_args)
@autoload.loadall(env)
end
end
describe "when reloading files" do
before :each do
@file_a = make_absolute("/a/file.rb")
@file_b = make_absolute("/b/file.rb")
@first_time = Time.utc(2010, 'jan', 1, 6, 30)
@second_time = @first_time + 60
end
after :each do
$LOADED_FEATURES.delete("a/file.rb")
$LOADED_FEATURES.delete("b/file.rb")
end
it "#changed? should return true for a file that was not loaded" do
expect(@autoload.class.changed?(@file_a, env)).to be
end
it "changes should be seen by changed? on the instance using the short name" do
allow(File).to receive(:mtime).and_return(@first_time)
allow(Puppet::FileSystem).to receive(:exist?).and_return(true)
allow(Kernel).to receive(:load)
@autoload.load("myfile", env)
expect(@autoload.loaded?("myfile")).to be
expect(@autoload.changed?("myfile", env)).not_to be
allow(File).to receive(:mtime).and_return(@second_time)
expect(@autoload.changed?("myfile", env)).to be
$LOADED_FEATURES.delete("tmp/myfile.rb")
end
describe "in one directory" do
before :each do
allow(@autoload.class).to receive(:search_directories).and_return([make_absolute("/a")])
expect(File).to receive(:mtime).with(@file_a).and_return(@first_time)
@autoload.class.mark_loaded("file", @file_a)
end
it "should reload if mtime changes" do
allow(File).to receive(:mtime).with(@file_a).and_return(@first_time + 60)
allow(Puppet::FileSystem).to receive(:exist?).with(@file_a).and_return(true)
expect(Kernel).to receive(:load).with(@file_a, any_args)
@autoload.class.reload_changed(env)
end
it "should do nothing if the file is deleted" do
allow(File).to receive(:mtime).with(@file_a).and_raise(Errno::ENOENT)
allow(Puppet::FileSystem).to receive(:exist?).with(@file_a).and_return(false)
expect(Kernel).not_to receive(:load)
@autoload.class.reload_changed(env)
end
end
describe "in two directories" do
before :each do
allow(@autoload.class).to receive(:search_directories).and_return([make_absolute("/a"), make_absolute("/b")])
end
it "should load b/file when a/file is deleted" do
expect(File).to receive(:mtime).with(@file_a).and_return(@first_time)
@autoload.class.mark_loaded("file", @file_a)
allow(File).to receive(:mtime).with(@file_a).and_raise(Errno::ENOENT)
allow(Puppet::FileSystem).to receive(:exist?).with(@file_a).and_return(false)
allow(Puppet::FileSystem).to receive(:exist?).with(@file_b).and_return(true)
allow(File).to receive(:mtime).with(@file_b).and_return(@first_time)
expect(Kernel).to receive(:load).with(@file_b, any_args)
@autoload.class.reload_changed(env)
expect(@autoload.class.send(:loaded)["file"]).to eq([@file_b, @first_time])
end
it "should load a/file when b/file is loaded and a/file is created" do
allow(File).to receive(:mtime).with(@file_b).and_return(@first_time)
allow(Puppet::FileSystem).to receive(:exist?).with(@file_b).and_return(true)
@autoload.class.mark_loaded("file", @file_b)
allow(File).to receive(:mtime).with(@file_a).and_return(@first_time)
allow(Puppet::FileSystem).to receive(:exist?).with(@file_a).and_return(true)
expect(Kernel).to receive(:load).with(@file_a, any_args)
@autoload.class.reload_changed(env)
expect(@autoload.class.send(:loaded)["file"]).to eq([@file_a, @first_time])
end
end
end
describe "#cleanpath" do
it "should leave relative paths relative" do
path = "hello/there"
expect(Puppet::Util::Autoload.cleanpath(path)).to eq(path)
end
describe "on Windows", :if => Puppet::Util::Platform.windows? do
it "should convert c:\ to c:/" do
expect(Puppet::Util::Autoload.cleanpath('c:\\')).to eq('c:/')
end
it "should convert all backslashes to forward slashes" do
expect(Puppet::Util::Autoload.cleanpath('c:\projects\ruby\bug\test.rb')).to eq('c:/projects/ruby/bug/test.rb')
end
end
end
describe "#expand" do
it "should expand relative to the autoloader's prefix" do
expect(@autoload.expand('bar')).to eq('tmp/bar')
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/json_lockfile_spec.rb | spec/unit/util/json_lockfile_spec.rb | require 'spec_helper'
require 'puppet/util/json_lockfile'
describe Puppet::Util::JsonLockfile do
require 'puppet_spec/files'
include PuppetSpec::Files
before(:each) do
@lockfile = tmpfile("lock")
@lock = Puppet::Util::JsonLockfile.new(@lockfile)
end
describe "#lock" do
it "should create a lock file containing a json hash" do
data = { "foo" => "foofoo", "bar" => "barbar" }
@lock.lock(data)
expect(JSON.parse(File.read(@lockfile))).to eq(data)
end
end
describe "reading lock data" do
it "returns deserialized JSON from the lockfile" do
data = { "foo" => "foofoo", "bar" => "barbar" }
@lock.lock(data)
expect(@lock.lock_data).to eq data
end
it "returns nil if the file read returned nil" do
@lock.lock
allow(File).to receive(:read).and_return(nil)
expect(@lock.lock_data).to be_nil
end
it "returns nil if the file was empty" do
@lock.lock
allow(File).to receive(:read).and_return('')
expect(@lock.lock_data).to be_nil
end
it "returns nil if the file was not in PSON" do
@lock.lock
allow(File).to receive(:read).and_return('][')
expect(@lock.lock_data).to be_nil
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/tagging_spec.rb | spec/unit/util/tagging_spec.rb | # coding: utf-8
require 'spec_helper'
require 'puppet/util/tagging'
describe Puppet::Util::Tagging do
let(:tagger) { Object.new.extend(Puppet::Util::Tagging) }
it "should add tags to the returned tag list" do
tagger.tag("one")
expect(tagger.tags).to include("one")
end
it "should add all provided tags to the tag list" do
tagger.tag("one", "two")
expect(tagger.tags).to include("one")
expect(tagger.tags).to include("two")
end
it "should fail on tags containing '*' characters" do
expect { tagger.tag("bad*tag") }.to raise_error(Puppet::ParseError)
end
it "should fail on tags starting with '-' characters" do
expect { tagger.tag("-badtag") }.to raise_error(Puppet::ParseError)
end
it "should fail on tags containing ' ' characters" do
expect { tagger.tag("bad tag") }.to raise_error(Puppet::ParseError)
end
it "should fail on tags containing newline characters" do
expect { tagger.tag("bad\ntag") }.to raise_error(Puppet::ParseError)
end
it "should allow alpha tags" do
expect { tagger.tag("good_tag") }.not_to raise_error
end
it "should allow tags containing '.' characters" do
expect { tagger.tag("good.tag") }.to_not raise_error
end
# different UTF-8 widths
# 1-byte A
# 2-byte ۿ - http://www.fileformat.info/info/unicode/char/06ff/index.htm - 0xDB 0xBF / 219 191
# 3-byte ᚠ - http://www.fileformat.info/info/unicode/char/16A0/index.htm - 0xE1 0x9A 0xA0 / 225 154 160
# 4-byte - http://www.fileformat.info/info/unicode/char/2070E/index.htm - 0xF0 0xA0 0x9C 0x8E / 240 160 156 142
let (:mixed_utf8) { "A\u06FF\u16A0\u{2070E}" } # Aۿᚠ
it "should allow UTF-8 alphanumeric characters" do
expect { tagger.tag(mixed_utf8) }.not_to raise_error
end
# completely non-exhaustive list of a few UTF-8 punctuation characters
# http://www.fileformat.info/info/unicode/block/general_punctuation/utf8test.htm
[
"\u2020", # dagger †
"\u203B", # reference mark ※
"\u204F", # reverse semicolon ⁏
"!",
"@",
"#",
"$",
"%",
"^",
"&",
"*",
"(",
")",
"-",
"+",
"=",
"{",
"}",
"[",
"]",
"|",
"\\",
"/",
"?",
"<",
">",
",",
".",
"~",
",",
":",
";",
"\"",
"'",
].each do |char|
it "should not allow UTF-8 punctuation characters, e.g. #{char}" do
expect { tagger.tag(char) }.to raise_error(Puppet::ParseError)
end
end
it "should allow encodings that can be coerced to UTF-8" do
chinese = "標記你是它".force_encoding(Encoding::UTF_8)
ascii = "tags--".force_encoding(Encoding::ASCII_8BIT)
jose = "jos\xE9".force_encoding(Encoding::ISO_8859_1)
[chinese, ascii, jose].each do |tag|
expect(tagger.valid_tag?(tag)).to be_truthy
end
end
it "should not allow strings that cannot be converted to UTF-8" do
invalid = "\xA0".force_encoding(Encoding::ASCII_8BIT)
expect(tagger.valid_tag?(invalid)).to be_falsey
end
it "should add qualified classes as tags" do
tagger.tag("one::two")
expect(tagger.tags).to include("one::two")
end
it "should add each part of qualified classes as tags" do
tagger.tag("one::two::three")
expect(tagger.tags).to include('one')
expect(tagger.tags).to include("two")
expect(tagger.tags).to include("three")
end
it "should indicate when the object is tagged with a provided tag" do
tagger.tag("one")
expect(tagger).to be_tagged("one")
end
it "should indicate when the object is not tagged with a provided tag" do
expect(tagger).to_not be_tagged("one")
end
it "should indicate when the object is tagged with any tag in an array" do
tagger.tag("one")
expect(tagger).to be_tagged("one","two","three")
end
it "should indicate when the object is not tagged with any tag in an array" do
tagger.tag("one")
expect(tagger).to_not be_tagged("two","three")
end
context "when tagging" do
it "converts symbols to strings" do
tagger.tag(:hello)
expect(tagger.tags).to include('hello')
end
it "downcases tags" do
tagger.tag(:HEllO)
tagger.tag("GooDByE")
expect(tagger).to be_tagged("hello")
expect(tagger).to be_tagged("goodbye")
end
it "downcases tag arguments" do
tagger.tag("hello")
tagger.tag("goodbye")
expect(tagger).to be_tagged(:HEllO)
expect(tagger).to be_tagged("GooDByE")
end
it "accepts hyphenated tags" do
tagger.tag("my-tag")
expect(tagger).to be_tagged("my-tag")
end
it 'skips undef /nil tags' do
tagger.tag('before')
tagger.tag(nil)
tagger.tag('after')
expect(tagger).to_not be_tagged(nil)
expect(tagger).to_not be_tagged('')
expect(tagger).to_not be_tagged('undef')
expect(tagger).to be_tagged('before')
expect(tagger).to be_tagged('after')
end
end
context "when querying if tagged" do
it "responds true if queried on the entire set" do
tagger.tag("one", "two")
expect(tagger).to be_tagged("one", "two")
end
it "responds true if queried on a subset" do
tagger.tag("one", "two", "three")
expect(tagger).to be_tagged("two", "one")
end
it "responds true if queried on an overlapping but not fully contained set" do
tagger.tag("one", "two")
expect(tagger).to be_tagged("zero", "one")
end
it "responds false if queried on a disjoint set" do
tagger.tag("one", "two", "three")
expect(tagger).to_not be_tagged("five")
end
it "responds false if queried on the empty set" do
expect(tagger).to_not be_tagged
end
end
context "when assigning tags" do
it "splits a string on ','" do
tagger.tags = "one, two, three"
expect(tagger).to be_tagged("one")
expect(tagger).to be_tagged("two")
expect(tagger).to be_tagged("three")
end
it "protects against empty tags" do
expect { tagger.tags = "one,,two"}.to raise_error(/Invalid tag ''/)
end
it "takes an array of tags" do
tagger.tags = ["one", "two"]
expect(tagger).to be_tagged("one")
expect(tagger).to be_tagged("two")
end
it "removes any existing tags when reassigning" do
tagger.tags = "one, two"
tagger.tags = "three, four"
expect(tagger).to_not be_tagged("one")
expect(tagger).to_not be_tagged("two")
expect(tagger).to be_tagged("three")
expect(tagger).to be_tagged("four")
end
it "allows empty tags that are generated from :: separated tags" do
tagger.tags = "one::::two::three"
expect(tagger).to be_tagged("one")
expect(tagger).to be_tagged("")
expect(tagger).to be_tagged("two")
expect(tagger).to be_tagged("three")
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/constant_inflector_spec.rb | spec/unit/util/constant_inflector_spec.rb | require 'spec_helper'
require 'puppet/util/constant_inflector'
describe Puppet::Util::ConstantInflector, "when converting file names to constants" do
it "should capitalize terms" do
expect(subject.file2constant("file")).to eq("File")
end
it "should switch all '/' characters to double colons" do
expect(subject.file2constant("file/other")).to eq("File::Other")
end
it "should remove underscores and capitalize the proceeding letter" do
expect(subject.file2constant("file_other")).to eq("FileOther")
end
it "should correctly replace as many underscores as exist in the file name" do
expect(subject.file2constant("two_under_scores/with_some_more_underscores")).to eq("TwoUnderScores::WithSomeMoreUnderscores")
end
it "should collapse multiple underscores" do
expect(subject.file2constant("many___scores")).to eq("ManyScores")
end
it "should correctly handle file names deeper than two directories" do
expect(subject.file2constant("one_two/three_four/five_six")).to eq("OneTwo::ThreeFour::FiveSix")
end
end
describe Puppet::Util::ConstantInflector, "when converting constnats to file names" do
it "should convert them to a string if necessary" do
expect(subject.constant2file(Puppet::Util::ConstantInflector)).to be_instance_of(String)
end
it "should accept string inputs" do
expect(subject.constant2file("Puppet::Util::ConstantInflector")).to be_instance_of(String)
end
it "should downcase all terms" do
expect(subject.constant2file("Puppet")).to eq("puppet")
end
it "should convert '::' to '/'" do
expect(subject.constant2file("Puppet::Util::Constant")).to eq("puppet/util/constant")
end
it "should convert mid-word capitalization to an underscore" do
expect(subject.constant2file("OneTwo::ThreeFour")).to eq("one_two/three_four")
end
it "should correctly handle constants with more than two parts" do
expect(subject.constant2file("OneTwoThree::FourFiveSixSeven")).to eq("one_two_three/four_five_six_seven")
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/pidlock_spec.rb | spec/unit/util/pidlock_spec.rb | require 'spec_helper'
require 'puppet/util/pidlock'
describe Puppet::Util::Pidlock, if: !Puppet::Util::Platform.jruby? do
require 'puppet_spec/files'
include PuppetSpec::Files
before(:each) do
@lockfile = tmpfile("lock")
@lock = Puppet::Util::Pidlock.new(@lockfile)
allow(Facter).to receive(:value).with(:kernel).and_return('Linux')
end
describe "#ps pid argument on posix", unless: Puppet::Util::Platform.windows? do
let(:other_pid) { Process.pid + 1 }
before do
# another process has locked the pidfile
File.write(@lockfile, other_pid)
# and it's still active
allow(Process).to receive(:kill).with(0, other_pid)
end
it "should fallback to '-p' when ps execution fails with '-eq' on Linux" do
allow(Puppet::Util::Execution).to receive(:execute).with(['ps', '-eq', other_pid, '-o', 'comm=']).and_raise(Puppet::ExecutionFailure, 'Execution of command returned 1: error')
expect(Puppet::Util::Execution).to receive(:execute).with(['ps', "-p", other_pid, '-o', 'comm=']).and_return('puppet')
expect(Puppet::Util::Execution).to receive(:execute).with(['ps', "-p", other_pid, '-o', 'args=']).and_return('puppet')
expect(@lock).to be_locked
end
shared_examples_for 'a valid ps argument was provided' do |desired_kernel, ps_argument|
it "should be '#{ps_argument}' when current kernel is #{desired_kernel}" do
allow(Facter).to receive(:value).with(:kernel).and_return(desired_kernel)
allow(Puppet::Util::Execution).to receive(:execute).with(['ps', ps_argument, other_pid, '-o', 'comm=']).and_return('ruby')
allow(Puppet::Util::Execution).to receive(:execute).with(['ps', ps_argument, other_pid, '-o', 'args=']).and_return('puppet')
expect(@lock).to be_locked
end
end
context "when current kernel is Linux" do
it_should_behave_like 'a valid ps argument was provided', "Linux", "-eq"
end
context "when current kernel is AIX" do
it_should_behave_like 'a valid ps argument was provided', "AIX", "-T"
end
context "when current kernel is Darwin" do
it_should_behave_like 'a valid ps argument was provided', "Darwin", "-p"
end
end
describe "#lock" do
it "should not be locked at start" do
expect(@lock).not_to be_locked
end
it "should not be mine at start" do
expect(@lock).not_to be_mine
end
it "should become locked" do
@lock.lock
expect(@lock).to be_locked
end
it "should become mine" do
@lock.lock
expect(@lock).to be_mine
end
it "should be possible to lock multiple times" do
@lock.lock
expect { @lock.lock }.not_to raise_error
end
it "should return true when locking" do
expect(@lock.lock).to be_truthy
end
it "should return true if locked by me" do
@lock.lock
expect(@lock.lock).to be_truthy
end
it "should create a lock file" do
@lock.lock
expect(Puppet::FileSystem.exist?(@lockfile)).to be_truthy
end
it 'should create an empty lock file even when pid is missing' do
allow(Process).to receive(:pid).and_return('')
@lock.lock
expect(Puppet::FileSystem.exist?(@lock.file_path)).to be_truthy
expect(Puppet::FileSystem.read(@lock.file_path)).to be_empty
end
it 'should replace an existing empty lockfile with a pid, given a subsequent lock call made against a valid pid' do
# empty pid results in empty lockfile
allow(Process).to receive(:pid).and_return('')
@lock.lock
expect(Puppet::FileSystem.exist?(@lock.file_path)).to be_truthy
# next lock call with valid pid kills existing empty lockfile
allow(Process).to receive(:pid).and_return(1234)
@lock.lock
expect(Puppet::FileSystem.exist?(@lock.file_path)).to be_truthy
expect(Puppet::FileSystem.read(@lock.file_path)).to eq('1234')
end
it "should expose the lock file_path" do
expect(@lock.file_path).to eq(@lockfile)
end
end
describe "#unlock" do
it "should not be locked anymore" do
@lock.lock
@lock.unlock
expect(@lock).not_to be_locked
end
it "should return false if not locked" do
expect(@lock.unlock).to be_falsey
end
it "should return true if properly unlocked" do
@lock.lock
expect(@lock.unlock).to be_truthy
end
it "should get rid of the lock file" do
@lock.lock
@lock.unlock
expect(Puppet::FileSystem.exist?(@lockfile)).to be_falsey
end
end
describe "#locked?" do
it "should return true if locked" do
@lock.lock
expect(@lock).to be_locked
end
it "should remove the lockfile when pid is missing" do
allow(Process).to receive(:pid).and_return('')
@lock.lock
expect(@lock.locked?).to be_falsey
expect(Puppet::FileSystem.exist?(@lock.file_path)).to be_falsey
end
end
describe '#lock_pid' do
it 'should return nil if the pid is empty' do
# fake pid to get empty lockfile
allow(Process).to receive(:pid).and_return('')
@lock.lock
expect(@lock.lock_pid).to eq(nil)
end
end
describe "with a stale lock" do
before(:each) do
# fake our pid to be 1234
allow(Process).to receive(:pid).and_return(1234)
# lock the file
@lock.lock
# fake our pid to be a different pid, to simulate someone else
# holding the lock
allow(Process).to receive(:pid).and_return(6789)
allow(Process).to receive(:kill).with(0, 6789)
allow(Process).to receive(:kill).with(0, 1234).and_raise(Errno::ESRCH)
end
it "should not be locked" do
expect(@lock).not_to be_locked
end
describe "#lock" do
it "should clear stale locks" do
expect(@lock.locked?).to be_falsey
expect(Puppet::FileSystem.exist?(@lockfile)).to be_falsey
end
it "should replace with new locks" do
@lock.lock
expect(Puppet::FileSystem.exist?(@lockfile)).to be_truthy
expect(@lock.lock_pid).to eq(6789)
expect(@lock).to be_mine
expect(@lock).to be_locked
end
end
describe "#unlock" do
it "should not be allowed" do
expect(@lock.unlock).to be_falsey
end
it "should not remove the lock file" do
@lock.unlock
expect(Puppet::FileSystem.exist?(@lockfile)).to be_truthy
end
end
end
describe "with no access to open the process on Windows", :if => Puppet.features.microsoft_windows? do
before(:each) do
allow(Process).to receive(:pid).and_return(6789)
@lock.lock
allow(Process).to receive(:pid).and_return(1234)
exception = Puppet::Util::Windows::Error.new('Access Denied', 5) # ERROR_ACCESS_DENIED
allow(Puppet::Util::Windows::Process).to receive(:get_process_image_name_by_pid).with(6789).and_raise(exception)
allow(Process).to receive(:kill).with(0, 6789)
allow(Process).to receive(:kill).with(0, 1234)
end
it "should be locked" do
expect(@lock).to be_locked
end
describe "#lock" do
it "should not be possible" do
expect(@lock.lock).to be_falsey
end
it "should not overwrite the lock" do
@lock.lock
expect(@lock).not_to be_mine
end
end
describe "#unlock" do
it "should not be possible" do
expect(@lock.unlock).to be_falsey
end
it "should not remove the lock file" do
@lock.unlock
expect(Puppet::FileSystem.exist?(@lockfile)).to be_truthy
end
it "should still not be our lock" do
@lock.unlock
expect(@lock).not_to be_mine
end
end
end
describe "with another process lock" do
before(:each) do
# fake our pid to be 1234
allow(Process).to receive(:pid).and_return(1234)
if Puppet::Util::Platform.windows?
allow(Puppet::Util::Windows::Process).to receive(:get_process_image_name_by_pid).with(1234).and_return('C:\Program Files\Puppet Labs\Puppet\puppet\bin\ruby.exe')
else
allow(Puppet::Util::Execution).to receive(:execute).with(['ps', '-eq', 1234, '-o', 'comm=']).and_return('puppet')
allow(Puppet::Util::Execution).to receive(:execute).with(['ps', '-eq', 1234, '-o', 'args=']).and_return('puppet')
end
# lock the file
@lock.lock
# fake our pid to be a different pid, to simulate someone else
# holding the lock
allow(Process).to receive(:pid).and_return(6789)
allow(Process).to receive(:kill).with(0, 6789)
allow(Process).to receive(:kill).with(0, 1234)
end
it "should be locked" do
expect(@lock).to be_locked
end
it "should not be mine" do
expect(@lock).not_to be_mine
end
it "should be locked if the other process is a puppet gem" do
File.write(@lockfile, "1234")
if Puppet::Util::Platform.windows?
allow(Puppet::Util::Windows::Process).to receive(:get_process_image_name_by_pid).with(1234).and_return('C:\Program Files\Puppet Labs\Puppet\puppet\bin\ruby.exe')
else
allow(Puppet::Util::Execution).to receive(:execute).with(['ps', '-p', 1234, '-o', 'comm=']).and_return('ruby')
allow(Puppet::Util::Execution).to receive(:execute).with(['ps', '-p', 1234, '-o', 'args=']).and_return('ruby /root/puppet/.bundle/ruby/2.3.0/bin/puppet agent --no-daemonize -v')
end
expect(@lock).to be_locked
end
it "should not be mine if the other process is a puppet gem" do
File.write(@lockfile, "1234")
if Puppet::Util::Platform.windows?
allow(Puppet::Util::Windows::Process).to receive(:get_process_image_name_by_pid).with(1234).and_return('C:\Program Files\Puppet Labs\Puppet\puppet\bin\ruby.exe')
else
allow(Puppet::Util::Execution).to receive(:execute).with(['ps', '-p', 1234, '-o', 'comm=']).and_return('ruby')
allow(Puppet::Util::Execution).to receive(:execute).with(['ps', '-p', 1234, '-o', 'args=']).and_return('ruby /root/puppet/.bundle/ruby/2.3.0/bin/puppet agent --no-daemonize -v')
end
expect(@lock).to_not be_mine
end
describe "#lock" do
it "should not be possible" do
expect(@lock.lock).to be_falsey
end
it "should not overwrite the lock" do
@lock.lock
expect(@lock).not_to be_mine
end
end
describe "#unlock" do
it "should not be possible" do
expect(@lock.unlock).to be_falsey
end
it "should not remove the lock file" do
@lock.unlock
expect(Puppet::FileSystem.exist?(@lockfile)).to be_truthy
end
it "should still not be our lock" do
@lock.unlock
expect(@lock).not_to be_mine
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/user_attr_spec.rb | spec/unit/util/user_attr_spec.rb | require 'spec_helper'
require 'puppet/util/user_attr'
describe UserAttr do
before do
user_attr = ["foo::::type=role", "bar::::type=normal;profile=foobar"]
allow(File).to receive(:readlines).and_return(user_attr)
end
describe "when getting attributes by name" do
it "should return nil if there is no entry for that name" do
expect(UserAttr.get_attributes_by_name('baz')).to eq(nil)
end
it "should return a hash if there is an entry in /etc/user_attr" do
expect(UserAttr.get_attributes_by_name('foo').class).to eq(Hash)
end
it "should return a hash with the name value from /etc/user_attr" do
expect(UserAttr.get_attributes_by_name('foo')[:name]).to eq('foo')
end
#this test is contrived
#there are a bunch of possible parameters that could be in the hash
#the role/normal is just a the convention of the file
describe "when the name is a role" do
it "should contain :type = role" do
expect(UserAttr.get_attributes_by_name('foo')[:type]).to eq('role')
end
end
describe "when the name is not a role" do
it "should contain :type = normal" do
expect(UserAttr.get_attributes_by_name('bar')[:type]).to eq('normal')
end
end
describe "when the name has more attributes" do
it "should contain all the attributes" do
expect(UserAttr.get_attributes_by_name('bar')[:profile]).to eq('foobar')
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/diff_spec.rb | spec/unit/util/diff_spec.rb | require 'spec_helper'
require 'puppet/util/diff'
require 'puppet/util/execution'
describe Puppet::Util::Diff do
let(:baz_output) { Puppet::Util::Execution::ProcessOutput.new('baz', 0) }
describe ".diff" do
it "should execute the diff command with arguments" do
Puppet[:diff] = 'foo'
Puppet[:diff_args] = 'bar'
expect(Puppet::Util::Execution).to receive(:execute)
.with(['foo', 'bar', 'a', 'b'], {:failonfail => false, :combine => false})
.and_return(baz_output)
expect(subject.diff('a', 'b')).to eq('baz')
end
it "should execute the diff command with multiple arguments" do
Puppet[:diff] = 'foo'
Puppet[:diff_args] = 'bar qux'
expect(Puppet::Util::Execution).to receive(:execute)
.with(['foo', 'bar', 'qux', 'a', 'b'], anything)
.and_return(baz_output)
expect(subject.diff('a', 'b')).to eq('baz')
end
it "should omit diff arguments if none are specified" do
Puppet[:diff] = 'foo'
Puppet[:diff_args] = ''
expect(Puppet::Util::Execution).to receive(:execute)
.with(['foo', 'a', 'b'], {:failonfail => false, :combine => false})
.and_return(baz_output)
expect(subject.diff('a', 'b')).to eq('baz')
end
it "should return empty string if the diff command is empty" do
Puppet[:diff] = ''
expect(Puppet::Util::Execution).not_to receive(:execute)
expect(subject.diff('a', 'b')).to eq('')
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/multi_match_spec.rb | spec/unit/util/multi_match_spec.rb | require 'spec_helper'
require 'puppet/util/multi_match'
describe "The Puppet::Util::MultiMatch" do
let(:not_nil) { Puppet::Util::MultiMatch::NOT_NIL }
let(:mm) { Puppet::Util::MultiMatch }
it "matches against not nil" do
expect(not_nil === 3).to be(true)
end
it "matches against multiple values" do
expect(mm.new(not_nil, not_nil) === [3, 3]).to be(true)
end
it "matches each value using ===" do
expect(mm.new(3, 3.14) === [Integer, Float]).to be(true)
end
it "matches are commutative" do
expect(mm.new(3, 3.14) === mm.new(Integer, Float)).to be(true)
expect(mm.new(Integer, Float) === mm.new(3, 3.14)).to be(true)
end
it "has TUPLE constant for match of array of two non nil values" do
expect(mm::TUPLE === [3, 3]).to be(true)
end
it "has TRIPLE constant for match of array of two non nil values" do
expect(mm::TRIPLE === [3, 3, 3]).to be(true)
end
it "considers length of array of values when matching" do
expect(mm.new(not_nil, not_nil) === [6, 6, 6]).to be(false)
expect(mm.new(not_nil, not_nil) === [6]).to be(false)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/rdoc_spec.rb | spec/unit/util/rdoc_spec.rb | require 'spec_helper'
require 'puppet/util/rdoc'
require 'rdoc/rdoc'
describe Puppet::Util::RDoc do
describe "when generating RDoc HTML documentation" do
before :each do
@rdoc = double('rdoc')
allow(RDoc::RDoc).to receive(:new).and_return(@rdoc)
end
it "should tell RDoc to generate documentation using the Puppet generator" do
expect(@rdoc).to receive(:document).with(include("--fmt").and(include("puppet")))
Puppet::Util::RDoc.rdoc("output", [])
end
it "should tell RDoc to be quiet" do
expect(@rdoc).to receive(:document).with(include("--quiet"))
Puppet::Util::RDoc.rdoc("output", [])
end
it "should pass charset to RDoc" do
expect(@rdoc).to receive(:document).with(include("--charset").and(include("utf-8")))
Puppet::Util::RDoc.rdoc("output", [], "utf-8")
end
it "should tell RDoc to use the given outputdir" do
expect(@rdoc).to receive(:document).with(include("--op").and(include("myoutputdir")))
Puppet::Util::RDoc.rdoc("myoutputdir", [])
end
it "should tell RDoc to exclude all files under any modules/<mod>/files section" do
expect(@rdoc).to receive(:document).with(include("--exclude").and(include("/modules/[^/]*/files/.*$")))
Puppet::Util::RDoc.rdoc("myoutputdir", [])
end
it "should tell RDoc to exclude all files under any modules/<mod>/templates section" do
expect(@rdoc).to receive(:document).with(include("--exclude").and(include("/modules/[^/]*/templates/.*$")))
Puppet::Util::RDoc.rdoc("myoutputdir", [])
end
it "should give all the source directories to RDoc" do
expect(@rdoc).to receive(:document).with(include("sourcedir"))
Puppet::Util::RDoc.rdoc("output", ["sourcedir"])
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/run_mode_spec.rb | spec/unit/util/run_mode_spec.rb | require 'spec_helper'
describe Puppet::Util::RunMode do
before do
@run_mode = Puppet::Util::RunMode.new('fake')
end
describe Puppet::Util::UnixRunMode, :unless => Puppet::Util::Platform.windows? do
before do
@run_mode = Puppet::Util::UnixRunMode.new('fake')
end
describe "#conf_dir" do
it "has confdir /etc/puppetlabs/puppet when run as root" do
as_root { expect(@run_mode.conf_dir).to eq(File.expand_path('/etc/puppetlabs/puppet')) }
end
it "has confdir ~/.puppetlabs/etc/puppet when run as non-root" do
as_non_root { expect(@run_mode.conf_dir).to eq(File.expand_path('~/.puppetlabs/etc/puppet')) }
end
context "server run mode" do
before do
@run_mode = Puppet::Util::UnixRunMode.new('server')
end
it "has confdir ~/.puppetlabs/etc/puppet when run as non-root and server run mode" do
as_non_root { expect(@run_mode.conf_dir).to eq(File.expand_path('~/.puppetlabs/etc/puppet')) }
end
end
end
describe "#code_dir" do
it "has codedir /etc/puppetlabs/code when run as root" do
as_root { expect(@run_mode.code_dir).to eq(File.expand_path('/etc/puppetlabs/code')) }
end
it "has codedir ~/.puppetlabs/etc/code when run as non-root" do
as_non_root { expect(@run_mode.code_dir).to eq(File.expand_path('~/.puppetlabs/etc/code')) }
end
context "server run mode" do
before do
@run_mode = Puppet::Util::UnixRunMode.new('server')
end
it "has codedir ~/.puppetlabs/etc/code when run as non-root and server run mode" do
as_non_root { expect(@run_mode.code_dir).to eq(File.expand_path('~/.puppetlabs/etc/code')) }
end
end
end
describe "#var_dir" do
it "has vardir /opt/puppetlabs/puppet/cache when run as root" do
as_root { expect(@run_mode.var_dir).to eq(File.expand_path('/opt/puppetlabs/puppet/cache')) }
end
it "has vardir ~/.puppetlabs/opt/puppet/cache when run as non-root" do
as_non_root { expect(@run_mode.var_dir).to eq(File.expand_path('~/.puppetlabs/opt/puppet/cache')) }
end
end
describe "#public_dir" do
it "has publicdir /opt/puppetlabs/puppet/public when run as root" do
as_root { expect(@run_mode.public_dir).to eq(File.expand_path('/opt/puppetlabs/puppet/public')) }
end
it "has publicdir ~/.puppetlabs/opt/puppet/public when run as non-root" do
as_non_root { expect(@run_mode.public_dir).to eq(File.expand_path('~/.puppetlabs/opt/puppet/public')) }
end
end
describe "#log_dir" do
describe "when run as root" do
it "has logdir /var/log/puppetlabs/puppet" do
as_root { expect(@run_mode.log_dir).to eq(File.expand_path('/var/log/puppetlabs/puppet')) }
end
end
describe "when run as non-root" do
it "has default logdir ~/.puppetlabs/var/log" do
as_non_root { expect(@run_mode.log_dir).to eq(File.expand_path('~/.puppetlabs/var/log')) }
end
end
end
describe "#run_dir" do
describe "when run as root" do
it "has rundir /var/run/puppetlabs" do
as_root { expect(@run_mode.run_dir).to eq(File.expand_path('/var/run/puppetlabs')) }
end
end
describe "when run as non-root" do
it "has default rundir ~/.puppetlabs/var/run" do
as_non_root { expect(@run_mode.run_dir).to eq(File.expand_path('~/.puppetlabs/var/run')) }
end
end
end
describe "#pkg_config_path" do
it { expect(@run_mode.pkg_config_path).to eq('/opt/puppetlabs/puppet/lib/pkgconfig') }
end
describe "#gem_cmd" do
it { expect(@run_mode.gem_cmd).to eq('/opt/puppetlabs/puppet/bin/gem') }
end
describe "#common_module_dir" do
it { expect(@run_mode.common_module_dir).to eq('/opt/puppetlabs/puppet/modules') }
end
describe "#vendor_module_dir" do
it { expect(@run_mode.vendor_module_dir).to eq('/opt/puppetlabs/puppet/vendor_modules') }
end
end
describe Puppet::Util::WindowsRunMode, :if => Puppet::Util::Platform.windows? do
before do
@run_mode = Puppet::Util::WindowsRunMode.new('fake')
end
describe "#conf_dir" do
it "has confdir ending in Puppetlabs/puppet/etc when run as root" do
as_root { expect(@run_mode.conf_dir).to eq(File.expand_path(File.join(ENV['ALLUSERSPROFILE'], "PuppetLabs", "puppet", "etc"))) }
end
it "has confdir in ~/.puppetlabs/etc/puppet when run as non-root" do
as_non_root { expect(@run_mode.conf_dir).to eq(File.expand_path("~/.puppetlabs/etc/puppet")) }
end
end
describe "#code_dir" do
it "has codedir ending in PuppetLabs/code when run as root" do
as_root { expect(@run_mode.code_dir).to eq(File.expand_path(File.join(ENV['ALLUSERSPROFILE'], "PuppetLabs", "code"))) }
end
it "has codedir in ~/.puppetlabs/etc/code when run as non-root" do
as_non_root { expect(@run_mode.code_dir).to eq(File.expand_path("~/.puppetlabs/etc/code")) }
end
end
describe "#var_dir" do
it "has vardir ending in PuppetLabs/puppet/cache when run as root" do
as_root { expect(@run_mode.var_dir).to eq(File.expand_path(File.join(ENV['ALLUSERSPROFILE'], "PuppetLabs", "puppet", "cache"))) }
end
it "has vardir in ~/.puppetlabs/opt/puppet/cache when run as non-root" do
as_non_root { expect(@run_mode.var_dir).to eq(File.expand_path("~/.puppetlabs/opt/puppet/cache")) }
end
end
describe "#public_dir" do
it "has publicdir ending in PuppetLabs/puppet/public when run as root" do
as_root { expect(@run_mode.public_dir).to eq(File.expand_path(File.join(ENV['ALLUSERSPROFILE'], "PuppetLabs", "puppet", "public"))) }
end
it "has publicdir in ~/.puppetlabs/opt/puppet/public when run as non-root" do
as_non_root { expect(@run_mode.public_dir).to eq(File.expand_path("~/.puppetlabs/opt/puppet/public")) }
end
end
describe "#log_dir" do
describe "when run as root" do
it "has logdir ending in PuppetLabs/puppet/var/log" do
as_root { expect(@run_mode.log_dir).to eq(File.expand_path(File.join(ENV['ALLUSERSPROFILE'], "PuppetLabs", "puppet", "var", "log"))) }
end
end
describe "when run as non-root" do
it "has default logdir ~/.puppetlabs/var/log" do
as_non_root { expect(@run_mode.log_dir).to eq(File.expand_path('~/.puppetlabs/var/log')) }
end
end
end
describe "#run_dir" do
describe "when run as root" do
it "has rundir ending in PuppetLabs/puppet/var/run" do
as_root { expect(@run_mode.run_dir).to eq(File.expand_path(File.join(ENV['ALLUSERSPROFILE'], "PuppetLabs", "puppet", "var", "run"))) }
end
end
describe "when run as non-root" do
it "has default rundir ~/.puppetlabs/var/run" do
as_non_root { expect(@run_mode.run_dir).to eq(File.expand_path('~/.puppetlabs/var/run')) }
end
end
end
describe '#gem_cmd' do
before do
allow(ENV).to receive(:fetch).and_call_original
allow(ENV).to receive(:fetch).with('PUPPET_DIR', nil).and_return(puppetdir)
end
context 'when PUPPET_DIR is not set' do
let(:puppetdir) { nil }
before do
allow(Gem).to receive(:default_bindir).and_return('default_gem_bin')
end
it 'uses Gem.default_bindir' do
expected_path = File.join('default_gem_bin', 'gem.bat')
expect(@run_mode.gem_cmd).to eql(expected_path)
end
end
context 'when PUPPET_DIR is set' do
let(:puppetdir) { 'puppet_dir' }
it 'uses Gem.default_bindir' do
expected_path = File.join('puppet_dir', 'bin', 'gem.bat')
expect(@run_mode.gem_cmd).to eql(expected_path)
end
end
end
describe '#common_module_dir' do
before do
allow(ENV).to receive(:fetch).and_call_original
allow(ENV).to receive(:fetch).with('FACTER_env_windows_installdir', nil).and_return(installdir)
end
context 'when installdir is not set' do
let(:installdir) { nil }
it 'returns nil' do
expect(@run_mode.common_module_dir).to be(nil)
end
end
context 'with installdir' do
let(:installdir) { 'C:\Program Files\Puppet Labs\Puppet' }
it 'returns INSTALLDIR/puppet/modules' do
expect(@run_mode.common_module_dir).to eq('C:\Program Files\Puppet Labs\Puppet/puppet/modules')
end
end
end
describe '#vendor_module_dir' do
before do
allow(ENV).to receive(:fetch).and_call_original
allow(ENV).to receive(:fetch).with('FACTER_env_windows_installdir', nil).and_return(installdir)
end
context 'when installdir is not set' do
let(:installdir) { nil }
it 'returns nil' do
expect(@run_mode.vendor_module_dir).to be(nil)
end
end
context 'with installdir' do
let(:installdir) { 'C:\Program Files\Puppet Labs\Puppet' }
it 'returns INSTALLDIR\puppet\vendor_modules' do
expect(@run_mode.vendor_module_dir).to eq('C:\Program Files\Puppet Labs\Puppet\puppet\vendor_modules')
end
end
end
end
def as_root
allow(Puppet.features).to receive(:root?).and_return(true)
yield
end
def as_non_root
allow(Puppet.features).to receive(:root?).and_return(false)
yield
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/backups_spec.rb | spec/unit/util/backups_spec.rb | require 'spec_helper'
require 'puppet/util/backups'
describe Puppet::Util::Backups do
include PuppetSpec::Files
let(:bucket) { double('bucket', :name => "foo") }
let!(:file) do
f = Puppet::Type.type(:file).new(:name => path, :backup => 'foo')
allow(f).to receive(:bucket).and_return(bucket)
f
end
describe "when backing up a file" do
let(:path) { make_absolute('/no/such/file') }
it "should noop if the file does not exist" do
expect(file).not_to receive(:bucket)
expect(Puppet::FileSystem).to receive(:exist?).with(path).and_return(false)
file.perform_backup
end
it "should succeed silently if self[:backup] is false" do
file = Puppet::Type.type(:file).new(:name => path, :backup => false)
expect(file).not_to receive(:bucket)
expect(Puppet::FileSystem).not_to receive(:exist?)
file.perform_backup
end
it "a bucket should be used when provided" do
lstat_path_as(path, 'file')
expect(bucket).to receive(:backup).with(path).and_return("mysum")
expect(Puppet::FileSystem).to receive(:exist?).with(path).and_return(true)
file.perform_backup
end
it "should propagate any exceptions encountered when backing up to a filebucket" do
lstat_path_as(path, 'file')
expect(bucket).to receive(:backup).and_raise(ArgumentError)
expect(Puppet::FileSystem).to receive(:exist?).with(path).and_return(true)
expect { file.perform_backup }.to raise_error(ArgumentError)
end
describe "and local backup is configured" do
let(:ext) { 'foobkp' }
let(:backup) { path + '.' + ext }
let(:file) { Puppet::Type.type(:file).new(:name => path, :backup => '.'+ext) }
it "should remove any local backup if one exists" do
lstat_path_as(backup, 'file')
expect(Puppet::FileSystem).to receive(:unlink).with(backup)
allow(FileUtils).to receive(:cp_r)
expect(Puppet::FileSystem).to receive(:exist?).with(path).and_return(true)
file.perform_backup
end
it "should fail when the old backup can't be removed" do
lstat_path_as(backup, 'file')
expect(Puppet::FileSystem).to receive(:unlink).with(backup).and_raise(ArgumentError)
expect(FileUtils).not_to receive(:cp_r)
expect(Puppet::FileSystem).to receive(:exist?).with(path).and_return(true)
expect { file.perform_backup }.to raise_error(Puppet::Error)
end
it "should not try to remove backups that don't exist" do
expect(Puppet::FileSystem).to receive(:lstat).with(backup).and_raise(Errno::ENOENT)
expect(Puppet::FileSystem).not_to receive(:unlink).with(backup)
allow(FileUtils).to receive(:cp_r)
expect(Puppet::FileSystem).to receive(:exist?).with(path).and_return(true)
file.perform_backup
end
it "a copy should be created in the local directory" do
expect(FileUtils).to receive(:cp_r).with(path, backup, {:preserve => true})
allow(Puppet::FileSystem).to receive(:exist?).with(path).and_return(true)
expect(file.perform_backup).to be_truthy
end
it "should propagate exceptions if no backup can be created" do
expect(FileUtils).to receive(:cp_r).and_raise(ArgumentError)
allow(Puppet::FileSystem).to receive(:exist?).with(path).and_return(true)
expect { file.perform_backup }.to raise_error(Puppet::Error)
end
end
end
describe "when backing up a directory" do
let(:path) { make_absolute('/my/dir') }
let(:filename) { File.join(path, 'file') }
it "a bucket should work when provided" do
allow(File).to receive(:file?).with(filename).and_return(true)
expect(Find).to receive(:find).with(path).and_yield(filename)
expect(bucket).to receive(:backup).with(filename).and_return(true)
lstat_path_as(path, 'directory')
allow(Puppet::FileSystem).to receive(:exist?).with(path).and_return(true)
allow(Puppet::FileSystem).to receive(:exist?).with(filename).and_return(true)
file.perform_backup
end
it "should do nothing when recursing" do
file = Puppet::Type.type(:file).new(:name => path, :backup => 'foo', :recurse => true)
expect(bucket).not_to receive(:backup)
allow(Puppet::FileSystem).to receive(:stat).with(path).and_return(double('stat', :ftype => 'directory'))
expect(Find).not_to receive(:find)
file.perform_backup
end
end
def lstat_path_as(path, ftype)
expect(Puppet::FileSystem).to receive(:lstat).with(path).and_return(double('File::Stat', :ftype => ftype))
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/execution_stub_spec.rb | spec/unit/util/execution_stub_spec.rb | require 'spec_helper'
describe Puppet::Util::ExecutionStub do
it "should use the provided stub code when 'set' is called" do
Puppet::Util::ExecutionStub.set do |command, options|
expect(command).to eq(['/bin/foo', 'bar'])
"stub output"
end
expect(Puppet::Util::ExecutionStub.current_value).not_to eq(nil)
expect(Puppet::Util::Execution.execute(['/bin/foo', 'bar'])).to eq("stub output")
end
it "should automatically restore normal execution at the conclusion of each spec test" do
# Note: this test relies on the previous test creating a stub.
expect(Puppet::Util::ExecutionStub.current_value).to eq(nil)
end
it "should restore normal execution after 'reset' is called", unless: Puppet::Util::Platform.jruby? do
# Note: "true" exists at different paths in different OSes
if Puppet::Util::Platform.windows?
true_command = [Puppet::Util.which('cmd.exe').tr('/', '\\'), '/c', 'exit 0']
else
true_command = [Puppet::Util.which('true')]
end
stub_call_count = 0
Puppet::Util::ExecutionStub.set do |command, options|
expect(command).to eq(true_command)
stub_call_count += 1
'stub called'
end
expect(Puppet::Util::Execution.execute(true_command)).to eq('stub called')
expect(stub_call_count).to eq(1)
Puppet::Util::ExecutionStub.reset
expect(Puppet::Util::ExecutionStub.current_value).to eq(nil)
expect(Puppet::Util::Execution.execute(true_command)).to eq('')
expect(stub_call_count).to eq(1)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/character_encoding_spec.rb | spec/unit/util/character_encoding_spec.rb | require 'spec_helper'
require 'puppet/util/character_encoding'
require 'puppet_spec/character_encoding'
describe Puppet::Util::CharacterEncoding do
describe "::convert_to_utf_8" do
context "when passed a string that is already UTF-8" do
context "with valid encoding" do
let(:utf8_string) { "\u06FF\u2603".force_encoding(Encoding::UTF_8) }
it "should return the string unmodified" do
expect(Puppet::Util::CharacterEncoding.convert_to_utf_8(utf8_string)).to eq("\u06FF\u2603".force_encoding(Encoding::UTF_8))
end
it "should not mutate the original string" do
expect(utf8_string).to eq("\u06FF\u2603".force_encoding(Encoding::UTF_8))
end
end
context "with invalid encoding" do
let(:invalid_utf8_string) { "\xfd\xf1".force_encoding(Encoding::UTF_8) }
it "should issue a debug message" do
expect(Puppet).to receive(:debug) { |&b| expect(b.call).to match(/encoding is invalid/) }
Puppet::Util::CharacterEncoding.convert_to_utf_8(invalid_utf8_string)
end
it "should return the string unmodified" do
expect(Puppet::Util::CharacterEncoding.convert_to_utf_8(invalid_utf8_string)).to eq("\xfd\xf1".force_encoding(Encoding::UTF_8))
end
it "should not mutate the original string" do
Puppet::Util::CharacterEncoding.convert_to_utf_8(invalid_utf8_string)
expect(invalid_utf8_string).to eq("\xfd\xf1".force_encoding(Encoding::UTF_8))
end
end
end
context "when passed a string in BINARY encoding" do
context "that is valid in Encoding.default_external" do
# When received as BINARY are not transcodable, but by "guessing"
# Encoding.default_external can transcode to UTF-8
let(:win_31j) { [130, 187].pack('C*') } # pack('C*') returns string in BINARY
it "should be able to convert to UTF-8 by labeling as Encoding.default_external" do
# そ - HIRAGANA LETTER SO
# In Windows_31J: \x82 \xbb - 130 187
# In Unicode: \u305d - \xe3 \x81 \x9d - 227 129 157
result = PuppetSpec::CharacterEncoding.with_external_encoding(Encoding::Windows_31J) do
Puppet::Util::CharacterEncoding.convert_to_utf_8(win_31j)
end
expect(result).to eq("\u305d")
expect(result.bytes.to_a).to eq([227, 129, 157])
end
it "should not mutate the original string" do
PuppetSpec::CharacterEncoding.with_external_encoding(Encoding::Windows_31J) do
Puppet::Util::CharacterEncoding.convert_to_utf_8(win_31j)
end
expect(win_31j).to eq([130, 187].pack('C*'))
end
end
context "that is invalid in Encoding.default_external" do
let(:invalid_win_31j) { [255, 254, 253].pack('C*') } # these bytes are not valid windows_31j
it "should return the string umodified" do
result = PuppetSpec::CharacterEncoding.with_external_encoding(Encoding::Windows_31J) do
Puppet::Util::CharacterEncoding.convert_to_utf_8(invalid_win_31j)
end
expect(result.bytes.to_a).to eq([255, 254, 253])
expect(result.encoding).to eq(Encoding::BINARY)
end
it "should not mutate the original string" do
PuppetSpec::CharacterEncoding.with_external_encoding(Encoding::Windows_31J) do
Puppet::Util::CharacterEncoding.convert_to_utf_8(invalid_win_31j)
end
expect(invalid_win_31j).to eq([255, 254, 253].pack('C*'))
end
it "should issue a debug message that the string was not transcodable" do
expect(Puppet).to receive(:debug) { |&b| expect(b.call).to match(/cannot be transcoded/) }
PuppetSpec::CharacterEncoding.with_external_encoding(Encoding::Windows_31J) do
Puppet::Util::CharacterEncoding.convert_to_utf_8(invalid_win_31j)
end
end
end
context "Given a string labeled as neither UTF-8 nor BINARY" do
context "that is transcodable" do
let (:shift_jis) { [130, 174].pack('C*').force_encoding(Encoding::Shift_JIS) }
it "should return a copy of the string transcoded to UTF-8 if it is transcodable" do
# http://www.fileformat.info/info/unicode/char/3050/index.htm
# ぐ - HIRAGANA LETTER GU
# In Shift_JIS: \x82 \xae - 130 174
# In Unicode: \u3050 - \xe3 \x81 \x90 - 227 129 144
# if we were only ruby > 2.3.0, we could do String.new("\x82\xae", :encoding => Encoding::Shift_JIS)
result = Puppet::Util::CharacterEncoding.convert_to_utf_8(shift_jis)
expect(result).to eq("\u3050".force_encoding(Encoding::UTF_8))
# largely redundant but reinforces the point - this was transcoded:
expect(result.bytes.to_a).to eq([227, 129, 144])
end
it "should not mutate the original string" do
Puppet::Util::CharacterEncoding.convert_to_utf_8(shift_jis)
expect(shift_jis).to eq([130, 174].pack('C*').force_encoding(Encoding::Shift_JIS))
end
end
context "when not transcodable" do
# An admittedly contrived case, but perhaps not so improbable
# http://www.fileformat.info/info/unicode/char/5e0c/index.htm
# 希 Han Character 'rare; hope, expect, strive for'
# In EUC_KR: \xfd \xf1 - 253 241
# In Unicode: \u5e0c - \xe5 \xb8 \x8c - 229 184 140
# In this case, this EUC_KR character has been read in as ASCII and is
# invalid in that encoding. This would raise an EncodingError
# exception on transcode but we catch this issue a debug message -
# leaving the original string unaltered.
let(:euc_kr) { [253, 241].pack('C*').force_encoding(Encoding::ASCII) }
it "should issue a debug message" do
expect(Puppet).to receive(:debug) { |&b| expect(b.call).to match(/cannot be transcoded/) }
Puppet::Util::CharacterEncoding.convert_to_utf_8(euc_kr)
end
it "should return the original string unmodified" do
result = Puppet::Util::CharacterEncoding.convert_to_utf_8(euc_kr)
expect(result).to eq([253, 241].pack('C*').force_encoding(Encoding::ASCII))
end
it "should not mutate the original string" do
Puppet::Util::CharacterEncoding.convert_to_utf_8(euc_kr)
expect(euc_kr).to eq([253, 241].pack('C*').force_encoding(Encoding::ASCII))
end
end
end
end
end
describe "::override_encoding_to_utf_8" do
context "given a string with bytes that represent valid UTF-8" do
# ☃ - unicode snowman
# \u2603 - \xe2 \x98 \x83 - 226 152 131
let(:snowman) { [226, 152, 131].pack('C*') }
it "should return a copy of the string with external encoding of the string to UTF-8" do
result = Puppet::Util::CharacterEncoding.override_encoding_to_utf_8(snowman)
expect(result).to eq("\u2603")
expect(result.encoding).to eq(Encoding::UTF_8)
end
it "should not modify the original string" do
Puppet::Util::CharacterEncoding.override_encoding_to_utf_8(snowman)
expect(snowman).to eq([226, 152, 131].pack('C*'))
end
end
context "given a string with bytes that do not represent valid UTF-8" do
# Ø - Latin capital letter O with stroke
# In ISO-8859-1: \xd8 - 216
# Invalid in UTF-8 without transcoding
let(:oslash) { [216].pack('C*').force_encoding(Encoding::ISO_8859_1) }
let(:foo) { 'foo' }
it "should issue a debug message" do
expect(Puppet).to receive(:debug) { |&b| expect(b.call).to match(/not valid UTF-8/) }
Puppet::Util::CharacterEncoding.override_encoding_to_utf_8(oslash)
end
it "should return the original string unmodified" do
result = Puppet::Util::CharacterEncoding.override_encoding_to_utf_8(oslash)
expect(result).to eq([216].pack('C*').force_encoding(Encoding::ISO_8859_1))
end
it "should not modify the string" do
Puppet::Util::CharacterEncoding.override_encoding_to_utf_8(oslash)
expect(oslash).to eq([216].pack('C*').force_encoding(Encoding::ISO_8859_1))
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/windows_spec.rb | spec/unit/util/windows_spec.rb | # frozen_string_literal: true
require 'spec_helper'
describe Puppet::Util::Windows do
%w[
ADSI
ADSI::ADSIObject
ADSI::User
ADSI::UserProfile
ADSI::Group
EventLog
File
Process
Registry
Service
SID
].each do |name|
it "defines Puppet::Util::Windows::#{name}" do
expect(described_class.const_get(name)).to be
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/metric_spec.rb | spec/unit/util/metric_spec.rb | require 'spec_helper'
require 'puppet/util/metric'
describe Puppet::Util::Metric do
before do
@metric = Puppet::Util::Metric.new("foo")
end
[:type, :name, :value, :label].each do |name|
it "should have a #{name} attribute" do
expect(@metric).to respond_to(name)
expect(@metric).to respond_to(name.to_s + "=")
end
end
it "should require a name at initialization" do
expect { Puppet::Util::Metric.new }.to raise_error(ArgumentError)
end
it "should always convert its name to a string" do
expect(Puppet::Util::Metric.new(:foo).name).to eq("foo")
end
it "should support a label" do
expect(Puppet::Util::Metric.new("foo", "mylabel").label).to eq("mylabel")
end
it "should autogenerate a label if none is provided" do
expect(Puppet::Util::Metric.new("foo_bar").label).to eq("Foo bar")
end
it "should have a method for adding values" do
expect(@metric).to respond_to(:newvalue)
end
it "should have a method for returning values" do
expect(@metric).to respond_to(:values)
end
it "should require a name and value for its values" do
expect { @metric.newvalue }.to raise_error(ArgumentError)
end
it "should support a label for values" do
@metric.newvalue("foo", 10, "label")
expect(@metric.values[0][1]).to eq("label")
end
it "should autogenerate value labels if none is provided" do
@metric.newvalue("foo_bar", 10)
expect(@metric.values[0][1]).to eq("Foo bar")
end
it "should return its values sorted by label" do
@metric.newvalue("foo", 10, "b")
@metric.newvalue("bar", 10, "a")
expect(@metric.values).to eq([["bar", "a", 10], ["foo", "b", 10]])
end
it "should use an array indexer method to retrieve individual values" do
@metric.newvalue("foo", 10)
expect(@metric["foo"]).to eq(10)
end
it "should return nil if the named value cannot be found" do
expect(@metric["foo"]).to eq(0)
end
let(:metric) do
metric = Puppet::Util::Metric.new("foo", "mylabel")
metric.newvalue("v1", 10.1, "something")
metric.newvalue("v2", 20, "something else")
metric
end
it "should round trip through json" do
tripped = Puppet::Util::Metric.from_data_hash(JSON.parse(metric.to_json))
expect(tripped.name).to eq(metric.name)
expect(tripped.label).to eq(metric.label)
expect(tripped.values).to eq(metric.values)
end
it 'to_data_hash returns value that is instance of to Data' do
expect(Puppet::Pops::Types::TypeFactory.data.instance?(metric.to_data_hash)).to be_truthy
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/docs_spec.rb | spec/unit/util/docs_spec.rb | require 'spec_helper'
describe Puppet::Util::Docs do
describe '.scrub' do
let(:my_cleaned_output) do
%q{This resource type uses the prescribed native tools for creating
groups and generally uses POSIX APIs for retrieving information
about them. It does not directly modify `/etc/passwd` or anything.
* Just for fun, we'll add a list.
* list item two,
which has some add'l lines included in it.
And here's a code block:
this is the piece of code
it does something cool
**Autorequires:** I would be listing autorequired resources here.}
end
it "strips the least common indent from multi-line strings, without mangling indentation beyond the least common indent" do
input = <<EOT
This resource type uses the prescribed native tools for creating
groups and generally uses POSIX APIs for retrieving information
about them. It does not directly modify `/etc/passwd` or anything.
* Just for fun, we'll add a list.
* list item two,
which has some add'l lines included in it.
And here's a code block:
this is the piece of code
it does something cool
**Autorequires:** I would be listing autorequired resources here.
EOT
output = Puppet::Util::Docs.scrub(input)
expect(output).to eq my_cleaned_output
end
it "ignores the first line when calculating least common indent" do
input = "This resource type uses the prescribed native tools for creating
groups and generally uses POSIX APIs for retrieving information
about them. It does not directly modify `/etc/passwd` or anything.
* Just for fun, we'll add a list.
* list item two,
which has some add'l lines included in it.
And here's a code block:
this is the piece of code
it does something cool
**Autorequires:** I would be listing autorequired resources here."
output = Puppet::Util::Docs.scrub(input)
expect(output).to eq my_cleaned_output
end
it "strips trailing whitespace from each line, and strips trailing newlines at end" do
input = "This resource type uses the prescribed native tools for creating \n groups and generally uses POSIX APIs for retrieving information \n about them. It does not directly modify `/etc/passwd` or anything. \n\n * Just for fun, we'll add a list. \n * list item two,\n which has some add'l lines included in it. \n\n And here's a code block:\n\n this is the piece of code \n it does something cool \n\n **Autorequires:** I would be listing autorequired resources here. \n\n"
output = Puppet::Util::Docs.scrub(input)
expect(output).to eq my_cleaned_output
end
it "has no side effects on original input string" do
input = "First line \n second line \n \n indented line \n \n last line\n\n"
clean_input = "First line \n second line \n \n indented line \n \n last line\n\n"
Puppet::Util::Docs.scrub(input)
expect(input).to eq clean_input
end
it "does not include whitespace-only lines when calculating least common indent" do
input = "First line\n second line\n \n indented line\n\n last line"
expected_output = "First line\nsecond line\n\n indented line\n\nlast line"
#bogus_output = "First line\nsecond line\n\n indented line\n\nlast line"
output = Puppet::Util::Docs.scrub(input)
expect(output).to eq expected_output
end
it "accepts a least common indent of zero, thus not adding errors when input string is already scrubbed" do
expect(Puppet::Util::Docs.scrub(my_cleaned_output)).to eq my_cleaned_output
end
it "trims leading space from one-liners (even when they're buffered with extra newlines)" do
input = "
Updates values in the `puppet.conf` configuration file.
"
expected_output = "Updates values in the `puppet.conf` configuration file."
output = Puppet::Util::Docs.scrub(input)
expect(output).to eq expected_output
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/warnings_spec.rb | spec/unit/util/warnings_spec.rb | require 'spec_helper'
describe Puppet::Util::Warnings do
before(:all) do
@msg1 = "booness"
@msg2 = "more booness"
end
before(:each) do
Puppet.debug = true
end
after (:each) do
Puppet.debug = false
end
{:notice => "notice_once", :warning => "warnonce", :debug => "debug_once"}.each do |log, method|
describe "when registring '#{log}' messages" do
it "should always return nil" do
expect(Puppet::Util::Warnings.send(method, @msg1)).to be(nil)
end
it "should issue a warning" do
expect(Puppet).to receive(log).with(@msg1)
Puppet::Util::Warnings.send(method, @msg1)
end
it "should issue a warning exactly once per unique message" do
expect(Puppet).to receive(log).with(@msg1).once
Puppet::Util::Warnings.send(method, @msg1)
Puppet::Util::Warnings.send(method, @msg1)
end
it "should issue multiple warnings for multiple unique messages" do
expect(Puppet).to receive(log).twice()
Puppet::Util::Warnings.send(method, @msg1)
Puppet::Util::Warnings.send(method, @msg2)
end
end
end
after(:each) do
Puppet::Util::Warnings.clear_warnings
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/util/execution_spec.rb | spec/unit/util/execution_spec.rb | # encoding: UTF-8
require 'spec_helper'
require 'puppet/file_system/uniquefile'
require 'puppet_spec/character_encoding'
describe Puppet::Util::Execution, if: !Puppet::Util::Platform.jruby? do
include Puppet::Util::Execution
# utility methods to help us test some private methods without being quite so verbose
def call_exec_posix(command, arguments, stdin, stdout, stderr)
Puppet::Util::Execution.send(:execute_posix, command, arguments, stdin, stdout, stderr)
end
def call_exec_windows(command, arguments, stdin, stdout, stderr)
Puppet::Util::Execution.send(:execute_windows, command, arguments, stdin, stdout, stderr)
end
describe "execution methods" do
let(:pid) { 5501 }
let(:process_handle) { 0xDEADBEEF }
let(:thread_handle) { 0xCAFEBEEF }
let(:proc_info_stub) { double('processinfo', :process_handle => process_handle, :thread_handle => thread_handle, :process_id => pid) }
let(:null_file) { Puppet::Util::Platform.windows? ? 'NUL' : '/dev/null' }
def stub_process_wait(exitstatus)
if Puppet::Util::Platform.windows?
allow(Puppet::Util::Windows::Process).to receive(:wait_process).with(process_handle).and_return(exitstatus)
allow(FFI::WIN32).to receive(:CloseHandle).with(process_handle)
allow(FFI::WIN32).to receive(:CloseHandle).with(thread_handle)
else
allow(Process).to receive(:waitpid2).with(pid, Process::WNOHANG).and_return(nil, [pid, double('child_status', :exitstatus => exitstatus)])
allow(Process).to receive(:waitpid2).with(pid, 0).and_return(nil, [pid, double('child_status', :exitstatus => exitstatus)])
allow(Process).to receive(:waitpid2).with(pid).and_return([pid, double('child_status', :exitstatus => exitstatus)])
end
end
describe "#execute_posix (stubs)", :unless => Puppet::Util::Platform.windows? do
before :each do
# Most of the things this method does are bad to do during specs. :/
allow(Kernel).to receive(:fork).and_return(pid).and_yield
allow(Process).to receive(:setsid)
allow(Kernel).to receive(:exec)
allow(Puppet::Util::SUIDManager).to receive(:change_user)
allow(Puppet::Util::SUIDManager).to receive(:change_group)
# ensure that we don't really close anything!
allow(IO).to receive(:new)
allow($stdin).to receive(:reopen)
allow($stdout).to receive(:reopen)
allow($stderr).to receive(:reopen)
@stdin = File.open(null_file, 'r')
@stdout = Puppet::FileSystem::Uniquefile.new('stdout')
@stderr = File.open(null_file, 'w')
# there is a danger here that ENV will be modified by exec_posix. Normally it would only affect the ENV
# of a forked process, but here, we're stubbing Kernel.fork, so the method has the ability to override the
# "real" ENV. To guard against this, we'll capture a snapshot of ENV before each test.
@saved_env = ENV.to_hash
# Now, we're going to effectively "mock" the magic ruby 'ENV' variable by creating a local definition of it
# inside of the module we're testing.
Puppet::Util::Execution::ENV = {}
end
after :each do
# And here we remove our "mock" version of 'ENV', which will allow us to validate that the real ENV has been
# left unharmed.
Puppet::Util::Execution.send(:remove_const, :ENV)
# capture the current environment and make sure it's the same as it was before the test
cur_env = ENV.to_hash
# we will get some fairly useless output if we just use the raw == operator on the hashes here, so we'll
# be a bit more explicit and laborious in the name of making the error more useful...
@saved_env.each_pair { |key,val| expect(cur_env[key]).to eq(val) }
expect(cur_env.keys - @saved_env.keys).to eq([])
end
it "should fork a child process to execute the command" do
expect(Kernel).to receive(:fork).and_return(pid).and_yield
expect(Kernel).to receive(:exec).with('test command')
call_exec_posix('test command', {}, @stdin, @stdout, @stderr)
end
it "should start a new session group" do
expect(Process).to receive(:setsid)
call_exec_posix('test command', {}, @stdin, @stdout, @stderr)
end
it "should permanently change to the correct user and group if specified" do
expect(Puppet::Util::SUIDManager).to receive(:change_group).with(55, true)
expect(Puppet::Util::SUIDManager).to receive(:change_user).with(50, true)
call_exec_posix('test command', {:uid => 50, :gid => 55}, @stdin, @stdout, @stderr)
end
it "should exit failure if there is a problem execing the command" do
expect(Kernel).to receive(:exec).with('test command').and_raise("failed to execute!")
allow(Puppet::Util::Execution).to receive(:puts)
expect(Puppet::Util::Execution).to receive(:exit!).with(1)
call_exec_posix('test command', {}, @stdin, @stdout, @stderr)
end
it "should properly execute commands specified as arrays" do
expect(Kernel).to receive(:exec).with('test command', 'with', 'arguments')
call_exec_posix(['test command', 'with', 'arguments'], {:uid => 50, :gid => 55}, @stdin, @stdout, @stderr)
end
it "should properly execute string commands with embedded newlines" do
expect(Kernel).to receive(:exec).with("/bin/echo 'foo' ; \n /bin/echo 'bar' ;")
call_exec_posix("/bin/echo 'foo' ; \n /bin/echo 'bar' ;", {:uid => 50, :gid => 55}, @stdin, @stdout, @stderr)
end
context 'cwd option' do
let(:cwd) { 'cwd' }
it 'should run the command in the specified working directory' do
expect(Dir).to receive(:chdir).with(cwd)
expect(Kernel).to receive(:exec).with('test command')
call_exec_posix('test command', { :cwd => cwd }, @stdin, @stdout, @stderr)
end
it "should not change the current working directory if cwd is unspecified" do
expect(Dir).to receive(:chdir).never
expect(Kernel).to receive(:exec).with('test command')
call_exec_posix('test command', {}, @stdin, @stdout, @stderr)
end
end
it "should return the pid of the child process" do
expect(call_exec_posix('test command', {}, @stdin, @stdout, @stderr)).to eq(pid)
end
end
describe "#execute_windows (stubs)", :if => Puppet::Util::Platform.windows? do
before :each do
allow(Process).to receive(:create).and_return(proc_info_stub)
stub_process_wait(0)
@stdin = File.open(null_file, 'r')
@stdout = Puppet::FileSystem::Uniquefile.new('stdout')
@stderr = File.open(null_file, 'w')
end
it "should create a new process for the command" do
expect(Process).to receive(:create).with({
:command_line => "test command",
:startup_info => {:stdin => @stdin, :stdout => @stdout, :stderr => @stderr},
:close_handles => false
}).and_return(proc_info_stub)
call_exec_windows('test command', {}, @stdin, @stdout, @stderr)
end
context 'cwd option' do
let(:cwd) { 'cwd' }
it "should execute the command in the specified working directory" do
expect(Process).to receive(:create).with({
:command_line => "test command",
:startup_info => {
:stdin => @stdin,
:stdout => @stdout,
:stderr => @stderr
},
:close_handles => false,
:cwd => cwd
})
call_exec_windows('test command', { :cwd => cwd }, @stdin, @stdout, @stderr)
end
it "should not change the current working directory if cwd is unspecified" do
expect(Dir).to receive(:chdir).never
expect(Process).to receive(:create) do |args|
expect(args[:cwd]).to be_nil
end
call_exec_windows('test command', {}, @stdin, @stdout, @stderr)
end
end
context 'suppress_window option' do
let(:cwd) { 'cwd' }
it "should execute the command in the specified working directory" do
expect(Process).to receive(:create).with({
:command_line => "test command",
:startup_info => {
:stdin => @stdin,
:stdout => @stdout,
:stderr => @stderr
},
:close_handles => false,
:creation_flags => Puppet::Util::Windows::Process::CREATE_NO_WINDOW
})
call_exec_windows('test command', { :suppress_window => true }, @stdin, @stdout, @stderr)
end
end
it "should return the process info of the child process" do
expect(call_exec_windows('test command', {}, @stdin, @stdout, @stderr)).to eq(proc_info_stub)
end
it "should quote arguments containing spaces if command is specified as an array" do
expect(Process).to receive(:create).with(hash_including(command_line: '"test command" with some "arguments \"with spaces"')).and_return(proc_info_stub)
call_exec_windows(['test command', 'with', 'some', 'arguments "with spaces'], {}, @stdin, @stdout, @stderr)
end
end
describe "#execute (stubs)" do
before :each do
stub_process_wait(0)
end
describe "when an execution stub is specified" do
before :each do
Puppet::Util::ExecutionStub.set do |command,args,stdin,stdout,stderr|
"execution stub output"
end
end
it "should call the block on the stub" do
expect(Puppet::Util::Execution.execute("/usr/bin/run_my_execute_stub")).to eq("execution stub output")
end
it "should not actually execute anything" do
expect(Puppet::Util::Execution).not_to receive(:execute_posix)
expect(Puppet::Util::Execution).not_to receive(:execute_windows)
Puppet::Util::Execution.execute("/usr/bin/run_my_execute_stub")
end
end
describe "when setting up input and output files" do
include PuppetSpec::Files
let(:executor) { Puppet::Util::Platform.windows? ? 'execute_windows' : 'execute_posix' }
let(:rval) { Puppet::Util::Platform.windows? ? proc_info_stub : pid }
before :each do
allow(Puppet::Util::Execution).to receive(:wait_for_output)
end
it "should set stdin to the stdinfile if specified" do
input = tmpfile('stdin')
FileUtils.touch(input)
expect(Puppet::Util::Execution).to receive(executor) do |_,_,stdin,_,_|
expect(stdin.path).to eq(input)
rval
end
Puppet::Util::Execution.execute('test command', :stdinfile => input)
end
it "should set stdin to the null file if not specified" do
expect(Puppet::Util::Execution).to receive(executor) do |_,_,stdin,_,_|
expect(stdin.path).to eq(null_file)
rval
end
Puppet::Util::Execution.execute('test command')
end
describe "when squelch is set" do
it "should set stdout and stderr to the null file" do
expect(Puppet::Util::Execution).to receive(executor) do |_,_,_,stdout,stderr|
expect(stdout.path).to eq(null_file)
expect(stderr.path).to eq(null_file)
rval
end
Puppet::Util::Execution.execute('test command', :squelch => true)
end
end
describe "cwd option" do
def expect_cwd_to_be(cwd)
expect(Puppet::Util::Execution).to receive(executor).with(
anything,
hash_including(cwd: cwd),
anything,
anything,
anything
).and_return(rval)
end
it 'should raise an ArgumentError if the specified working directory does not exist' do
cwd = 'cwd'
allow(Puppet::FileSystem).to receive(:directory?).with(cwd).and_return(false)
expect {
Puppet::Util::Execution.execute('test command', cwd: cwd)
}.to raise_error do |error|
expect(error).to be_a(ArgumentError)
expect(error.message).to match(cwd)
end
end
it "should set the cwd to the user-specified one" do
allow(Puppet::FileSystem).to receive(:directory?).with('cwd').and_return(true)
expect_cwd_to_be('cwd')
Puppet::Util::Execution.execute('test command', cwd: 'cwd')
end
end
describe "on POSIX", :if => Puppet.features.posix? do
describe "when squelch is not set" do
it "should set stdout to a pipe" do
expect(Puppet::Util::Execution).to receive(executor).with(anything, anything, anything, be_a(IO), anything).and_return(rval)
Puppet::Util::Execution.execute('test command', :squelch => false)
end
it "should set stderr to the same file as stdout if combine is true" do
expect(Puppet::Util::Execution).to receive(executor) do |_,_,_,stdout,stderr|
expect(stdout).to eq(stderr)
rval
end
Puppet::Util::Execution.execute('test command', :squelch => false, :combine => true)
end
it "should set stderr to the null device if combine is false" do
expect(Puppet::Util::Execution).to receive(executor) do |_,_,_,stdout,stderr|
expect(stdout.class).to eq(IO)
expect(stderr.path).to eq(null_file)
rval
end
Puppet::Util::Execution.execute('test command', :squelch => false, :combine => false)
end
it "should default combine to true when no options are specified" do
expect(Puppet::Util::Execution).to receive(executor) do |_,_,_,stdout,stderr|
expect(stdout).to eq(stderr)
rval
end
Puppet::Util::Execution.execute('test command')
end
it "should default combine to false when options are specified, but combine is not" do
expect(Puppet::Util::Execution).to receive(executor) do |_,_,_,stdout,stderr|
expect(stdout.class).to eq(IO)
expect(stderr.path).to eq(null_file)
rval
end
Puppet::Util::Execution.execute('test command', :failonfail => false)
end
it "should default combine to false when an empty hash of options is specified" do
expect(Puppet::Util::Execution).to receive(executor) do |_,_,_,stdout,stderr|
expect(stdout.class).to eq(IO)
expect(stderr.path).to eq(null_file)
rval
end
Puppet::Util::Execution.execute('test command', {})
end
end
end
describe "on Windows", :if => Puppet::Util::Platform.windows? do
describe "when squelch is not set" do
it "should set stdout to a temporary output file" do
outfile = Puppet::FileSystem::Uniquefile.new('stdout')
allow(Puppet::FileSystem::Uniquefile).to receive(:new).and_return(outfile)
expect(Puppet::Util::Execution).to receive(executor) do |_,_,_,stdout,_|
expect(stdout.path).to eq(outfile.path)
rval
end
Puppet::Util::Execution.execute('test command', :squelch => false)
end
it "should set stderr to the same file as stdout if combine is true" do
outfile = Puppet::FileSystem::Uniquefile.new('stdout')
allow(Puppet::FileSystem::Uniquefile).to receive(:new).and_return(outfile)
expect(Puppet::Util::Execution).to receive(executor) do |_,_,_,stdout,stderr|
expect(stdout.path).to eq(outfile.path)
expect(stderr.path).to eq(outfile.path)
rval
end
Puppet::Util::Execution.execute('test command', :squelch => false, :combine => true)
end
it "should set stderr to the null device if combine is false" do
outfile = Puppet::FileSystem::Uniquefile.new('stdout')
allow(Puppet::FileSystem::Uniquefile).to receive(:new).and_return(outfile)
expect(Puppet::Util::Execution).to receive(executor) do |_,_,_,stdout,stderr|
expect(stdout.path).to eq(outfile.path)
expect(stderr.path).to eq(null_file)
rval
end
Puppet::Util::Execution.execute('test command', :squelch => false, :combine => false)
end
it "should combine stdout and stderr if combine is true" do
outfile = Puppet::FileSystem::Uniquefile.new('stdout')
allow(Puppet::FileSystem::Uniquefile).to receive(:new).and_return(outfile)
expect(Puppet::Util::Execution).to receive(executor) do |_,_,_,stdout,stderr|
expect(stdout.path).to eq(outfile.path)
expect(stderr.path).to eq(outfile.path)
rval
end
Puppet::Util::Execution.execute('test command', :combine => true)
end
it "should default combine to true when no options are specified" do
outfile = Puppet::FileSystem::Uniquefile.new('stdout')
allow(Puppet::FileSystem::Uniquefile).to receive(:new).and_return(outfile)
expect(Puppet::Util::Execution).to receive(executor) do |_,_,_,stdout,stderr|
expect(stdout.path).to eq(outfile.path)
expect(stderr.path).to eq(outfile.path)
rval
end
Puppet::Util::Execution.execute('test command')
end
it "should default combine to false when options are specified, but combine is not" do
outfile = Puppet::FileSystem::Uniquefile.new('stdout')
allow(Puppet::FileSystem::Uniquefile).to receive(:new).and_return(outfile)
expect(Puppet::Util::Execution).to receive(executor) do |_,_,_,stdout,stderr|
expect(stdout.path).to eq(outfile.path)
expect(stderr.path).to eq(null_file)
rval
end
Puppet::Util::Execution.execute('test command', :failonfail => false)
end
it "should default combine to false when an empty hash of options is specified" do
outfile = Puppet::FileSystem::Uniquefile.new('stdout')
allow(Puppet::FileSystem::Uniquefile).to receive(:new).and_return(outfile)
expect(Puppet::Util::Execution).to receive(executor) do |_,_,_,stdout,stderr|
expect(stdout.path).to eq(outfile.path)
expect(stderr.path).to eq(null_file)
rval
end
Puppet::Util::Execution.execute('test command', {})
end
end
end
end
describe "on Windows", :if => Puppet::Util::Platform.windows? do
it "should always close the process and thread handles" do
allow(Puppet::Util::Execution).to receive(:execute_windows).and_return(proc_info_stub)
expect(Puppet::Util::Windows::Process).to receive(:wait_process).with(process_handle).and_raise('whatever')
expect(FFI::WIN32).to receive(:CloseHandle).with(thread_handle)
expect(FFI::WIN32).to receive(:CloseHandle).with(process_handle)
expect { Puppet::Util::Execution.execute('test command') }.to raise_error(RuntimeError)
end
it "should return the correct exit status even when exit status is greater than 256" do
real_exit_status = 3010
allow(Puppet::Util::Execution).to receive(:execute_windows).and_return(proc_info_stub)
stub_process_wait(real_exit_status)
allow(Puppet::Util::Execution).to receive(:exitstatus).and_return(real_exit_status % 256) # The exitstatus is changed to be mod 256 so that ruby can fit it into 8 bits.
expect(Puppet::Util::Execution.execute('test command', :failonfail => false).exitstatus).to eq(real_exit_status)
end
end
end
describe "#execute (posix locale)", :unless => Puppet::Util::Platform.windows? do
before :each do
# there is a danger here that ENV will be modified by exec_posix. Normally it would only affect the ENV
# of a forked process, but, in some of the previous tests in this file we're stubbing Kernel.fork., which could
# allow the method to override the "real" ENV. This shouldn't be a problem for these tests because they are
# not stubbing Kernel.fork, but, better safe than sorry... so, to guard against this, we'll capture a snapshot
# of ENV before each test.
@saved_env = ENV.to_hash
end
after :each do
# capture the current environment and make sure it's the same as it was before the test
cur_env = ENV.to_hash
# we will get some fairly useless output if we just use the raw == operator on the hashes here, so we'll
# be a bit more explicit and laborious in the name of making the error more useful...
@saved_env.each_pair { |key,val| expect(cur_env[key]).to eq(val) }
expect(cur_env.keys - @saved_env.keys).to eq([])
end
# build up a printf-style string that contains a command to get the value of an environment variable
# from the operating system. We can substitute into this with the names of the desired environment variables later.
get_env_var_cmd = 'echo $%s'
# a sentinel value that we can use to emulate what locale environment variables might be set to on an international
# system.
lang_sentinel_value = "en_US.UTF-8"
# a temporary hash that contains sentinel values for each of the locale environment variables that we override in
# "execute"
locale_sentinel_env = {}
Puppet::Util::POSIX::LOCALE_ENV_VARS.each { |var| locale_sentinel_env[var] = lang_sentinel_value }
it "should override the locale environment variables when :override_locale is not set (defaults to true)" do
# temporarily override the locale environment vars with a sentinel value, so that we can confirm that
# execute is actually setting them.
Puppet::Util.withenv(locale_sentinel_env) do
Puppet::Util::POSIX::LOCALE_ENV_VARS.each do |var|
# we expect that all of the POSIX vars will have been cleared except for LANG and LC_ALL
expected_value = (['LANG', 'LC_ALL'].include?(var)) ? "C" : ""
expect(Puppet::Util::Execution.execute(get_env_var_cmd % var).strip).to eq(expected_value)
end
end
end
it "should override the LANG environment variable when :override_locale is set to true" do
# temporarily override the locale environment vars with a sentinel value, so that we can confirm that
# execute is actually setting them.
Puppet::Util.withenv(locale_sentinel_env) do
Puppet::Util::POSIX::LOCALE_ENV_VARS.each do |var|
# we expect that all of the POSIX vars will have been cleared except for LANG and LC_ALL
expected_value = (['LANG', 'LC_ALL'].include?(var)) ? "C" : ""
expect(Puppet::Util::Execution.execute(get_env_var_cmd % var, {:override_locale => true}).strip).to eq(expected_value)
end
end
end
it "should *not* override the LANG environment variable when :override_locale is set to false" do
# temporarily override the locale environment vars with a sentinel value, so that we can confirm that
# execute is not setting them.
Puppet::Util.withenv(locale_sentinel_env) do
Puppet::Util::POSIX::LOCALE_ENV_VARS.each do |var|
expect(Puppet::Util::Execution.execute(get_env_var_cmd % var, {:override_locale => false}).strip).to eq(lang_sentinel_value)
end
end
end
it "should have restored the LANG and locale environment variables after execution" do
# we'll do this once without any sentinel values, to give us a little more test coverage
orig_env_vals = {}
Puppet::Util::POSIX::LOCALE_ENV_VARS.each do |var|
orig_env_vals[var] = ENV[var]
end
# now we can really execute any command--doesn't matter what it is...
Puppet::Util::Execution.execute(get_env_var_cmd % 'anything', {:override_locale => true})
# now we check and make sure the original environment was restored
Puppet::Util::POSIX::LOCALE_ENV_VARS.each do |var|
expect(ENV[var]).to eq(orig_env_vals[var])
end
# now, once more... but with our sentinel values
Puppet::Util.withenv(locale_sentinel_env) do
# now we can really execute any command--doesn't matter what it is...
Puppet::Util::Execution.execute(get_env_var_cmd % 'anything', {:override_locale => true})
# now we check and make sure the original environment was restored
Puppet::Util::POSIX::LOCALE_ENV_VARS.each do |var|
expect(ENV[var]).to eq(locale_sentinel_env[var])
end
end
end
end
describe "#execute (posix user env vars)", :unless => Puppet::Util::Platform.windows? do
# build up a printf-style string that contains a command to get the value of an environment variable
# from the operating system. We can substitute into this with the names of the desired environment variables later.
get_env_var_cmd = 'echo $%s'
# a sentinel value that we can use to emulate what locale environment variables might be set to on an international
# system.
user_sentinel_value = "Abracadabra"
# a temporary hash that contains sentinel values for each of the locale environment variables that we override in
# "execute"
user_sentinel_env = {}
Puppet::Util::POSIX::USER_ENV_VARS.each { |var| user_sentinel_env[var] = user_sentinel_value }
it "should unset user-related environment vars during execution" do
# first we set up a temporary execution environment with sentinel values for the user-related environment vars
# that we care about.
Puppet::Util.withenv(user_sentinel_env) do
# with this environment, we loop over the vars in question
Puppet::Util::POSIX::USER_ENV_VARS.each do |var|
# ensure that our temporary environment is set up as we expect
expect(ENV[var]).to eq(user_sentinel_env[var])
# run an "exec" via the provider and ensure that it unsets the vars
expect(Puppet::Util::Execution.execute(get_env_var_cmd % var).strip).to eq("")
# ensure that after the exec, our temporary env is still intact
expect(ENV[var]).to eq(user_sentinel_env[var])
end
end
end
it "should have restored the user-related environment variables after execution" do
# we'll do this once without any sentinel values, to give us a little more test coverage
orig_env_vals = {}
Puppet::Util::POSIX::USER_ENV_VARS.each do |var|
orig_env_vals[var] = ENV[var]
end
# now we can really execute any command--doesn't matter what it is...
Puppet::Util::Execution.execute(get_env_var_cmd % 'anything')
# now we check and make sure the original environment was restored
Puppet::Util::POSIX::USER_ENV_VARS.each do |var|
expect(ENV[var]).to eq(orig_env_vals[var])
end
# now, once more... but with our sentinel values
Puppet::Util.withenv(user_sentinel_env) do
# now we can really execute any command--doesn't matter what it is...
Puppet::Util::Execution.execute(get_env_var_cmd % 'anything')
# now we check and make sure the original environment was restored
Puppet::Util::POSIX::USER_ENV_VARS.each do |var|
expect(ENV[var]).to eq(user_sentinel_env[var])
end
end
end
end
describe "#execute (debug logging)" do
before :each do
Puppet[:log_level] = 'debug'
stub_process_wait(0)
if Puppet::Util::Platform.windows?
allow(Puppet::Util::Execution).to receive(:execute_windows).and_return(proc_info_stub)
else
allow(Puppet::Util::Execution).to receive(:execute_posix).and_return(pid)
end
end
it "should log if no uid or gid specified" do
expect(Puppet).to receive(:send_log).with(:debug, "Executing: 'echo hello'")
Puppet::Util::Execution.execute('echo hello')
end
it "should log numeric uid if specified" do
expect(Puppet).to receive(:send_log).with(:debug, "Executing with uid=100: 'echo hello'")
Puppet::Util::Execution.execute('echo hello', {:uid => 100})
end
it "should log numeric gid if specified" do
expect(Puppet).to receive(:send_log).with(:debug, "Executing with gid=500: 'echo hello'")
Puppet::Util::Execution.execute('echo hello', {:gid => 500})
end
it "should log numeric uid and gid if specified" do
expect(Puppet).to receive(:send_log).with(:debug, "Executing with uid=100 gid=500: 'echo hello'")
Puppet::Util::Execution.execute('echo hello', {:uid => 100, :gid => 500})
end
it "should log string uid if specified" do
expect(Puppet).to receive(:send_log).with(:debug, "Executing with uid=myuser: 'echo hello'")
Puppet::Util::Execution.execute('echo hello', {:uid => 'myuser'})
end
it "should log string gid if specified" do
expect(Puppet).to receive(:send_log).with(:debug, "Executing with gid=mygroup: 'echo hello'")
Puppet::Util::Execution.execute('echo hello', {:gid => 'mygroup'})
end
it "should log string uid and gid if specified" do
expect(Puppet).to receive(:send_log).with(:debug, "Executing with uid=myuser gid=mygroup: 'echo hello'")
Puppet::Util::Execution.execute('echo hello', {:uid => 'myuser', :gid => 'mygroup'})
end
it "should log numeric uid and string gid if specified" do
expect(Puppet).to receive(:send_log).with(:debug, "Executing with uid=100 gid=mygroup: 'echo hello'")
Puppet::Util::Execution.execute('echo hello', {:uid => 100, :gid => 'mygroup'})
end
it 'should redact commands in debug output when passed sensitive option' do
expect(Puppet).to receive(:send_log).with(:debug, "Executing: '[redacted]'")
Puppet::Util::Execution.execute('echo hello', {:sensitive => true})
end
end
describe "after execution" do
before :each do
stub_process_wait(0)
if Puppet::Util::Platform.windows?
allow(Puppet::Util::Execution).to receive(:execute_windows).and_return(proc_info_stub)
else
allow(Puppet::Util::Execution).to receive(:execute_posix).and_return(pid)
end
end
it "should wait for the child process to exit" do
allow(Puppet::Util::Execution).to receive(:wait_for_output)
Puppet::Util::Execution.execute('test command')
end
it "should close the stdin/stdout/stderr files used by the child" do
stdin = double('file')
stdout = double('file')
stderr = double('file')
[stdin, stdout, stderr].each {|io| expect(io).to receive(:close).at_least(:once)}
expect(File).to receive(:open).
exactly(3).times().
and_return(stdin, stdout, stderr)
Puppet::Util::Execution.execute('test command', {:squelch => true, :combine => false})
end
describe "on POSIX", :if => Puppet.features.posix? do
context "reading the output" do
before :each do
r, w = IO.pipe
expect(IO).to receive(:pipe).and_return([r, w])
w.write("My expected \u2744 command output")
end
it "should return output with external encoding ISO_8859_1" do
result = PuppetSpec::CharacterEncoding.with_external_encoding(Encoding::ISO_8859_1) do
Puppet::Util::Execution.execute('test command')
end
expect(result.encoding).to eq(Encoding::ISO_8859_1)
expect(result).to eq("My expected \u2744 command output".force_encoding(Encoding::ISO_8859_1))
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.