repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | true |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 '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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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).to include(/\/tmp\/test2\.pp:20/)
puppetstack = log.backtrace.select { |l| l =~ /tmp\/test\d\.pp/ }
expect(puppetstack.length).to eq(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 eq(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 eq(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 eq(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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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
# 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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/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 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | true |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/util/lockfile_spec.rb | spec/unit/util/lockfile_spec.rb | require 'spec_helper'
require 'puppet/util/lockfile'
module LockfileSpecHelper
def self.run_in_forks(count, &blk)
forks = {}
results = []
count.times do |i|
forks[i] = {}
forks[i][:read], forks[i][:write] = IO.pipe
forks[i][:pid] = fork do
forks[i][:read].close
res = yield
Marshal.dump(res, forks[i][:write])
exit!
end
end
count.times do |i|
forks[i][:write].close
result = forks[i][:read].read
forks[i][:read].close
Process.wait2(forks[i][:pid])
results << Marshal.load(result)
end
results
end
end
describe Puppet::Util::Lockfile do
require 'puppet_spec/files'
include PuppetSpec::Files
before(:each) do
@lockfile = tmpfile("lock")
@lock = Puppet::Util::Lockfile.new(@lockfile)
end
describe "#lock" do
it "should return true if it successfully locked" do
expect(@lock.lock).to be_truthy
end
it "should return false if already locked" do
@lock.lock
expect(@lock.lock).to be_falsey
end
it "should create a lock file" do
@lock.lock
expect(Puppet::FileSystem.exist?(@lockfile)).to be_truthy
end
# We test simultaneous locks using fork which isn't supported on Windows.
it "should not be acquired by another process", :unless => Puppet::Util::Platform.windows? || RUBY_PLATFORM == 'java' do
30.times do
forks = 3
results = LockfileSpecHelper.run_in_forks(forks) do
@lock.lock(Process.pid)
end
@lock.unlock
# Confirm one fork returned true and everyone else false.
expect((results - [true]).size).to eq(forks - 1)
expect((results - [false]).size).to eq(1)
end
end
it "should create a lock file containing a string" do
data = "foofoo barbar"
@lock.lock(data)
expect(File.read(@lockfile)).to eq(data)
end
end
describe "#unlock" do
it "should return true when unlocking" do
@lock.lock
expect(@lock.unlock).to be_truthy
end
it "should return false when not locked" do
expect(@lock.unlock).to be_falsey
end
it "should clear the lock file" do
File.open(@lockfile, 'w') { |fd| fd.print("locked") }
@lock.unlock
expect(Puppet::FileSystem.exist?(@lockfile)).to be_falsey
end
end
it "should be locked when locked" do
@lock.lock
expect(@lock).to be_locked
end
it "should not be locked when not locked" do
expect(@lock).not_to be_locked
end
it "should not be locked when unlocked" do
@lock.lock
@lock.unlock
expect(@lock).not_to be_locked
end
it "should return the lock data" do
data = "foofoo barbar"
@lock.lock(data)
expect(@lock.lock_data).to eq(data)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/util/filetype_spec.rb | spec/unit/util/filetype_spec.rb | require 'spec_helper'
require 'puppet/util/filetype'
# XXX Import all of the tests into this file.
describe Puppet::Util::FileType do
describe "the flat filetype" do
let(:path) { '/my/file' }
let(:type) { Puppet::Util::FileType.filetype(:flat) }
let(:file) { type.new(path) }
it "should exist" do
expect(type).not_to be_nil
end
describe "when the file already exists" do
it "should return the file's contents when asked to read it" do
expect(Puppet::FileSystem).to receive(:exist?).with(path).and_return(true)
expect(Puppet::FileSystem).to receive(:read).with(path, {:encoding => Encoding.default_external}).and_return("my text")
expect(file.read).to eq("my text")
end
it "should unlink the file when asked to remove it" do
expect(Puppet::FileSystem).to receive(:exist?).with(path).and_return(true)
expect(Puppet::FileSystem).to receive(:unlink).with(path)
file.remove
end
end
describe "when the file does not exist" do
it "should return an empty string when asked to read the file" do
expect(Puppet::FileSystem).to receive(:exist?).with(path).and_return(false)
expect(file.read).to eq("")
end
end
describe "when writing the file" do
let(:tempfile) { double('tempfile', :print => nil, :close => nil, :flush => nil, :path => "/other/file") }
before do
allow(FileUtils).to receive(:cp)
allow(Tempfile).to receive(:new).and_return(tempfile)
end
it "should first create a temp file and copy its contents over to the file location" do
expect(Tempfile).to receive(:new).with("puppet", {:encoding => Encoding.default_external}).and_return(tempfile)
expect(tempfile).to receive(:print).with("my text")
expect(tempfile).to receive(:flush)
expect(tempfile).to receive(:close)
expect(FileUtils).to receive(:cp).with(tempfile.path, path)
file.write "my text"
end
it "should set the selinux default context on the file" do
expect(file).to receive(:set_selinux_default_context).with(path)
file.write "eh"
end
end
describe "when backing up a file" do
it "should do nothing if the file does not exist" do
expect(Puppet::FileSystem).to receive(:exist?).with(path).and_return(false)
expect(file).not_to receive(:bucket)
file.backup
end
it "should use its filebucket to backup the file if it exists" do
expect(Puppet::FileSystem).to receive(:exist?).with(path).and_return(true)
bucket = double('bucket')
expect(bucket).to receive(:backup).with(path)
expect(file).to receive(:bucket).and_return(bucket)
file.backup
end
it "should use the default filebucket" do
bucket = double('bucket')
expect(bucket).to receive(:bucket).and_return("mybucket")
expect(Puppet::Type.type(:filebucket)).to receive(:mkdefaultbucket).and_return(bucket)
expect(file.bucket).to eq("mybucket")
end
end
end
shared_examples_for "crontab provider" do
let(:cron) { type.new('no_such_user') }
let(:crontab) { File.read(my_fixture(crontab_output)) }
let(:options) { { :failonfail => true, :combine => true } }
let(:uid) { 'no_such_user' }
let(:user_options) { options.merge({:uid => uid}) }
it "should exist" do
expect(type).not_to be_nil
end
# make Puppet::Util::SUIDManager return something deterministic, not the
# uid of the user running the tests, except where overridden below.
before :each do
allow(Puppet::Util::SUIDManager).to receive(:uid).and_return(1234)
end
describe "#read" do
before(:each) do
allow(Puppet::Util).to receive(:uid).with(uid).and_return(9000)
end
it "should run crontab -l as the target user" do
expect(Puppet::Util::Execution).to receive(:execute)
.with(['crontab', '-l'], user_options)
.and_return(Puppet::Util::Execution::ProcessOutput.new(crontab, 0))
expect(cron.read).to eq(crontab)
end
it "should not switch user if current user is the target user" do
expect(Puppet::Util).to receive(:uid).with(uid).twice.and_return(9000)
expect(Puppet::Util::SUIDManager).to receive(:uid).and_return(9000)
expect(Puppet::Util::Execution).to receive(:execute)
.with(['crontab', '-l'], options)
.and_return(Puppet::Util::Execution::ProcessOutput.new(crontab, 0))
expect(cron.read).to eq(crontab)
end
it "should treat an absent crontab as empty" do
expect(Puppet::Util::Execution).to receive(:execute).with(['crontab', '-l'], user_options).and_raise(Puppet::ExecutionFailure, absent_crontab)
expect(cron.read).to eq('')
end
it "should treat a nonexistent user's crontab as empty" do
expect(Puppet::Util).to receive(:uid).with(uid).and_return(nil)
expect(cron.read).to eq('')
end
it "should return empty if the user is not authorized to use cron" do
expect(Puppet::Util::Execution).to receive(:execute).with(['crontab', '-l'], user_options).and_raise(Puppet::ExecutionFailure, unauthorized_crontab)
expect(cron.read).to eq('')
end
end
describe "#remove" do
it "should run crontab -r as the target user" do
expect(Puppet::Util::Execution).to receive(:execute).with(['crontab', '-r'], user_options)
cron.remove
end
it "should not switch user if current user is the target user" do
expect(Puppet::Util).to receive(:uid).with(uid).and_return(9000)
expect(Puppet::Util::SUIDManager).to receive(:uid).and_return(9000)
expect(Puppet::Util::Execution).to receive(:execute).with(['crontab','-r'], options)
cron.remove
end
end
describe "#write" do
before :each do
@tmp_cron = Tempfile.new("puppet_crontab_spec")
@tmp_cron_path = @tmp_cron.path
allow(Puppet::Util).to receive(:uid).with(uid).and_return(9000)
expect(Tempfile).to receive(:new).with("puppet_#{name}", {:encoding => Encoding.default_external}).and_return(@tmp_cron)
end
after :each do
expect(Puppet::FileSystem.exist?(@tmp_cron_path)).to be_falsey
end
it "should run crontab as the target user on a temporary file" do
expect(File).to receive(:chown).with(9000, nil, @tmp_cron_path)
expect(Puppet::Util::Execution).to receive(:execute).with(["crontab", @tmp_cron_path], user_options)
expect(@tmp_cron).to receive(:print).with("foo\n")
cron.write "foo\n"
end
it "should not switch user if current user is the target user" do
expect(Puppet::Util::SUIDManager).to receive(:uid).and_return(9000)
expect(File).to receive(:chown).with(9000, nil, @tmp_cron_path)
expect(Puppet::Util::Execution).to receive(:execute).with(["crontab", @tmp_cron_path], options)
expect(@tmp_cron).to receive(:print).with("foo\n")
cron.write "foo\n"
end
end
end
describe "the suntab filetype", :unless => Puppet::Util::Platform.windows? do
let(:type) { Puppet::Util::FileType.filetype(:suntab) }
let(:name) { type.name }
let(:crontab_output) { 'suntab_output' }
# possible crontab output was taken from here:
# https://docs.oracle.com/cd/E19082-01/819-2380/sysrescron-60/index.html
let(:absent_crontab) do
'crontab: can\'t open your crontab file'
end
let(:unauthorized_crontab) do
'crontab: you are not authorized to use cron. Sorry.'
end
it_should_behave_like "crontab provider"
end
describe "the aixtab filetype", :unless => Puppet::Util::Platform.windows? do
let(:type) { Puppet::Util::FileType.filetype(:aixtab) }
let(:name) { type.name }
let(:crontab_output) { 'aixtab_output' }
let(:absent_crontab) do
'0481-103 Cannot open a file in the /var/spool/cron/crontabs directory.'
end
let(:unauthorized_crontab) do
'0481-109 You are not authorized to use the cron command.'
end
it_should_behave_like "crontab provider"
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/util/json_spec.rb | spec/unit/util/json_spec.rb | # coding: utf-8
require 'spec_helper'
require 'puppet/util/json'
describe Puppet::Util::Json do
include PuppetSpec::Files
shared_examples_for 'json file loader' do |load_method|
it 'reads a JSON file from disk' do
file_path = file_containing('input', JSON.dump({ "my" => "data" }))
expect(load_method.call(file_path)).to eq({ "my" => "data" })
end
it 'reads JSON as UTF-8' do
file_path = file_containing('input', JSON.dump({ "my" => "𠜎" }))
expect(load_method.call(file_path)).to eq({ "my" => "𠜎" })
end
end
context "#load" do
it 'raises an error if JSON is invalid' do
expect {
Puppet::Util::Json.load('{ invalid')
}.to raise_error(Puppet::Util::Json::ParseError)
end
it 'raises an error if the content is empty' do
expect {
Puppet::Util::Json.load('')
}.to raise_error(Puppet::Util::Json::ParseError)
end
it 'loads true' do
expect(Puppet::Util::Json.load('true')).to eq(true)
end
it 'loads false' do
expect(Puppet::Util::Json.load('false')).to eq(false)
end
it 'loads a numeric' do
expect(Puppet::Util::Json.load('42')).to eq(42)
end
it 'loads a string' do
expect(Puppet::Util::Json.load('"puppet"')).to eq('puppet')
end
it 'loads an array' do
expect(Puppet::Util::Json.load(<<~JSON)).to eq([1, 2])
[1, 2]
JSON
end
it 'loads a hash' do
expect(Puppet::Util::Json.load(<<~JSON)).to eq('a' => 1, 'b' => 2)
{
"a": 1,
"b": 2
}
JSON
end
end
context "load_file_if_valid" do
before do
Puppet[:log_level] = 'debug'
end
it_should_behave_like 'json file loader', Puppet::Util::Json.method(:load_file_if_valid)
it 'returns nil when the file is invalid JSON and debug logs about it' do
file_path = file_containing('input', '{ invalid')
expect(Puppet).to receive(:debug)
.with(/Could not retrieve JSON content/).and_call_original
expect(Puppet::Util::Json.load_file_if_valid(file_path)).to eql(nil)
end
it 'returns nil when the filename is illegal and debug logs about it' do
expect(Puppet).to receive(:debug)
.with(/Could not retrieve JSON content .+: pathname contains null byte/).and_call_original
expect(Puppet::Util::Json.load_file_if_valid("not\0allowed")).to eql(nil)
end
it 'returns nil when the file does not exist and debug logs about it' do
expect(Puppet).to receive(:debug)
.with(/Could not retrieve JSON content .+: No such file or directory/).and_call_original
expect(Puppet::Util::Json.load_file_if_valid('does/not/exist.json')).to eql(nil)
end
end
context '#load_file' do
it_should_behave_like 'json file loader', Puppet::Util::Json.method(:load_file)
it 'raises an error when the file is invalid JSON' do
file_path = file_containing('input', '{ invalid')
expect {
Puppet::Util::Json.load_file(file_path)
}.to raise_error(Puppet::Util::Json::ParseError)
end
it 'raises an error when the filename is illegal' do
expect {
Puppet::Util::Json.load_file("not\0allowed")
}.to raise_error(ArgumentError, /null byte/)
end
it 'raises an error when the file does not exist' do
expect {
Puppet::Util::Json.load_file('does/not/exist.json')
}.to raise_error(Errno::ENOENT, /No such file or directory/)
end
it 'writes data formatted as JSON to disk' do
file_path = file_containing('input', Puppet::Util::Json.dump({ "my" => "data" }))
expect(Puppet::Util::Json.load_file(file_path)).to eq({ "my" => "data" })
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/util/checksums_spec.rb | spec/unit/util/checksums_spec.rb | require 'spec_helper'
require 'puppet/util/checksums'
describe Puppet::Util::Checksums do
include PuppetSpec::Files
before do
@summer = Puppet::Util::Checksums
end
content_sums = [:md5, :md5lite, :sha1, :sha1lite, :sha256, :sha256lite, :sha512, :sha384, :sha224]
file_only = [:ctime, :mtime, :none]
content_sums.each do |sumtype|
it "should be able to calculate #{sumtype} sums from strings" do
expect(@summer).to be_respond_to(sumtype)
end
end
content_sums.each do |sumtype|
it "should know the expected length of #{sumtype} sums" do
expect(@summer).to be_respond_to(sumtype.to_s + "_hex_length")
end
end
[content_sums, file_only].flatten.each do |sumtype|
it "should be able to calculate #{sumtype} sums from files" do
expect(@summer).to be_respond_to(sumtype.to_s + "_file")
end
end
[content_sums, file_only].flatten.each do |sumtype|
it "should be able to calculate #{sumtype} sums from stream" do
expect(@summer).to be_respond_to(sumtype.to_s + "_stream")
end
end
it "should have a method for determining whether a given string is a checksum" do
expect(@summer).to respond_to(:checksum?)
end
%w{{md5}asdfasdf {sha1}asdfasdf {ctime}asdasdf {mtime}asdfasdf
{sha256}asdfasdf {sha256lite}asdfasdf {sha512}asdfasdf {sha384}asdfasdf {sha224}asdfasdf}.each do |sum|
it "should consider #{sum} to be a checksum" do
expect(@summer).to be_checksum(sum)
end
end
%w{{nosuchsumthislong}asdfasdf {a}asdfasdf {ctime}}.each do |sum|
it "should not consider #{sum} to be a checksum" do
expect(@summer).not_to be_checksum(sum)
end
end
it "should have a method for stripping a sum type from an existing checksum" do
expect(@summer.sumtype("{md5}asdfasdfa")).to eq("md5")
end
it "should have a method for stripping the data from a checksum" do
expect(@summer.sumdata("{md5}asdfasdfa")).to eq("asdfasdfa")
end
it "should return a nil sumtype if the checksum does not mention a checksum type" do
expect(@summer.sumtype("asdfasdfa")).to be_nil
end
it "has a list of known checksum types" do
expect(@summer.known_checksum_types).to match_array(content_sums + file_only)
end
it "returns true if the checksum is valid" do
expect(@summer).to be_valid_checksum('sha1', 'fcc1715b22278a9dae322b0a34935f10d1608b9f')
end
it "returns false if the checksum is known but invalid" do
expect(@summer).to_not be_valid_checksum('sha1', 'wronglength')
end
it "returns false if the checksum type is unknown" do
expect(@summer).to_not be_valid_checksum('rot13', 'doesntmatter')
end
{:md5 => Digest::MD5, :sha1 => Digest::SHA1, :sha256 => Digest::SHA256, :sha512 => Digest::SHA512, :sha384 => Digest::SHA384}.each do |sum, klass|
describe("when using #{sum}") do
it "should use #{klass} to calculate string checksums" do
expect(klass).to receive(:hexdigest).with("mycontent").and_return("whatever")
expect(@summer.send(sum, "mycontent")).to eq("whatever")
end
it "should use incremental #{klass} sums to calculate file checksums" do
digest = double('digest')
expect(klass).to receive(:new).and_return(digest)
file = "/path/to/my/file"
fh = double('filehandle')
expect(fh).to receive(:read).with(4096).exactly(3).times().and_return("firstline", "secondline", nil)
expect(File).to receive(:open).with(file, "rb").and_yield(fh)
expect(digest).to receive(:<<).with("firstline")
expect(digest).to receive(:<<).with("secondline")
expect(digest).to receive(:hexdigest).and_return(:mydigest)
expect(@summer.send(sum.to_s + "_file", file)).to eq(:mydigest)
end
it "should behave like #{klass} to calculate stream checksums" do
digest = double('digest')
expect(klass).to receive(:new).and_return(digest)
expect(digest).to receive(:<<).with "firstline"
expect(digest).to receive(:<<).with "secondline"
expect(digest).to receive(:hexdigest).and_return(:mydigest)
expect(@summer.send(sum.to_s + "_stream") do |checksum|
checksum << "firstline"
checksum << "secondline"
end).to eq(:mydigest)
end
end
end
{:md5lite => Digest::MD5, :sha1lite => Digest::SHA1, :sha256lite => Digest::SHA256}.each do |sum, klass|
describe("when using #{sum}") do
it "should use #{klass} to calculate string checksums from the first 512 characters of the string" do
content = "this is a test" * 100
expect(klass).to receive(:hexdigest).with(content[0..511]).and_return("whatever")
expect(@summer.send(sum, content)).to eq("whatever")
end
it "should use #{klass} to calculate a sum from the first 512 characters in the file" do
digest = double('digest')
expect(klass).to receive(:new).and_return(digest)
file = "/path/to/my/file"
fh = double('filehandle')
expect(fh).to receive(:read).with(512).and_return('my content')
expect(File).to receive(:open).with(file, "rb").and_yield(fh)
expect(digest).to receive(:<<).with("my content")
expect(digest).to receive(:hexdigest).and_return(:mydigest)
expect(@summer.send(sum.to_s + "_file", file)).to eq(:mydigest)
end
it "should use #{klass} to calculate a sum from the first 512 characters in a stream" do
digest = double('digest')
content = "this is a test" * 100
expect(klass).to receive(:new).and_return(digest)
expect(digest).to receive(:<<).with(content[0..511])
expect(digest).to receive(:hexdigest).and_return(:mydigest)
expect(@summer.send(sum.to_s + "_stream") do |checksum|
checksum << content
end).to eq(:mydigest)
end
it "should use #{klass} to calculate a sum from the first 512 characters in a multi-part stream" do
digest = double('digest')
content = "this is a test" * 100
expect(klass).to receive(:new).and_return(digest)
expect(digest).to receive(:<<).with(content[0..5])
expect(digest).to receive(:<<).with(content[6..510])
expect(digest).to receive(:<<).with(content[511..511])
expect(digest).to receive(:hexdigest).and_return(:mydigest)
expect(@summer.send(sum.to_s + "_stream") do |checksum|
checksum << content[0..5]
checksum << content[6..510]
checksum << content[511..-1]
end).to eq(:mydigest)
end
end
end
[:ctime, :mtime].each do |sum|
describe("when using #{sum}") do
it "should use the '#{sum}' on the file to determine the ctime" do
file = "/my/file"
stat = double('stat', sum => "mysum")
expect(Puppet::FileSystem).to receive(:stat).with(file).and_return(stat)
expect(@summer.send(sum.to_s + "_file", file)).to eq("mysum")
end
it "should return nil for streams" do
expectation = double("expectation")
expect(expectation).to receive(:do_something!).at_least(:once)
expect(@summer.send(sum.to_s + "_stream"){ |checksum| checksum << "anything" ; expectation.do_something! }).to be_nil
end
end
end
describe "when using the none checksum" do
it "should return an empty string" do
expect(@summer.none_file("/my/file")).to eq("")
end
it "should return an empty string for streams" do
expectation = double("expectation")
expect(expectation).to receive(:do_something!).at_least(:once)
expect(@summer.none_stream{ |checksum| checksum << "anything" ; expectation.do_something! }).to eq("")
end
end
{:md5 => Digest::MD5, :sha1 => Digest::SHA1}.each do |sum, klass|
describe "when using #{sum}" do
let(:content) { "hello\r\nworld" }
let(:path) do
path = tmpfile("checksum_#{sum}")
File.open(path, 'wb') {|f| f.write(content)}
path
end
it "should preserve nl/cr sequences" do
expect(@summer.send(sum.to_s + "_file", path)).to eq(klass.hexdigest(content))
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/util/watched_file_spec.rb | spec/unit/util/watched_file_spec.rb | require 'spec_helper'
require 'puppet/util/watched_file'
require 'puppet/util/watcher'
describe Puppet::Util::WatchedFile do
let(:an_absurdly_long_timeout) { Puppet::Util::Watcher::Timer.new(100000) }
let(:an_immediate_timeout) { Puppet::Util::Watcher::Timer.new(0) }
it "acts like a string so that it can be used as a filename" do
watched = Puppet::Util::WatchedFile.new("foo")
expect(watched.to_str).to eq("foo")
end
it "considers the file to be unchanged before the timeout expires" do
watched = Puppet::Util::WatchedFile.new(a_file_that_doesnt_exist, an_absurdly_long_timeout)
expect(watched).to_not be_changed
end
it "considers a file that is created to be changed" do
watched_filename = a_file_that_doesnt_exist
watched = Puppet::Util::WatchedFile.new(watched_filename, an_immediate_timeout)
create_file(watched_filename)
expect(watched).to be_changed
end
it "considers a missing file to remain unchanged" do
watched = Puppet::Util::WatchedFile.new(a_file_that_doesnt_exist, an_immediate_timeout)
expect(watched).to_not be_changed
end
it "considers a file that has changed but the timeout is not expired to still be unchanged" do
watched_filename = a_file_that_doesnt_exist
watched = Puppet::Util::WatchedFile.new(watched_filename, an_absurdly_long_timeout)
create_file(watched_filename)
expect(watched).to_not be_changed
end
def create_file(name)
File.open(name, "wb") { |file| file.puts("contents") }
end
def a_file_that_doesnt_exist
PuppetSpec::Files.tmpfile("watched_file")
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/util/resource_template_spec.rb | spec/unit/util/resource_template_spec.rb | require 'spec_helper'
require 'puppet/util/resource_template'
describe Puppet::Util::ResourceTemplate do
describe "when initializing" do
it "should fail if the template does not exist" do
expect(Puppet::FileSystem).to receive(:exist?).with("/my/template").and_return(false)
expect { Puppet::Util::ResourceTemplate.new("/my/template", double('resource')) }.to raise_error(ArgumentError)
end
it "should not create the ERB template" do
expect(ERB).not_to receive(:new)
expect(Puppet::FileSystem).to receive(:exist?).with("/my/template").and_return(true)
Puppet::Util::ResourceTemplate.new("/my/template", double('resource'))
end
end
describe "when evaluating" do
before do
allow(Puppet::FileSystem).to receive(:exist?).and_return(true)
allow(Puppet::FileSystem).to receive(:read).and_return("eh")
@template = double('template', :result => nil)
allow(ERB).to receive(:new).and_return(@template)
@resource = double('resource')
@wrapper = Puppet::Util::ResourceTemplate.new("/my/template", @resource)
end
it "should set all of the resource's parameters as instance variables" do
expect(@resource).to receive(:to_hash).and_return(:one => "uno", :two => "dos")
expect(@template).to receive(:result) do |bind|
expect(eval("@one", bind)).to eq("uno")
expect(eval("@two", bind)).to eq("dos")
end
@wrapper.evaluate
end
it "should create a template instance with the contents of the file" do
expect(Puppet::FileSystem).to receive(:read).with("/my/template", {:encoding => 'utf-8'}).and_return("yay")
expect(Puppet::Util).to receive(:create_erb).with("yay").and_return(@template)
allow(@wrapper).to receive(:set_resource_variables)
@wrapper.evaluate
end
it "should return the result of the template" do
allow(@wrapper).to receive(:set_resource_variables)
expect(@wrapper).to receive(:binding).and_return("mybinding")
expect(@template).to receive(:result).with("mybinding").and_return("myresult")
expect(@wrapper.evaluate).to eq("myresult")
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/util/skip_tags_spec.rb | spec/unit/util/skip_tags_spec.rb | # coding: utf-8
require 'spec_helper'
require 'puppet/util/skip_tags'
describe Puppet::Util::SkipTags do
let(:tagger) { Puppet::Util::SkipTags.new([]) }
it "should add qualified classes as single tags" do
tagger.tag("one::two::three")
expect(tagger.tags).to include("one::two::three")
expect(tagger.tags).not_to include("one", "two", "three")
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/util/yaml_spec.rb | spec/unit/util/yaml_spec.rb | # coding: utf-8
require 'spec_helper'
require 'puppet/util/yaml'
describe Puppet::Util::Yaml do
include PuppetSpec::Files
let(:filename) { tmpfile("yaml") }
shared_examples_for 'yaml file loader' do |load_method|
it 'returns false when the file is empty' do
file_path = file_containing('input', '')
expect(load_method.call(file_path)).to eq(false)
end
it 'reads a YAML file from disk' do
file_path = file_containing('input', YAML.dump({ "my" => "data" }))
expect(load_method.call(file_path)).to eq({ "my" => "data" })
end
it 'reads YAML as UTF-8' do
file_path = file_containing('input', YAML.dump({ "my" => "𠜎" }))
expect(load_method.call(file_path)).to eq({ "my" => "𠜎" })
end
end
context "#safe_load" do
it 'raises an error if YAML is invalid' do
expect {
Puppet::Util::Yaml.safe_load('{ invalid')
}.to raise_error(Puppet::Util::Yaml::YamlLoadError, %r[\(<unknown>\): .* at line \d+ column \d+])
end
it 'raises if YAML contains classes not in the list' do
expect {
Puppet::Util::Yaml.safe_load(<<FACTS, [])
--- !ruby/object:Puppet::Node::Facts
name: localhost
FACTS
}.to raise_error(Puppet::Util::Yaml::YamlLoadError, "(<unknown>): Tried to load unspecified class: Puppet::Node::Facts")
end
it 'includes the filename if YAML contains classes not in the list' do
expect {
Puppet::Util::Yaml.safe_load(<<FACTS, [], 'foo.yaml')
--- !ruby/object:Puppet::Node::Facts
name: localhost
FACTS
}.to raise_error(Puppet::Util::Yaml::YamlLoadError, "(foo.yaml): Tried to load unspecified class: Puppet::Node::Facts")
end
it 'allows classes to be loaded' do
facts = Puppet::Util::Yaml.safe_load(<<FACTS, [Puppet::Node::Facts])
--- !ruby/object:Puppet::Node::Facts
name: localhost
values:
puppetversion: 6.0.0
FACTS
expect(facts.name).to eq('localhost')
end
it 'returns false if the content is empty' do
expect(Puppet::Util::Yaml.safe_load('')).to eq(false)
end
it 'loads true' do
expect(Puppet::Util::Yaml.safe_load('true')).to eq(true)
end
it 'loads false' do
expect(Puppet::Util::Yaml.safe_load('false')).to eq(false)
end
it 'loads nil' do
expect(Puppet::Util::Yaml.safe_load(<<~YAML)).to eq('a' => nil)
---
a: null
YAML
end
it 'loads a numeric' do
expect(Puppet::Util::Yaml.safe_load('42')).to eq(42)
end
it 'loads a string' do
expect(Puppet::Util::Yaml.safe_load('puppet')).to eq('puppet')
end
it 'loads an array' do
expect(Puppet::Util::Yaml.safe_load(<<~YAML)).to eq([1, 2])
---
- 1
- 2
YAML
end
it 'loads a hash' do
expect(Puppet::Util::Yaml.safe_load(<<~YAML)).to eq('a' => 1, 'b' => 2)
---
a: 1
b: 2
YAML
end
it 'loads an alias' do
expect(Puppet::Util::Yaml.safe_load(<<~YAML)).to eq('a' => [], 'b' => [])
---
a: &1 []
b: *1
YAML
end
end
context "#safe_load_file" do
it_should_behave_like 'yaml file loader', Puppet::Util::Yaml.method(:safe_load_file)
it 'raises an error when the file is invalid YAML' do
file_path = file_containing('input', '{ invalid')
expect {
Puppet::Util::Yaml.safe_load_file(file_path)
}.to raise_error(Puppet::Util::Yaml::YamlLoadError, %r[\(#{file_path}\): .* at line \d+ column \d+])
end
it 'raises an error when the filename is illegal' do
expect {
Puppet::Util::Yaml.safe_load_file("not\0allowed")
}.to raise_error(ArgumentError, /pathname contains null byte/)
end
it 'raises an error when the file does not exist' do
expect {
Puppet::Util::Yaml.safe_load_file('does/not/exist.yaml')
}.to raise_error(Errno::ENOENT, /No such file or directory/)
end
end
context "#safe_load_file_if_valid" do
before do
Puppet[:log_level] = 'debug'
end
it_should_behave_like 'yaml file loader', Puppet::Util::Yaml.method(:safe_load_file_if_valid)
it 'returns nil when the file is invalid YAML and debug logs about it' do
file_path = file_containing('input', '{ invalid')
expect(Puppet).to receive(:debug)
.with(/Could not retrieve YAML content .+ expected ',' or '}'/).and_call_original
expect(Puppet::Util::Yaml.safe_load_file_if_valid(file_path)).to eql(nil)
end
it 'returns nil when the filename is illegal and debug logs about it' do
expect(Puppet).to receive(:debug)
.with(/Could not retrieve YAML content .+: pathname contains null byte/).and_call_original
expect(Puppet::Util::Yaml.safe_load_file_if_valid("not\0allowed")).to eql(nil)
end
it 'returns nil when the file does not exist and debug logs about it' do
expect(Puppet).to receive(:debug)
.with(/Could not retrieve YAML content .+: No such file or directory/).and_call_original
expect(Puppet::Util::Yaml.safe_load_file_if_valid('does/not/exist.yaml')).to eql(nil)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/util/feature_spec.rb | spec/unit/util/feature_spec.rb | require 'spec_helper'
require 'puppet/util/feature'
describe Puppet::Util::Feature do
before do
@features = Puppet::Util::Feature.new("features")
allow(@features).to receive(:warn)
end
it "should not call associated code when adding a feature" do
$loaded_feature = false
@features.add(:myfeature) { $loaded_feature = true}
expect($loaded_feature).to eq(false)
end
it "should consider a feature absent when the feature load fails" do
@features.add(:failer) { raise "foo" }
expect(@features.failer?).to eq(false)
end
it "should consider a feature to be absent when the feature load returns false" do
@features.add(:failer) { false }
expect(@features.failer?).to eq(false)
end
it "should consider a feature to be absent when the feature load returns nil" do
@features.add(:failer) { nil }
expect(@features.failer?).to eq(false)
end
it "should consider a feature to be present when the feature load returns true" do
@features.add(:available) { true }
expect(@features.available?).to eq(true)
end
it "should consider a feature to be present when the feature load returns truthy" do
@features.add(:available) { "yes" }
expect(@features.available?).to eq(true)
end
it "should cache the results of a feature load via code block when the block returns true" do
$loaded_feature = 0
@features.add(:myfeature) { $loaded_feature += 1; true }
@features.myfeature?
@features.myfeature?
expect($loaded_feature).to eq(1)
end
it "should cache the results of a feature load via code block when the block returns false" do
$loaded_feature = 0
@features.add(:myfeature) { $loaded_feature += 1; false }
@features.myfeature?
@features.myfeature?
expect($loaded_feature).to eq(1)
end
it "should not cache the results of a feature load via code block when the block returns nil" do
$loaded_feature = 0
@features.add(:myfeature) { $loaded_feature += 1; nil }
@features.myfeature?
@features.myfeature?
expect($loaded_feature).to eq(2)
end
it "should invalidate the cache for the feature when loading" do
@features.add(:myfeature) { false }
expect(@features).not_to be_myfeature
@features.add(:myfeature)
expect(@features).to be_myfeature
end
it "should support features with libraries" do
expect { @features.add(:puppet, :libs => %w{puppet}) }.not_to raise_error
end
it "should consider a feature to be present if all of its libraries are present" do
@features.add(:myfeature, :libs => %w{foo bar})
expect(@features).to receive(:require).with("foo")
expect(@features).to receive(:require).with("bar")
expect(@features).to be_myfeature
end
it "should log and consider a feature to be absent if any of its libraries are absent" do
@features.add(:myfeature, :libs => %w{foo bar})
expect(@features).to receive(:require).with("foo").and_raise(LoadError)
allow(@features).to receive(:require).with("bar")
expect(@features).to receive(:debug_once)
expect(@features).not_to be_myfeature
end
it "should change the feature to be present when its libraries become available" do
@features.add(:myfeature, :libs => %w{foo bar})
times_feature_require_called = 0
expect(@features).to receive(:require).twice().with("foo") do
times_feature_require_called += 1
if times_feature_require_called == 1
raise LoadError
else
nil
end
end
allow(@features).to receive(:require).with("bar")
allow(Puppet::Util::RubyGems::Source).to receive(:source).and_return(Puppet::Util::RubyGems::Gems18Source)
times_clear_paths_called = 0
allow_any_instance_of(Puppet::Util::RubyGems::Gems18Source).to receive(:clear_paths) { times_clear_paths_called += 1 }
expect(@features).to receive(:debug_once)
expect(@features).not_to be_myfeature
expect(@features).to be_myfeature
expect(times_clear_paths_called).to eq(3)
end
it "should cache load failures when configured to do so" do
Puppet[:always_retry_plugins] = false
@features.add(:myfeature, :libs => %w{foo bar})
expect(@features).to receive(:require).with("foo").and_raise(LoadError)
expect(@features).not_to be_myfeature
# second call would cause an expectation exception if 'require' was
# called a second time
expect(@features).not_to be_myfeature
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/util/errors_spec.rb | spec/unit/util/errors_spec.rb | require 'spec_helper'
require 'puppet/util/errors'
class ErrorTester
include Puppet::Util::Errors
attr_accessor :line, :file
end
describe Puppet::Util::Errors do
before do
@tester = ErrorTester.new
end
it "should provide a 'fail' method" do
expect(@tester).to respond_to(:fail)
end
it "should provide a 'devfail' method" do
expect(@tester).to respond_to(:devfail)
end
it "should raise any provided error when failing" do
expect { @tester.fail(Puppet::ParseError, "stuff") }.to raise_error(Puppet::ParseError)
end
it "should default to Puppet::Error when failing" do
expect { @tester.fail("stuff") }.to raise_error(Puppet::Error)
end
it "should have a method for converting error context into a string" do
@tester.file = "/my/file"
@tester.line = 50
expect(@tester.error_context).to eq(" (file: /my/file, line: 50)")
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/util/log_spec.rb | spec/unit/util/log_spec.rb | # coding: utf-8
require 'spec_helper'
require 'puppet/util/log'
describe Puppet::Util::Log do
include PuppetSpec::Files
def log_notice(message)
Puppet::Util::Log.new(:level => :notice, :message => message)
end
it "should write a given message to the specified destination" do
arraydest = []
Puppet::Util::Log.newdestination(Puppet::Test::LogCollector.new(arraydest))
Puppet::Util::Log.new(:level => :notice, :message => "foo")
message = arraydest.last.message
expect(message).to eq("foo")
end
context "given a message with invalid encoding" do
let(:logs) { [] }
let(:invalid_message) { "\xFD\xFBfoo".force_encoding(Encoding::Shift_JIS) }
before do
Puppet::Util::Log.newdestination(Puppet::Test::LogCollector.new(logs))
Puppet::Util::Log.new(:level => :notice, :message => invalid_message)
end
it "does not raise an error" do
expect { Puppet::Util::Log.new(:level => :notice, :message => invalid_message) }.not_to raise_error
end
it "includes a backtrace in the log" do
expect(logs.last.message).to match(/Backtrace:\n.*newmessage'\n.*initialize'/)
end
it "warns that message included invalid encoding" do
expect(logs.last.message).to match(/Received a Log attribute with invalid encoding/)
end
it "includes the 'dump' of the invalid message" do
expect(logs.last.message).to match(/\"\\xFD\\xFBfoo\"/)
end
end
# need a string that cannot be converted to US-ASCII or other encodings easily
# different UTF-8 widths
# 1-byte A
# 2-byte ۿ - http://www.fileformat.info/info/unicode/char/06ff/index.htm - 0xDB 0xBF / 219 191
# 3-byte ᚠ - http://www.fileformat.info/info/unicode/char/16A0/index.htm - 0xE1 0x9A 0xA0 / 225 154 160
# 4-byte - http://www.fileformat.info/info/unicode/char/2070E/index.htm - 0xF0 0xA0 0x9C 0x8E / 240 160 156 142
let (:mixed_utf8) { "A\u06FF\u16A0\u{2070E}" } # Aۿᚠ
it "converts a given non-UTF-8 message to UTF-8" do
logs = []
Puppet::Util::Log.newdestination(Puppet::Test::LogCollector.new(logs))
Puppet::Util::Log.newdestination(:console)
# HIRAGANA LETTER SO
# In Windows_31J: \x82 \xbb - 130 187
# In Unicode: \u305d - \xe3 \x81 \x9d - 227 129 157
win_31j_msg = [130, 187].pack('C*').force_encoding(Encoding::Windows_31J)
utf_8_msg = "\u305d"
expect($stdout).to receive(:puts).with("\e[mNotice: #{mixed_utf8}: #{utf_8_msg}\e[0m")
# most handlers do special things with a :source => 'Puppet', so use something else
Puppet::Util::Log.new(:level => :notice, :message => win_31j_msg, :source => mixed_utf8)
expect(logs.last.message).to eq(utf_8_msg)
end
it "converts a given non-UTF-8 source to UTF-8" do
logs = []
Puppet::Util::Log.newdestination(Puppet::Test::LogCollector.new(logs))
Puppet::Util::Log.newdestination(:console)
# HIRAGANA LETTER SO
# In Windows_31J: \x82 \xbb - 130 187
# In Unicode: \u305d - \xe3 \x81 \x9d - 227 129 157
win_31j_msg = [130, 187].pack('C*').force_encoding(Encoding::Windows_31J)
utf_8_msg = "\u305d"
expect($stdout).to receive(:puts).with("\e[mNotice: #{utf_8_msg}: #{mixed_utf8}\e[0m")
Puppet::Util::Log.new(:level => :notice, :message => mixed_utf8, :source => win_31j_msg)
expect(logs.last.source).to eq(utf_8_msg)
end
require 'puppet/util/log/destinations'
it "raises an error when it has no successful logging destinations" do
# spec_helper.rb redirects log output away from the console,
# so we have to stop that here, or else the logic we are testing
# will not be reached.
allow(Puppet::Util::Log).to receive(:destinations).and_return({})
our_exception = Puppet::DevError.new("test exception")
expect(Puppet::FileSystem).to receive(:dir).and_raise(our_exception)
bad_file = tmpfile("bad_file")
expect { Puppet::Util::Log.newdestination(bad_file) }.to raise_error(Puppet::DevError)
end
describe ".setup_default" do
it "should default to :syslog" do
allow(Puppet.features).to receive(:syslog?).and_return(true)
expect(Puppet::Util::Log).to receive(:newdestination).with(:syslog)
Puppet::Util::Log.setup_default
end
it "should fall back to :eventlog" do
without_partial_double_verification do
allow(Puppet.features).to receive(:syslog?).and_return(false)
allow(Puppet.features).to receive(:eventlog?).and_return(true)
end
expect(Puppet::Util::Log).to receive(:newdestination).with(:eventlog)
Puppet::Util::Log.setup_default
end
it "should fall back to :file" do
without_partial_double_verification do
allow(Puppet.features).to receive(:syslog?).and_return(false)
allow(Puppet.features).to receive(:eventlog?).and_return(false)
end
expect(Puppet::Util::Log).to receive(:newdestination).with(Puppet[:puppetdlog])
Puppet::Util::Log.setup_default
end
end
describe "#with_destination" do
it "does nothing when nested" do
logs = []
destination = Puppet::Test::LogCollector.new(logs)
Puppet::Util::Log.with_destination(destination) do
Puppet::Util::Log.with_destination(destination) do
log_notice("Inner block")
end
log_notice("Outer block")
end
log_notice("Outside")
expect(logs.collect(&:message)).to include("Inner block", "Outer block")
expect(logs.collect(&:message)).not_to include("Outside")
end
it "logs when called a second time" do
logs = []
destination = Puppet::Test::LogCollector.new(logs)
Puppet::Util::Log.with_destination(destination) do
log_notice("First block")
end
log_notice("Between blocks")
Puppet::Util::Log.with_destination(destination) do
log_notice("Second block")
end
expect(logs.collect(&:message)).to include("First block", "Second block")
expect(logs.collect(&:message)).not_to include("Between blocks")
end
it "doesn't close the destination if already set manually" do
logs = []
destination = Puppet::Test::LogCollector.new(logs)
Puppet::Util::Log.newdestination(destination)
Puppet::Util::Log.with_destination(destination) do
log_notice "Inner block"
end
log_notice "Outer block"
Puppet::Util::Log.close(destination)
expect(logs.collect(&:message)).to include("Inner block", "Outer block")
end
end
describe Puppet::Util::Log::DestConsole do
before do
@console = Puppet::Util::Log::DestConsole.new
end
it "should colorize if Puppet[:color] is :ansi" do
Puppet[:color] = :ansi
expect(@console.colorize(:alert, "abc")).to eq("\e[0;31mabc\e[0m")
end
it "should colorize if Puppet[:color] is 'yes'" do
Puppet[:color] = "yes"
expect(@console.colorize(:alert, "abc")).to eq("\e[0;31mabc\e[0m")
end
it "should htmlize if Puppet[:color] is :html" do
Puppet[:color] = :html
expect(@console.colorize(:alert, "abc")).to eq("<span style=\"color: #FFA0A0\">abc</span>")
end
it "should do nothing if Puppet[:color] is false" do
Puppet[:color] = false
expect(@console.colorize(:alert, "abc")).to eq("abc")
end
it "should do nothing if Puppet[:color] is invalid" do
Puppet[:color] = "invalid option"
expect(@console.colorize(:alert, "abc")).to eq("abc")
end
end
describe Puppet::Util::Log::DestSyslog do
before do
@syslog = Puppet::Util::Log::DestSyslog.new
end
end
describe Puppet::Util::Log::DestEventlog, :if => Puppet.features.eventlog? do
before :each do
allow(Puppet::Util::Windows::EventLog).to receive(:open).and_return(double('mylog', :close => nil))
end
it "should restrict its suitability to Windows" do
allow(Puppet::Util::Platform).to receive(:windows?).and_return(false)
expect(Puppet::Util::Log::DestEventlog.suitable?('whatever')).to eq(false)
end
it "should open the 'Puppet' event log" do
expect(Puppet::Util::Windows::EventLog).to receive(:open).with('Puppet')
Puppet::Util::Log.newdestination(:eventlog)
end
it "should close the event log" do
log = double('myeventlog')
expect(log).to receive(:close)
expect(Puppet::Util::Windows::EventLog).to receive(:open).and_return(log)
Puppet::Util::Log.newdestination(:eventlog)
Puppet::Util::Log.close(:eventlog)
end
it "should handle each puppet log level" do
log = Puppet::Util::Log::DestEventlog.new
Puppet::Util::Log.eachlevel do |level|
expect(log.to_native(level)).to be_is_a(Array)
end
end
end
describe "instances" do
before do
allow(Puppet::Util::Log).to receive(:newmessage)
end
[:level, :message, :time, :remote].each do |attr|
it "should have a #{attr} attribute" do
log = Puppet::Util::Log.new :level => :notice, :message => "A test message"
expect(log).to respond_to(attr)
expect(log).to respond_to(attr.to_s + "=")
end
end
it "should fail if created without a level" do
expect { Puppet::Util::Log.new(:message => "A test message") }.to raise_error(ArgumentError)
end
it "should fail if created without a message" do
expect { Puppet::Util::Log.new(:level => :notice) }.to raise_error(ArgumentError)
end
it "should make available the level passed in at initialization" do
expect(Puppet::Util::Log.new(:level => :notice, :message => "A test message").level).to eq(:notice)
end
it "should make available the message passed in at initialization" do
expect(Puppet::Util::Log.new(:level => :notice, :message => "A test message").message).to eq("A test message")
end
# LAK:NOTE I don't know why this behavior is here, I'm just testing what's in the code,
# at least at first.
it "should always convert messages to strings" do
expect(Puppet::Util::Log.new(:level => :notice, :message => :foo).message).to eq("foo")
end
it "should flush the log queue when the first destination is specified" do
Puppet::Util::Log.close_all
expect(Puppet::Util::Log).to receive(:flushqueue)
Puppet::Util::Log.newdestination(:console)
end
it "should convert the level to a symbol if it's passed in as a string" do
expect(Puppet::Util::Log.new(:level => "notice", :message => :foo).level).to eq(:notice)
end
it "should fail if the level is not a symbol or string" do
expect { Puppet::Util::Log.new(:level => 50, :message => :foo) }.to raise_error(ArgumentError)
end
it "should fail if the provided level is not valid" do
expect(Puppet::Util::Log).to receive(:validlevel?).with(:notice).and_return(false)
expect { Puppet::Util::Log.new(:level => :notice, :message => :foo) }.to raise_error(ArgumentError)
end
it "should set its time to the initialization time" do
time = double('time')
expect(Time).to receive(:now).and_return(time)
expect(Puppet::Util::Log.new(:level => "notice", :message => :foo).time).to equal(time)
end
it "should make available any passed-in tags" do
log = Puppet::Util::Log.new(:level => "notice", :message => :foo, :tags => %w{foo bar})
expect(log.tags).to be_include("foo")
expect(log.tags).to be_include("bar")
end
it "should use a passed-in source" do
expect_any_instance_of(Puppet::Util::Log).to receive(:source=).with("foo")
Puppet::Util::Log.new(:level => "notice", :message => :foo, :source => "foo")
end
[:file, :line].each do |attr|
it "should use #{attr} if provided" do
expect_any_instance_of(Puppet::Util::Log).to receive(attr.to_s + "=").with("foo")
Puppet::Util::Log.new(:level => "notice", :message => :foo, attr => "foo")
end
end
it "should default to 'Puppet' as its source" do
expect(Puppet::Util::Log.new(:level => "notice", :message => :foo).source).to eq("Puppet")
end
it "should register itself with Log" do
expect(Puppet::Util::Log).to receive(:newmessage)
Puppet::Util::Log.new(:level => "notice", :message => :foo)
end
it "should update Log autoflush when Puppet[:autoflush] is set" do
expect(Puppet::Util::Log).to receive(:autoflush=).once.with(true)
Puppet[:autoflush] = true
end
it "should have a method for determining if a tag is present" do
expect(Puppet::Util::Log.new(:level => "notice", :message => :foo)).to respond_to(:tagged?)
end
it "should match a tag if any of the tags are equivalent to the passed tag as a string" do
expect(Puppet::Util::Log.new(:level => "notice", :message => :foo, :tags => %w{one two})).to be_tagged(:one)
end
it "should tag itself with its log level" do
expect(Puppet::Util::Log.new(:level => "notice", :message => :foo)).to be_tagged(:notice)
end
it "should return its message when converted to a string" do
expect(Puppet::Util::Log.new(:level => "notice", :message => :foo).to_s).to eq("foo")
end
it "should include its time, source, level, and message when prepared for reporting" do
log = Puppet::Util::Log.new(:level => "notice", :message => :foo)
report = log.to_report
expect(report).to be_include("notice")
expect(report).to be_include("foo")
expect(report).to be_include(log.source)
expect(report).to be_include(log.time.to_s)
end
it "should not create unsuitable log destinations" do
allow(Puppet.features).to receive(:syslog?).and_return(false)
expect(Puppet::Util::Log::DestSyslog).to receive(:suitable?)
expect(Puppet::Util::Log::DestSyslog).not_to receive(:new)
Puppet::Util::Log.newdestination(:syslog)
end
describe "when setting the source as a RAL object" do
let(:path) { File.expand_path('/foo/bar') }
it "should tag itself with any tags the source has" do
source = Puppet::Type.type(:file).new :path => path
log = Puppet::Util::Log.new(:level => "notice", :message => :foo, :source => source)
source.tags.each do |tag|
expect(log.tags).to be_include(tag)
end
end
it "should set the source to a type's 'path', when available" do
source = Puppet::Type.type(:file).new :path => path
source.tags = ["tag", "tag2"]
log = Puppet::Util::Log.new(:level => "notice", :message => :foo)
log.source = source
expect(log).to be_tagged('file')
expect(log).to be_tagged('tag')
expect(log).to be_tagged('tag2')
expect(log.source).to eq("/File[#{path}]")
end
it "should set the source to a provider's type's 'path', when available" do
source = Puppet::Type.type(:file).new :path => path
source.tags = ["tag", "tag2"]
log = Puppet::Util::Log.new(:level => "notice", :message => :foo)
log.source = source.provider
expect(log.source).to match Regexp.quote("File\[#{path}\]\(provider=")
end
it "should copy over any file and line information" do
source = Puppet::Type.type(:file).new :path => path
source.file = "/my/file"
source.line = 50
log = Puppet::Util::Log.new(:level => "notice", :message => :foo, :source => source)
expect(log.line).to eq(50)
expect(log.file).to eq("/my/file")
end
end
describe "when setting the source as a non-RAL object" do
it "should not try to copy over file, version, line, or tag information" do
source = double('source')
expect(source).not_to receive(:file)
Puppet::Util::Log.new(:level => "notice", :message => :foo, :source => source)
end
end
end
describe "to_yaml" do
it "should not include the @version attribute" do
log = Puppet::Util::Log.new(:level => "notice", :message => :foo, :version => 100)
expect(log.to_data_hash.keys).not_to include('version')
end
it "should include attributes 'file', 'line', 'level', 'message', 'source', 'tags', and 'time'" do
log = Puppet::Util::Log.new(:level => "notice", :message => :foo, :version => 100)
expect(log.to_data_hash.keys).to match_array(%w(file line level message source tags time))
end
it "should include attributes 'file' and 'line' if specified" do
log = Puppet::Util::Log.new(:level => "notice", :message => :foo, :file => "foo", :line => 35)
expect(log.to_data_hash.keys).to include('file')
expect(log.to_data_hash.keys).to include('line')
end
end
let(:log) { Puppet::Util::Log.new(:level => 'notice', :message => 'hooray', :file => 'thefile', :line => 1729, :source => 'specs', :tags => ['a', 'b', 'c']) }
it "should round trip through json" do
tripped = Puppet::Util::Log.from_data_hash(JSON.parse(log.to_json))
expect(tripped.file).to eq(log.file)
expect(tripped.line).to eq(log.line)
expect(tripped.level).to eq(log.level)
expect(tripped.message).to eq(log.message)
expect(tripped.source).to eq(log.source)
expect(tripped.tags).to eq(log.tags)
expect(tripped.time).to eq(log.time)
end
it 'to_data_hash returns value that is instance of to Data' do
expect(Puppet::Pops::Types::TypeFactory.data.instance?(log.to_data_hash)).to be_truthy
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/util/storage_spec.rb | spec/unit/util/storage_spec.rb | require 'spec_helper'
require 'yaml'
require 'fileutils'
require 'puppet/util/storage'
describe Puppet::Util::Storage do
include PuppetSpec::Files
before(:each) do
@basepath = File.expand_path("/somepath")
end
describe "when caching a symbol" do
it "should return an empty hash" do
expect(Puppet::Util::Storage.cache(:yayness)).to eq({})
expect(Puppet::Util::Storage.cache(:more_yayness)).to eq({})
end
it "should add the symbol to its internal state" do
Puppet::Util::Storage.cache(:yayness)
expect(Puppet::Util::Storage.state).to eq({:yayness=>{}})
end
it "should not clobber existing state when caching additional objects" do
Puppet::Util::Storage.cache(:yayness)
expect(Puppet::Util::Storage.state).to eq({:yayness=>{}})
Puppet::Util::Storage.cache(:bubblyness)
expect(Puppet::Util::Storage.state).to eq({:yayness=>{},:bubblyness=>{}})
end
end
describe "when caching a Puppet::Type" do
before(:each) do
@file_test = Puppet::Type.type(:file).new(:name => @basepath+"/yayness", :audit => %w{checksum type})
@exec_test = Puppet::Type.type(:exec).new(:name => @basepath+"/bin/ls /yayness")
end
it "should return an empty hash" do
expect(Puppet::Util::Storage.cache(@file_test)).to eq({})
expect(Puppet::Util::Storage.cache(@exec_test)).to eq({})
end
it "should add the resource ref to its internal state" do
expect(Puppet::Util::Storage.state).to eq({})
Puppet::Util::Storage.cache(@file_test)
expect(Puppet::Util::Storage.state).to eq({"File[#{@basepath}/yayness]"=>{}})
Puppet::Util::Storage.cache(@exec_test)
expect(Puppet::Util::Storage.state).to eq({"File[#{@basepath}/yayness]"=>{}, "Exec[#{@basepath}/bin/ls /yayness]"=>{}})
end
end
describe "when caching something other than a resource or symbol" do
it "should cache by converting to a string" do
data = Puppet::Util::Storage.cache(42)
data[:yay] = true
expect(Puppet::Util::Storage.cache("42")[:yay]).to be_truthy
end
end
it "should clear its internal state when clear() is called" do
Puppet::Util::Storage.cache(:yayness)
expect(Puppet::Util::Storage.state).to eq({:yayness=>{}})
Puppet::Util::Storage.clear
expect(Puppet::Util::Storage.state).to eq({})
end
describe "when loading from the state file" do
before do
allow(Puppet.settings).to receive(:use).and_return(true)
end
describe "when the state file/directory does not exist" do
before(:each) do
@path = tmpfile('storage_test')
end
it "should not fail to load" do
expect(Puppet::FileSystem.exist?(@path)).to be_falsey
Puppet[:statedir] = @path
Puppet::Util::Storage.load
Puppet[:statefile] = @path
Puppet::Util::Storage.load
end
it "should not lose its internal state when load() is called" do
expect(Puppet::FileSystem.exist?(@path)).to be_falsey
Puppet::Util::Storage.cache(:yayness)
expect(Puppet::Util::Storage.state).to eq({:yayness=>{}})
Puppet[:statefile] = @path
Puppet::Util::Storage.load
expect(Puppet::Util::Storage.state).to eq({:yayness=>{}})
end
end
describe "when the state file/directory exists" do
before(:each) do
@state_file = tmpfile('storage_test')
FileUtils.touch(@state_file)
Puppet[:statefile] = @state_file
end
def write_state_file(contents)
File.open(@state_file, 'w') { |f| f.write(contents) }
end
it "should overwrite its internal state if load() is called" do
# Should the state be overwritten even if Puppet[:statefile] is not valid YAML?
Puppet::Util::Storage.cache(:yayness)
expect(Puppet::Util::Storage.state).to eq({:yayness=>{}})
Puppet::Util::Storage.load
expect(Puppet::Util::Storage.state).to eq({})
end
it "should restore its internal state if the state file contains valid YAML" do
test_yaml = {'File["/yayness"]'=>{"name"=>{:a=>:b,:c=>:d}}}
write_state_file(test_yaml.to_yaml)
Puppet::Util::Storage.load
expect(Puppet::Util::Storage.state).to eq(test_yaml)
end
it "should initialize with a clear internal state if the state file does not contain valid YAML" do
write_state_file('{ invalid')
Puppet::Util::Storage.load
expect(Puppet::Util::Storage.state).to eq({})
end
it "should initialize with a clear internal state if the state file does not contain a hash of data" do
write_state_file("not_a_hash")
Puppet::Util::Storage.load
expect(Puppet::Util::Storage.state).to eq({})
end
it "should raise an error if the state file does not contain valid YAML and cannot be renamed" do
allow(File).to receive(:rename).and_call_original
write_state_file('{ invalid')
expect(File).to receive(:rename).with(@state_file, "#{@state_file}.bad").and_raise(SystemCallError)
expect { Puppet::Util::Storage.load }.to raise_error(Puppet::Error, /Could not rename/)
end
it "should attempt to rename the state file if the file is corrupted" do
write_state_file('{ invalid')
expect(File).to receive(:rename).at_least(:once)
Puppet::Util::Storage.load
end
it "should fail gracefully on load() if the state file is not a regular file" do
FileUtils.rm_f(@state_file)
Dir.mkdir(@state_file)
Puppet::Util::Storage.load
end
it 'should load Time and Symbols' do
state = {
'File[/etc/puppetlabs/puppet]' =>
{ :checked => Time.new(2018, 8, 8, 15, 28, 25, "-07:00") }
}
write_state_file(YAML.dump(state))
Puppet::Util::Storage.load
expect(Puppet::Util::Storage.state).to eq(state.dup)
end
end
end
describe "when storing to the state file" do
A_SMALL_AMOUNT_OF_TIME = 0.001 #Seconds
before(:each) do
@state_file = tmpfile('storage_test')
@saved_statefile = Puppet[:statefile]
Puppet[:statefile] = @state_file
end
it "should create the state file if it does not exist" do
expect(Puppet::FileSystem.exist?(Puppet[:statefile])).to be_falsey
Puppet::Util::Storage.cache(:yayness)
Puppet::Util::Storage.store
expect(Puppet::FileSystem.exist?(Puppet[:statefile])).to be_truthy
end
it "should raise an exception if the state file is not a regular file" do
Dir.mkdir(Puppet[:statefile])
Puppet::Util::Storage.cache(:yayness)
expect { Puppet::Util::Storage.store }.to raise_error(Errno::EISDIR, /Is a directory/)
Dir.rmdir(Puppet[:statefile])
end
it "should load() the same information that it store()s" do
Puppet::Util::Storage.cache(:yayness)
expect(Puppet::Util::Storage.state).to eq({:yayness=>{}})
Puppet::Util::Storage.store
Puppet::Util::Storage.clear
expect(Puppet::Util::Storage.state).to eq({})
Puppet::Util::Storage.load
expect(Puppet::Util::Storage.state).to eq({:yayness=>{}})
end
it "expires entries with a :checked older than statettl seconds ago" do
Puppet[:statettl] = '1d'
recent_checked = Time.now.round
stale_checked = recent_checked - (Puppet[:statettl] + 10)
Puppet::Util::Storage.cache(:yayness)[:checked] = recent_checked
Puppet::Util::Storage.cache(:stale)[:checked] = stale_checked
expect(Puppet::Util::Storage.state).to match(
{
:yayness => {
:checked => a_value_within(A_SMALL_AMOUNT_OF_TIME).of(recent_checked)
},
:stale => {
:checked => a_value_within(A_SMALL_AMOUNT_OF_TIME).of(stale_checked)
}
}
)
Puppet::Util::Storage.store
Puppet::Util::Storage.clear
expect(Puppet::Util::Storage.state).to eq({})
Puppet::Util::Storage.load
expect(Puppet::Util::Storage.state).to match(
{
:yayness => {
:checked => a_value_within(A_SMALL_AMOUNT_OF_TIME).of(recent_checked)
}
}
)
end
it "does not expire entries when statettl is 0" do
Puppet[:statettl] = '0'
recent_checked = Time.now.round
older_checked = recent_checked - 10_000_000
Puppet::Util::Storage.cache(:yayness)[:checked] = recent_checked
Puppet::Util::Storage.cache(:older)[:checked] = older_checked
expect(Puppet::Util::Storage.state).to match(
{
:yayness => {
:checked => a_value_within(A_SMALL_AMOUNT_OF_TIME).of(recent_checked)
},
:older => {
:checked => a_value_within(A_SMALL_AMOUNT_OF_TIME).of(older_checked)
}
}
)
Puppet::Util::Storage.store
Puppet::Util::Storage.clear
expect(Puppet::Util::Storage.state).to eq({})
Puppet::Util::Storage.load
expect(Puppet::Util::Storage.state).to match(
{
:yayness => {
:checked => a_value_within(A_SMALL_AMOUNT_OF_TIME).of(recent_checked)
},
:older => {
:checked => a_value_within(A_SMALL_AMOUNT_OF_TIME).of(older_checked)
}
}
)
end
it "does not expire entries when statettl is 'unlimited'" do
Puppet[:statettl] = 'unlimited'
recent_checked = Time.now
older_checked = Time.now - 10_000_000
Puppet::Util::Storage.cache(:yayness)[:checked] = recent_checked
Puppet::Util::Storage.cache(:older)[:checked] = older_checked
expect(Puppet::Util::Storage.state).to match(
{
:yayness => {
:checked => a_value_within(A_SMALL_AMOUNT_OF_TIME).of(recent_checked)
},
:older => {
:checked => a_value_within(A_SMALL_AMOUNT_OF_TIME).of(older_checked)
}
}
)
Puppet::Util::Storage.store
Puppet::Util::Storage.clear
expect(Puppet::Util::Storage.state).to eq({})
Puppet::Util::Storage.load
expect(Puppet::Util::Storage.state).to match(
{
:yayness => {
:checked => a_value_within(A_SMALL_AMOUNT_OF_TIME).of(recent_checked)
},
:older => {
:checked => a_value_within(A_SMALL_AMOUNT_OF_TIME).of(older_checked)
}
}
)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/util/command_line_spec.rb | spec/unit/util/command_line_spec.rb | require 'spec_helper'
require 'puppet/face'
require 'puppet/util/command_line'
describe Puppet::Util::CommandLine do
include PuppetSpec::Files
context "#initialize" do
it "should pull off the first argument if it looks like a subcommand" do
command_line = Puppet::Util::CommandLine.new("puppet", %w{ client --help whatever.pp })
expect(command_line.subcommand_name).to eq("client")
expect(command_line.args).to eq(%w{ --help whatever.pp })
end
it "should return nil if the first argument looks like a .pp file" do
command_line = Puppet::Util::CommandLine.new("puppet", %w{ whatever.pp })
expect(command_line.subcommand_name).to eq(nil)
expect(command_line.args).to eq(%w{ whatever.pp })
end
it "should return nil if the first argument looks like a flag" do
command_line = Puppet::Util::CommandLine.new("puppet", %w{ --debug })
expect(command_line.subcommand_name).to eq(nil)
expect(command_line.args).to eq(%w{ --debug })
end
it "should return nil if the first argument is -" do
command_line = Puppet::Util::CommandLine.new("puppet", %w{ - })
expect(command_line.subcommand_name).to eq(nil)
expect(command_line.args).to eq(%w{ - })
end
it "should return nil if the first argument is --help" do
command_line = Puppet::Util::CommandLine.new("puppet", %w{ --help })
expect(command_line.subcommand_name).to eq(nil)
end
it "should return nil if there are no arguments" do
command_line = Puppet::Util::CommandLine.new("puppet", [])
expect(command_line.subcommand_name).to eq(nil)
expect(command_line.args).to eq([])
end
it "should pick up changes to the array of arguments" do
args = %w{subcommand}
command_line = Puppet::Util::CommandLine.new("puppet", args)
args[0] = 'different_subcommand'
expect(command_line.subcommand_name).to eq('different_subcommand')
end
end
context "#execute" do
%w{--version -V}.each do |arg|
it "should print the version and exit if #{arg} is given" do
expect do
described_class.new("puppet", [arg]).execute
end.to output(/^#{Regexp.escape(Puppet.version)}$/).to_stdout
end
end
%w{--help -h help}.each do|arg|
it "should print help and exit if #{arg} is given" do
commandline = Puppet::Util::CommandLine.new("puppet", [arg])
expect(commandline).not_to receive(:exec)
expect {
commandline.execute
}.to exit_with(0)
.and output(/Usage: puppet <subcommand> \[options\] <action> \[options\]/).to_stdout
end
end
it "should fail if the config file isn't readable and we're running a subcommand that requires a readable config file" do
allow(Puppet::FileSystem).to receive(:exist?).with(Puppet[:config]).and_return(true)
allow_any_instance_of(Puppet::Settings).to receive(:read_file).and_return('')
expect_any_instance_of(Puppet::Settings).to receive(:read_file).with(Puppet[:config]).and_raise('Permission denied')
expect{ described_class.new("puppet", ['config']).execute }.to raise_error(SystemExit)
end
it "should not fail if the config file isn't readable and we're running a subcommand that does not require a readable config file" do
allow(Puppet::FileSystem).to receive(:exist?)
allow(Puppet::FileSystem).to receive(:exist?).with(Puppet[:config]).and_return(true)
allow_any_instance_of(Puppet::Settings).to receive(:read_file).and_return('')
expect_any_instance_of(Puppet::Settings).to receive(:read_file).with(anything).and_return('')
commandline = described_class.new("puppet", ['help'])
expect {
commandline.execute
}.to exit_with(0)
.and output(/Usage: puppet <subcommand> \[options\] <action> \[options\]/).to_stdout
end
end
describe "when dealing with puppet commands" do
it "should return the executable name if it is not puppet" do
command_line = Puppet::Util::CommandLine.new("puppetmasterd", [])
expect(command_line.subcommand_name).to eq("puppetmasterd")
end
describe "when the subcommand is not implemented" do
it "should find and invoke an executable with a hyphenated name" do
commandline = Puppet::Util::CommandLine.new("puppet", ['whatever', 'argument'])
expect(Puppet::Util).to receive(:which).with('puppet-whatever').
and_return('/dev/null/puppet-whatever')
expect(Kernel).to receive(:exec).with('/dev/null/puppet-whatever', 'argument')
commandline.execute
end
describe "and an external implementation cannot be found" do
it "should abort and show the usage message" do
expect(Puppet::Util).to receive(:which).with('puppet-whatever').and_return(nil)
commandline = Puppet::Util::CommandLine.new("puppet", ['whatever', 'argument'])
expect(commandline).not_to receive(:exec)
expect {
commandline.execute
}.to exit_with(1)
.and output(/Unknown subcommand 'whatever'/).to_stdout
end
it "should abort and show the help message" do
expect(Puppet::Util).to receive(:which).with('puppet-whatever').and_return(nil)
commandline = Puppet::Util::CommandLine.new("puppet", ['whatever', 'argument'])
expect(commandline).not_to receive(:exec)
expect {
commandline.execute
}.to exit_with(1)
.and output(/See 'puppet help' for help on available subcommands/).to_stdout
end
%w{--version -V}.each do |arg|
it "should abort and display #{arg} information" do
expect(Puppet::Util).to receive(:which).with('puppet-whatever').and_return(nil)
commandline = Puppet::Util::CommandLine.new("puppet", ['whatever', arg])
expect(commandline).not_to receive(:exec)
expect {
commandline.execute
}.to exit_with(1)
.and output(%r[^#{Regexp.escape(Puppet.version)}$]).to_stdout
end
end
end
end
describe 'when setting process priority' do
let(:command_line) do
Puppet::Util::CommandLine.new("puppet", %w{ agent })
end
before :each do
allow_any_instance_of(Puppet::Util::CommandLine::ApplicationSubcommand).to receive(:run)
end
it 'should never set priority by default' do
expect(Process).not_to receive(:setpriority)
command_line.execute
end
it 'should lower the process priority if one has been specified' do
Puppet[:priority] = 10
expect(Process).to receive(:setpriority).with(0, Process.pid, 10)
command_line.execute
end
it 'should warn if trying to raise priority, but not privileged user' do
Puppet[:priority] = -10
expect(Process).to receive(:setpriority).and_raise(Errno::EACCES, 'Permission denied')
expect(Puppet).to receive(:warning).with("Failed to set process priority to '-10'")
command_line.execute
end
it "should warn if the platform doesn't support `Process.setpriority`" do
Puppet[:priority] = 15
expect(Process).to receive(:setpriority).and_raise(NotImplementedError, 'NotImplementedError: setpriority() function is unimplemented on this machine')
expect(Puppet).to receive(:warning).with("Failed to set process priority to '15'")
command_line.execute
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/util/rubygems_spec.rb | spec/unit/util/rubygems_spec.rb | require 'spec_helper'
require 'puppet/util/rubygems'
describe Puppet::Util::RubyGems::Source do
let(:gem_path) { File.expand_path('/foo/gems') }
let(:gem_lib) { File.join(gem_path, 'lib') }
let(:fake_gem) { double(:full_gem_path => gem_path) }
describe "::new" do
it "returns NoGemsSource if rubygems is not present" do
expect(described_class).to receive(:has_rubygems?).and_return(false)
expect(described_class.new).to be_kind_of(Puppet::Util::RubyGems::NoGemsSource)
end
it "returns Gems18Source if Gem::Specification responds to latest_specs" do
expect(described_class).to receive(:has_rubygems?).and_return(true)
expect(described_class.new).to be_kind_of(Puppet::Util::RubyGems::Gems18Source)
end
end
describe '::NoGemsSource' do
before(:each) { allow(described_class).to receive(:source).and_return(Puppet::Util::RubyGems::NoGemsSource) }
it "#directories returns an empty list" do
expect(described_class.new.directories).to eq([])
end
it "#clear_paths returns nil" do
expect(described_class.new.clear_paths).to be_nil
end
end
describe '::Gems18Source' do
before(:each) { allow(described_class).to receive(:source).and_return(Puppet::Util::RubyGems::Gems18Source) }
it "#directories returns the lib subdirs of Gem::Specification.stubs" do
expect(Gem::Specification).to receive(:stubs).and_return([fake_gem])
expect(described_class.new.directories).to eq([gem_lib])
end
it "#clear_paths calls Gem.clear_paths" do
expect(Gem).to receive(:clear_paths)
described_class.new.clear_paths
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/util/profiler/wall_clock_spec.rb | spec/unit/util/profiler/wall_clock_spec.rb | require 'spec_helper'
require 'puppet/util/profiler'
describe Puppet::Util::Profiler::WallClock do
it "logs the number of seconds it took to execute the segment" do
profiler = Puppet::Util::Profiler::WallClock.new(nil, nil)
message = profiler.do_finish(profiler.start(["foo", "bar"], "Testing"), ["foo", "bar"], "Testing")[:msg]
expect(message).to match(/took \d\.\d{4} seconds/)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/util/profiler/logging_spec.rb | spec/unit/util/profiler/logging_spec.rb | require 'spec_helper'
require 'puppet/util/profiler'
describe Puppet::Util::Profiler::Logging do
let(:logger) { SimpleLog.new }
let(:identifier) { "Profiling ID" }
let(:logging_profiler) { TestLoggingProfiler.new(logger, identifier) }
let(:profiler) do
p = Puppet::Util::Profiler::AroundProfiler.new
p.add_profiler(logging_profiler)
p
end
it "logs the explanation of the profile results" do
profiler.profile("Testing", ["test"]) { }
expect(logger.messages.first).to match(/the explanation/)
end
it "describes the profiled segment" do
profiler.profile("Tested measurement", ["test"]) { }
expect(logger.messages.first).to match(/PROFILE \[#{identifier}\] \d Tested measurement/)
end
it "indicates the order in which segments are profiled" do
profiler.profile("Measurement", ["measurement"]) { }
profiler.profile("Another measurement", ["measurement"]) { }
expect(logger.messages[0]).to match(/1 Measurement/)
expect(logger.messages[1]).to match(/2 Another measurement/)
end
it "indicates the nesting of profiled segments" do
profiler.profile("Measurement", ["measurement1"]) do
profiler.profile("Nested measurement", ["measurement2"]) { }
end
profiler.profile("Another measurement", ["measurement1"]) do
profiler.profile("Another nested measurement", ["measurement2"]) { }
end
expect(logger.messages[0]).to match(/1.1 Nested measurement/)
expect(logger.messages[1]).to match(/1 Measurement/)
expect(logger.messages[2]).to match(/2.1 Another nested measurement/)
expect(logger.messages[3]).to match(/2 Another measurement/)
end
class TestLoggingProfiler < Puppet::Util::Profiler::Logging
def do_start(metric, description)
"the start"
end
def do_finish(context, metric, description)
{:msg => "the explanation of #{context}"}
end
end
class SimpleLog
attr_reader :messages
def initialize
@messages = []
end
def call(msg)
@messages << msg
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/util/profiler/aggregate_spec.rb | spec/unit/util/profiler/aggregate_spec.rb | require 'spec_helper'
require 'puppet/util/profiler'
require 'puppet/util/profiler/around_profiler'
require 'puppet/util/profiler/aggregate'
describe Puppet::Util::Profiler::Aggregate do
let(:logger) { AggregateSimpleLog.new }
let(:profiler) { Puppet::Util::Profiler::Aggregate.new(logger, nil) }
let(:profiler_mgr) do
p = Puppet::Util::Profiler::AroundProfiler.new
p.add_profiler(profiler)
p
end
it "tracks the aggregate counts and time for the hierarchy of metrics" do
profiler_mgr.profile("Looking up hiera data in production environment", ["function", "hiera_lookup", "production"]) { sleep 0.01 }
profiler_mgr.profile("Looking up hiera data in test environment", ["function", "hiera_lookup", "test"]) {}
profiler_mgr.profile("looking up stuff for compilation", ["compiler", "lookup"]) { sleep 0.01 }
profiler_mgr.profile("COMPILING ALL OF THE THINGS!", ["compiler", "compiling"]) {}
expect(profiler.values["function"].count).to eq(2)
expect(profiler.values["function"].time).to be > 0
expect(profiler.values["function"]["hiera_lookup"].count).to eq(2)
expect(profiler.values["function"]["hiera_lookup"]["production"].count).to eq(1)
expect(profiler.values["function"]["hiera_lookup"]["test"].count).to eq(1)
expect(profiler.values["function"].time).to be >= profiler.values["function"]["hiera_lookup"]["test"].time
expect(profiler.values["compiler"].count).to eq(2)
expect(profiler.values["compiler"].time).to be > 0
expect(profiler.values["compiler"]["lookup"].count).to eq(1)
expect(profiler.values["compiler"]["compiling"].count).to eq(1)
expect(profiler.values["compiler"].time).to be >= profiler.values["compiler"]["lookup"].time
profiler.shutdown
expect(logger.output).to match(/function -> hiera_lookup: .*\(2 calls\)\nfunction -> hiera_lookup ->.*\(1 calls\)/)
expect(logger.output).to match(/compiler: .*\(2 calls\)\ncompiler ->.*\(1 calls\)/)
end
it "supports both symbols and strings as components of a metric id" do
profiler_mgr.profile("yo", [:foo, "bar"]) {}
end
class AggregateSimpleLog
attr_reader :output
def initialize
@output = ""
end
def call(msg)
@output << msg << "\n"
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/util/profiler/object_counts_spec.rb | spec/unit/util/profiler/object_counts_spec.rb | require 'spec_helper'
require 'puppet/util/profiler'
describe Puppet::Util::Profiler::ObjectCounts, unless: Puppet::Util::Platform.jruby? do
# ObjectSpace is not enabled by default on JRuby
it "reports the changes in the system object counts" do
profiler = Puppet::Util::Profiler::ObjectCounts.new(nil, nil)
message = profiler.finish(profiler.start)
expect(message).to match(/ T_STRING: \d+, /)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/util/profiler/around_profiler_spec.rb | spec/unit/util/profiler/around_profiler_spec.rb | require 'spec_helper'
require 'puppet/util/profiler'
describe Puppet::Util::Profiler::AroundProfiler do
let(:child) { TestAroundProfiler.new() }
let(:profiler) { Puppet::Util::Profiler::AroundProfiler.new }
before :each do
profiler.add_profiler(child)
end
it "returns the value of the profiled segment" do
retval = profiler.profile("Testing", ["testing"]) { "the return value" }
expect(retval).to eq("the return value")
end
it "propagates any errors raised in the profiled segment" do
expect do
profiler.profile("Testing", ["testing"]) { raise "a problem" }
end.to raise_error("a problem")
end
it "makes the description and the context available to the `start` and `finish` methods" do
profiler.profile("Testing", ["testing"]) { }
expect(child.context).to eq("Testing")
expect(child.description).to eq("Testing")
end
it "calls finish even when an error is raised" do
begin
profiler.profile("Testing", ["testing"]) { raise "a problem" }
rescue
expect(child.context).to eq("Testing")
end
end
it "supports multiple profilers" do
profiler2 = TestAroundProfiler.new
profiler.add_profiler(profiler2)
profiler.profile("Testing", ["testing"]) {}
expect(child.context).to eq("Testing")
expect(profiler2.context).to eq("Testing")
end
class TestAroundProfiler
attr_accessor :context, :description
def start(description, metric_id)
description
end
def finish(context, description, metric_id)
@context = context
@description = description
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/util/watcher/periodic_watcher_spec.rb | spec/unit/util/watcher/periodic_watcher_spec.rb | require 'spec_helper'
require 'puppet/util/watcher'
describe Puppet::Util::Watcher::PeriodicWatcher do
let(:enabled_timeout) { 1 }
let(:disabled_timeout) { -1 }
let(:a_value) { 15 }
let(:a_different_value) { 16 }
let(:unused_watcher) { double('unused watcher') }
let(:unchanged_watcher) { a_watcher_reporting(a_value) }
let(:changed_watcher) { a_watcher_reporting(a_value, a_different_value) }
it 'reads only the initial change state when the timeout has not yet expired' do
watcher = Puppet::Util::Watcher::PeriodicWatcher.new(unchanged_watcher, an_unexpired_timer(enabled_timeout))
expect(watcher).to_not be_changed
end
it 'reads enough values to determine change when the timeout has expired' do
watcher = Puppet::Util::Watcher::PeriodicWatcher.new(changed_watcher, an_expired_timer(enabled_timeout))
expect(watcher).to be_changed
end
it 'is always marked as changed when the timeout is disabled' do
watcher = Puppet::Util::Watcher::PeriodicWatcher.new(unused_watcher, an_expired_timer(disabled_timeout))
expect(watcher).to be_changed
end
def a_watcher_reporting(*observed_values)
Puppet::Util::Watcher::ChangeWatcher.watch(proc do
observed_values.shift or raise "No more observed values to report!"
end)
end
def an_expired_timer(timeout)
a_time_that_reports_expired_as(true, timeout)
end
def an_unexpired_timer(timeout)
a_time_that_reports_expired_as(false, timeout)
end
def a_time_that_reports_expired_as(expired, timeout)
timer = Puppet::Util::Watcher::Timer.new(timeout)
allow(timer).to receive(:expired?).and_return(expired)
timer
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/util/ldap/connection_spec.rb | spec/unit/util/ldap/connection_spec.rb | require 'spec_helper'
require 'puppet/util/ldap/connection'
# So our mocks and such all work, even when ldap isn't available.
unless Puppet.features.ldap?
class LDAP
class Conn
def initialize(*args)
end
end
class SSLConn < Conn; end
LDAP_OPT_PROTOCOL_VERSION = 1
LDAP_OPT_REFERRALS = 2
LDAP_OPT_ON = 3
end
end
describe Puppet::Util::Ldap::Connection do
before do
allow(Puppet.features).to receive(:ldap?).and_return(true)
@ldapconn = double(
'ldap',
set_option: nil,
simple_bind: nil,
)
allow(LDAP::Conn).to receive(:new).and_return(@ldapconn)
allow(LDAP::SSLConn).to receive(:new).and_return(@ldapconn)
@connection = Puppet::Util::Ldap::Connection.new("host", 1234)
end
describe "when creating connections" do
it "should require the host and port" do
expect { Puppet::Util::Ldap::Connection.new("myhost") }.to raise_error(ArgumentError)
end
it "should allow specification of a user and password" do
expect { Puppet::Util::Ldap::Connection.new("myhost", 1234, :user => "blah", :password => "boo") }.not_to raise_error
end
it "should allow specification of ssl" do
expect { Puppet::Util::Ldap::Connection.new("myhost", 1234, :ssl => :tsl) }.not_to raise_error
end
it "should support requiring a new connection" do
expect { Puppet::Util::Ldap::Connection.new("myhost", 1234, :reset => true) }.not_to raise_error
end
it "should fail if ldap is unavailable" do
expect(Puppet.features).to receive(:ldap?).and_return(false)
expect { Puppet::Util::Ldap::Connection.new("host", 1234) }.to raise_error(Puppet::Error)
end
it "should use neither ssl nor tls by default" do
expect(LDAP::Conn).to receive(:new).with("host", 1234).and_return(@ldapconn)
@connection.start
end
it "should use LDAP::SSLConn if ssl is requested" do
expect(LDAP::SSLConn).to receive(:new).with("host", 1234).and_return(@ldapconn)
@connection.ssl = true
@connection.start
end
it "should use LDAP::SSLConn and tls if tls is requested" do
expect(LDAP::SSLConn).to receive(:new).with("host", 1234, true).and_return(@ldapconn)
@connection.ssl = :tls
@connection.start
end
it "should set the protocol version to 3 and enable referrals" do
expect(@ldapconn).to receive(:set_option).with(LDAP::LDAP_OPT_PROTOCOL_VERSION, 3)
expect(@ldapconn).to receive(:set_option).with(LDAP::LDAP_OPT_REFERRALS, LDAP::LDAP_OPT_ON)
@connection.start
end
it "should bind with the provided user and password" do
@connection.user = "myuser"
@connection.password = "mypassword"
expect(@ldapconn).to receive(:simple_bind).with("myuser", "mypassword")
@connection.start
end
it "should bind with no user and password if none has been provided" do
expect(@ldapconn).to receive(:simple_bind).with(nil, nil)
@connection.start
end
end
describe "when closing connections" do
it "should not close connections that are not open" do
allow(@connection).to receive(:connection).and_return(@ldapconn)
expect(@ldapconn).to receive(:bound?).and_return(false)
expect(@ldapconn).not_to receive(:unbind)
@connection.close
end
end
it "should have a class-level method for creating a default connection" do
expect(Puppet::Util::Ldap::Connection).to respond_to(:instance)
end
describe "when creating a default connection" do
it "should use the :ldapserver setting to determine the host" do
Puppet[:ldapserver] = "myserv"
expect(Puppet::Util::Ldap::Connection).to receive(:new).with("myserv", anything, anything)
Puppet::Util::Ldap::Connection.instance
end
it "should use the :ldapport setting to determine the port" do
Puppet[:ldapport] = 456
expect(Puppet::Util::Ldap::Connection).to receive(:new).with(anything, 456, anything)
Puppet::Util::Ldap::Connection.instance
end
it "should set ssl to :tls if tls is enabled" do
Puppet[:ldaptls] = true
expect(Puppet::Util::Ldap::Connection).to receive(:new).with(anything, anything, hash_including(ssl: :tls))
Puppet::Util::Ldap::Connection.instance
end
it "should set ssl to 'true' if ssl is enabled and tls is not" do
Puppet[:ldaptls] = false
Puppet[:ldapssl] = true
expect(Puppet::Util::Ldap::Connection).to receive(:new).with(anything, anything, hash_including(ssl: true))
Puppet::Util::Ldap::Connection.instance
end
it "should set ssl to false if neither ssl nor tls are enabled" do
Puppet[:ldaptls] = false
Puppet[:ldapssl] = false
expect(Puppet::Util::Ldap::Connection).to receive(:new).with(anything, anything, hash_including(ssl: false))
Puppet::Util::Ldap::Connection.instance
end
it "should set the ldapuser if one is set" do
Puppet[:ldapuser] = "foo"
expect(Puppet::Util::Ldap::Connection).to receive(:new).with(anything, anything, hash_including(user: "foo"))
Puppet::Util::Ldap::Connection.instance
end
it "should set the ldapuser and ldappassword if both is set" do
Puppet[:ldapuser] = "foo"
Puppet[:ldappassword] = "bar"
expect(Puppet::Util::Ldap::Connection).to receive(:new).with(anything, anything, hash_including(user: "foo", password: "bar"))
Puppet::Util::Ldap::Connection.instance
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/util/ldap/manager_spec.rb | spec/unit/util/ldap/manager_spec.rb | require 'spec_helper'
require 'puppet/util/ldap/manager'
describe Puppet::Util::Ldap::Manager, :if => Puppet.features.ldap? do
before do
@manager = Puppet::Util::Ldap::Manager.new
end
it "should return self when specifying objectclasses" do
expect(@manager.manages(:one, :two)).to equal(@manager)
end
it "should allow specification of what objectclasses are managed" do
expect(@manager.manages(:one, :two).objectclasses).to eq([:one, :two])
end
it "should return self when specifying the relative base" do
expect(@manager.at("yay")).to equal(@manager)
end
it "should allow specification of the relative base" do
expect(@manager.at("yay").location).to eq("yay")
end
it "should return self when specifying the attribute map" do
expect(@manager.maps(:one => :two)).to equal(@manager)
end
it "should allow specification of the rdn attribute" do
expect(@manager.named_by(:uid).rdn).to eq(:uid)
end
it "should allow specification of the attribute map" do
expect(@manager.maps(:one => :two).puppet2ldap).to eq({:one => :two})
end
it "should have a no-op 'and' method that just returns self" do
expect(@manager.and).to equal(@manager)
end
it "should allow specification of generated attributes" do
expect(@manager.generates(:thing)).to be_instance_of(Puppet::Util::Ldap::Generator)
end
describe "when generating attributes" do
before do
@generator = double('generator', :source => "one", :name => "myparam")
allow(Puppet::Util::Ldap::Generator).to receive(:new).with(:myparam).and_return(@generator)
end
it "should create a generator to do the parameter generation" do
expect(Puppet::Util::Ldap::Generator).to receive(:new).with(:myparam).and_return(@generator)
@manager.generates(:myparam)
end
it "should return the generator from the :generates method" do
expect(@manager.generates(:myparam)).to equal(@generator)
end
it "should not replace already present values" do
@manager.generates(:myparam)
attrs = {"myparam" => "testing"}
expect(@generator).not_to receive(:generate)
@manager.generate attrs
expect(attrs["myparam"]).to eq("testing")
end
it "should look for the parameter as a string, not a symbol" do
@manager.generates(:myparam)
expect(@generator).to receive(:generate).with("yay").and_return(%w{double yay})
attrs = {"one" => "yay"}
@manager.generate attrs
expect(attrs["myparam"]).to eq(%w{double yay})
end
it "should fail if a source is specified and no source value is not defined" do
@manager.generates(:myparam)
expect { @manager.generate "two" => "yay" }.to raise_error(ArgumentError)
end
it "should use the source value to generate the new value if a source attribute is specified" do
@manager.generates(:myparam)
expect(@generator).to receive(:generate).with("yay").and_return(%w{double yay})
@manager.generate "one" => "yay"
end
it "should not pass in any value if no source attribute is specified" do
allow(@generator).to receive(:source).and_return(nil)
@manager.generates(:myparam)
expect(@generator).to receive(:generate).and_return(%w{double yay})
@manager.generate "one" => "yay"
end
it "should convert any results to arrays of strings if necessary" do
expect(@generator).to receive(:generate).and_return(:test)
@manager.generates(:myparam)
attrs = {"one" => "two"}
@manager.generate(attrs)
expect(attrs["myparam"]).to eq(["test"])
end
it "should add the result to the passed-in attribute hash" do
expect(@generator).to receive(:generate).and_return(%w{test})
@manager.generates(:myparam)
attrs = {"one" => "two"}
@manager.generate(attrs)
expect(attrs["myparam"]).to eq(%w{test})
end
end
it "should be considered invalid if it is missing a location" do
@manager.manages :me
@manager.maps :me => :you
expect(@manager).not_to be_valid
end
it "should be considered invalid if it is missing an objectclass list" do
@manager.maps :me => :you
@manager.at "ou=yayness"
expect(@manager).not_to be_valid
end
it "should be considered invalid if it is missing an attribute map" do
@manager.manages :me
@manager.at "ou=yayness"
expect(@manager).not_to be_valid
end
it "should be considered valid if it has an attribute map, location, and objectclass list" do
@manager.maps :me => :you
@manager.manages :me
@manager.at "ou=yayness"
expect(@manager).to be_valid
end
it "should calculate an instance's dn using the :ldapbase setting and the relative base" do
Puppet[:ldapbase] = "dc=testing"
@manager.at "ou=mybase"
expect(@manager.dn("me")).to eq("cn=me,ou=mybase,dc=testing")
end
it "should use the specified rdn when calculating an instance's dn" do
Puppet[:ldapbase] = "dc=testing"
@manager.named_by :uid
@manager.at "ou=mybase"
expect(@manager.dn("me")).to match(/^uid=me/)
end
it "should calculate its base using the :ldapbase setting and the relative base" do
Puppet[:ldapbase] = "dc=testing"
@manager.at "ou=mybase"
expect(@manager.base).to eq("ou=mybase,dc=testing")
end
describe "when generating its search filter" do
it "should using a single 'objectclass=<name>' filter if a single objectclass is specified" do
@manager.manages("testing")
expect(@manager.filter).to eq("objectclass=testing")
end
it "should create an LDAP AND filter if multiple objectclasses are specified" do
@manager.manages "testing", "okay", "done"
expect(@manager.filter).to eq("(&(objectclass=testing)(objectclass=okay)(objectclass=done))")
end
end
it "should have a method for converting a Puppet attribute name to an LDAP attribute name as a string" do
@manager.maps :puppet_attr => :ldap_attr
expect(@manager.ldap_name(:puppet_attr)).to eq("ldap_attr")
end
it "should have a method for converting an LDAP attribute name to a Puppet attribute name" do
@manager.maps :puppet_attr => :ldap_attr
expect(@manager.puppet_name(:ldap_attr)).to eq(:puppet_attr)
end
it "should have a :create method for creating ldap entries" do
expect(@manager).to respond_to(:create)
end
it "should have a :delete method for deleting ldap entries" do
expect(@manager).to respond_to(:delete)
end
it "should have a :modify method for modifying ldap entries" do
expect(@manager).to respond_to(:modify)
end
it "should have a method for finding an entry by name in ldap" do
expect(@manager).to respond_to(:find)
end
describe "when converting ldap entries to hashes for providers" do
before do
@manager.maps :uno => :one, :dos => :two
@result = @manager.entry2provider("dn" => ["cn=one,ou=people,dc=madstop"], "one" => ["two"], "three" => %w{four}, "objectclass" => %w{yay ness})
end
it "should set the name to the short portion of the dn" do
expect(@result[:name]).to eq("one")
end
it "should remove the objectclasses" do
expect(@result["objectclass"]).to be_nil
end
it "should remove any attributes that are not mentioned in the map" do
expect(@result["three"]).to be_nil
end
it "should rename convert to symbols all attributes to their puppet names" do
expect(@result[:uno]).to eq(%w{two})
end
it "should set the value of all unset puppet attributes as :absent" do
expect(@result[:dos]).to eq(:absent)
end
end
describe "when using an ldap connection" do
before do
@ldapconn = double('ldapconn')
@conn = double('connection', :connection => @ldapconn, :start => nil, :close => nil)
allow(Puppet::Util::Ldap::Connection).to receive(:new).and_return(@conn)
end
it "should fail unless a block is given" do
expect { @manager.connect }.to raise_error(ArgumentError, /must pass a block/)
end
it "should open the connection with its server set to :ldapserver" do
Puppet[:ldapserver] = "myserver"
expect(Puppet::Util::Ldap::Connection).to receive(:new).with("myserver", anything, anything).and_return(@conn)
@manager.connect { |c| }
end
it "should open the connection with its port set to the :ldapport" do
Puppet[:ldapport] = 28
expect(Puppet::Util::Ldap::Connection).to receive(:new).with(anything, 28, anything).and_return(@conn)
@manager.connect { |c| }
end
it "should open the connection with no user if :ldapuser is not set" do
Puppet[:ldapuser] = ""
expect(Puppet::Util::Ldap::Connection).to receive(:new).with(anything, anything, hash_excluding(:user)).and_return(@conn)
@manager.connect { |c| }
end
it "should open the connection with its user set to the :ldapuser if it is set" do
Puppet[:ldapuser] = "mypass"
expect(Puppet::Util::Ldap::Connection).to receive(:new).with(anything, anything, hash_including(user: "mypass")).and_return(@conn)
@manager.connect { |c| }
end
it "should open the connection with no password if :ldappassword is not set" do
Puppet[:ldappassword] = ""
expect(Puppet::Util::Ldap::Connection).to receive(:new).with(anything, anything, hash_excluding(:password)).and_return(@conn)
@manager.connect { |c| }
end
it "should open the connection with its password set to the :ldappassword if it is set" do
Puppet[:ldappassword] = "mypass"
expect(Puppet::Util::Ldap::Connection).to receive(:new).with(anything, anything, hash_including(password: "mypass")).and_return(@conn)
@manager.connect { |c| }
end
it "should set ssl to :tls if ldaptls is enabled" do
Puppet[:ldaptls] = true
expect(Puppet::Util::Ldap::Connection).to receive(:new).with(anything, anything, hash_including(ssl: :tls)).and_return(@conn)
@manager.connect { |c| }
end
it "should set ssl to true if ldapssl is enabled" do
Puppet[:ldapssl] = true
expect(Puppet::Util::Ldap::Connection).to receive(:new).with(anything, anything, hash_including(ssl: true)).and_return(@conn)
@manager.connect { |c| }
end
it "should set ssl to false if neither ldaptls nor ldapssl is enabled" do
Puppet[:ldapssl] = false
expect(Puppet::Util::Ldap::Connection).to receive(:new).with(anything, anything, hash_including(ssl: false)).and_return(@conn)
@manager.connect { |c| }
end
it "should open, yield, and then close the connection" do
expect(@conn).to receive(:start)
expect(@conn).to receive(:close)
expect(Puppet::Util::Ldap::Connection).to receive(:new).and_return(@conn)
expect(@ldapconn).to receive(:test)
@manager.connect { |c| c.test }
end
it "should close the connection even if there's an exception in the passed block" do
expect(@conn).to receive(:close)
expect { @manager.connect { |c| raise ArgumentError } }.to raise_error(ArgumentError)
end
end
describe "when using ldap" do
before do
@conn = double('connection')
allow(@manager).to receive(:connect).and_yield(@conn)
allow(@manager).to receive(:objectclasses).and_return([:oc1, :oc2])
@manager.maps :one => :uno, :two => :dos, :three => :tres, :four => :quatro
end
describe "to create entries" do
it "should convert the first argument to its :create method to a full dn and pass the resulting argument list to its connection" do
expect(@manager).to receive(:dn).with("myname").and_return("mydn")
expect(@conn).to receive(:add).with("mydn", anything)
@manager.create("myname", {"attr" => "myattrs"})
end
it "should add the objectclasses to the attributes" do
expect(@manager).to receive(:dn).with("myname").and_return("mydn")
expect(@conn).to receive(:add) do |_, attrs|
expect(attrs["objectClass"]).to include("oc1", "oc2")
end
@manager.create("myname", {:one => :testing})
end
it "should add the rdn to the attributes" do
expect(@manager).to receive(:dn).with("myname").and_return("mydn")
expect(@conn).to receive(:add).with(anything, hash_including("cn" => %w{myname}))
@manager.create("myname", {:one => :testing})
end
it "should add 'top' to the objectclasses if it is not listed" do
expect(@manager).to receive(:dn).with("myname").and_return("mydn")
expect(@conn).to receive(:add) do |_, attrs|
expect(attrs["objectClass"]).to include("top")
end
@manager.create("myname", {:one => :testing})
end
it "should add any generated values that are defined" do
generator = double('generator', :source => :one, :name => "myparam")
expect(Puppet::Util::Ldap::Generator).to receive(:new).with(:myparam).and_return(generator)
@manager.generates(:myparam)
allow(@manager).to receive(:dn).with("myname").and_return("mydn")
expect(generator).to receive(:generate).with(:testing).and_return(["generated value"])
expect(@conn).to receive(:add).with(anything, hash_including("myparam" => ["generated value"]))
@manager.create("myname", {:one => :testing})
end
it "should convert any generated values to arrays of strings if necessary" do
generator = double('generator', :source => :one, :name => "myparam")
expect(Puppet::Util::Ldap::Generator).to receive(:new).with(:myparam).and_return(generator)
@manager.generates(:myparam)
allow(@manager).to receive(:dn).and_return("mydn")
expect(generator).to receive(:generate).and_return(:generated)
expect(@conn).to receive(:add).with(anything, hash_including("myparam" => ["generated"]))
@manager.create("myname", {:one => :testing})
end
end
describe "do delete entries" do
it "should convert the first argument to its :delete method to a full dn and pass the resulting argument list to its connection" do
expect(@manager).to receive(:dn).with("myname").and_return("mydn")
expect(@conn).to receive(:delete).with("mydn")
@manager.delete("myname")
end
end
describe "to modify entries" do
it "should convert the first argument to its :modify method to a full dn and pass the resulting argument list to its connection" do
expect(@manager).to receive(:dn).with("myname").and_return("mydn")
expect(@conn).to receive(:modify).with("mydn", :mymods)
@manager.modify("myname", :mymods)
end
end
describe "to find a single entry" do
it "should use the dn of the provided name as the search base, a scope of 0, and 'objectclass=*' as the filter for a search2 call" do
expect(@manager).to receive(:dn).with("myname").and_return("mydn")
expect(@conn).to receive(:search2).with("mydn", 0, "objectclass=*")
@manager.find("myname")
end
it "should return nil if an exception is thrown because no result is found" do
expect(@manager).to receive(:dn).with("myname").and_return("mydn")
expect(@conn).to receive(:search2).and_raise(LDAP::ResultError)
expect(@manager.find("myname")).to be_nil
end
it "should return a converted provider hash if the result is found" do
expect(@manager).to receive(:dn).with("myname").and_return("mydn")
result = {"one" => "two"}
expect(@conn).to receive(:search2).and_yield(result)
expect(@manager).to receive(:entry2provider).with(result).and_return("myprovider")
expect(@manager.find("myname")).to eq("myprovider")
end
end
describe "to search for multiple entries" do
before do
allow(@manager).to receive(:filter).and_return("myfilter")
end
it "should use the manager's search base as the dn of the provided name as the search base" do
expect(@manager).to receive(:base).and_return("mybase")
expect(@conn).to receive(:search2).with("mybase", anything, anything)
@manager.search
end
it "should use a scope of 1" do
expect(@conn).to receive(:search2).with(anything, 1, anything)
@manager.search
end
it "should use any specified search filter" do
expect(@manager).not_to receive(:filter)
expect(@conn).to receive(:search2).with(anything, anything, "boo")
@manager.search("boo")
end
it "should turn its objectclass list into its search filter if one is not specified" do
expect(@manager).to receive(:filter).and_return("yay")
expect(@conn).to receive(:search2).with(anything, anything, "yay")
@manager.search
end
it "should return nil if no result is found" do
expect(@conn).to receive(:search2)
expect(@manager.search).to be_nil
end
it "should return an array of the found results converted to provider hashes" do
# LAK: AFAICT, it's impossible to yield multiple times in an expectation.
one = {"dn" => "cn=one,dc=madstop,dc=com", "one" => "two"}
expect(@conn).to receive(:search2).and_yield(one)
expect(@manager).to receive(:entry2provider).with(one).and_return("myprov")
expect(@manager.search).to eq(["myprov"])
end
end
end
describe "when an instance" do
before do
@name = "myname"
@manager.maps :one => :uno, :two => :dos, :three => :tres, :four => :quatro
end
describe "is being updated" do
it "should get created if the current attribute list is empty and the desired attribute list has :ensure == :present" do
expect(@manager).to receive(:create)
@manager.update(@name, {}, {:ensure => :present})
end
it "should get created if the current attribute list has :ensure == :absent and the desired attribute list has :ensure == :present" do
expect(@manager).to receive(:create)
@manager.update(@name, {:ensure => :absent}, {:ensure => :present})
end
it "should get deleted if the current attribute list has :ensure == :present and the desired attribute list has :ensure == :absent" do
expect(@manager).to receive(:delete)
@manager.update(@name, {:ensure => :present}, {:ensure => :absent})
end
it "should get modified if both attribute lists have :ensure == :present" do
expect(@manager).to receive(:modify)
@manager.update(@name, {:ensure => :present, :one => :two}, {:ensure => :present, :one => :three})
end
end
describe "is being deleted" do
it "should call the :delete method with its name and manager" do
expect(@manager).to receive(:delete).with(@name)
@manager.update(@name, {}, {:ensure => :absent})
end
end
describe "is being created" do
before do
@is = {}
@should = {:ensure => :present, :one => :yay, :two => :absent}
end
it "should call the :create method with its name" do
expect(@manager).to receive(:create).with(@name, anything)
@manager.update(@name, @is, @should)
end
it "should call the :create method with its property hash converted to ldap attribute names" do
expect(@manager).to receive(:create).with(anything, hash_including("uno" => ["yay"]))
@manager.update(@name, @is, @should)
end
it "should not include :ensure in the properties sent" do
expect(@manager).to receive(:create).with(anything, hash_excluding(:ensure))
@manager.update(@name, @is, @should)
end
it "should not include attributes set to :absent in the properties sent" do
expect(@manager).to receive(:create).with(anything, hash_excluding(:dos))
@manager.update(@name, @is, @should)
end
end
describe "is being modified" do
it "should call the :modify method with its name and an array of LDAP::Mod instances" do
allow(LDAP::Mod).to receive(:new).and_return("whatever")
@is = {:one => :yay}
@should = {:one => :yay, :two => :foo}
expect(@manager).to receive(:modify).with(@name, anything)
@manager.update(@name, @is, @should)
end
it "should create the LDAP::Mod with the property name converted to the ldap name as a string" do
@is = {:one => :yay}
@should = {:one => :yay, :two => :foo}
mod = double('module')
expect(LDAP::Mod).to receive(:new).with(anything, "dos", anything).and_return(mod)
allow(@manager).to receive(:modify)
@manager.update(@name, @is, @should)
end
it "should create an LDAP::Mod instance of type LDAP_MOD_ADD for each attribute being added, with the attribute value converted to a string of arrays" do
@is = {:one => :yay}
@should = {:one => :yay, :two => :foo}
mod = double('module')
expect(LDAP::Mod).to receive(:new).with(LDAP::LDAP_MOD_ADD, "dos", ["foo"]).and_return(mod)
allow(@manager).to receive(:modify)
@manager.update(@name, @is, @should)
end
it "should create an LDAP::Mod instance of type LDAP_MOD_DELETE for each attribute being deleted" do
@is = {:one => :yay, :two => :foo}
@should = {:one => :yay, :two => :absent}
mod = double('module')
expect(LDAP::Mod).to receive(:new).with(LDAP::LDAP_MOD_DELETE, "dos", []).and_return(mod)
allow(@manager).to receive(:modify)
@manager.update(@name, @is, @should)
end
it "should create an LDAP::Mod instance of type LDAP_MOD_REPLACE for each attribute being modified, with the attribute converted to a string of arrays" do
@is = {:one => :yay, :two => :four}
@should = {:one => :yay, :two => :five}
mod = double('module')
expect(LDAP::Mod).to receive(:new).with(LDAP::LDAP_MOD_REPLACE, "dos", ["five"]).and_return(mod)
allow(@manager).to receive(:modify)
@manager.update(@name, @is, @should)
end
it "should pass all created Mod instances to the modify method" do
@is = {:one => :yay, :two => :foo, :three => :absent}
@should = {:one => :yay, :two => :foe, :three => :fee, :four => :fie}
expect(LDAP::Mod).to receive(:new).exactly(3).times().and_return("mod1", "mod2", "mod3")
expect(@manager).to receive(:modify).with(anything, contain_exactly(*%w{mod1 mod2 mod3}))
@manager.update(@name, @is, @should)
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/util/ldap/generator_spec.rb | spec/unit/util/ldap/generator_spec.rb | require 'spec_helper'
require 'puppet/util/ldap/generator'
describe Puppet::Util::Ldap::Generator do
before do
@generator = Puppet::Util::Ldap::Generator.new(:uno)
end
it "should require a parameter name at initialization" do
expect { Puppet::Util::Ldap::Generator.new }.to raise_error(ArgumentError, /wrong number of arguments/)
end
it "should always return its name as a string" do
g = Puppet::Util::Ldap::Generator.new(:myname)
expect(g.name).to eq("myname")
end
it "should provide a method for declaring the source parameter" do
@generator.from(:dos)
end
it "should always return a set source as a string" do
@generator.from(:dos)
expect(@generator.source).to eq("dos")
end
it "should return the source as nil if there is no source" do
expect(@generator.source).to be_nil
end
it "should return itself when declaring the source" do
expect(@generator.from(:dos)).to equal(@generator)
end
it "should run the provided block when asked to generate the value" do
@generator.with { "yayness" }
expect(@generator.generate).to eq("yayness")
end
it "should pass in any provided value to the block" do
@generator.with { |value| value.upcase }
expect(@generator.generate("myval")).to eq("MYVAL")
end
it "should return itself when declaring the code used for generating" do
expect(@generator.with { |value| value.upcase }).to equal(@generator)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/util/network_device/config_spec.rb | spec/unit/util/network_device/config_spec.rb | require 'spec_helper'
require 'puppet/util/network_device/config'
describe Puppet::Util::NetworkDevice::Config do
include PuppetSpec::Files
before(:each) do
Puppet[:deviceconfig] = tmpfile('deviceconfig')
end
describe "when parsing device" do
let(:config) { Puppet::Util::NetworkDevice::Config.new }
def write_device_config(*lines)
File.open(Puppet[:deviceconfig], 'w') {|f| f.puts lines}
end
it "should skip comments" do
write_device_config(' # comment')
expect(config.devices).to be_empty
end
it "should increment line number even on commented lines" do
write_device_config(' # comment','[router.puppetlabs.com]')
expect(config.devices).to be_include('router.puppetlabs.com')
end
it "should skip blank lines" do
write_device_config(' ')
expect(config.devices).to be_empty
end
it "should produce the correct line number" do
write_device_config(' ', '[router.puppetlabs.com]')
expect(config.devices['router.puppetlabs.com'].line).to eq(2)
end
it "should throw an error if the current device already exists" do
write_device_config('[router.puppetlabs.com]', '[router.puppetlabs.com]')
end
it "should accept device certname containing dashes" do
write_device_config('[router-1.puppetlabs.com]')
expect(config.devices).to include('router-1.puppetlabs.com')
end
it "should create a new device for each found device line" do
write_device_config('[router.puppetlabs.com]', '[swith.puppetlabs.com]')
expect(config.devices.size).to eq(2)
end
it "should parse the device type" do
write_device_config('[router.puppetlabs.com]', 'type cisco')
expect(config.devices['router.puppetlabs.com'].provider).to eq('cisco')
end
it "should parse the device url" do
write_device_config('[router.puppetlabs.com]', 'type cisco', 'url ssh://test/')
expect(config.devices['router.puppetlabs.com'].url).to eq('ssh://test/')
end
it "should error with a malformed device url" do
write_device_config('[router.puppetlabs.com]', 'type cisco', 'url ssh://test node/')
expect { config.devices['router.puppetlabs.com'] }.to raise_error Puppet::Error
end
it "should parse the debug mode" do
write_device_config('[router.puppetlabs.com]', 'type cisco', 'url ssh://test/', 'debug')
expect(config.devices['router.puppetlabs.com'].options).to eq({ :debug => true })
end
it "should set the debug mode to false by default" do
write_device_config('[router.puppetlabs.com]', 'type cisco', 'url ssh://test/')
expect(config.devices['router.puppetlabs.com'].options).to eq({ :debug => false })
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/util/network_device/transport/base_spec.rb | spec/unit/util/network_device/transport/base_spec.rb | require 'spec_helper'
require 'puppet/util/network_device/transport/base'
describe Puppet::Util::NetworkDevice::Transport::Base do
class TestTransport < Puppet::Util::NetworkDevice::Transport::Base
end
before(:each) do
@transport = TestTransport.new
end
describe "when sending commands" do
it "should send the command to the telnet session" do
expect(@transport).to receive(:send).with("line")
@transport.command("line")
end
it "should expect an output matching the given prompt" do
expect(@transport).to receive(:expect).with(/prompt/)
@transport.command("line", :prompt => /prompt/)
end
it "should expect an output matching the default prompt" do
@transport.default_prompt = /defprompt/
expect(@transport).to receive(:expect).with(/defprompt/)
@transport.command("line")
end
it "should yield telnet output to the given block" do
expect(@transport).to receive(:expect).and_yield("output")
@transport.command("line") { |out| expect(out).to eq("output") }
end
it "should return telnet output to the caller" do
expect(@transport).to receive(:expect).and_return("output")
expect(@transport.command("line")).to eq("output")
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/util/command_line_utils/puppet_option_parser_spec.rb | spec/unit/util/command_line_utils/puppet_option_parser_spec.rb | require 'spec_helper'
require 'puppet/util/command_line/puppet_option_parser'
describe Puppet::Util::CommandLine::PuppetOptionParser do
let(:option_parser) { described_class.new }
describe "an option with a value" do
it "parses a 'long' option with a value" do
parses(
:option => ["--angry", "Angry", :REQUIRED],
:from_arguments => ["--angry", "foo"],
:expects => "foo"
)
expect(@logs).to be_empty
end
it "parses a 'long' option with a value and converts '-' to '_' & warns" do
parses(
:option => ["--an_gry", "Angry", :REQUIRED],
:from_arguments => ["--an-gry", "foo"],
:expects => "foo"
)
expect(@logs).to have_matching_log(/Partial argument match detected: correct argument is --an_gry, got --an-gry. Partial argument matching is deprecated and will be removed in a future release./)
end
it "parses a 'long' option with a value and converts '_' to '-' & warns" do
parses(
:option => ["--an-gry", "Angry", :REQUIRED],
:from_arguments => ["--an_gry", "foo"],
:expects => "foo"
)
expect(@logs).to have_matching_log(/Partial argument match detected: correct argument is --an-gry, got --an_gry. Partial argument matching is deprecated and will be removed in a future release./)
end
it "parses a 'short' option with a value" do
parses(
:option => ["--angry", "-a", "Angry", :REQUIRED],
:from_arguments => ["-a", "foo"],
:expects => "foo"
)
expect(@logs).to be_empty
end
it "overrides a previous argument with a later one" do
parses(
:option => ["--later", "Later", :REQUIRED],
:from_arguments => ["--later", "tomorrow", "--later", "morgen"],
:expects => "morgen"
)
expect(@logs).to be_empty
end
end
describe "an option without a value" do
it "parses a 'long' option" do
parses(
:option => ["--angry", "Angry", :NONE],
:from_arguments => ["--angry"],
:expects => true
)
end
it "converts '_' to '-' with a 'long' option & warns" do
parses(
:option => ["--an-gry", "Angry", :NONE],
:from_arguments => ["--an_gry"],
:expects => true
)
expect(@logs).to have_matching_log(/Partial argument match detected: correct argument is --an-gry, got --an_gry. Partial argument matching is deprecated and will be removed in a future release./)
end
it "converts '-' to '_' with a 'long' option & warns" do
parses(
:option => ["--an_gry", "Angry", :NONE],
:from_arguments => ["--an-gry"],
:expects => true
)
expect(@logs).to have_matching_log(/Partial argument match detected: correct argument is --an_gry, got --an-gry. Partial argument matching is deprecated and will be removed in a future release./)
end
it "parses a 'short' option" do
parses(
:option => ["--angry", "-a", "Angry", :NONE],
:from_arguments => ["-a"],
:expects => true
)
end
it "supports the '--no-blah' syntax" do
parses(
:option => ["--[no-]rage", "Rage", :NONE],
:from_arguments => ["--no-rage"],
:expects => false
)
expect(@logs).to be_empty
end
it "resolves '-' to '_' with '--no-blah' syntax" do
parses(
:option => ["--[no-]an_gry", "Angry", :NONE],
:from_arguments => ["--no-an-gry"],
:expects => false
)
expect(@logs).to have_matching_log(/Partial argument match detected: correct argument is --\[no-\]an_gry, got --no-an-gry. Partial argument matching is deprecated and will be removed in a future release./)
end
it "resolves '_' to '-' with '--no-blah' syntax" do
parses(
:option => ["--[no-]an-gry", "Angry", :NONE],
:from_arguments => ["--no-an_gry"],
:expects => false
)
expect(@logs).to have_matching_log(/Partial argument match detected: correct argument is --\[no-\]an-gry, got --no-an_gry. Partial argument matching is deprecated and will be removed in a future release./)
end
it "resolves '-' to '_' & warns when option is defined with '--no-blah syntax' but argument is given in '--option' syntax" do
parses(
:option => ["--[no-]rag-e", "Rage", :NONE],
:from_arguments => ["--rag_e"],
:expects => true
)
expect(@logs).to have_matching_log(/Partial argument match detected: correct argument is --\[no-\]rag-e, got --rag_e. Partial argument matching is deprecated and will be removed in a future release./)
end
it "resolves '_' to '-' & warns when option is defined with '--no-blah syntax' but argument is given in '--option' syntax" do
parses(
:option => ["--[no-]rag_e", "Rage", :NONE],
:from_arguments => ["--rag-e"],
:expects => true
)
expect(@logs).to have_matching_log(/Partial argument match detected: correct argument is --\[no-\]rag_e, got --rag-e. Partial argument matching is deprecated and will be removed in a future release./)
end
it "overrides a previous argument with a later one" do
parses(
:option => ["--[no-]rage", "Rage", :NONE],
:from_arguments => ["--rage", "--no-rage"],
:expects => false
)
expect(@logs).to be_empty
end
end
it "does not accept an unknown option specification" do
expect {
option_parser.on("not", "enough")
}.to raise_error(ArgumentError, /this method only takes 3 or 4 arguments/)
end
it "does not modify the original argument array" do
option_parser.on("--foo", "Foo", :NONE) { |val| }
args = ["--foo"]
option_parser.parse(args)
expect(args.length).to eq(1)
end
# The ruby stdlib OptionParser has an awesome "feature" that you cannot disable, whereby if
# it sees a short option that you haven't specifically registered with it (e.g., "-r"), it
# will automatically attempt to expand it out to whatever long options that you might have
# registered. Since we need to do our option parsing in two passes (one pass against only
# the global/puppet-wide settings definitions, and then a second pass that includes the
# application or face settings--because we can't load the app/face until we've determined
# the libdir), it is entirely possible that we intend to define our "short" option as part
# of the second pass. Therefore, if the option parser attempts to expand it out into a
# long option during the first pass, terrible things will happen.
#
# A long story short: we need to have the ability to control this kind of behavior in our
# option parser, and this test simply affirms that we do.
it "does not try to expand short options that weren't explicitly registered" do
[
["--ridiculous", "This is ridiculous", :REQUIRED],
["--rage-inducing", "This is rage-inducing", :REQUIRED]
].each do |option|
option_parser.on(*option) {}
end
expect { option_parser.parse(["-r"]) }.to raise_error(Puppet::Util::CommandLine::PuppetOptionError)
end
it "respects :ignore_invalid_options" do
option_parser.ignore_invalid_options = true
expect { option_parser.parse(["--unknown-option"]) }.not_to raise_error
end
it "raises if there is an invalid option and :ignore_invalid_options is not set" do
expect { option_parser.parse(["--unknown-option"]) }.to raise_error(Puppet::Util::CommandLine::PuppetOptionError)
end
def parses(option_case)
option = option_case[:option]
expected_value = option_case[:expects]
arguments = option_case[:from_arguments]
seen_value = nil
option_parser.on(*option) do |val|
seen_value = val
end
option_parser.parse(arguments)
expect(seen_value).to eq(expected_value)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/util/windows/file_spec.rb | spec/unit/util/windows/file_spec.rb | require 'spec_helper'
require 'puppet/util/windows'
describe Puppet::Util::Windows::File, :if => Puppet::Util::Platform.windows? do
include PuppetSpec::Files
let(:nonexist_file) { 'C:\foo.bar' }
let(:nonexist_path) { 'C:\somefile\that\wont\ever\exist' }
let(:invalid_file_attributes) { 0xFFFFFFFF } #define INVALID_FILE_ATTRIBUTES (DWORD (-1))
describe "get_attributes" do
it "should raise an error for files that do not exist by default" do
expect {
described_class.get_attributes(nonexist_file)
}.to raise_error(Puppet::Error, /GetFileAttributes/)
end
it "should raise an error for files that do not exist when specified" do
expect {
described_class.get_attributes(nonexist_file, true)
}.to raise_error(Puppet::Error, /GetFileAttributes/)
end
it "should not raise an error for files that do not exist when specified" do
expect {
described_class.get_attributes(nonexist_file, false)
}.not_to raise_error
end
it "should return INVALID_FILE_ATTRIBUTES for files that do not exist when specified" do
expect(described_class.get_attributes(nonexist_file, false)).to eq(invalid_file_attributes)
end
end
describe "get_long_pathname" do
it "should raise an ERROR_FILE_NOT_FOUND for a file that does not exist in a valid path" do
expect {
described_class.get_long_pathname(nonexist_file)
}.to raise_error do |error|
expect(error).to be_a(Puppet::Util::Windows::Error)
expect(error.code).to eq(Puppet::Util::Windows::File::ERROR_FILE_NOT_FOUND)
end
end
it "should raise an ERROR_PATH_NOT_FOUND for a path that does not exist" do
expect {
described_class.get_long_pathname(nonexist_path)
}.to raise_error do |error|
expect(error).to be_a(Puppet::Util::Windows::Error)
expect(error.code).to eq(Puppet::Util::Windows::File::ERROR_PATH_NOT_FOUND)
end
end
it "should return the fully expanded path 'Program Files' given 'Progra~1'" do
# this test could be resolve some of these values at runtime rather than hard-coding
shortened = ENV['SystemDrive'] + '\\Progra~1'
expanded = ENV['SystemDrive'] + '\\Program Files'
expect(described_class.get_long_pathname(shortened)).to eq (expanded)
end
end
describe "get_short_pathname" do
it "should raise an ERROR_FILE_NOT_FOUND for a file that does not exist in a valid path" do
expect {
described_class.get_short_pathname(nonexist_file)
}.to raise_error do |error|
expect(error).to be_a(Puppet::Util::Windows::Error)
expect(error.code).to eq(Puppet::Util::Windows::File::ERROR_FILE_NOT_FOUND)
end
end
it "should raise an ERROR_PATH_NOT_FOUND for a path that does not exist" do
expect {
described_class.get_short_pathname(nonexist_path)
}.to raise_error do |error|
expect(error).to be_a(Puppet::Util::Windows::Error)
expect(error.code).to eq(Puppet::Util::Windows::File::ERROR_PATH_NOT_FOUND)
end
end
it "should return the shortened 'PROGRA~1' given fully expanded path 'Program Files'" do
# this test could be resolve some of these values at runtime rather than hard-coding
expanded = ENV['SystemDrive'] + '\\Program Files'
shortened = ENV['SystemDrive'] + '\\PROGRA~1'
expect(described_class.get_short_pathname(expanded)).to eq (shortened)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/util/windows/string_spec.rb | spec/unit/util/windows/string_spec.rb | # encoding: UTF-8
require 'spec_helper'
require 'puppet/util/windows'
describe "Puppet::Util::Windows::String", :if => Puppet::Util::Platform.windows? do
def wide_string(str)
Puppet::Util::Windows::String.wide_string(str)
end
def converts_to_wide_string(string_value)
expected = string_value.encode(Encoding::UTF_16LE)
expected_bytes = expected.bytes.to_a
expect(wide_string(string_value).bytes.to_a).to eq(expected_bytes)
end
context "wide_string" do
it "should return encoding of UTF-16LE" do
expect(wide_string("bob").encoding).to eq(Encoding::UTF_16LE)
end
it "should return valid encoding" do
expect(wide_string("bob").valid_encoding?).to be_truthy
end
it "should convert an ASCII string" do
converts_to_wide_string("bob".encode(Encoding::US_ASCII))
end
it "should convert a UTF-8 string" do
converts_to_wide_string("bob".encode(Encoding::UTF_8))
end
it "should convert a UTF-16LE string" do
converts_to_wide_string("bob\u00E8".encode(Encoding::UTF_16LE))
end
it "should convert a UTF-16BE string" do
converts_to_wide_string("bob\u00E8".encode(Encoding::UTF_16BE))
end
it "should convert an UTF-32LE string" do
converts_to_wide_string("bob\u00E8".encode(Encoding::UTF_32LE))
end
it "should convert an UTF-32BE string" do
converts_to_wide_string("bob\u00E8".encode(Encoding::UTF_32BE))
end
it "should return a nil when given a nil" do
expect(wide_string(nil)).to eq(nil)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/util/windows/adsi_spec.rb | spec/unit/util/windows/adsi_spec.rb | require 'spec_helper'
require 'puppet/util/windows'
describe Puppet::Util::Windows::ADSI, :if => Puppet::Util::Platform.windows? do
let(:connection) { double('connection') }
let(:builtin_localized) { Puppet::Util::Windows::SID.sid_to_name('S-1-5-32') }
# SYSTEM is special as English can retrieve it via Windows API
# but will return localized names
let(:ntauthority_localized) { Puppet::Util::Windows::SID::Principal.lookup_account_name('SYSTEM').domain }
before(:each) do
Puppet::Util::Windows::ADSI.instance_variable_set(:@computer_name, 'testcomputername')
allow(Puppet::Util::Windows::ADSI).to receive(:connect).and_return(connection)
end
after(:each) do
Puppet::Util::Windows::ADSI.instance_variable_set(:@computer_name, nil)
end
it "should generate the correct URI for a resource" do
expect(Puppet::Util::Windows::ADSI.uri('test', 'user')).to eq("WinNT://./test,user")
end
it "should be able to get the name of the computer" do
expect(Puppet::Util::Windows::ADSI.computer_name).to eq('testcomputername')
end
it "should be able to provide the correct WinNT base URI for the computer" do
expect(Puppet::Util::Windows::ADSI.computer_uri).to eq("WinNT://.")
end
it "should generate a fully qualified WinNT URI" do
expect(Puppet::Util::Windows::ADSI.computer_uri('testcomputername')).to eq("WinNT://testcomputername")
end
describe ".computer_name" do
it "should return a non-empty ComputerName string" do
Puppet::Util::Windows::ADSI.instance_variable_set(:@computer_name, nil)
expect(Puppet::Util::Windows::ADSI.computer_name).not_to be_empty
end
end
describe ".domain_role" do
DOMAIN_ROLES = Puppet::Util::Platform.windows? ? Puppet::Util::Windows::ADSI::DOMAIN_ROLES : {}
DOMAIN_ROLES.each do |id, role|
it "should be able to return #{role} as the domain role of the computer" do
Puppet::Util::Windows::ADSI.instance_variable_set(:@domain_role, nil)
domain_role = [double('WMI', :DomainRole => id)]
allow(Puppet::Util::Windows::ADSI).to receive(:execquery).with('select DomainRole from Win32_ComputerSystem').and_return(domain_role)
expect(Puppet::Util::Windows::ADSI.domain_role).to eq(role)
end
end
end
describe ".sid_uri" do
it "should raise an error when the input is not a SID Principal" do
[Object.new, {}, 1, :symbol, '', nil].each do |input|
expect {
Puppet::Util::Windows::ADSI.sid_uri(input)
}.to raise_error(Puppet::Error, /Must use a valid SID::Principal/)
end
end
it "should return a SID uri for a well-known SID (SYSTEM)" do
sid = Puppet::Util::Windows::SID::Principal.lookup_account_name('SYSTEM')
expect(Puppet::Util::Windows::ADSI.sid_uri(sid)).to eq('WinNT://S-1-5-18')
end
end
shared_examples 'a local only resource query' do |klass, account_type|
before(:each) do
allow(Puppet::Util::Windows::ADSI).to receive(:domain_role).and_return(:MEMBER_SERVER)
end
it "should be able to check for a local resource" do
local_domain = 'testcomputername'
principal = double('Principal', :account => resource_name, :domain => local_domain, :account_type => account_type)
allow(Puppet::Util::Windows::SID).to receive(:name_to_principal).with(resource_name).and_return(principal)
expect(klass.exists?(resource_name)).to eq(true)
end
it "should be case insensitive when comparing the domain with the computer name" do
local_domain = 'TESTCOMPUTERNAME'
principal = double('Principal', :account => resource_name, :domain => local_domain, :account_type => account_type)
allow(Puppet::Util::Windows::SID).to receive(:name_to_principal).with(resource_name).and_return(principal)
expect(klass.exists?(resource_name)).to eq(true)
end
it "should return false if no local resource exists" do
principal = double('Principal', :account => resource_name, :domain => 'AD_DOMAIN', :account_type => account_type)
allow(Puppet::Util::Windows::SID).to receive(:name_to_principal).with(resource_name).and_return(principal)
expect(klass.exists?(resource_name)).to eq(false)
end
end
describe '.get_sids' do
it 'returns an array of SIDs given two an array of ADSI children' do
child1 = double('child1', name: 'Administrator', sid: 'S-1-5-21-3882680660-671291151-3888264257-500')
child2 = double('child2', name: 'Guest', sid: 'S-1-5-21-3882680660-671291151-3888264257-501')
allow(Puppet::Util::Windows::SID).to receive(:ads_to_principal).with(child1).and_return('Administrator')
allow(Puppet::Util::Windows::SID).to receive(:ads_to_principal).with(child2).and_return('Guest')
sids = Puppet::Util::Windows::ADSI::ADSIObject.get_sids([child1, child2])
expect(sids).to eq(['Administrator', 'Guest'])
end
it 'returns an array of SIDs given an ADSI child and ads_to_principal returning domain failure' do
child = double('child1', name: 'Administrator', sid: 'S-1-5-21-3882680660-671291151-3888264257-500')
allow(Puppet::Util::Windows::SID).to receive(:ads_to_principal).with(child).and_raise(Puppet::Util::Windows::Error.new('', Puppet::Util::Windows::SID::ERROR_TRUSTED_DOMAIN_FAILURE))
sids = Puppet::Util::Windows::ADSI::ADSIObject.get_sids([child])
expect(sids[0]).to eq(Puppet::Util::Windows::SID::Principal.new(child.name, child.sid, child.name, nil, :SidTypeUnknown))
end
it 'returns an array of SIDs given an ADSI child and ads_to_principal returning relationship failure' do
child = double('child1', name: 'Administrator', sid: 'S-1-5-21-3882680660-671291151-3888264257-500')
allow(Puppet::Util::Windows::SID).to receive(:ads_to_principal).with(child).and_raise(Puppet::Util::Windows::Error.new('', Puppet::Util::Windows::SID::ERROR_TRUSTED_RELATIONSHIP_FAILURE))
sids = Puppet::Util::Windows::ADSI::ADSIObject.get_sids([child])
expect(sids[0]).to eq(Puppet::Util::Windows::SID::Principal.new(child.name, child.sid, child.name, nil, :SidTypeUnknown))
end
end
describe Puppet::Util::Windows::ADSI::User do
let(:username) { 'testuser' }
let(:domain) { 'DOMAIN' }
let(:domain_username) { "#{domain}\\#{username}"}
it "should generate the correct URI" do
expect(Puppet::Util::Windows::ADSI::User.uri(username)).to eq("WinNT://./#{username},user")
end
it "should generate the correct URI for a user with a domain" do
expect(Puppet::Util::Windows::ADSI::User.uri(username, domain)).to eq("WinNT://#{domain}/#{username},user")
end
it "should generate the correct URI for a BUILTIN user" do
expect(Puppet::Util::Windows::ADSI::User.uri(username, builtin_localized)).to eq("WinNT://./#{username},user")
end
it "should generate the correct URI for a NT AUTHORITY user" do
expect(Puppet::Util::Windows::ADSI::User.uri(username, ntauthority_localized)).to eq("WinNT://./#{username},user")
end
it "should be able to parse a username without a domain" do
expect(Puppet::Util::Windows::ADSI::User.parse_name(username)).to eq([username, '.'])
end
it "should be able to parse a username with a domain" do
expect(Puppet::Util::Windows::ADSI::User.parse_name(domain_username)).to eq([username, domain])
end
it "should raise an error with a username that contains a /" do
expect {
Puppet::Util::Windows::ADSI::User.parse_name("#{domain}/#{username}")
}.to raise_error(Puppet::Error, /Value must be in DOMAIN\\user style syntax/)
end
it "should be able to create a user" do
adsi_user = double('adsi')
expect(connection).to receive(:Create).with('user', username).and_return(adsi_user)
expect(Puppet::Util::Windows::ADSI::Group).to receive(:exists?).with(username).and_return(false)
user = Puppet::Util::Windows::ADSI::User.create(username)
expect(user).to be_a(Puppet::Util::Windows::ADSI::User)
expect(user.native_object).to eq(adsi_user)
end
context "when domain-joined" do
it_should_behave_like 'a local only resource query', Puppet::Util::Windows::ADSI::User, :SidTypeUser do
let(:resource_name) { username }
end
end
it "should be able to check the existence of a user" do
expect(Puppet::Util::Windows::SID).to receive(:name_to_principal).with(username).and_return(nil)
expect(Puppet::Util::Windows::ADSI).to receive(:connect).with("WinNT://./#{username},user").and_return(connection)
expect(connection).to receive(:Class).and_return('User')
expect(Puppet::Util::Windows::ADSI::User.exists?(username)).to be_truthy
end
it "should be able to check the existence of a domain user" do
expect(Puppet::Util::Windows::SID).to receive(:name_to_principal).with("#{domain}\\#{username}").and_return(nil)
expect(Puppet::Util::Windows::ADSI).to receive(:connect).with("WinNT://#{domain}/#{username},user").and_return(connection)
expect(connection).to receive(:Class).and_return('User')
expect(Puppet::Util::Windows::ADSI::User.exists?(domain_username)).to be_truthy
end
it "should be able to confirm the existence of a user with a well-known SID" do
system_user = Puppet::Util::Windows::SID::LocalSystem
# ensure that the underlying OS is queried here
allow(Puppet::Util::Windows::ADSI).to receive(:connect).and_call_original()
expect(Puppet::Util::Windows::ADSI::User.exists?(system_user)).to be_truthy
end
it "should return false with a well-known Group SID" do
group = Puppet::Util::Windows::SID::BuiltinAdministrators
# ensure that the underlying OS is queried here
allow(Puppet::Util::Windows::ADSI).to receive(:connect).and_call_original()
expect(Puppet::Util::Windows::ADSI::User.exists?(group)).to be_falsey
end
it "should return nil with an unknown SID" do
bogus_sid = 'S-1-2-3-4'
# ensure that the underlying OS is queried here
allow(Puppet::Util::Windows::ADSI).to receive(:connect).and_call_original()
expect(Puppet::Util::Windows::ADSI::User.exists?(bogus_sid)).to be_falsey
end
it "should be able to delete a user" do
expect(connection).to receive(:Delete).with('user', username)
Puppet::Util::Windows::ADSI::User.delete(username)
end
it "should return an enumeration of IADsUser wrapped objects" do
name = 'Administrator'
wmi_users = [double('WMI', :name => name)]
expect(Puppet::Util::Windows::ADSI).to receive(:execquery).with('select name from win32_useraccount where localaccount = "TRUE"').and_return(wmi_users)
native_object = double('IADsUser')
homedir = "C:\\Users\\#{name}"
expect(native_object).to receive(:Get).with('HomeDirectory').and_return(homedir)
expect(Puppet::Util::Windows::ADSI).to receive(:connect).with("WinNT://./#{name},user").and_return(native_object)
users = Puppet::Util::Windows::ADSI::User.to_a
expect(users.length).to eq(1)
expect(users[0].name).to eq(name)
expect(users[0]['HomeDirectory']).to eq(homedir)
end
describe "an instance" do
let(:adsi_user) { double('user', :objectSID => []) }
let(:sid) { double(:account => username, :domain => 'testcomputername') }
let(:user) { Puppet::Util::Windows::ADSI::User.new(username, adsi_user) }
it "should provide its groups as a list of names" do
names = ["group1", "group2"]
groups = names.map { |name| double('group', :Name => name) }
expect(adsi_user).to receive(:Groups).and_return(groups)
expect(user.groups).to match(names)
end
it "should be able to test whether a given password is correct" do
expect(Puppet::Util::Windows::ADSI::User).to receive(:logon).with(username, 'pwdwrong').and_return(false)
expect(Puppet::Util::Windows::ADSI::User).to receive(:logon).with(username, 'pwdright').and_return(true)
expect(user.password_is?('pwdwrong')).to be_falsey
expect(user.password_is?('pwdright')).to be_truthy
end
it "should be able to set a password" do
expect(adsi_user).to receive(:SetPassword).with('pwd')
expect(adsi_user).to receive(:SetInfo).at_least(:once)
flagname = "UserFlags"
fADS_UF_DONT_EXPIRE_PASSWD = 0x10000
expect(adsi_user).to receive(:Get).with(flagname).and_return(0)
expect(adsi_user).to receive(:Put).with(flagname, fADS_UF_DONT_EXPIRE_PASSWD)
user.password = 'pwd'
end
it "should be able manage a user without a password" do
expect(adsi_user).not_to receive(:SetPassword).with('pwd')
expect(adsi_user).to receive(:SetInfo).at_least(:once)
flagname = "UserFlags"
fADS_UF_DONT_EXPIRE_PASSWD = 0x10000
expect(adsi_user).to receive(:Get).with(flagname).and_return(0)
expect(adsi_user).to receive(:Put).with(flagname, fADS_UF_DONT_EXPIRE_PASSWD)
user.password = nil
end
it "should generate the correct URI" do
allow(Puppet::Util::Windows::SID).to receive(:octet_string_to_principal).and_return(sid)
expect(user.uri).to eq("WinNT://testcomputername/#{username},user")
end
describe "when given a set of groups to which to add the user" do
let(:existing_groups) { ['group2','group3'] }
let(:group_sids) { existing_groups.each_with_index.map{|n,i| double(:Name => n, :objectSID => double(:sid => i))} }
let(:groups_to_set) { 'group1,group2' }
let(:desired_sids) { groups_to_set.split(',').each_with_index.map{|n,i| double(:Name => n, :objectSID => double(:sid => i-1))} }
before(:each) do
expect(user).to receive(:group_sids).and_return(group_sids.map {|s| s.objectSID })
end
describe "if membership is specified as inclusive" do
it "should add the user to those groups, and remove it from groups not in the list" do
expect(Puppet::Util::Windows::ADSI::User).to receive(:name_sid_hash).and_return(Hash[ desired_sids.map { |s| [s.objectSID.sid, s.objectSID] }])
expect(user).to receive(:add_group_sids) { |value| expect(value.sid).to eq(-1) }
expect(user).to receive(:remove_group_sids) { |value| expect(value.sid).to eq(1) }
user.set_groups(groups_to_set, false)
end
it "should remove all users from a group if desired is empty" do
expect(Puppet::Util::Windows::ADSI::User).to receive(:name_sid_hash).and_return({})
expect(user).not_to receive(:add_group_sids)
expect(user).to receive(:remove_group_sids) do |user1, user2|
expect(user1.sid).to eq(0)
expect(user2.sid).to eq(1)
end
user.set_groups('', false)
end
end
describe "if membership is specified as minimum" do
it "should add the user to the specified groups without affecting its other memberships" do
expect(Puppet::Util::Windows::ADSI::User).to receive(:name_sid_hash).and_return(Hash[ desired_sids.map { |s| [s.objectSID.sid, s.objectSID] }])
expect(user).to receive(:add_group_sids) { |value| expect(value.sid).to eq(-1) }
expect(user).not_to receive(:remove_group_sids)
user.set_groups(groups_to_set, true)
end
it "should do nothing if desired is empty" do
expect(Puppet::Util::Windows::ADSI::User).to receive(:name_sid_hash).and_return({})
expect(user).not_to receive(:remove_group_sids)
expect(user).not_to receive(:add_group_sids)
user.set_groups('', true)
end
end
end
describe 'userflags' do
# Avoid having to type out the constant everytime we want to
# retrieve a userflag's value.
def ads_userflags(flag)
Puppet::Util::Windows::ADSI::User::ADS_USERFLAGS[flag]
end
before(:each) do
userflags = [
:ADS_UF_SCRIPT,
:ADS_UF_ACCOUNTDISABLE,
:ADS_UF_HOMEDIR_REQUIRED,
:ADS_UF_LOCKOUT
].inject(0) do |flags, flag|
flags | ads_userflags(flag)
end
allow(user).to receive(:[]).with('UserFlags').and_return(userflags)
end
describe '#userflag_set?' do
it 'returns true if the specified userflag is set' do
expect(user.userflag_set?(:ADS_UF_SCRIPT)).to be true
end
it 'returns false if the specified userflag is not set' do
expect(user.userflag_set?(:ADS_UF_PASSWD_NOTREQD)).to be false
end
it 'returns false if the specified userflag is an unrecognized userflag' do
expect(user.userflag_set?(:ADS_UF_UNRECOGNIZED_FLAG)).to be false
end
end
shared_examples 'set/unset common tests' do |method|
it 'raises an ArgumentError for any unrecognized userflags' do
unrecognized_flags = [
:ADS_UF_UNRECOGNIZED_FLAG_ONE,
:ADS_UF_UNRECOGNIZED_FLAG_TWO
]
input_flags = unrecognized_flags + [
:ADS_UF_PASSWORD_EXPIRED,
:ADS_UF_DONT_EXPIRE_PASSWD
]
expect { user.send(method, *input_flags) }.to raise_error(
ArgumentError, /#{unrecognized_flags.join(', ')}/
)
end
it 'noops if no userflags are passed-in' do
expect(user).not_to receive(:[]=)
expect(user).not_to receive(:commit)
user.send(method)
end
end
describe '#set_userflags' do
include_examples 'set/unset common tests', :set_userflags
it 'should add the passed-in flags to the current set of userflags' do
input_flags = [
:ADS_UF_PASSWORD_EXPIRED,
:ADS_UF_DONT_EXPIRE_PASSWD
]
userflags = user['UserFlags']
expected_userflags = userflags | ads_userflags(input_flags[0]) | ads_userflags(input_flags[1])
expect(user).to receive(:[]=).with('UserFlags', expected_userflags)
user.set_userflags(*input_flags)
end
end
describe '#unset_userflags' do
include_examples 'set/unset common tests', :unset_userflags
it 'should remove the passed-in flags from the current set of userflags' do
input_flags = [
:ADS_UF_SCRIPT,
:ADS_UF_ACCOUNTDISABLE
]
# ADS_UF_HOMEDIR_REQUIRED and ADS_UF_LOCKOUT should be the only flags set.
expected_userflags = 0 | ads_userflags(:ADS_UF_HOMEDIR_REQUIRED) | ads_userflags(:ADS_UF_LOCKOUT)
expect(user).to receive(:[]=).with('UserFlags', expected_userflags)
user.unset_userflags(*input_flags)
end
end
end
end
end
describe Puppet::Util::Windows::ADSI::Group do
let(:groupname) { 'testgroup' }
describe "an instance" do
let(:adsi_group) { double('group') }
let(:group) { Puppet::Util::Windows::ADSI::Group.new(groupname, adsi_group) }
let(:someone_sid){ double(:account => 'someone', :domain => 'testcomputername')}
describe "should be able to use SID objects" do
let(:system) { Puppet::Util::Windows::SID.name_to_principal('SYSTEM') }
let(:invalid) { Puppet::Util::Windows::SID.name_to_principal('foobar') }
it "to add a member" do
expect(adsi_group).to receive(:Add).with("WinNT://S-1-5-18")
group.add_member_sids(system)
end
it "and raise when passed a non-SID object to add" do
expect{ group.add_member_sids(invalid)}.to raise_error(Puppet::Error, /Must use a valid SID::Principal/)
end
it "to remove a member" do
expect(adsi_group).to receive(:Remove).with("WinNT://S-1-5-18")
group.remove_member_sids(system)
end
it "and raise when passed a non-SID object to remove" do
expect{ group.remove_member_sids(invalid)}.to raise_error(Puppet::Error, /Must use a valid SID::Principal/)
end
end
it "should provide its groups as a list of names" do
names = ['user1', 'user2']
users = names.map { |name| double('user', :Name => name, :objectSID => name, :ole_respond_to? => true) }
expect(adsi_group).to receive(:Members).and_return(users)
expect(Puppet::Util::Windows::SID).to receive(:octet_string_to_principal).with('user1').and_return(double(:domain_account => 'HOSTNAME\user1'))
expect(Puppet::Util::Windows::SID).to receive(:octet_string_to_principal).with('user2').and_return(double(:domain_account => 'HOSTNAME\user2'))
expect(group.members.map(&:domain_account)).to match(['HOSTNAME\user1', 'HOSTNAME\user2'])
end
context "calling .set_members" do
it "should set the members of a group to only desired_members when inclusive" do
names = ['DOMAIN\user1', 'user2']
sids = [
double(:account => 'user1', :domain => 'DOMAIN', :sid => 1),
double(:account => 'user2', :domain => 'testcomputername', :sid => 2),
double(:account => 'user3', :domain => 'DOMAIN2', :sid => 3),
]
# use stubbed objectSid on member to return stubbed SID
expect(Puppet::Util::Windows::SID).to receive(:octet_string_to_principal).with([0]).and_return(sids[0])
expect(Puppet::Util::Windows::SID).to receive(:octet_string_to_principal).with([1]).and_return(sids[1])
expect(Puppet::Util::Windows::SID).to receive(:name_to_principal).with('user2', false).and_return(sids[1])
expect(Puppet::Util::Windows::SID).to receive(:name_to_principal).with('DOMAIN2\user3', false).and_return(sids[2])
expect(Puppet::Util::Windows::ADSI).to receive(:sid_uri).with(sids[0]).and_return("WinNT://DOMAIN/user1,user")
expect(Puppet::Util::Windows::ADSI).to receive(:sid_uri).with(sids[2]).and_return("WinNT://DOMAIN2/user3,user")
members = names.each_with_index.map{|n,i| double(:Name => n, :objectSID => [i], :ole_respond_to? => true)}
expect(adsi_group).to receive(:Members).and_return(members)
expect(adsi_group).to receive(:Remove).with('WinNT://DOMAIN/user1,user')
expect(adsi_group).to receive(:Add).with('WinNT://DOMAIN2/user3,user')
group.set_members(['user2', 'DOMAIN2\user3'])
end
it "should add the desired_members to an existing group when not inclusive" do
names = ['DOMAIN\user1', 'user2']
sids = [
double(:account => 'user1', :domain => 'DOMAIN', :sid => 1),
double(:account => 'user2', :domain => 'testcomputername', :sid => 2),
double(:account => 'user3', :domain => 'DOMAIN2', :sid => 3),
]
# use stubbed objectSid on member to return stubbed SID
expect(Puppet::Util::Windows::SID).to receive(:octet_string_to_principal).with([0]).and_return(sids[0])
expect(Puppet::Util::Windows::SID).to receive(:octet_string_to_principal).with([1]).and_return(sids[1])
expect(Puppet::Util::Windows::SID).to receive(:name_to_principal).with('user2', any_args).and_return(sids[1])
expect(Puppet::Util::Windows::SID).to receive(:name_to_principal).with('DOMAIN2\user3', any_args).and_return(sids[2])
expect(Puppet::Util::Windows::ADSI).to receive(:sid_uri).with(sids[2]).and_return("WinNT://DOMAIN2/user3,user")
members = names.each_with_index.map {|n,i| double(:Name => n, :objectSID => [i], :ole_respond_to? => true)}
expect(adsi_group).to receive(:Members).and_return(members)
expect(adsi_group).not_to receive(:Remove).with('WinNT://DOMAIN/user1,user')
expect(adsi_group).to receive(:Add).with('WinNT://DOMAIN2/user3,user')
group.set_members(['user2', 'DOMAIN2\user3'],false)
end
it "should return immediately when desired_members is nil" do
expect(adsi_group).not_to receive(:Members)
expect(adsi_group).not_to receive(:Remove)
expect(adsi_group).not_to receive(:Add)
group.set_members(nil)
end
it "should remove all members when desired_members is empty and inclusive" do
names = ['DOMAIN\user1', 'user2']
sids = [
double(:account => 'user1', :domain => 'DOMAIN', :sid => 1 ),
double(:account => 'user2', :domain => 'testcomputername', :sid => 2 ),
]
# use stubbed objectSid on member to return stubbed SID
expect(Puppet::Util::Windows::SID).to receive(:octet_string_to_principal).with([0]).and_return(sids[0])
expect(Puppet::Util::Windows::SID).to receive(:octet_string_to_principal).with([1]).and_return(sids[1])
expect(Puppet::Util::Windows::ADSI).to receive(:sid_uri).with(sids[0]).and_return("WinNT://DOMAIN/user1,user")
expect(Puppet::Util::Windows::ADSI).to receive(:sid_uri).with(sids[1]).and_return("WinNT://testcomputername/user2,user")
members = names.each_with_index.map{|n,i| double(:Name => n, :objectSID => [i], :ole_respond_to? => true)}
expect(adsi_group).to receive(:Members).and_return(members)
expect(adsi_group).to receive(:Remove).with('WinNT://DOMAIN/user1,user')
expect(adsi_group).to receive(:Remove).with('WinNT://testcomputername/user2,user')
group.set_members([])
end
it "should do nothing when desired_members is empty and not inclusive" do
names = ['DOMAIN\user1', 'user2']
sids = [
double(:account => 'user1', :domain => 'DOMAIN', :sid => 1 ),
double(:account => 'user2', :domain => 'testcomputername', :sid => 2 ),
]
# use stubbed objectSid on member to return stubbed SID
expect(Puppet::Util::Windows::SID).to receive(:octet_string_to_principal).with([0]).and_return(sids[0])
expect(Puppet::Util::Windows::SID).to receive(:octet_string_to_principal).with([1]).and_return(sids[1])
members = names.each_with_index.map{|n,i| double(:Name => n, :objectSID => [i], :ole_respond_to? => true)}
expect(adsi_group).to receive(:Members).and_return(members)
expect(adsi_group).not_to receive(:Remove)
expect(adsi_group).not_to receive(:Add)
group.set_members([],false)
end
it "should raise an error when a username does not resolve to a SID" do
expect {
expect(adsi_group).to receive(:Members).and_return([])
group.set_members(['foobar'])
}.to raise_error(Puppet::Error, /Could not resolve name: foobar/)
end
end
it "should generate the correct URI" do
expect(adsi_group).to receive(:objectSID).and_return([0])
expect(Socket).to receive(:gethostname).and_return('TESTcomputerNAME')
computer_sid = double(:account => groupname,:domain => 'testcomputername')
expect(Puppet::Util::Windows::SID).to receive(:octet_string_to_principal).with([0]).and_return(computer_sid)
expect(group.uri).to eq("WinNT://./#{groupname},group")
end
end
it "should generate the correct URI" do
expect(Puppet::Util::Windows::ADSI::Group.uri("people")).to eq("WinNT://./people,group")
end
it "should generate the correct URI for a BUILTIN group" do
expect(Puppet::Util::Windows::ADSI::Group.uri(groupname, builtin_localized)).to eq("WinNT://./#{groupname},group")
end
it "should generate the correct URI for a NT AUTHORITY group" do
expect(Puppet::Util::Windows::ADSI::Group.uri(groupname, ntauthority_localized)).to eq("WinNT://./#{groupname},group")
end
context "when domain-joined" do
it_should_behave_like 'a local only resource query', Puppet::Util::Windows::ADSI::Group, :SidTypeGroup do
let(:resource_name) { groupname }
end
end
it "should be able to create a group" do
adsi_group = double("adsi")
expect(connection).to receive(:Create).with('group', groupname).and_return(adsi_group)
expect(Puppet::Util::Windows::ADSI::User).to receive(:exists?).with(groupname).and_return(false)
group = Puppet::Util::Windows::ADSI::Group.create(groupname)
expect(group).to be_a(Puppet::Util::Windows::ADSI::Group)
expect(group.native_object).to eq(adsi_group)
end
it "should be able to confirm the existence of a group" do
expect(Puppet::Util::Windows::SID).to receive(:name_to_principal).with(groupname).and_return(nil)
expect(Puppet::Util::Windows::ADSI).to receive(:connect).with("WinNT://./#{groupname},group").and_return(connection)
expect(connection).to receive(:Class).and_return('Group')
expect(Puppet::Util::Windows::ADSI::Group.exists?(groupname)).to be_truthy
end
it "should be able to confirm the existence of a group with a well-known SID" do
service_group = Puppet::Util::Windows::SID::Service
# ensure that the underlying OS is queried here
allow(Puppet::Util::Windows::ADSI).to receive(:connect).and_call_original()
expect(Puppet::Util::Windows::ADSI::Group.exists?(service_group)).to be_truthy
end
it "will return true with a well-known User SID, as there is no way to resolve it with a WinNT:// style moniker" do
user = Puppet::Util::Windows::SID::NtLocal
# ensure that the underlying OS is queried here
allow(Puppet::Util::Windows::ADSI).to receive(:connect).and_call_original()
expect(Puppet::Util::Windows::ADSI::Group.exists?(user)).to be_truthy
end
it "should return nil with an unknown SID" do
bogus_sid = 'S-1-2-3-4'
# ensure that the underlying OS is queried here
allow(Puppet::Util::Windows::ADSI).to receive(:connect).and_call_original()
expect(Puppet::Util::Windows::ADSI::Group.exists?(bogus_sid)).to be_falsey
end
it "should be able to delete a group" do
expect(connection).to receive(:Delete).with('group', groupname)
Puppet::Util::Windows::ADSI::Group.delete(groupname)
end
it "should return an enumeration of IADsGroup wrapped objects" do
name = 'Administrators'
wmi_groups = [double('WMI', :name => name)]
expect(Puppet::Util::Windows::ADSI).to receive(:execquery).with('select name from win32_group where localaccount = "TRUE"').and_return(wmi_groups)
native_object = double('IADsGroup')
expect(Puppet::Util::Windows::SID).to receive(:octet_string_to_principal).with([]).and_return(double(:domain_account => '.\Administrator'))
expect(native_object).to receive(:Members).and_return([double(:Name => 'Administrator', :objectSID => [], :ole_respond_to? => true)])
expect(Puppet::Util::Windows::ADSI).to receive(:connect).with("WinNT://./#{name},group").and_return(native_object)
groups = Puppet::Util::Windows::ADSI::Group.to_a
expect(groups.length).to eq(1)
expect(groups[0].name).to eq(name)
expect(groups[0].members.map(&:domain_account)).to eq(['.\Administrator'])
end
end
describe Puppet::Util::Windows::ADSI::UserProfile do
it "should be able to delete a user profile" do
expect(connection).to receive(:Delete).with("Win32_UserProfile.SID='S-A-B-C'")
Puppet::Util::Windows::ADSI::UserProfile.delete('S-A-B-C')
end
it "should warn on 2003" do
expect(connection).to receive(:Delete).and_raise(WIN32OLERuntimeError,
"Delete (WIN32OLERuntimeError)
OLE error code:80041010 in SWbemServicesEx
Invalid class
HRESULT error code:0x80020009
Exception occurred.")
expect(Puppet).to receive(:warning).with("Cannot delete user profile for 'S-A-B-C' prior to Vista SP1")
Puppet::Util::Windows::ADSI::UserProfile.delete('S-A-B-C')
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/util/windows/access_control_list_spec.rb | spec/unit/util/windows/access_control_list_spec.rb | require 'spec_helper'
require 'puppet/util/windows'
describe "Puppet::Util::Windows::AccessControlList", :if => Puppet::Util::Platform.windows? do
let(:klass) { Puppet::Util::Windows::AccessControlList }
let(:system_sid) { 'S-1-5-18' }
let(:admins_sid) { 'S-1-5-544' }
let(:none_sid) { 'S-1-0-0' }
let(:system_ace) do
Puppet::Util::Windows::AccessControlEntry.new(system_sid, 0x1)
end
let(:admins_ace) do
Puppet::Util::Windows::AccessControlEntry.new(admins_sid, 0x2)
end
let(:none_ace) do
Puppet::Util::Windows::AccessControlEntry.new(none_sid, 0x3)
end
it "constructs an empty list" do
acl = klass.new
expect(acl.to_a).to be_empty
end
it "supports copy constructor" do
aces = klass.new([system_ace]).to_a
expect(aces.to_a).to eq([system_ace])
end
context "appending" do
it "appends an allow ace" do
acl = klass.new
acl.allow(system_sid, 0x1, 0x2)
expect(acl.first.type).to eq(klass::ACCESS_ALLOWED_ACE_TYPE)
end
it "appends a deny ace" do
acl = klass.new
acl.deny(system_sid, 0x1, 0x2)
expect(acl.first.type).to eq(klass::ACCESS_DENIED_ACE_TYPE)
end
it "always appends, never overwrites an ACE" do
acl = klass.new([system_ace])
acl.allow(admins_sid, admins_ace.mask, admins_ace.flags)
aces = acl.to_a
expect(aces.size).to eq(2)
expect(aces[0]).to eq(system_ace)
expect(aces[1].sid).to eq(admins_sid)
expect(aces[1].mask).to eq(admins_ace.mask)
expect(aces[1].flags).to eq(admins_ace.flags)
end
end
context "reassigning" do
it "preserves the mask from the old sid when reassigning to the new sid" do
dacl = klass.new([system_ace])
dacl.reassign!(system_ace.sid, admins_ace.sid)
# we removed system, so ignore prepended ace
ace = dacl.to_a[1]
expect(ace.sid).to eq(admins_sid)
expect(ace.mask).to eq(system_ace.mask)
end
it "matches multiple sids" do
dacl = klass.new([system_ace, system_ace])
dacl.reassign!(system_ace.sid, admins_ace.sid)
# we removed system, so ignore prepended ace
aces = dacl.to_a
expect(aces.size).to eq(3)
aces.to_a[1,2].each do |ace|
expect(ace.sid).to eq(admins_ace.sid)
end
end
it "preserves aces for sids that don't match, in their original order" do
dacl = klass.new([system_ace, admins_ace])
dacl.reassign!(system_sid, none_sid)
aces = dacl.to_a
aces[1].sid == admins_ace.sid
end
it "preserves inherited aces, even if the sids match" do
flags = Puppet::Util::Windows::AccessControlEntry::INHERITED_ACE
inherited_ace = Puppet::Util::Windows::AccessControlEntry.new(system_sid, 0x1, flags)
dacl = klass.new([inherited_ace, system_ace])
dacl.reassign!(system_sid, none_sid)
aces = dacl.to_a
expect(aces[0].sid).to eq(system_sid)
end
it "prepends an explicit ace for the new sid with the same mask and basic inheritance as the inherited ace" do
expected_flags =
Puppet::Util::Windows::AccessControlEntry::OBJECT_INHERIT_ACE |
Puppet::Util::Windows::AccessControlEntry::CONTAINER_INHERIT_ACE |
Puppet::Util::Windows::AccessControlEntry::INHERIT_ONLY_ACE
flags = Puppet::Util::Windows::AccessControlEntry::INHERITED_ACE | expected_flags
inherited_ace = Puppet::Util::Windows::AccessControlEntry.new(system_sid, 0x1, flags)
dacl = klass.new([inherited_ace])
dacl.reassign!(system_sid, none_sid)
aces = dacl.to_a
expect(aces.size).to eq(2)
expect(aces[0].sid).to eq(none_sid)
expect(aces[0]).not_to be_inherited
expect(aces[0].flags).to eq(expected_flags)
expect(aces[1].sid).to eq(system_sid)
expect(aces[1]).to be_inherited
end
it "makes a copy of the ace prior to modifying it" do
arr = [system_ace]
acl = klass.new(arr)
acl.reassign!(system_sid, none_sid)
expect(arr[0].sid).to eq(system_sid)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/util/windows/sid_spec.rb | spec/unit/util/windows/sid_spec.rb | require 'spec_helper'
describe "Puppet::Util::Windows::SID", :if => Puppet::Util::Platform.windows? do
if Puppet::Util::Platform.windows?
require 'puppet/util/windows'
end
let(:subject) { Puppet::Util::Windows::SID }
let(:sid) { Puppet::Util::Windows::SID::LocalSystem }
let(:invalid_sid) { 'bogus' }
let(:unknown_sid) { 'S-0-0-0' }
let(:null_sid) { 'S-1-0-0' }
let(:unknown_name) { 'chewbacca' }
context "#octet_string_to_principal" do
it "should properly convert an array of bytes for a well-known non-localized SID" do
bytes = [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
converted = subject.octet_string_to_principal(bytes)
expect(converted).to be_an_instance_of Puppet::Util::Windows::SID::Principal
expect(converted.sid_bytes).to eq(bytes)
expect(converted.sid).to eq(null_sid)
# carefully select a SID here that is not localized on international Windows
expect(converted.account).to eq('NULL SID')
end
it "should raise an error for non-array input" do
expect {
subject.octet_string_to_principal(invalid_sid)
}.to raise_error(Puppet::Error, /Octet string must be an array of bytes/)
end
it "should raise an error for an empty byte array" do
expect {
subject.octet_string_to_principal([])
}.to raise_error(Puppet::Error, /Octet string must be an array of bytes/)
end
it "should raise an error for a valid byte array with no mapping to a user" do
expect {
# S-1-1-1 which is not a valid account
valid_octet_invalid_user =[1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0]
subject.octet_string_to_principal(valid_octet_invalid_user)
}.to raise_error do |error|
expect(error).to be_a(Puppet::Util::Windows::Error)
expect(error.code).to eq(1332) # ERROR_NONE_MAPPED
end
end
it "should raise an error for a malformed byte array" do
expect {
invalid_octet = [2]
subject.octet_string_to_principal(invalid_octet)
}.to raise_error do |error|
expect(error).to be_a(Puppet::Util::Windows::Error)
expect(error.code).to eq(87) # ERROR_INVALID_PARAMETER
end
end
end
context "#name_to_sid" do
it "should return nil if the account does not exist" do
expect(subject.name_to_sid(unknown_name)).to be_nil
end
it "should accept unqualified account name" do
# NOTE: lookup by name works in localized environments only for a few instances
# this works in French Windows, even though the account is really Syst\u00E8me
expect(subject.name_to_sid('SYSTEM')).to eq(sid)
end
it "should return a SID for a passed user or group name" do
expect(subject).to receive(:name_to_principal).with('testers').and_return(double(:sid => 'S-1-5-32-547'))
expect(subject.name_to_sid('testers')).to eq('S-1-5-32-547')
end
it "should return a SID for a passed fully-qualified user or group name" do
expect(subject).to receive(:name_to_principal).with('MACHINE\testers').and_return(double(:sid => 'S-1-5-32-547'))
expect(subject.name_to_sid('MACHINE\testers')).to eq('S-1-5-32-547')
end
it "should be case-insensitive" do
expect(subject.name_to_sid('SYSTEM')).to eq(subject.name_to_sid('system'))
end
it "should be leading and trailing whitespace-insensitive" do
expect(subject.name_to_sid('SYSTEM')).to eq(subject.name_to_sid(' SYSTEM '))
end
it "should accept domain qualified account names" do
# NOTE: lookup by name works in localized environments only for a few instances
# this works in French Windows, even though the account is really AUTORITE NT\\Syst\u00E8me
expect(subject.name_to_sid('NT AUTHORITY\SYSTEM')).to eq(sid)
end
it "should be the identity function for any sid" do
expect(subject.name_to_sid(sid)).to eq(sid)
end
describe "with non-US languages" do
UMLAUT = [195, 164].pack('c*').force_encoding(Encoding::UTF_8)
let(:username) { SecureRandom.uuid.to_s.gsub(/\-/, '')[0..13] + UMLAUT }
after(:each) {
Puppet::Util::Windows::ADSI::User.delete(username)
}
it "should properly resolve a username with an umlaut" do
# Ruby seems to use the local codepage when making COM calls
# if this fails, might want to use Windows API directly instead to ensure bytes
user = Puppet::Util::Windows::ADSI.create(username, 'user')
user.SetPassword('PUPPET_RULeZ_123!')
user.SetInfo()
# compare the new SID to the name_to_sid result
sid_bytes = user.objectSID.to_a
sid_string = ''
FFI::MemoryPointer.new(:byte, sid_bytes.length) do |sid_byte_ptr|
sid_byte_ptr.write_array_of_uchar(sid_bytes)
sid_string = Puppet::Util::Windows::SID.sid_ptr_to_string(sid_byte_ptr)
end
expect(subject.name_to_sid(username)).to eq(sid_string)
end
end
end
context "#name_to_principal" do
it "should return nil if the account does not exist" do
expect(subject.name_to_principal(unknown_name)).to be_nil
end
it "should print a debug message if the account does not exist" do
expect(Puppet).to receive(:debug).with(/No mapping between account names and security IDs was done/)
subject.name_to_principal(unknown_name)
end
it "should return a Puppet::Util::Windows::SID::Principal instance for any valid sid" do
expect(subject.name_to_principal(sid)).to be_an_instance_of(Puppet::Util::Windows::SID::Principal)
end
it "should not print debug messages for valid sid" do
expect(Puppet).not_to receive(:debug).with(/Could not retrieve raw SID bytes from/)
expect(Puppet).not_to receive(:debug).with(/No mapping between account names and security IDs was done/)
subject.name_to_principal(sid)
end
it "should print a debug message for invalid sid" do
expect(Puppet).not_to receive(:debug).with(/Could not retrieve raw SID bytes from/)
expect(Puppet).to receive(:debug).with(/No mapping between account names and security IDs was done/)
subject.name_to_principal('S-1-5-21-INVALID-SID')
end
it "should accept unqualified account name" do
# NOTE: lookup by name works in localized environments only for a few instances
# this works in French Windows, even though the account is really Syst\u00E8me
expect(subject.name_to_principal('SYSTEM').sid).to eq(sid)
end
it "should not print debug messages for unqualified account name" do
expect(Puppet).not_to receive(:debug).with(/Could not retrieve raw SID bytes from/)
expect(Puppet).not_to receive(:debug).with(/No mapping between account names and security IDs was done/)
subject.name_to_principal('SYSTEM')
end
it "should be case-insensitive" do
# NOTE: lookup by name works in localized environments only for a few instances
# this works in French Windows, even though the account is really Syst\u00E8me
expect(subject.name_to_principal('SYSTEM')).to eq(subject.name_to_principal('system'))
end
it "should not print debug messages for wrongly cased account name" do
expect(Puppet).not_to receive(:debug).with(/Could not retrieve raw SID bytes from/)
expect(Puppet).not_to receive(:debug).with(/No mapping between account names and security IDs was done/)
subject.name_to_principal('system')
end
it "should be leading and trailing whitespace-insensitive" do
# NOTE: lookup by name works in localized environments only for a few instances
# this works in French Windows, even though the account is really Syst\u00E8me
expect(subject.name_to_principal('SYSTEM')).to eq(subject.name_to_principal(' SYSTEM '))
end
it "should not print debug messages for account name with leading and trailing whitespace" do
expect(Puppet).not_to receive(:debug).with(/Could not retrieve raw SID bytes from/)
expect(Puppet).not_to receive(:debug).with(/No mapping between account names and security IDs was done/)
subject.name_to_principal(' SYSTEM ')
end
it "should accept domain qualified account names" do
# NOTE: lookup by name works in localized environments only for a few instances
# this works in French Windows, even though the account is really AUTORITE NT\\Syst\u00E8me
expect(subject.name_to_principal('NT AUTHORITY\SYSTEM').sid).to eq(sid)
end
it "should not print debug messages for domain qualified account names" do
expect(Puppet).not_to receive(:debug).with(/Could not retrieve raw SID bytes from/)
expect(Puppet).not_to receive(:debug).with(/No mapping between account names and security IDs was done/)
subject.name_to_principal('NT AUTHORITY\SYSTEM')
end
end
context "#ads_to_principal" do
it "should raise an error for non-WIN32OLE input" do
expect {
subject.ads_to_principal(double('WIN32OLE', { :Name => 'foo' }))
}.to raise_error(Puppet::Error, /ads_object must be an IAdsUser or IAdsGroup instance/)
end
it "should raise an error for an empty byte array in the objectSID property" do
expect {
subject.ads_to_principal(double('WIN32OLE', { :objectSID => [], :Name => '', :ole_respond_to? => true }))
}.to raise_error(Puppet::Error, /Octet string must be an array of bytes/)
end
it "should raise an error for a malformed byte array" do
expect {
invalid_octet = [2]
subject.ads_to_principal(double('WIN32OLE', { :objectSID => invalid_octet, :Name => '', :ole_respond_to? => true }))
}.to raise_error do |error|
expect(error).to be_a(Puppet::Util::Windows::Error)
expect(error.code).to eq(87) # ERROR_INVALID_PARAMETER
end
end
it "should raise an error when a valid byte array for SID is unresolvable and its Name does not match" do
expect {
# S-1-1-1 is a valid SID that will not resolve
valid_octet_invalid_user = [1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0]
subject.ads_to_principal(double('WIN32OLE', { :objectSID => valid_octet_invalid_user, :Name => unknown_name, :ole_respond_to? => true }))
}.to raise_error do |error|
expect(error).to be_a(Puppet::Error)
expect(error.cause.code).to eq(1332) # ERROR_NONE_MAPPED
end
end
it "should return a Principal object even when the SID is unresolvable, as long as the Name matches" do
# S-1-1-1 is a valid SID that will not resolve
valid_octet_invalid_user = [1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0]
unresolvable_user = double('WIN32OLE', { :objectSID => valid_octet_invalid_user, :Name => 'S-1-1-1', :ole_respond_to? => true })
principal = subject.ads_to_principal(unresolvable_user)
expect(principal).to be_an_instance_of(Puppet::Util::Windows::SID::Principal)
expect(principal.account).to eq('S-1-1-1')
expect(principal.domain).to eq(nil)
expect(principal.domain_account).to eq('S-1-1-1')
expect(principal.sid).to eq('S-1-1-1')
expect(principal.sid_bytes).to eq(valid_octet_invalid_user)
expect(principal.account_type).to eq(:SidTypeUnknown)
end
it "should return a Puppet::Util::Windows::SID::Principal instance for any valid sid" do
system_bytes = [1, 1, 0, 0, 0, 0, 0, 5, 18, 0, 0, 0]
adsuser = double('WIN32OLE', { :objectSID => system_bytes, :Name => 'SYSTEM', :ole_respond_to? => true })
expect(subject.ads_to_principal(adsuser)).to be_an_instance_of(Puppet::Util::Windows::SID::Principal)
end
it "should properly convert an array of bytes for a well-known non-localized SID, ignoring the Name from the WIN32OLE object" do
bytes = [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
adsuser = double('WIN32OLE', { :objectSID => bytes, :Name => unknown_name, :ole_respond_to? => true })
converted = subject.ads_to_principal(adsuser)
expect(converted).to be_an_instance_of Puppet::Util::Windows::SID::Principal
expect(converted.sid_bytes).to eq(bytes)
expect(converted.sid).to eq(null_sid)
# carefully select a SID here that is not localized on international Windows
expect(converted.account).to eq('NULL SID')
# garbage name supplied does not carry forward as SID is looked up again
expect(converted.account).to_not eq(adsuser.Name)
end
end
context "#sid_to_name" do
it "should return nil if given a sid for an account that doesn't exist" do
expect(subject.sid_to_name(unknown_sid)).to be_nil
end
it "should accept a sid" do
# choose a value that is not localized, for instance
# S-1-5-18 can be NT AUTHORITY\\SYSTEM or AUTORITE NT\\Syst\u00E8me
# but NULL SID appears universal
expect(subject.sid_to_name(null_sid)).to eq('NULL SID')
end
end
context "#sid_ptr_to_string" do
it "should raise if given an invalid sid" do
expect {
subject.sid_ptr_to_string(nil)
}.to raise_error(Puppet::Error, /Invalid SID/)
end
it "should yield a valid sid pointer" do
string = nil
subject.string_to_sid_ptr(sid) do |ptr|
string = subject.sid_ptr_to_string(ptr)
end
expect(string).to eq(sid)
end
end
context "#string_to_sid_ptr" do
it "should yield sid_ptr" do
ptr = nil
subject.string_to_sid_ptr(sid) do |p|
ptr = p
end
expect(ptr).not_to be_nil
end
it "should raise on an invalid sid" do
expect {
subject.string_to_sid_ptr(invalid_sid)
}.to raise_error(Puppet::Error, /Failed to convert string SID/)
end
end
context "#valid_sid?" do
it "should return true for a valid SID" do
expect(subject.valid_sid?(sid)).to be_truthy
end
it "should return false for an invalid SID" do
expect(subject.valid_sid?(invalid_sid)).to be_falsey
end
it "should raise if the conversion fails" do
expect(subject).to receive(:string_to_sid_ptr).with(sid).
and_raise(Puppet::Util::Windows::Error.new("Failed to convert string SID: #{sid}", Puppet::Util::Windows::Error::ERROR_ACCESS_DENIED))
expect {
subject.string_to_sid_ptr(sid) {|ptr| }
}.to raise_error(Puppet::Util::Windows::Error, /Failed to convert string SID: #{sid}/)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/util/windows/root_certs_spec.rb | spec/unit/util/windows/root_certs_spec.rb | require 'spec_helper'
require 'puppet/util/windows'
describe "Puppet::Util::Windows::RootCerts", :if => Puppet::Util::Platform.windows? do
let(:x509_store) { Puppet::Util::Windows::RootCerts.instance.to_a }
it "should return at least one X509 certificate" do
expect(x509_store.to_a.size).to be >= 1
end
it "should return an X509 certificate with a subject" do
x509 = x509_store.first
expect(x509.subject.to_utf8).to match(/CN=.*/)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/util/windows/service_spec.rb | spec/unit/util/windows/service_spec.rb | require 'spec_helper'
describe "Puppet::Util::Windows::Service", :if => Puppet.features.microsoft_windows? do
require 'puppet/util/windows'
before(:each) do
allow(Puppet::Util::Windows::Error).to receive(:format_error_code)
.with(anything)
.and_return("fake error!")
end
def service_state_str(state)
Puppet::Util::Windows::Service::SERVICE_STATES[state].to_s
end
# The following should emulate a successful call to the private function
# query_status that returns the value of query_return. This should give
# us a way to mock changes in service status.
#
# Everything else is stubbed, the emulation of the successful call is really
# just an expectation of subject::SERVICE_STATUS_PROCESS.new in sequence that
# returns the value passed in as a param
def expect_successful_status_query_and_return(query_return)
expect(subject::SERVICE_STATUS_PROCESS).to receive(:new).and_return(query_return)
end
def expect_successful_status_queries_and_return(*query_returns)
query_returns.each do |query_return|
expect_successful_status_query_and_return(query_return)
end
end
# The following should emulate a successful call to the private function
# query_config that returns the value of query_return. This should give
# us a way to mock changes in service configuration.
#
# Everything else is stubbed, the emulation of the successful call is really
# just an expectation of subject::QUERY_SERVICE_CONFIGW.new in sequence that
# returns the value passed in as a param
def expect_successful_config_query_and_return(query_return)
expect(subject::QUERY_SERVICE_CONFIGW).to receive(:new).and_return(query_return)
end
def expect_successful_config_query2_and_return(param, query_return)
expect(param).to receive(:new).and_return(query_return)
end
let(:subject) { Puppet::Util::Windows::Service }
let(:pointer) { double() }
let(:mock_service_name) { double() }
let(:service) { double() }
let(:scm) { double() }
let(:timeout) { 30 }
before do
allow(subject).to receive(:QueryServiceStatusEx).and_return(1)
allow(subject).to receive(:QueryServiceConfigW).and_return(1)
allow(subject).to receive(:QueryServiceConfig2W).and_return(1)
allow(subject).to receive(:ChangeServiceConfigW).and_return(1)
allow(subject).to receive(:ChangeServiceConfig2W).and_return(1)
allow(subject).to receive(:OpenSCManagerW).and_return(scm)
allow(subject).to receive(:OpenServiceW).and_return(service)
allow(subject).to receive(:CloseServiceHandle)
allow(subject).to receive(:EnumServicesStatusExW).and_return(1)
allow(subject).to receive(:wide_string)
allow(subject::SERVICE_STATUS_PROCESS).to receive(:new)
allow(subject::QUERY_SERVICE_CONFIGW).to receive(:new)
allow(subject::SERVICE_STATUS).to receive(:new).and_return({:dwCurrentState => subject::SERVICE_RUNNING})
allow(FFI).to receive(:errno).and_return(0)
allow(FFI::MemoryPointer).to receive(:new).and_yield(pointer)
allow(pointer).to receive(:read_dword)
allow(pointer).to receive(:write_dword)
allow(pointer).to receive(:size)
allow(subject).to receive(:sleep)
end
describe "#exists?" do
context "when the service control manager cannot be opened" do
let(:scm) { FFI::Pointer::NULL_HANDLE }
it "raises a puppet error" do
expect{ subject.exists?(mock_service_name) }.to raise_error(Puppet::Error)
end
end
context "when the service cannot be opened" do
let(:service) { FFI::Pointer::NULL_HANDLE }
it "returns false if it fails to open because the service does not exist" do
allow(FFI).to receive(:errno).and_return(Puppet::Util::Windows::Service::ERROR_SERVICE_DOES_NOT_EXIST)
expect(subject.exists?(mock_service_name)).to be false
end
it "raises a puppet error if it fails to open for some other reason" do
expect{ subject.exists?(mock_service_name) }.to raise_error(Puppet::Error)
end
end
context "when the service can be opened" do
it "returns true" do
expect(subject.exists?(mock_service_name)).to be true
end
end
end
# This shared example contains the unit tests for the wait_on_pending_state
# helper as used by service actions like #start and #stop. Before including
# this shared example, be sure to mock out any intermediate calls prior to
# the pending transition, and make sure that the post-condition _after_ those
# intermediate calls leaves the service in the pending state. Before including
# this example in your tests, be sure to define the following variables in a `let`
# context:
# * action -- The service action
shared_examples "a service action waiting on a pending transition" do |pending_state|
pending_state_str = Puppet::Util::Windows::Service::SERVICE_STATES[pending_state].to_s
final_state = Puppet::Util::Windows::Service::FINAL_STATES[pending_state]
final_state_str = Puppet::Util::Windows::Service::SERVICE_STATES[final_state].to_s
it "raises a Puppet::Error if the service query fails" do
expect(subject).to receive(:QueryServiceStatusEx).and_return(FFI::WIN32_FALSE)
expect { subject.send(action, mock_service_name, timeout: timeout) }.to raise_error(Puppet::Error)
end
it "raises a Puppet::Error if the service unexpectedly transitions to a state other than #{pending_state_str} or #{final_state_str}" do
invalid_state = (subject::SERVICE_STATES.keys - [pending_state, final_state]).first
expect_successful_status_query_and_return(dwCurrentState: invalid_state)
expect { subject.send(action, mock_service_name, timeout: timeout) }.to raise_error(Puppet::Error)
end
it "waits for at least 1 second if the wait_hint/10 is < 1 second" do
expect_successful_status_queries_and_return(
{ :dwCurrentState => pending_state, :dwWaitHint => 0, :dwCheckPoint => 1 },
{ :dwCurrentState => final_state }
)
expect(subject).to receive(:sleep).with(1)
subject.send(action, mock_service_name, timeout: timeout)
end
it "waits for at most 10 seconds if wait_hint/10 is > 10 seconds" do
expect_successful_status_queries_and_return(
{ :dwCurrentState => pending_state, :dwWaitHint => 1000000, :dwCheckPoint => 1 },
{ :dwCurrentState => final_state }
)
expect(subject).to receive(:sleep).with(10)
subject.send(action, mock_service_name, timeout: timeout)
end
it "does not raise an error if the service makes any progress while transitioning to #{final_state_str}" do
expect_successful_status_queries_and_return(
# The three "pending_state" statuses simulate the scenario where the service
# makes some progress during the transition right when Puppet's about to
# time out.
{ :dwCurrentState => pending_state, :dwWaitHint => 100000, :dwCheckPoint => 1 },
{ :dwCurrentState => pending_state, :dwWaitHint => 100000, :dwCheckPoint => 1 },
{ :dwCurrentState => pending_state, :dwWaitHint => 100000, :dwCheckPoint => 2 },
{ :dwCurrentState => final_state }
)
expect { subject.send(action, mock_service_name, timeout: timeout) }.to_not raise_error
end
it "raises a Puppet::Error if it times out while waiting for the transition to #{final_state_str}" do
31.times do
expect_successful_status_query_and_return(
dwCurrentState: pending_state,
dwWaitHint: 10000,
dwCheckPoint: 1
)
end
expect { subject.send(action, mock_service_name, timeout: timeout) }.to raise_error(Puppet::Error)
end
end
# This shared example contains the unit tests for the transition_service_state
# helper, which is the helper that all of our service actions like #start, #stop
# delegate to. Including these tests under a shared example lets us include them in each of
# those service action's unit tests. Before including this example in your tests, be
# sure to define the following variables in a `let` context:
# * initial_state -- The initial state of the service prior to performing the state
# transition
#
# * mock_state_transition -- A lambda that mocks the state transition. This should mock
# any code in the block that's passed to the
# transition_service_state helper
#
# See the unit tests for the #start method to see how this shared example's
# included.
#
shared_examples "a service action that transitions the service state" do |action, valid_initial_states, pending_state, final_state|
valid_initial_states_str = valid_initial_states.map do |state|
Puppet::Util::Windows::Service::SERVICE_STATES[state]
end.join(', ')
pending_state_str = Puppet::Util::Windows::Service::SERVICE_STATES[pending_state].to_s
final_state_str = Puppet::Util::Windows::Service::SERVICE_STATES[final_state].to_s
it "noops if the service is already in the #{final_state} state" do
expect_successful_status_query_and_return(dwCurrentState: final_state)
expect { subject.send(action, mock_service_name, timeout: timeout) }.to_not raise_error
end
# invalid_initial_states will be empty for the #stop action
invalid_initial_states = Puppet::Util::Windows::Service::SERVICE_STATES.keys - valid_initial_states - [final_state]
unless invalid_initial_states.empty?
it "raises a Puppet::Error if the service's initial state is not one of #{valid_initial_states_str}" do
invalid_initial_state = invalid_initial_states.first
expect_successful_status_query_and_return(dwCurrentState: invalid_initial_state)
expect{ subject.send(action, mock_service_name, timeout: timeout) }.to raise_error(Puppet::Error)
end
end
context "when there's a pending transition to the #{final_state} state" do
before(:each) do
expect_successful_status_query_and_return(dwCurrentState: pending_state)
end
include_examples "a service action waiting on a pending transition", pending_state do
let(:action) { action }
end
end
# If the service action accepts an unsafe pending state as one of the service's
# initial states, then we need to test that the action waits for the service to
# transition from that unsafe pending state before doing anything else.
unsafe_pending_states = valid_initial_states & Puppet::Util::Windows::Service::UNSAFE_PENDING_STATES
unless unsafe_pending_states.empty?
unsafe_pending_state = unsafe_pending_states.first
unsafe_pending_state_str = Puppet::Util::Windows::Service::SERVICE_STATES[unsafe_pending_state]
context "waiting for a service with #{unsafe_pending_state_str} as its initial state" do
before(:each) do
# This mocks the status query to return the 'final_state' by default. Otherwise,
# we will fail the tests in the latter parts of the code where we wait for the
# service to finish transitioning to the 'final_state'.
allow(subject::SERVICE_STATUS_PROCESS).to receive(:new).and_return(dwCurrentState: final_state)
# Set our service's initial state
expect_successful_status_query_and_return(dwCurrentState: unsafe_pending_state)
mock_state_transition.call
end
include_examples "a service action waiting on a pending transition", unsafe_pending_state do
let(:action) { action }
end
end
end
# reads e.g. "waiting for the service to transition to the SERVICE_RUNNING state after executing the 'start' action"
#
# NOTE: This is really unit testing the wait_on_state_transition helper
context "waiting for the service to transition to the #{final_state_str} state after executing the '#{action}' action" do
before(:each) do
# Set our service's initial state prior to performing the state transition
expect_successful_status_query_and_return(dwCurrentState: initial_state)
mock_state_transition.call
end
it "raises a Puppet::Error if the service query fails" do
expect(subject).to receive(:QueryServiceStatusEx).and_return(FFI::WIN32_FALSE)
expect { subject.send(action, mock_service_name, timeout: timeout) }.to raise_error(Puppet::Error)
end
it "waits, then queries again until it transitions to #{final_state_str}" do
expect_successful_status_queries_and_return(
{ :dwCurrentState => initial_state },
{ :dwCurrentState => initial_state },
{ :dwCurrentState => final_state }
)
expect(subject).to receive(:sleep).with(1).twice
subject.send(action, mock_service_name, timeout: timeout)
end
context "when it transitions to the #{pending_state_str} state" do
before(:each) do
expect_successful_status_query_and_return(dwCurrentState: pending_state)
end
include_examples "a service action waiting on a pending transition", pending_state do
let(:action) { action }
end
end
it "raises a Puppet::Error if it times out while waiting for the transition to #{final_state_str}" do
31.times do
expect_successful_status_query_and_return(dwCurrentState: initial_state)
end
expect { subject.send(action, mock_service_name, timeout: timeout) }.to raise_error(Puppet::Error)
end
end
end
describe "#start" do
# rspec will still try to load the tests even though
# the :if => Puppet.features.microsoft_windows? filter
# is passed-in to the top-level describe block on
# non-Windows platforms; it just won't run them. However
# on these platforms, the loading will fail because this
# test uses a shared example that references variables
# from the Windows::Service module when building the unit
# tests, which is only available on Windows platforms.
# Thus, we add the next here to ensure that rspec does not
# attempt to load our test code. This is OK for us to do
# because we do not want to run these tests on non-Windows
# platforms.
next unless Puppet.features.microsoft_windows?
context "when the service control manager cannot be opened" do
let(:scm) { FFI::Pointer::NULL_HANDLE }
it "raises a puppet error" do
expect{ subject.start(mock_service_name, timeout: timeout) }.to raise_error(Puppet::Error)
end
end
context "when the service cannot be opened" do
let(:service) { FFI::Pointer::NULL_HANDLE }
it "raises a puppet error" do
expect{ subject.start(mock_service_name, timeout: timeout) }.to raise_error(Puppet::Error)
end
end
context "when the service can be opened" do
# Can't use rspec's subject here because that
# can only be referenced inside an 'it' block.
service = Puppet::Util::Windows::Service
valid_initial_states = [
service::SERVICE_STOP_PENDING,
service::SERVICE_STOPPED,
service::SERVICE_START_PENDING
]
final_state = service::SERVICE_RUNNING
include_examples "a service action that transitions the service state", :start, valid_initial_states, service::SERVICE_START_PENDING, final_state do
let(:initial_state) { subject::SERVICE_STOPPED }
let(:mock_state_transition) do
lambda do
allow(subject).to receive(:StartServiceW).and_return(1)
end
end
end
it "raises a Puppet::Error if StartServiceW returns false" do
expect_successful_status_query_and_return(dwCurrentState: subject::SERVICE_STOPPED)
expect(subject).to receive(:StartServiceW).and_return(FFI::WIN32_FALSE)
expect { subject.start(mock_service_name, timeout: timeout) }.to raise_error(Puppet::Error)
end
it "starts the service" do
expect_successful_status_queries_and_return(
{ dwCurrentState: subject::SERVICE_STOPPED },
{ dwCurrentState: subject::SERVICE_RUNNING }
)
expect(subject).to receive(:StartServiceW).and_return(1)
subject.start(mock_service_name, timeout: timeout)
end
end
end
describe "#stop" do
next unless Puppet.features.microsoft_windows?
context "when the service control manager cannot be opened" do
let(:scm) { FFI::Pointer::NULL_HANDLE }
it "raises a puppet error" do
expect{ subject.start(mock_service_name, timeout: timeout) }.to raise_error(Puppet::Error)
end
end
context "when the service cannot be opened" do
let(:service) { FFI::Pointer::NULL_HANDLE }
it "raises a puppet error" do
expect{ subject.start(mock_service_name, timeout: timeout) }.to raise_error(Puppet::Error)
end
end
context "when the service can be opened" do
service = Puppet::Util::Windows::Service
valid_initial_states = service::SERVICE_STATES.keys - [service::SERVICE_STOPPED]
final_state = service::SERVICE_STOPPED
include_examples "a service action that transitions the service state", :stop, valid_initial_states, service::SERVICE_STOP_PENDING, final_state do
let(:initial_state) { subject::SERVICE_RUNNING }
let(:mock_state_transition) do
lambda do
allow(subject).to receive(:ControlService).and_return(1)
end
end
end
it "raises a Puppet::Error if ControlService returns false" do
expect_successful_status_query_and_return(dwCurrentState: subject::SERVICE_RUNNING)
allow(subject).to receive(:ControlService).and_return(FFI::WIN32_FALSE)
expect { subject.stop(mock_service_name, timeout: timeout) }.to raise_error(Puppet::Error)
end
it "stops the service" do
expect_successful_status_queries_and_return(
{ dwCurrentState: subject::SERVICE_RUNNING },
{ dwCurrentState: subject::SERVICE_STOPPED }
)
expect(subject).to receive(:ControlService).and_return(1)
subject.stop(mock_service_name, timeout: timeout)
end
end
end
describe "#resume" do
next unless Puppet.features.microsoft_windows?
context "when the service control manager cannot be opened" do
let(:scm) { FFI::Pointer::NULL_HANDLE }
it "raises a puppet error" do
expect{ subject.start(mock_service_name, timeout: timeout) }.to raise_error(Puppet::Error)
end
end
context "when the service cannot be opened" do
let(:service) { FFI::Pointer::NULL_HANDLE }
it "raises a puppet error" do
expect{ subject.start(mock_service_name, timeout: timeout) }.to raise_error(Puppet::Error)
end
end
context "when the service can be opened" do
service = Puppet::Util::Windows::Service
valid_initial_states = [
service::SERVICE_PAUSE_PENDING,
service::SERVICE_PAUSED,
service::SERVICE_CONTINUE_PENDING
]
final_state = service::SERVICE_RUNNING
include_examples "a service action that transitions the service state", :resume, valid_initial_states, service::SERVICE_CONTINUE_PENDING, final_state do
let(:initial_state) { service::SERVICE_PAUSED }
let(:mock_state_transition) do
lambda do
# We need to mock the status query because in the block for #resume, we
# wait for the service to enter the SERVICE_PAUSED state prior to
# performing the transition (in case it is in SERVICE_PAUSE_PENDING).
expect_successful_status_query_and_return(dwCurrentState: subject::SERVICE_PAUSED)
allow(subject).to receive(:ControlService).and_return(1)
end
end
end
context "waiting for the SERVICE_PAUSE_PENDING => SERVICE_PAUSED transition to finish before resuming it" do
before(:each) do
# This mocks the status query to return the SERVICE_RUNNING state by default.
# Otherwise, we will fail the tests in the latter parts of the code where we
# wait for the service to finish transitioning to the 'SERVICE_RUNNING' state.
allow(subject::SERVICE_STATUS_PROCESS).to receive(:new).and_return(dwCurrentState: subject::SERVICE_RUNNING)
expect_successful_status_query_and_return(dwCurrentState: subject::SERVICE_PAUSE_PENDING)
allow(subject).to receive(:ControlService).and_return(1)
end
include_examples "a service action waiting on a pending transition", service::SERVICE_PAUSE_PENDING do
let(:action) { :resume }
end
end
it "raises a Puppet::Error if ControlService returns false" do
expect_successful_status_query_and_return(dwCurrentState: subject::SERVICE_PAUSED)
expect_successful_status_query_and_return(dwCurrentState: subject::SERVICE_PAUSED)
allow(subject).to receive(:ControlService).and_return(FFI::WIN32_FALSE)
expect { subject.resume(mock_service_name, timeout: timeout) }.to raise_error(Puppet::Error)
end
it "resumes the service" do
expect_successful_status_queries_and_return(
{ dwCurrentState: subject::SERVICE_PAUSED },
{ dwCurrentState: subject::SERVICE_PAUSED },
{ dwCurrentState: subject::SERVICE_RUNNING }
)
expect(subject).to receive(:ControlService).and_return(1)
subject.resume(mock_service_name, timeout: timeout)
end
end
end
describe "#service_state" do
context "when the service control manager cannot be opened" do
let(:scm) { FFI::Pointer::NULL_HANDLE }
it "raises a puppet error" do
expect{ subject.service_state(mock_service_name) }.to raise_error(Puppet::Error)
end
end
context "when the service cannot be opened" do
let(:service) { FFI::Pointer::NULL_HANDLE }
it "raises a puppet error" do
expect{ subject.service_state(mock_service_name) }.to raise_error(Puppet::Error)
end
end
context "when the service can be opened" do
it "raises Puppet::Error if the result of the query is empty" do
expect_successful_status_query_and_return({})
expect{subject.service_state(mock_service_name)}.to raise_error(Puppet::Error)
end
it "raises Puppet::Error if the result of the query is an unknown state" do
expect_successful_status_query_and_return({:dwCurrentState => 999})
expect{subject.service_state(mock_service_name)}.to raise_error(Puppet::Error)
end
# We need to guard this section explicitly since rspec will always
# construct all examples, even if it isn't going to run them.
if Puppet.features.microsoft_windows?
{
:SERVICE_STOPPED => Puppet::Util::Windows::Service::SERVICE_STOPPED,
:SERVICE_PAUSED => Puppet::Util::Windows::Service::SERVICE_PAUSED,
:SERVICE_STOP_PENDING => Puppet::Util::Windows::Service::SERVICE_STOP_PENDING,
:SERVICE_PAUSE_PENDING => Puppet::Util::Windows::Service::SERVICE_PAUSE_PENDING,
:SERVICE_RUNNING => Puppet::Util::Windows::Service::SERVICE_RUNNING,
:SERVICE_CONTINUE_PENDING => Puppet::Util::Windows::Service::SERVICE_CONTINUE_PENDING,
:SERVICE_START_PENDING => Puppet::Util::Windows::Service::SERVICE_START_PENDING,
}.each do |state_name, state|
it "queries the service and returns #{state_name}" do
expect_successful_status_query_and_return({:dwCurrentState => state})
expect(subject.service_state(mock_service_name)).to eq(state_name)
end
end
end
end
end
describe "#service_start_type" do
context "when the service control manager cannot be opened" do
let(:scm) { FFI::Pointer::NULL_HANDLE }
it "raises a puppet error" do
expect{ subject.service_start_type(mock_service_name) }.to raise_error(Puppet::Error)
end
end
context "when the service cannot be opened" do
let(:service) { FFI::Pointer::NULL_HANDLE }
it "raises a puppet error" do
expect{ subject.service_start_type(mock_service_name) }.to raise_error(Puppet::Error)
end
end
context "when the service can be opened" do
# We need to guard this section explicitly since rspec will always
# construct all examples, even if it isn't going to run them.
if Puppet.features.microsoft_windows?
{
:SERVICE_AUTO_START => Puppet::Util::Windows::Service::SERVICE_AUTO_START,
:SERVICE_BOOT_START => Puppet::Util::Windows::Service::SERVICE_BOOT_START,
:SERVICE_SYSTEM_START => Puppet::Util::Windows::Service::SERVICE_SYSTEM_START,
:SERVICE_DEMAND_START => Puppet::Util::Windows::Service::SERVICE_DEMAND_START,
:SERVICE_DISABLED => Puppet::Util::Windows::Service::SERVICE_DISABLED,
}.each do |start_type_name, start_type|
it "queries the service and returns the service start type #{start_type_name}" do
expect_successful_config_query_and_return({:dwStartType => start_type})
if start_type_name == :SERVICE_AUTO_START
expect_successful_config_query2_and_return(subject::SERVICE_DELAYED_AUTO_START_INFO, {:fDelayedAutostart => 0})
end
expect(subject.service_start_type(mock_service_name)).to eq(start_type_name)
end
end
end
it "raises a puppet error if the service query fails" do
expect(subject).to receive(:QueryServiceConfigW)
expect(subject).to receive(:QueryServiceConfigW).and_return(FFI::WIN32_FALSE)
expect{ subject.service_start_type(mock_service_name) }.to raise_error(Puppet::Error)
end
end
end
describe "#set_startup_configuration" do
let(:status_checks) { sequence('status_checks') }
context "when the service control manager cannot be opened" do
let(:scm) { FFI::Pointer::NULL_HANDLE }
it "raises a puppet error" do
expect{ subject.set_startup_configuration(mock_service_name, options: {startup_type: :SERVICE_DEMAND_START}) }.to raise_error(Puppet::Error)
end
end
context "when the service cannot be opened" do
let(:service) { FFI::Pointer::NULL_HANDLE }
it "raises a puppet error" do
expect{ subject.set_startup_configuration(mock_service_name, options: {startup_type: :SERVICE_DEMAND_START}) }.to raise_error(Puppet::Error)
end
end
context "when the service can be opened" do
it "Raises an error on an unsuccessful change" do
expect(subject).to receive(:ChangeServiceConfigW).and_return(FFI::WIN32_FALSE)
expect{ subject.set_startup_configuration(mock_service_name, options: {startup_type: :SERVICE_DEMAND_START}) }.to raise_error(Puppet::Error)
end
end
end
describe "#services" do
let(:pointer_sequence) { sequence('pointer_sequence') }
context "when the service control manager cannot be opened" do
let(:scm) { FFI::Pointer::NULL_HANDLE }
it "raises a puppet error" do
expect{ subject.services }.to raise_error(Puppet::Error)
end
end
context "when the service control manager is open" do
let(:cursor) { [ 'svc1', 'svc2', 'svc3' ] }
let(:svc1name_ptr) { double() }
let(:svc2name_ptr) { double() }
let(:svc3name_ptr) { double() }
let(:svc1displayname_ptr) { double() }
let(:svc2displayname_ptr) { double() }
let(:svc3displayname_ptr) { double() }
let(:svc1) { { :lpServiceName => svc1name_ptr, :lpDisplayName => svc1displayname_ptr, :ServiceStatusProcess => 'foo' } }
let(:svc2) { { :lpServiceName => svc2name_ptr, :lpDisplayName => svc2displayname_ptr, :ServiceStatusProcess => 'foo' } }
let(:svc3) { { :lpServiceName => svc3name_ptr, :lpDisplayName => svc3displayname_ptr, :ServiceStatusProcess => 'foo' } }
it "Raises an error if EnumServicesStatusExW fails" do
expect(subject).to receive(:EnumServicesStatusExW)
expect(subject).to receive(:EnumServicesStatusExW).and_return(FFI::WIN32_FALSE)
expect{ subject.services }.to raise_error(Puppet::Error)
end
it "Reads the buffer using pointer arithmetic to create a hash of service entries" do
# the first read_dword is for reading the bytes required, let that return 3 too.
# the second read_dword will actually read the number of services returned
expect(pointer).to receive(:read_dword).twice.and_return(3)
expect(FFI::Pointer).to receive(:new).with(subject::ENUM_SERVICE_STATUS_PROCESSW, pointer).and_return(cursor)
expect(subject::ENUM_SERVICE_STATUS_PROCESSW).to receive(:new).with('svc1').and_return(svc1)
expect(subject::ENUM_SERVICE_STATUS_PROCESSW).to receive(:new).with('svc2').and_return(svc2)
expect(subject::ENUM_SERVICE_STATUS_PROCESSW).to receive(:new).with('svc3').and_return(svc3)
expect(svc1name_ptr).to receive(:read_arbitrary_wide_string_up_to).and_return('svc1')
expect(svc2name_ptr).to receive(:read_arbitrary_wide_string_up_to).and_return('svc2')
expect(svc3name_ptr).to receive(:read_arbitrary_wide_string_up_to).and_return('svc3')
expect(svc1displayname_ptr).to receive(:read_arbitrary_wide_string_up_to).and_return('service 1')
expect(svc2displayname_ptr).to receive(:read_arbitrary_wide_string_up_to).and_return('service 2')
expect(svc3displayname_ptr).to receive(:read_arbitrary_wide_string_up_to).and_return('service 3')
expect(subject.services).to eq({
'svc1' => { :display_name => 'service 1', :service_status_process => 'foo' },
'svc2' => { :display_name => 'service 2', :service_status_process => 'foo' },
'svc3' => { :display_name => 'service 3', :service_status_process => 'foo' }
})
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/util/windows/api_types_spec.rb | spec/unit/util/windows/api_types_spec.rb | # encoding: UTF-8
require 'spec_helper'
describe "FFI::MemoryPointer", :if => Puppet::Util::Platform.windows? do
# use 2 bad bytes at end so we have even number of bytes / characters
let(:bad_string) { "hello invalid world".encode(Encoding::UTF_16LE) + "\xDD\xDD".force_encoding(Encoding::UTF_16LE) }
let(:bad_string_bytes) { bad_string.bytes.to_a }
let(:a_wide_bytes) { "A".encode(Encoding::UTF_16LE).bytes.to_a }
let(:b_wide_bytes) { "B".encode(Encoding::UTF_16LE).bytes.to_a }
context "read_wide_string" do
let (:string) { "foo_bar" }
it "should properly roundtrip a given string" do
FFI::MemoryPointer.from_string_to_wide_string(string) do |ptr|
expect(ptr.read_wide_string(string.length)).to eq(string)
end
end
it "should return a given string in UTF-8" do
FFI::MemoryPointer.from_string_to_wide_string(string) do |ptr|
read_string = ptr.read_wide_string(string.length)
expect(read_string.encoding).to eq(Encoding::UTF_8)
end
end
it "should raise an error and emit a debug message when receiving a string containing invalid bytes in the destination encoding" do
Puppet[:log_level] = 'debug'
expect {
FFI::MemoryPointer.new(:byte, bad_string_bytes.count) do |ptr|
# uchar here is synonymous with byte
ptr.put_array_of_uchar(0, bad_string_bytes)
ptr.read_wide_string(bad_string.length)
end
}.to raise_error(Encoding::InvalidByteSequenceError)
expect(@logs.last.message).to eq("Unable to convert value #{bad_string.dump} to encoding UTF-8 due to #<Encoding::InvalidByteSequenceError: \"\\xDD\\xDD\" on UTF-16LE>")
end
it "should not raise an error when receiving a string containing invalid bytes in the destination encoding, when specifying :invalid => :replace" do
FFI::MemoryPointer.new(:byte, bad_string_bytes.count) do |ptr|
# uchar here is synonymous with byte
ptr.put_array_of_uchar(0, bad_string_bytes)
read_string = ptr.read_wide_string(bad_string.length, Encoding::UTF_8, false, :invalid => :replace)
expect(read_string).to eq("hello invalid world\uFFFD")
end
end
it "raises an IndexError if asked to read more characters than there are bytes allocated" do
expect {
FFI::MemoryPointer.new(:byte, 1) do |ptr|
ptr.read_wide_string(1) # 1 wchar = 2 bytes
end
}.to raise_error(IndexError, /out of bounds/)
end
it "raises an IndexError if asked to read a negative number of characters" do
expect {
FFI::MemoryPointer.new(:byte, 1) do |ptr|
ptr.read_wide_string(-1)
end
}.to raise_error(IndexError, /out of bounds/)
end
it "returns an empty string if asked to read 0 characters" do
FFI::MemoryPointer.new(:byte, 1) do |ptr|
expect(ptr.read_wide_string(0)).to eq("")
end
end
it "returns a substring if asked to read fewer characters than are in the byte array" do
FFI::MemoryPointer.new(:byte, 4) do |ptr|
ptr.write_array_of_uint8("AB".encode('UTF-16LE').bytes.to_a)
expect(ptr.read_wide_string(1)).to eq("A")
end
end
it "preserves wide null characters in the string" do
FFI::MemoryPointer.new(:byte, 6) do |ptr|
ptr.write_array_of_uint8(a_wide_bytes + [0, 0] + b_wide_bytes)
expect(ptr.read_wide_string(3)).to eq("A\x00B")
end
end
end
context "read_arbitrary_wide_string_up_to" do
let (:string) { "foo_bar" }
let (:single_null_string) { string + "\x00" }
let (:double_null_string) { string + "\x00\x00" }
it "should read a short single null terminated string" do
FFI::MemoryPointer.from_string_to_wide_string(single_null_string) do |ptr|
expect(ptr.read_arbitrary_wide_string_up_to).to eq(string)
end
end
it "should read a short double null terminated string" do
FFI::MemoryPointer.from_string_to_wide_string(double_null_string) do |ptr|
expect(ptr.read_arbitrary_wide_string_up_to(512, :double_null)).to eq(string)
end
end
it "detects trailing single null wchar" do
FFI::MemoryPointer.from_string_to_wide_string(single_null_string) do |ptr|
expect(ptr).to receive(:read_wide_string).with(string.length, anything, anything, anything).and_call_original
expect(ptr.read_arbitrary_wide_string_up_to).to eq(string)
end
end
it "detects trailing double null wchar" do
FFI::MemoryPointer.from_string_to_wide_string(double_null_string) do |ptr|
expect(ptr).to receive(:read_wide_string).with(string.length, anything, anything, anything).and_call_original
expect(ptr.read_arbitrary_wide_string_up_to(512, :double_null)).to eq(string)
end
end
it "should raises an IndexError if max_length is negative" do
FFI::MemoryPointer.from_string_to_wide_string(single_null_string) do |ptr|
expect {
ptr.read_arbitrary_wide_string_up_to(-1)
}.to raise_error(IndexError, /out of bounds/)
end
end
it "should return an empty string when the max_length is 0" do
FFI::MemoryPointer.from_string_to_wide_string(single_null_string) do |ptr|
expect(ptr.read_arbitrary_wide_string_up_to(0)).to eq("")
end
end
it "should return a string of max_length characters when specified" do
FFI::MemoryPointer.from_string_to_wide_string(single_null_string) do |ptr|
expect(ptr.read_arbitrary_wide_string_up_to(3)).to eq(string[0..2])
end
end
it "should return wide strings in UTF-8" do
FFI::MemoryPointer.from_string_to_wide_string(string) do |ptr|
read_string = ptr.read_arbitrary_wide_string_up_to
expect(read_string.encoding).to eq(Encoding::UTF_8)
end
end
it "should not raise an error when receiving a string containing invalid bytes in the destination encoding, when specifying :invalid => :replace" do
FFI::MemoryPointer.new(:byte, bad_string_bytes.count) do |ptr|
# uchar here is synonymous with byte
ptr.put_array_of_uchar(0, bad_string_bytes)
read_string = ptr.read_arbitrary_wide_string_up_to(ptr.size / 2, :single_null, :invalid => :replace)
expect(read_string).to eq("hello invalid world\uFFFD")
end
end
it "should raise an IndexError if there isn't a null terminator" do
# This only works when using a memory pointer with a known number of cells
# and size per cell, but not arbitrary Pointers
FFI::MemoryPointer.new(:wchar, 1) do |ptr|
ptr.write_array_of_uint8(a_wide_bytes)
expect {
ptr.read_arbitrary_wide_string_up_to(42)
}.to raise_error(IndexError, /out of bounds/)
end
end
it "should raise an IndexError if there isn't a double null terminator" do
# This only works when using a memory pointer with a known number of cells
# and size per cell, but not arbitrary Pointers
FFI::MemoryPointer.new(:wchar, 1) do |ptr|
ptr.write_array_of_uint8(a_wide_bytes)
expect {
ptr.read_arbitrary_wide_string_up_to(42, :double_null)
}.to raise_error(IndexError, /out of bounds/)
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/util/windows/access_control_entry_spec.rb | spec/unit/util/windows/access_control_entry_spec.rb | require 'spec_helper'
require 'puppet/util/windows'
describe "Puppet::Util::Windows::AccessControlEntry", :if => Puppet::Util::Platform.windows? do
let(:klass) { Puppet::Util::Windows::AccessControlEntry }
let(:sid) { 'S-1-5-18' }
let(:mask) { Puppet::Util::Windows::File::FILE_ALL_ACCESS }
it "creates an access allowed ace" do
ace = klass.new(sid, mask)
expect(ace.type).to eq(klass::ACCESS_ALLOWED_ACE_TYPE)
end
it "creates an access denied ace" do
ace = klass.new(sid, mask, 0, klass::ACCESS_DENIED_ACE_TYPE)
expect(ace.type).to eq(klass::ACCESS_DENIED_ACE_TYPE)
end
it "creates a non-inherited ace by default" do
ace = klass.new(sid, mask)
expect(ace).not_to be_inherited
end
it "creates an inherited ace" do
ace = klass.new(sid, mask, klass::INHERITED_ACE)
expect(ace).to be_inherited
end
it "creates a non-inherit-only ace by default" do
ace = klass.new(sid, mask)
expect(ace).not_to be_inherit_only
end
it "creates an inherit-only ace" do
ace = klass.new(sid, mask, klass::INHERIT_ONLY_ACE)
expect(ace).to be_inherit_only
end
context "when comparing aces" do
let(:ace1) { klass.new(sid, mask, klass::INHERIT_ONLY_ACE, klass::ACCESS_DENIED_ACE_TYPE) }
let(:ace2) { klass.new(sid, mask, klass::INHERIT_ONLY_ACE, klass::ACCESS_DENIED_ACE_TYPE) }
it "returns true if different objects have the same set of values" do
expect(ace1).to eq(ace2)
end
it "returns false if different objects have different sets of values" do
ace = klass.new(sid, mask)
expect(ace).not_to eq(ace1)
end
it "returns true when testing if two objects are eql?" do
ace1.eql?(ace2)
end
it "returns false when comparing object identity" do
expect(ace1).not_to be_equal(ace2)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/util/windows/eventlog_spec.rb | spec/unit/util/windows/eventlog_spec.rb | require 'spec_helper'
require 'puppet/util/windows'
describe Puppet::Util::Windows::EventLog, :if => Puppet::Util::Platform.windows? do
before(:each) { @event_log = Puppet::Util::Windows::EventLog.new }
after(:each) { @event_log.close }
describe "class constants" do
it "should define NULL_HANDLE as 0" do
expect(Puppet::Util::Windows::EventLog::NULL_HANDLE).to eq(0)
end
it "should define WIN32_FALSE as 0" do
expect(Puppet::Util::Windows::EventLog::WIN32_FALSE).to eq(0)
end
end
describe "self.open" do
it "sets a handle to the event log" do
default_name = Puppet::Util::Windows::String.wide_string('Puppet')
# return nil explicitly just to reinforce that we're not leaking eventlog handle
expect_any_instance_of(Puppet::Util::Windows::EventLog).to receive(:RegisterEventSourceW).with(anything, default_name).and_return(nil)
Puppet::Util::Windows::EventLog.new
end
context "when it fails to open the event log" do
before do
# RegisterEventSourceW will return NULL on failure
# Stubbing prevents leaking eventlog handle
allow_any_instance_of(Puppet::Util::Windows::EventLog).to receive(:RegisterEventSourceW).and_return(Puppet::Util::Windows::EventLog::NULL_HANDLE)
end
it "raises an exception warning that the event log failed to open" do
expect { Puppet::Util::Windows::EventLog.open('foo') }.to raise_error(Puppet::Util::Windows::EventLog::EventLogError, /failed to open Windows eventlog/)
end
it "passes the exit code to the exception constructor" do
fake_error = Puppet::Util::Windows::EventLog::EventLogError.new('foo', 87)
allow(FFI).to receive(:errno).and_return(87)
# All we're testing here is that the constructor actually receives the exit code from FFI.errno (87)
# We do so because `expect to...raise_error` doesn't support multiple parameter match arguments
# We return fake_error just because `raise` expects an exception class
expect(Puppet::Util::Windows::EventLog::EventLogError).to receive(:new).with(/failed to open Windows eventlog/, 87).and_return(fake_error)
expect { Puppet::Util::Windows::EventLog.open('foo') }.to raise_error(Puppet::Util::Windows::EventLog::EventLogError)
end
end
end
describe "#close" do
it "closes the handle to the event log" do
@handle = "12345"
allow_any_instance_of(Puppet::Util::Windows::EventLog).to receive(:RegisterEventSourceW).and_return(@handle)
event_log = Puppet::Util::Windows::EventLog.new
expect(event_log).to receive(:DeregisterEventSource).with(@handle).and_return(1)
event_log.close
end
end
describe "#report_event" do
it "raises an exception if the message passed is not a string" do
expect { @event_log.report_event(:data => 123, :event_type => nil, :event_id => nil) }.to raise_error(ArgumentError, /data must be a string/)
end
context "when an event report fails" do
before do
# ReportEventW returns 0 on failure, which is mapped to WIN32_FALSE
allow(@event_log).to receive(:ReportEventW).and_return(Puppet::Util::Windows::EventLog::WIN32_FALSE)
end
it "raises an exception warning that the event report failed" do
expect { @event_log.report_event(:data => 'foo', :event_type => Puppet::Util::Windows::EventLog::EVENTLOG_ERROR_TYPE, :event_id => 0x03) }.to raise_error(Puppet::Util::Windows::EventLog::EventLogError, /failed to report event/)
end
it "passes the exit code to the exception constructor" do
fake_error = Puppet::Util::Windows::EventLog::EventLogError.new('foo', 5)
allow(FFI).to receive(:errno).and_return(5)
# All we're testing here is that the constructor actually receives the exit code from FFI.errno (5)
# We do so because `expect to...raise_error` doesn't support multiple parameter match arguments
# We return fake_error just because `raise` expects an exception class
expect(Puppet::Util::Windows::EventLog::EventLogError).to receive(:new).with(/failed to report event/, 5).and_return(fake_error)
expect { @event_log.report_event(:data => 'foo', :event_type => Puppet::Util::Windows::EventLog::EVENTLOG_ERROR_TYPE, :event_id => 0x03) }.to raise_error(Puppet::Util::Windows::EventLog::EventLogError)
end
end
end
describe "self.to_native" do
it "raises an exception if the log level is not supported" do
expect { Puppet::Util::Windows::EventLog.to_native(:foo) }.to raise_error(ArgumentError)
end
# This is effectively duplicating the data assigned to the constants in
# Puppet::Util::Windows::EventLog but since these are public constants we
# ensure their values don't change lightly.
log_levels_to_type_and_id = {
:debug => [0x0004, 0x01],
:info => [0x0004, 0x01],
:notice => [0x0004, 0x01],
:warning => [0x0002, 0x02],
:err => [0x0001, 0x03],
:alert => [0x0001, 0x03],
:emerg => [0x0001, 0x03],
:crit => [0x0001, 0x03],
}
shared_examples_for "#to_native" do |level|
it "should return the correct INFORMATION_TYPE and ID" do
result = Puppet::Util::Windows::EventLog.to_native(level)
expect(result).to eq(log_levels_to_type_and_id[level])
end
end
log_levels_to_type_and_id.each_key do |level|
describe "logging at #{level}" do
it_should_behave_like "#to_native", level
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/util/windows/security_descriptor_spec.rb | spec/unit/util/windows/security_descriptor_spec.rb | require 'spec_helper'
require 'puppet/util/windows'
describe "Puppet::Util::Windows::SecurityDescriptor", :if => Puppet::Util::Platform.windows? do
let(:system_sid) { Puppet::Util::Windows::SID::LocalSystem }
let(:admins_sid) { Puppet::Util::Windows::SID::BuiltinAdministrators }
let(:group_sid) { Puppet::Util::Windows::SID::Nobody }
let(:new_sid) { 'S-1-5-32-500-1-2-3' }
def empty_dacl
Puppet::Util::Windows::AccessControlList.new
end
def system_ace_dacl
dacl = Puppet::Util::Windows::AccessControlList.new
dacl.allow(system_sid, 0x1)
dacl
end
context "owner" do
it "changes the owner" do
sd = Puppet::Util::Windows::SecurityDescriptor.new(system_sid, group_sid, system_ace_dacl)
sd.owner = new_sid
expect(sd.owner).to eq(new_sid)
end
it "performs a noop if the new owner is the same as the old one" do
dacl = system_ace_dacl
sd = Puppet::Util::Windows::SecurityDescriptor.new(system_sid, group_sid, dacl)
sd.owner = sd.owner
expect(sd.dacl.object_id).to eq(dacl.object_id)
end
it "prepends SYSTEM when security descriptor owner is no longer SYSTEM" do
sd = Puppet::Util::Windows::SecurityDescriptor.new(system_sid, group_sid, system_ace_dacl)
sd.owner = new_sid
aces = sd.dacl.to_a
expect(aces.size).to eq(2)
expect(aces[0].sid).to eq(system_sid)
expect(aces[1].sid).to eq(new_sid)
end
it "does not prepend SYSTEM when DACL already contains inherited SYSTEM ace" do
sd = Puppet::Util::Windows::SecurityDescriptor.new(admins_sid, system_sid, empty_dacl)
sd.dacl.allow(admins_sid, 0x1)
sd.dacl.allow(system_sid, 0x1, Puppet::Util::Windows::AccessControlEntry::INHERITED_ACE)
sd.owner = new_sid
aces = sd.dacl.to_a
expect(aces.size).to eq(2)
expect(aces[0].sid).to eq(new_sid)
end
it "does not prepend SYSTEM when security descriptor owner wasn't SYSTEM" do
sd = Puppet::Util::Windows::SecurityDescriptor.new(group_sid, group_sid, empty_dacl)
sd.dacl.allow(group_sid, 0x1)
sd.owner = new_sid
aces = sd.dacl.to_a
expect(aces.size).to eq(1)
expect(aces[0].sid).to eq(new_sid)
end
end
context "group" do
it "changes the group" do
sd = Puppet::Util::Windows::SecurityDescriptor.new(system_sid, group_sid, system_ace_dacl)
sd.group = new_sid
expect(sd.group).to eq(new_sid)
end
it "performs a noop if the new group is the same as the old one" do
dacl = system_ace_dacl
sd = Puppet::Util::Windows::SecurityDescriptor.new(system_sid, group_sid, dacl)
sd.group = sd.group
expect(sd.dacl.object_id).to eq(dacl.object_id)
end
it "prepends SYSTEM when security descriptor group is no longer SYSTEM" do
sd = Puppet::Util::Windows::SecurityDescriptor.new(new_sid, system_sid, system_ace_dacl)
sd.group = new_sid
aces = sd.dacl.to_a
expect(aces.size).to eq(2)
expect(aces[0].sid).to eq(system_sid)
expect(aces[1].sid).to eq(new_sid)
end
it "does not prepend SYSTEM when DACL already contains inherited SYSTEM ace" do
sd = Puppet::Util::Windows::SecurityDescriptor.new(admins_sid, admins_sid, empty_dacl)
sd.dacl.allow(admins_sid, 0x1)
sd.dacl.allow(system_sid, 0x1, Puppet::Util::Windows::AccessControlEntry::INHERITED_ACE)
sd.group = new_sid
aces = sd.dacl.to_a
expect(aces.size).to eq(2)
expect(aces[0].sid).to eq(new_sid)
end
it "does not prepend SYSTEM when security descriptor group wasn't SYSTEM" do
sd = Puppet::Util::Windows::SecurityDescriptor.new(group_sid, group_sid, empty_dacl)
sd.dacl.allow(group_sid, 0x1)
sd.group = new_sid
aces = sd.dacl.to_a
expect(aces.size).to eq(1)
expect(aces[0].sid).to eq(new_sid)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/util/package/version/pip_spec.rb | spec/unit/util/package/version/pip_spec.rb | require 'spec_helper'
require 'puppet/util/package/version/pip'
describe Puppet::Util::Package::Version::Pip do
describe "initialization" do
shared_examples_for 'a valid version' do |input_version, output = input_version|
[input_version, input_version.swapcase].each do |input|
it "transforms #{input} back to string(#{output}) succesfully" do
version = described_class.parse(input)
expect(version.to_s).to eq(output)
end
end
describe "comparison" do
version = described_class.parse(input_version)
# rubocop:disable UselessComparison
it "#{input_version} shouldn't be lesser than itself" do
expect(version < version).to eq(false)
end
it "#{input_version} shouldn't be greater than itself" do
expect(version > version).to eq(false)
end
it "#{input_version} shouldn't be equal with itself" do
expect(version != version).to eq(false)
end
it "#{input_version} should be equal to itself" do
expect(version == version).to eq(true)
end
end
end
shared_examples_for 'an invalid version' do |invalid_input|
[invalid_input, invalid_input.swapcase].each do |input|
it "should not be able to transform #{invalid_input} to string" do
expect{ described_class.parse(input) }.to raise_error(described_class::ValidationFailure)
end
end
describe "comparison" do
valid_version = described_class.parse("1.0")
it "should raise error when checking if #{invalid_input} is lesser than a valid version" do
expect{ valid_version < invalid_input }.to raise_error(described_class::ValidationFailure)
end
it "should raise error when checking if #{invalid_input} is greater than a valid version" do
expect{ valid_version > invalid_input }.to raise_error(described_class::ValidationFailure)
end
it "should raise error when checking if #{invalid_input} is greater or equal than a valid version" do
expect{ valid_version >= invalid_input }.to raise_error(described_class::ValidationFailure)
end
it "should raise error when checking if #{invalid_input} is lesser or equal than a valid version" do
expect{ valid_version <= invalid_input }.to raise_error(described_class::ValidationFailure)
end
end
end
describe "when only release segment is present in provided version" do
context "should work with any number of integer elements" do
context "when it has 1 element" do
it_should_behave_like 'a valid version', "1"
end
context "when it has 2 elements" do
it_should_behave_like 'a valid version', "1.1"
end
context "when it has 3 elements" do
it_should_behave_like 'a valid version', "1.1.1"
end
context "when it has 4 elements" do
it_should_behave_like 'a valid version', "1.1.1.1"
end
context "when it has 10 elements" do
it_should_behave_like 'a valid version', "1.1.1.1.1.1.1.1.1.1"
end
end
describe "should work with elements which are zero" do
context "when it ends with 1 zero" do
it_should_behave_like 'a valid version', "1.0"
end
context "when it ends with 2 zeros" do
it_should_behave_like 'a valid version', "1.0.0"
end
context "when it ends with 3 zeros" do
it_should_behave_like 'a valid version', "1.0.0.0"
end
context "when it starts with 1 zero" do
it_should_behave_like 'a valid version', "0.1"
end
context "when it starts with 2 zeros" do
it_should_behave_like 'a valid version', "0.0.1"
end
context "when it starts with 3 zeros" do
it_should_behave_like 'a valid version', "0.0.0.1"
end
context "when it is just a zero" do
it_should_behave_like 'a valid version', "0"
end
context "when it is full of just zeros" do
it_should_behave_like 'a valid version', "0.0.0"
end
end
describe "should work with elements containing multiple digits" do
context "when it has two digit elements" do
it_should_behave_like 'a valid version', "1.10.1"
end
context "when it has three digit elements" do
it_should_behave_like 'a valid version', "1.101.1.11"
end
context "when it has four digit elements" do
it_should_behave_like 'a valid version', "2019.0.11"
end
context "when it has a numerical element starting with zero" do
# the zero will dissapear
it_should_behave_like 'a valid version', "1.09.10", "1.9.10"
end
context "when it starts with multiple zeros" do
# the zeros will dissapear
it_should_behave_like 'a valid version', "0010.0000.0011", "10.0.11"
end
end
context "should fail because of misplaced letters" do
context "when it starts with letters" do
it_should_behave_like 'an invalid version', "d.2"
it_should_behave_like 'an invalid version', "ee.2"
end
context "when it has only letters" do
it_should_behave_like 'an invalid version', "d.c"
it_should_behave_like 'an invalid version', "dd.c"
end
end
end
describe "when the epoch segment is present in provided version" do
context "should work when epoch is an integer" do
context "when epoch has 1 digit" do
it_should_behave_like 'a valid version', "1!1.0.0"
end
context "when epoch has 2 digits" do
it_should_behave_like 'a valid version', "10!1.0.0"
end
context "when epoch is zero" do
# versions without epoch specified are considered to have epoch 0
# it is accepted as input but it should be ignored at output
it_should_behave_like 'a valid version', "0!1.0.0", "1.0.0"
end
end
context "should fail when epoch contains letters" do
context "when epoch starts with a letter" do
it_should_behave_like 'an invalid version', "a9!1.0.0"
end
context "when epoch ends with a letter" do
it_should_behave_like 'an invalid version', "9a!1.0.0"
end
end
end
describe "when the pre-release segment is present in provided version" do
context "when pre-release contains the letter a" do
it_should_behave_like 'a valid version', "1.0a", "1.0a0"
it_should_behave_like 'a valid version', "1.0a0"
end
context "when pre-release contains the letter b" do
it_should_behave_like 'a valid version', "1.0b", "1.0b0"
it_should_behave_like 'a valid version', "1.0b0"
end
context "when pre-release contains the letter c" do
it_should_behave_like 'a valid version', "1.0c", "1.0rc0"
it_should_behave_like 'a valid version', "1.0c0", "1.0rc0"
end
context "when pre-release contains the string alpha" do
it_should_behave_like 'a valid version', "1.0alpha", "1.0a0"
it_should_behave_like 'a valid version', "1.0alpha0", "1.0a0"
end
context "when pre-release contains the string beta" do
it_should_behave_like 'a valid version', "1.0beta", "1.0b0"
it_should_behave_like 'a valid version', "1.0beta0", "1.0b0"
end
context "when pre-release contains the string rc" do
it_should_behave_like 'a valid version', "1.0rc", "1.0rc0"
it_should_behave_like 'a valid version', "1.0rc0", "1.0rc0"
end
context "when pre-release contains the string pre" do
it_should_behave_like 'a valid version', "1.0pre", "1.0rc0"
it_should_behave_like 'a valid version', "1.0pre0", "1.0rc0"
end
context "when pre-release contains the string preview" do
it_should_behave_like 'a valid version', "1.0preview", "1.0rc0"
it_should_behave_like 'a valid version', "1.0preview0", "1.0rc0"
end
context "when pre-release contains multiple zeros at the beginning" do
it_should_behave_like 'a valid version', "1.0.beta.00", "1.0b0"
it_should_behave_like 'a valid version', "1.0.beta.002", "1.0b2"
end
context "when pre-release elements are separated by dots" do
it_should_behave_like 'a valid version', "1.0.alpha", "1.0a0"
it_should_behave_like 'a valid version', "1.0.alpha.0", "1.0a0"
it_should_behave_like 'a valid version', "1.0.alpha.2", "1.0a2"
end
context "when pre-release elements are separated by dashes" do
it_should_behave_like 'a valid version', "1.0-alpha", "1.0a0"
it_should_behave_like 'a valid version', "1.0-alpha-0", "1.0a0"
it_should_behave_like 'a valid version', "1.0-alpha-2", "1.0a2"
end
context "when pre-release elements are separated by underscores" do
it_should_behave_like 'a valid version', "1.0_alpha", "1.0a0"
it_should_behave_like 'a valid version', "1.0_alpha_0", "1.0a0"
it_should_behave_like 'a valid version', "1.0_alpha_2", "1.0a2"
end
context "when pre-release elements are separated by mixed symbols" do
it_should_behave_like 'a valid version', "1.0-alpha_5", "1.0a5"
it_should_behave_like 'a valid version', "1.0-alpha.5", "1.0a5"
it_should_behave_like 'a valid version', "1.0_alpha-5", "1.0a5"
it_should_behave_like 'a valid version', "1.0_alpha.5", "1.0a5"
it_should_behave_like 'a valid version', "1.0.alpha-5", "1.0a5"
it_should_behave_like 'a valid version', "1.0.alpha_5", "1.0a5"
end
end
describe "when the post-release segment is present in provided version" do
context "when post-release is just an integer" do
it_should_behave_like 'a valid version', "1.0-9", "1.0.post9"
it_should_behave_like 'a valid version', "1.0-10", "1.0.post10"
end
context "when post-release is just an integer and starts with zero" do
it_should_behave_like 'a valid version', "1.0-09", "1.0.post9"
it_should_behave_like 'a valid version', "1.0-009", "1.0.post9"
end
context "when post-release contains the string post" do
it_should_behave_like 'a valid version', "1.0post", "1.0.post0"
it_should_behave_like 'a valid version', "1.0post0", "1.0.post0"
it_should_behave_like 'a valid version', "1.0post1", "1.0.post1"
it_should_behave_like 'an invalid version', "1.0-0.post1"
end
context "when post-release contains the string rev" do
it_should_behave_like 'a valid version', "1.0rev", "1.0.post0"
it_should_behave_like 'a valid version', "1.0rev0", "1.0.post0"
it_should_behave_like 'a valid version', "1.0rev1", "1.0.post1"
it_should_behave_like 'an invalid version', "1.0-0.rev1"
end
context "when post-release contains the letter r" do
it_should_behave_like 'a valid version', "1.0r", "1.0.post0"
it_should_behave_like 'a valid version', "1.0r0", "1.0.post0"
it_should_behave_like 'a valid version', "1.0r1", "1.0.post1"
it_should_behave_like 'an invalid version', "1.0-0.r1"
end
context "when post-release elements are separated by dashes" do
it_should_behave_like 'a valid version', "1.0-post-22", "1.0.post22"
it_should_behave_like 'a valid version', "1.0-rev-22", "1.0.post22"
it_should_behave_like 'a valid version', "1.0-r-22", "1.0.post22"
end
context "when post-release elements are separated by underscores" do
it_should_behave_like 'a valid version', "1.0_post_22", "1.0.post22"
it_should_behave_like 'a valid version', "1.0_rev_22", "1.0.post22"
it_should_behave_like 'a valid version', "1.0_r_22", "1.0.post22"
end
context "when post-release elements are separated by dots" do
it_should_behave_like 'a valid version', "1.0.post.22", "1.0.post22"
it_should_behave_like 'a valid version', "1.0.rev.22", "1.0.post22"
it_should_behave_like 'a valid version', "1.0.r.22", "1.0.post22"
end
context "when post-release elements are separated by mixed symbols" do
it_should_behave_like 'a valid version', "1.0-r_5", "1.0.post5"
it_should_behave_like 'a valid version', "1.0-r.5", "1.0.post5"
it_should_behave_like 'a valid version', "1.0_r-5", "1.0.post5"
it_should_behave_like 'a valid version', "1.0_r.5", "1.0.post5"
it_should_behave_like 'a valid version', "1.0.r-5", "1.0.post5"
it_should_behave_like 'a valid version', "1.0.r_5", "1.0.post5"
end
end
describe "when the dev release segment is present in provided version" do
context "when dev release is only the keyword dev" do
it_should_behave_like 'a valid version', "1.0dev", "1.0.dev0"
it_should_behave_like 'a valid version', "1.0-dev", "1.0.dev0"
it_should_behave_like 'a valid version', "1.0_dev", "1.0.dev0"
it_should_behave_like 'a valid version', "1.0.dev", "1.0.dev0"
end
context "when dev release contains the keyword dev and a number" do
it_should_behave_like 'a valid version', "1.0dev2", "1.0.dev2"
it_should_behave_like 'a valid version', "1.0-dev33", "1.0.dev33"
it_should_behave_like 'a valid version', "1.0.dev11", "1.0.dev11"
it_should_behave_like 'a valid version', "1.0_dev101", "1.0.dev101"
end
context "when dev release's number element starts with 0" do
it_should_behave_like 'a valid version', "1.0dev02", "1.0.dev2"
it_should_behave_like 'a valid version', "1.0-dev033", "1.0.dev33"
it_should_behave_like 'a valid version', "1.0_dev0101", "1.0.dev101"
it_should_behave_like 'a valid version', "1.0.dev00011", "1.0.dev11"
end
context "when dev release elements are separated by dashes" do
it_should_behave_like 'a valid version', "1.0-dev", "1.0.dev0"
it_should_behave_like 'a valid version', "1.0-dev-2", "1.0.dev2"
it_should_behave_like 'a valid version', "1.0-dev-22", "1.0.dev22"
end
context "when dev release elements are separated by underscores" do
it_should_behave_like 'a valid version', "1.0_dev", "1.0.dev0"
it_should_behave_like 'a valid version', "1.0_dev_2", "1.0.dev2"
it_should_behave_like 'a valid version', "1.0_dev_22", "1.0.dev22"
end
context "when dev release elements are separated by dots" do
it_should_behave_like 'a valid version', "1.0.dev", "1.0.dev0"
it_should_behave_like 'a valid version', "1.0.dev.2", "1.0.dev2"
it_should_behave_like 'a valid version', "1.0.dev.22", "1.0.dev22"
end
context "when dev release elements are separated by mixed symbols" do
it_should_behave_like 'a valid version', "1.0-dev_5", "1.0.dev5"
it_should_behave_like 'a valid version', "1.0-dev.5", "1.0.dev5"
it_should_behave_like 'a valid version', "1.0_dev-5", "1.0.dev5"
it_should_behave_like 'a valid version', "1.0_dev.5", "1.0.dev5"
it_should_behave_like 'a valid version', "1.0.dev-5", "1.0.dev5"
it_should_behave_like 'a valid version', "1.0.dev_5", "1.0.dev5"
end
end
describe "when the local version segment is present in provided version" do
it_should_behave_like 'an invalid version', "1.0+"
context "when local version is just letters" do
it_should_behave_like 'a valid version', "1.0+local"
it_should_behave_like 'a valid version', "1.0+Local", "1.0+local"
end
context "when local version contains numbers" do
it_should_behave_like 'a valid version', "1.0+10"
it_should_behave_like 'a valid version', "1.0+01", "1.0+1"
it_should_behave_like 'a valid version', "1.0+01L", "1.0+01l"
it_should_behave_like 'a valid version', "1.0+L101L", "1.0+l101l"
end
context "when local version contains multiple elements" do
it_should_behave_like 'a valid version', "1.0+10.local"
it_should_behave_like 'a valid version', "1.0+abc.def.ghi"
it_should_behave_like 'a valid version', "1.0+01.abc", "1.0+1.abc"
it_should_behave_like 'a valid version', "1.0+01L.0001", "1.0+01l.1"
it_should_behave_like 'a valid version', "1.0+L101L.local", "1.0+l101l.local"
it_should_behave_like 'a valid version', "1.0+dash-undrsc_dot.5", "1.0+dash.undrsc.dot.5"
end
end
end
describe "comparison of versions" do
# This array must remain sorted (smallest to highest version).
versions = [
"0.1",
"0.10",
"0.10.1",
"0.10.1.0.1",
"1.0.dev456",
"1.0a1",
"1.0a2.dev456",
"1.0a12.dev456",
"1.0a12",
"1.0b1.dev456",
"1.0b2",
"1.0b2.post345.dev456",
"1.0b2.post345",
"1.0b2-346",
"1.0c1.dev456",
"1.0c1",
"1.0rc2",
"1.0c3",
"1.0",
"1.0.post456.dev34",
"1.0.post456",
"1.1.dev1",
"1.2",
"1.2+123abc",
"1.2+123abc456",
"1.2+abc",
"1.2+abc123",
"1.2+abc123-def2",
"1.2+abc123-def2-0",
"1.2+abc123def",
"1.2+1234.abc",
"1.2+123456",
"1.2.r32+123456",
"1.2.rev33+123456",
"1!1.0b2.post345.dev456",
"1!1.0",
"1!1.0.post456.dev34",
"1!1.0.post456",
"1!1.2.rev33+123456",
"2!2.3.4.alpha5.rev6.dev7+abc89"
]
it "should find versions list to be already sorted" do
sorted_versions = versions.sort do |x,y|
described_class.compare(x, y)
end
expect(versions).to eq(sorted_versions)
end
versions.combination(2).to_a.each do |version_pair|
lower_version = described_class.parse(version_pair.first)
greater_version = described_class.parse(version_pair.last)
it "#{lower_version} should be equal to #{lower_version}" do
expect(lower_version == lower_version).to eq(true)
end
it "#{lower_version} should not be equal to #{greater_version}" do
expect(lower_version != greater_version).to eq(true)
end
it "#{lower_version} should be lower than #{greater_version}" do
expect(lower_version < greater_version).to eq(true)
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/util/package/version/debian_spec.rb | spec/unit/util/package/version/debian_spec.rb | require 'spec_helper'
require 'puppet/util/package/version/debian'
describe Puppet::Util::Package::Version::Debian do
context "when creating new version should fail" do
it "if is parsing symbols" do
expect { described_class.parse(:absent) }.to raise_error(described_class::ValidationFailure)
end
end
context "when creating new version" do
it "is parsing basic version" do
v = described_class.parse('1:20191210.1-0ubuntu0.19.04.2')
expect(v.epoch).to eql(1)
expect(v.upstream_version).to eql('20191210.1')
expect(v.debian_revision).to eql('0ubuntu0.19.04.2')
end
it "is parsing no epoch basic version" do
v = described_class.parse('20191210.1-0ubuntu0.19.04.2')
expect(v.epoch).to eql(0)
expect(v.upstream_version).to eql('20191210.1')
expect(v.debian_revision).to eql('0ubuntu0.19.04.2')
end
it "is parsing no debian revision basic version" do
v = described_class.parse('2.42.1+19.04')
expect(v.epoch).to eql(0)
expect(v.upstream_version).to eql('2.42.1+19.04')
expect(v.debian_revision).to eql(nil)
end
it "is parsing no epoch complex version" do
v = described_class.parse('3.32.2+git20190711-2ubuntu1~19.04.1')
expect(v.epoch).to eql(0)
expect(v.upstream_version).to eql('3.32.2+git20190711')
expect(v.debian_revision).to eql('2ubuntu1~19.04.1')
end
it "is parsing even more complex version" do
v = described_class.parse('5:1.0.0+git-20190109.133f4c4-0ubuntu2')
expect(v.epoch).to eql(5)
expect(v.upstream_version).to eql('1.0.0+git-20190109.133f4c4')
expect(v.debian_revision).to eql('0ubuntu2')
end
end
context "when comparing two versions" do
it "epoch has precedence" do
first = described_class.parse('9:99-99')
second = described_class.parse('10:01-01')
expect(first < second).to eql(true)
end
it "handles equals letters-only versions" do
lower = described_class.parse('abd-def')
higher = described_class.parse('abd-def')
expect(lower == higher).to eql(true)
end
it "shorter version is smaller" do
lower = described_class.parse('abd-de')
higher = described_class.parse('abd-def')
expect(lower < higher).to eql(true)
end
it "shorter version is smaller even with digits" do
lower = described_class.parse('a1b2d-d3e')
higher = described_class.parse('a1b2d-d3ef')
expect(lower < higher).to eql(true)
end
it "shorter version is smaller when number is less" do
lower = described_class.parse('a1b2d-d9')
higher = described_class.parse('a1b2d-d13')
expect(lower < higher).to eql(true)
end
it "handles ~ version" do
lower = described_class.parse('a1b2d-d10~')
higher = described_class.parse('a1b2d-d10')
expect(lower < higher).to eql(true)
end
it "handles letters versus -" do
lower = described_class.parse('a1b2d-d1a')
higher = described_class.parse('a1b2d-d1-')
expect(lower < higher).to eql(true)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/util/package/version/rpm_spec.rb | spec/unit/util/package/version/rpm_spec.rb | require 'spec_helper'
require 'puppet/util/package/version/rpm'
describe Puppet::Util::Package::Version::Rpm do
context "when parsing an invalid version" do
it "raises ArgumentError" do
expect { described_class.parse(:absent)}.to raise_error(ArgumentError)
end
end
context "when creating new version" do
it "is parsing basic version" do
v = described_class.parse('1:2.8.8-1.el6')
expect([v.epoch, v.version, v.release, v.arch ]).to eq(['1', '2.8.8', '1.el6' , nil])
end
it "is parsing no epoch basic version" do
v = described_class.parse('2.8.8-1.el6')
expect([v.epoch, v.version, v.release, v.arch ]).to eq([nil, '2.8.8', '1.el6', nil])
end
it "is parsing no epoch basic short version" do
v = described_class.parse('7.15-8.fc29')
expect([v.epoch, v.version, v.release, v.arch ]).to eq([nil, '7.15', '8.fc29', nil])
end
it "is parsing no epoch and no release basic version" do
v = described_class.parse('2.8.8')
expect([v.epoch, v.version, v.release, v.arch ]).to eq([nil, '2.8.8', nil, nil])
end
it "is parsing no epoch complex version" do
v = described_class.parse('1.4-0.24.20120830CVS.fc31')
expect([v.epoch, v.version, v.release, v.arch ]).to eq([nil, '1.4', '0.24.20120830CVS.fc31', nil])
end
end
context "when comparing two versions" do
context 'with invalid version' do
it 'raises ArgumentError' do
version = described_class.parse('0:1.5.3-3.el6')
invalid = 'invalid'
expect { version < invalid }.to \
raise_error(ArgumentError, 'Cannot compare, as invalid is not a Rpm Version')
end
end
context 'with valid versions' do
it "epoch has precedence" do
lower = described_class.parse('0:1.5.3-3.el6')
higher = described_class.parse('1:1.7.0-15.fc29')
expect(lower).to be < higher
end
it 'handles no epoch as 0 epoch' do
lower = described_class.parse('1.5.3-3.el6')
higher = described_class.parse('1:1.7.0-15.fc29')
expect(lower).to be < higher
end
it "handles equals letters-only versions" do
first = described_class.parse('abd-def')
second = described_class.parse('abd-def')
expect(first).to eq(second)
end
it "shorter version is smaller letters-only versions" do
lower = described_class.parse('ab')
higher = described_class.parse('abd')
expect(lower).to be < higher
end
it "shorter version is smaller even with digits" do
lower = described_class.parse('1.7')
higher = described_class.parse('1.7.0')
expect(lower).to be < higher
end
it "shorter version is smaller when number is less" do
lower = described_class.parse('1.7.0')
higher = described_class.parse('1.7.1')
expect(lower).to be < higher
end
it "shorter release is smaller " do
lower = described_class.parse('1.7.0-11.fc26')
higher = described_class.parse('1.7.0-11.fc27')
expect(lower).to be < higher
end
it "release letters are smaller letters-only" do
lower = described_class.parse('1.7.0-abc')
higher = described_class.parse('1.7.0-abd')
expect(lower).to be < higher
end
it "shorter release is smaller" do
lower = described_class.parse('1.7.0-11.fc2')
higher = described_class.parse('1.7.0-11.fc17')
expect(lower).to be < higher
end
it "handles equal release" do
first = described_class.parse('1.7.0-11.fc27')
second = described_class.parse('1.7.0-11.fc27')
expect(first).to eq(second)
end
end
context 'when one has no epoch' do
it 'handles no epoch as zero' do
version1 = described_class.parse('1:1.2')
version2 = described_class.parse('1.4')
expect(version1).to be > version2
expect(version2).to be < version1
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/util/package/version/range_spec.rb | spec/unit/util/package/version/range_spec.rb | require 'spec_helper'
require 'puppet/util/package/version/range'
class IntegerVersion
class ValidationFailure < ArgumentError; end
include Comparable
REGEX_FULL = '(\d+)'.freeze
REGEX_FULL_RX = /\A#{REGEX_FULL}\Z/.freeze
def self.parse(ver)
match, version = *ver.match(REGEX_FULL_RX)
raise ValidationFailure, "Unable to parse '#{ver}' as a version identifier" unless match
new(version).freeze
end
attr_reader :version
def initialize(version)
@version = version.to_i
end
def <=>(other)
@version <=> other.version
end
end
describe Puppet::Util::Package::Version::Range do
context 'when creating new version range' do
it 'should raise unless String is passed' do
expect { Puppet::Util::Package::Version::Range.parse(:abc, IntegerVersion) }.to raise_error(Puppet::Util::Package::Version::Range::ValidationFailure)
end
it 'should raise if operator is not implemented' do
expect { Puppet::Util::Package::Version::Range.parse('=a', IntegerVersion) }.to raise_error(Puppet::Util::Package::Version::Range::ValidationFailure)
end
it 'should raise if operator cannot be parsed' do
expect { Puppet::Util::Package::Version::Range.parse('~=a', IntegerVersion) }.to raise_error(IntegerVersion::ValidationFailure)
end
it 'should raise if version cannot be parsed' do
expect { Puppet::Util::Package::Version::Range.parse('>=a', IntegerVersion) }.to raise_error(IntegerVersion::ValidationFailure)
end
end
context 'when creating new version range with regular version' do
it 'it does not include greater version' do
vr = Puppet::Util::Package::Version::Range.parse('3', IntegerVersion)
v = IntegerVersion.parse('4')
expect(vr.include?(v)).to eql(false)
end
it 'it includes specified version' do
vr = Puppet::Util::Package::Version::Range.parse('3', IntegerVersion)
v = IntegerVersion.parse('3')
expect(vr.include?(v)).to eql(true)
end
it 'it does not include lower version' do
vr = Puppet::Util::Package::Version::Range.parse('3', IntegerVersion)
v = IntegerVersion.parse('2')
expect(vr.include?(v)).to eql(false)
end
end
context 'when creating new version range with greater or equal operator' do
it 'it includes greater version' do
vr = Puppet::Util::Package::Version::Range.parse('>=3', IntegerVersion)
v = IntegerVersion.parse('4')
expect(vr.include?(v)).to eql(true)
end
it 'it includes specified version' do
vr = Puppet::Util::Package::Version::Range.parse('>=3', IntegerVersion)
v = IntegerVersion.parse('3')
expect(vr.include?(v)).to eql(true)
end
it 'it does not include lower version' do
vr = Puppet::Util::Package::Version::Range.parse('>=3', IntegerVersion)
v = IntegerVersion.parse('2')
expect(vr.include?(v)).to eql(false)
end
end
context 'when creating new version range with greater operator' do
it 'it includes greater version' do
vr = Puppet::Util::Package::Version::Range.parse('>3', IntegerVersion)
v = IntegerVersion.parse('10')
expect(vr.include?(v)).to eql(true)
end
it 'it does not include specified version' do
vr = Puppet::Util::Package::Version::Range.parse('>3', IntegerVersion)
v = IntegerVersion.parse('3')
expect(vr.include?(v)).to eql(false)
end
it 'it does not include lower version' do
vr = Puppet::Util::Package::Version::Range.parse('>3', IntegerVersion)
v = IntegerVersion.parse('1')
expect(vr.include?(v)).to eql(false)
end
end
context 'when creating new version range with lower or equal operator' do
it 'it does not include greater version' do
vr = Puppet::Util::Package::Version::Range.parse('<=3', IntegerVersion)
v = IntegerVersion.parse('5')
expect(vr.include?(v)).to eql(false)
end
it 'it includes specified version' do
vr = Puppet::Util::Package::Version::Range.parse('<=3', IntegerVersion)
v = IntegerVersion.parse('3')
expect(vr.include?(v)).to eql(true)
end
it 'it includes lower version' do
vr = Puppet::Util::Package::Version::Range.parse('<=3', IntegerVersion)
v = IntegerVersion.parse('1')
expect(vr.include?(v)).to eql(true)
end
end
context 'when creating new version range with lower operator' do
it 'it does not include greater version' do
vr = Puppet::Util::Package::Version::Range.parse('<3', IntegerVersion)
v = IntegerVersion.parse('8')
expect(vr.include?(v)).to eql(false)
end
it 'it does not include specified version' do
vr = Puppet::Util::Package::Version::Range.parse('<3', IntegerVersion)
v = IntegerVersion.parse('3')
expect(vr.include?(v)).to eql(false)
end
it 'it includes lower version' do
vr = Puppet::Util::Package::Version::Range.parse('<3', IntegerVersion)
v = IntegerVersion.parse('2')
expect(vr.include?(v)).to eql(true)
end
end
context 'when creating new version range with interval' do
it 'it does not include greater version' do
vr = Puppet::Util::Package::Version::Range.parse('>3 <=5', IntegerVersion)
v = IntegerVersion.parse('7')
expect(vr.include?(v)).to eql(false)
end
it 'it includes specified max interval value' do
vr = Puppet::Util::Package::Version::Range.parse('>3 <=5', IntegerVersion)
v = IntegerVersion.parse('5')
expect(vr.include?(v)).to eql(true)
end
it 'it includes in interval version' do
vr = Puppet::Util::Package::Version::Range.parse('>3 <=5', IntegerVersion)
v = IntegerVersion.parse('4')
expect(vr.include?(v)).to eql(true)
end
it 'it does not include min interval value ' do
vr = Puppet::Util::Package::Version::Range.parse('>3 <=5', IntegerVersion)
v = IntegerVersion.parse('3')
expect(vr.include?(v)).to eql(false)
end
it 'it does not include lower value ' do
vr = Puppet::Util::Package::Version::Range.parse('>3 <=5', IntegerVersion)
v = IntegerVersion.parse('2')
expect(vr.include?(v)).to eql(false)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/util/log/destinations_spec.rb | spec/unit/util/log/destinations_spec.rb | require 'spec_helper'
require 'puppet/util/json'
require 'puppet/util/log'
describe Puppet::Util::Log.desttypes[:report] do
before do
@dest = Puppet::Util::Log.desttypes[:report]
end
it "should require a report at initialization" do
expect(@dest.new("foo").report).to eq("foo")
end
it "should send new messages to the report" do
report = double('report')
dest = @dest.new(report)
expect(report).to receive(:<<).with("my log")
dest.handle "my log"
end
end
describe Puppet::Util::Log.desttypes[:file] do
include PuppetSpec::Files
before do
@class = Puppet::Util::Log.desttypes[:file]
end
it "should default to autoflush false" do
expect(@class.new(tmpfile('log')).autoflush).to eq(true)
end
describe "when matching" do
shared_examples_for "file destination" do
it "should match an absolute path" do
expect(@class.match?(abspath)).to be_truthy
end
it "should not match a relative path" do
expect(@class.match?(relpath)).to be_falsey
end
end
describe "on POSIX systems", :unless => Puppet::Util::Platform.windows? do
describe "with a normal file" do
let (:parent) { Pathname.new('/tmp') }
let (:abspath) { '/tmp/log' }
let (:relpath) { 'log' }
it_behaves_like "file destination"
end
describe "with a JSON file" do
let (:abspath) { '/tmp/log.json' }
let (:relpath) { 'log.json' }
it_behaves_like "file destination"
it "should log messages as JSON" do
msg = Puppet::Util::Log.new(:level => :info, :message => "don't panic")
dest = @class.new(abspath)
dest.handle(msg)
expect(JSON.parse(File.read(abspath) + ']')).to include(a_hash_including({"message" => "don't panic"}))
end
end
describe "with a JSON lines file" do
let (:abspath) { '/tmp/log.jsonl' }
let (:relpath) { 'log.jsonl' }
it_behaves_like "file destination"
it "should log messages as JSON lines" do
msg1 = Puppet::Util::Log.new(:level => :info, :message => "don't panic")
msg2 = Puppet::Util::Log.new(:level => :err, :message => "panic!")
dest = @class.new(abspath)
dest.handle(msg1)
dest.handle(msg2)
lines = IO.readlines(abspath)
expect(JSON.parse(lines[-2])).to include("level" => "info", "message" => "don't panic")
expect(JSON.parse(lines[-1])).to include("level" => "err", "message" => "panic!")
end
end
end
describe "on Windows systems", :if => Puppet::Util::Platform.windows? do
let (:abspath) { 'C:\\temp\\log.txt' }
let (:relpath) { 'log.txt' }
it_behaves_like "file destination"
end
end
end
describe Puppet::Util::Log.desttypes[:syslog] do
let (:klass) { Puppet::Util::Log.desttypes[:syslog] }
# these tests can only be run when syslog is present, because
# we can't stub the top-level Syslog module
describe "when syslog is available", :if => Puppet.features.syslog? do
before :each do
allow(Syslog).to receive(:opened?).and_return(false)
allow(Syslog).to receive(:const_get).and_return("LOG_KERN", 0)
allow(Syslog).to receive(:open)
end
it "should open syslog" do
expect(Syslog).to receive(:open)
klass.new
end
it "should close syslog" do
expect(Syslog).to receive(:close)
dest = klass.new
dest.close
end
it "should send messages to syslog" do
syslog = double('syslog')
expect(syslog).to receive(:info).with("don't panic")
allow(Syslog).to receive(:open).and_return(syslog)
msg = Puppet::Util::Log.new(:level => :info, :message => "don't panic")
dest = klass.new
dest.handle(msg)
end
end
describe "when syslog is unavailable" do
it "should not be a suitable log destination" do
allow(Puppet.features).to receive(:syslog?).and_return(false)
expect(klass.suitable?(:syslog)).to be_falsey
end
end
end
describe Puppet::Util::Log.desttypes[:logstash_event] do
describe "when using structured log format with logstash_event schema" do
before :each do
@msg = Puppet::Util::Log.new(:level => :info, :message => "So long, and thanks for all the fish.", :source => "a dolphin")
end
it "format should fix the hash to have the correct structure" do
dest = described_class.new
result = dest.format(@msg)
expect(result["version"]).to eq(1)
expect(result["level"]).to eq('info')
expect(result["message"]).to eq("So long, and thanks for all the fish.")
expect(result["source"]).to eq("a dolphin")
# timestamp should be within 10 seconds
expect(Time.parse(result["@timestamp"])).to be >= ( Time.now - 10 )
end
it "format returns a structure that can be converted to json" do
dest = described_class.new
hash = dest.format(@msg)
Puppet::Util::Json.load(hash.to_json)
end
it "handle should send the output to stdout" do
expect($stdout).to receive(:puts).once
dest = described_class.new
dest.handle(@msg)
end
end
end
describe Puppet::Util::Log.desttypes[:console] do
let (:klass) { Puppet::Util::Log.desttypes[:console] }
it "should support color output" do
Puppet[:color] = true
expect(subject.colorize(:red, 'version')).to eq("\e[0;31mversion\e[0m")
end
it "should withhold color output when not appropriate" do
Puppet[:color] = false
expect(subject.colorize(:red, 'version')).to eq("version")
end
it "should handle multiple overlapping colors in a stack-like way" do
Puppet[:color] = true
vstring = subject.colorize(:red, 'version')
expect(subject.colorize(:green, "(#{vstring})")).to eq("\e[0;32m(\e[0;31mversion\e[0;32m)\e[0m")
end
it "should handle resets in a stack-like way" do
Puppet[:color] = true
vstring = subject.colorize(:reset, 'version')
expect(subject.colorize(:green, "(#{vstring})")).to eq("\e[0;32m(\e[mversion\e[0;32m)\e[0m")
end
it "should include the log message's source/context in the output when available" do
Puppet[:color] = false
expect($stdout).to receive(:puts).with("Info: a hitchhiker: don't panic")
msg = Puppet::Util::Log.new(:level => :info, :message => "don't panic", :source => "a hitchhiker")
dest = klass.new
dest.handle(msg)
end
end
describe ":eventlog", :if => Puppet::Util::Platform.windows? do
let(:klass) { Puppet::Util::Log.desttypes[:eventlog] }
def expects_message_with_type(klass, level, eventlog_type, eventlog_id)
eventlog = double('eventlog')
expect(eventlog).to receive(:report_event).with(hash_including(:event_type => eventlog_type, :event_id => eventlog_id, :data => "a hitchhiker: don't panic"))
allow(Puppet::Util::Windows::EventLog).to receive(:open).and_return(eventlog)
msg = Puppet::Util::Log.new(:level => level, :message => "don't panic", :source => "a hitchhiker")
dest = klass.new
dest.handle(msg)
end
it "supports the eventlog feature" do
expect(Puppet.features.eventlog?).to be_truthy
end
it "should truncate extremely long log messages" do
long_msg = "x" * 32000
expected_truncated_msg = "#{'x' * 31785}...Message exceeds character length limit, truncating."
expected_data = "a vogon ship: " + expected_truncated_msg
eventlog = double('eventlog')
expect(eventlog).to receive(:report_event).with(hash_including(:event_type => 2, :event_id => 2, :data => expected_data))
msg = Puppet::Util::Log.new(:level => :warning, :message => long_msg, :source => "a vogon ship")
allow(Puppet::Util::Windows::EventLog).to receive(:open).and_return(eventlog)
dest = klass.new
dest.handle(msg)
end
it "logs to the Puppet Application event log" do
expect(Puppet::Util::Windows::EventLog).to receive(:open).with('Puppet').and_return(double('eventlog'))
klass.new
end
it "logs :debug level as an information type event" do
expects_message_with_type(klass, :debug, klass::EVENTLOG_INFORMATION_TYPE, 0x1)
end
it "logs :warning level as an warning type event" do
expects_message_with_type(klass, :warning, klass::EVENTLOG_WARNING_TYPE, 0x2)
end
it "logs :err level as an error type event" do
expects_message_with_type(klass, :err, klass::EVENTLOG_ERROR_TYPE, 0x3)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/type/file_spec.rb | spec/unit/type/file_spec.rb | # coding: utf-8
require 'spec_helper'
describe Puppet::Type.type(:file) do
include PuppetSpec::Files
# precomputed checksum values for FILE_CONTENT
FILE_CONTENT = 'file content'.freeze
CHECKSUM_VALUES = {
md5: 'd10b4c3ff123b26dc068d43a8bef2d23',
md5lite: 'd10b4c3ff123b26dc068d43a8bef2d23',
sha256: 'e0ac3601005dfa1864f5392aabaf7d898b1b5bab854f1acb4491bcd806b76b0c',
sha256lite: 'e0ac3601005dfa1864f5392aabaf7d898b1b5bab854f1acb4491bcd806b76b0c',
sha1: '87758871f598e1a3b4679953589ae2f57a0bb43c',
sha1lite: '87758871f598e1a3b4679953589ae2f57a0bb43c',
sha224: '2aefaaa5f4d8f17f82f3e1bb407e190cede9aa1311fa4533ce505531',
sha384: '61c7783501ebd90233650357fefbe5a141b7618f907b8f043bbaa92c0f610c785a641ddd479fa81d650cd86e29aa6858',
sha512: '2fb1877301854ac92dd518018f97407a0a88bb696bfef0a51e9efbd39917353500009e15bd72c3f0e4bf690115870bfab926565d5ad97269d922dbbb41261221',
mtime: 'Jan 26 13:59:49 2016',
ctime: 'Jan 26 13:59:49 2016'
}.freeze
INVALID_CHECKSUM_VALUES = {
md5: '00000000000000000000000000000000',
md5lite: '00000000000000000000000000000000',
sha256: '0000000000000000000000000000000000000000000000000000000000000000',
sha256lite: '0000000000000000000000000000000000000000000000000000000000000000',
sha1: '0000000000000000000000000000000000000000',
sha1lite: '0000000000000000000000000000000000000000',
sha224: '00000000000000000000000000000000000000000000000000000000',
sha384: '000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',
sha512: '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'
}.freeze
let(:path) { tmpfile('file_testing') }
let(:file) { described_class.new(:path => path, :catalog => catalog) }
let(:provider) { file.provider }
let(:catalog) { Puppet::Resource::Catalog.new }
before do
allow(Puppet.features).to receive("posix?").and_return(true)
end
describe "the path parameter" do
describe "on POSIX systems", :if => Puppet.features.posix? do
it "should remove trailing slashes" do
file[:path] = "/foo/bar/baz/"
expect(file[:path]).to eq("/foo/bar/baz")
end
it "should remove double slashes" do
file[:path] = "/foo/bar//baz"
expect(file[:path]).to eq("/foo/bar/baz")
end
it "should remove triple slashes" do
file[:path] = "/foo/bar///baz"
expect(file[:path]).to eq("/foo/bar/baz")
end
it "should remove trailing double slashes" do
file[:path] = "/foo/bar/baz//"
expect(file[:path]).to eq("/foo/bar/baz")
end
it "should leave a single slash alone" do
file[:path] = "/"
expect(file[:path]).to eq("/")
end
it "should accept and collapse a double-slash at the start of the path" do
file[:path] = "//tmp/xxx"
expect(file[:path]).to eq('/tmp/xxx')
end
it "should accept and collapse a triple-slash at the start of the path" do
file[:path] = "///tmp/xxx"
expect(file[:path]).to eq('/tmp/xxx')
end
end
describe "on Windows systems", :if => Puppet::Util::Platform.windows? do
it "should remove trailing slashes" do
file[:path] = "X:/foo/bar/baz/"
expect(file[:path]).to eq("X:/foo/bar/baz")
end
it "should remove double slashes" do
file[:path] = "X:/foo/bar//baz"
expect(file[:path]).to eq("X:/foo/bar/baz")
end
it "should remove trailing double slashes" do
file[:path] = "X:/foo/bar/baz//"
expect(file[:path]).to eq("X:/foo/bar/baz")
end
it "should leave a drive letter with a slash alone" do
file[:path] = "X:/"
expect(file[:path]).to eq("X:/")
end
it "should not accept a drive letter without a slash" do
expect { file[:path] = "X:" }.to raise_error(/File paths must be fully qualified/)
end
describe "when using UNC filenames", :if => Puppet::Util::Platform.windows? do
it "should remove trailing slashes" do
file[:path] = "//localhost/foo/bar/baz/"
expect(file[:path]).to eq("//localhost/foo/bar/baz")
end
it "should remove double slashes" do
file[:path] = "//localhost/foo/bar//baz"
expect(file[:path]).to eq("//localhost/foo/bar/baz")
end
it "should remove trailing double slashes" do
file[:path] = "//localhost/foo/bar/baz//"
expect(file[:path]).to eq("//localhost/foo/bar/baz")
end
it "should remove a trailing slash from a sharename" do
file[:path] = "//localhost/foo/"
expect(file[:path]).to eq("//localhost/foo")
end
it "should not modify a sharename" do
file[:path] = "//localhost/foo"
expect(file[:path]).to eq("//localhost/foo")
end
end
end
end
describe "the backup parameter" do
it 'should be disabled by default' do
expect(file[:backup]).to eq(nil)
end
[false, 'false', :false].each do |value|
it "should disable backup if the value is #{value.inspect}" do
file[:backup] = value
expect(file[:backup]).to eq(false)
end
end
[true, 'true', '.puppet-bak'].each do |value|
it "should use .puppet-bak if the value is #{value.inspect}" do
file[:backup] = value
expect(file[:backup]).to eq('.puppet-bak')
end
end
it "should use the provided value if it's any other string" do
file[:backup] = "over there"
expect(file[:backup]).to eq("over there")
end
it "should fail if backup is set to anything else" do
expect do
file[:backup] = 97
end.to raise_error(Puppet::Error, /Invalid backup type 97/)
end
end
describe "the recurse parameter" do
it "should default to recursion being disabled" do
expect(file[:recurse]).to be_falsey
end
[true, "true", "remote"].each do |value|
it "should consider #{value} to enable recursion" do
file[:recurse] = value
expect(file[:recurse]).to be_truthy
end
end
it "should not allow numbers" do
expect { file[:recurse] = 10 }.to raise_error(
Puppet::Error, /Parameter recurse failed on File\[[^\]]+\]: Invalid recurse value 10/)
end
[false, "false"].each do |value|
it "should consider #{value} to disable recursion" do
file[:recurse] = value
expect(file[:recurse]).to be_falsey
end
end
end
describe "the recurselimit parameter" do
it "should accept integers" do
file[:recurselimit] = 12
expect(file[:recurselimit]).to eq(12)
end
it "should munge string numbers to number numbers" do
file[:recurselimit] = '12'
expect(file[:recurselimit]).to eq(12)
end
it "should fail if given a non-number" do
expect do
file[:recurselimit] = 'twelve'
end.to raise_error(Puppet::Error, /Invalid value "twelve"/)
end
end
describe "the replace parameter" do
[true, :true, :yes].each do |value|
it "should consider #{value} to be true" do
file[:replace] = value
expect(file[:replace]).to be_truthy
end
end
[false, :false, :no].each do |value|
it "should consider #{value} to be false" do
file[:replace] = value
expect(file[:replace]).to be_falsey
end
end
end
describe ".instances" do
it "should return an empty array" do
expect(described_class.instances).to eq([])
end
end
describe "#bucket" do
it "should return nil if backup is off" do
file[:backup] = false
expect(file.bucket).to eq(nil)
end
it "should not return a bucket if using a file extension for backup" do
file[:backup] = '.backup'
expect(file.bucket).to eq(nil)
end
it "should return the default filebucket if using the 'puppet' filebucket" do
file[:backup] = 'puppet'
bucket = double('bucket')
allow(file).to receive(:default_bucket).and_return(bucket)
expect(file.bucket).to eq(bucket)
end
it "should fail if using a remote filebucket and no catalog exists" do
file.catalog = nil
file[:backup] = 'my_bucket'
expect { file.bucket }.to raise_error(Puppet::Error, "Can not find filebucket for backups without a catalog")
end
it "should fail if the specified filebucket isn't in the catalog" do
file[:backup] = 'my_bucket'
expect { file.bucket }.to raise_error(Puppet::Error, "Could not find filebucket my_bucket specified in backup")
end
it "should use the specified filebucket if it is in the catalog" do
file[:backup] = 'my_bucket'
filebucket = Puppet::Type.type(:filebucket).new(:name => 'my_bucket')
catalog.add_resource(filebucket)
expect(file.bucket).to eq(filebucket.bucket)
end
end
describe "#asuser" do
before :each do
# Mocha won't let me just stub SUIDManager.asuser to yield and return,
# but it will do exactly that if we're not root.
allow(Puppet::Util::SUIDManager).to receive(:root?).and_return(false)
end
it "should return the desired owner if they can write to the parent directory" do
file[:owner] = 1001
allow(FileTest).to receive(:writable?).with(File.dirname file[:path]).and_return(true)
expect(file.asuser).to eq(1001)
end
it "should return nil if the desired owner can't write to the parent directory" do
file[:owner] = 1001
allow(FileTest).to receive(:writable?).with(File.dirname file[:path]).and_return(false)
expect(file.asuser).to eq(nil)
end
it "should return nil if not managing owner" do
expect(file.asuser).to eq(nil)
end
end
describe "#exist?" do
it "should be considered existent if it can be stat'ed" do
expect(file).to receive(:stat).and_return(double('stat'))
expect(file).to be_exist
end
it "should be considered nonexistent if it can not be stat'ed" do
expect(file).to receive(:stat).and_return(nil)
expect(file).to_not be_exist
end
end
describe "#eval_generate" do
before do
@graph = double('graph', :add_edge => nil)
allow(catalog).to receive(:relationship_graph).and_return(@graph)
end
it "should recurse if recursion is enabled" do
resource = double('resource', :[] => 'resource')
expect(file).to receive(:recurse).and_return([resource])
file[:recurse] = true
expect(file.eval_generate).to eq([resource])
end
it "should not recurse if recursion is disabled" do
expect(file).not_to receive(:recurse)
file[:recurse] = false
expect(file.eval_generate).to eq([])
end
end
describe "#ancestors" do
it "should return the ancestors of the file, in ascending order" do
file = described_class.new(:path => make_absolute("/tmp/foo/bar/baz/qux"))
pieces = %W[#{make_absolute('/')} tmp foo bar baz]
ancestors = file.ancestors
expect(ancestors).not_to be_empty
ancestors.reverse.each_with_index do |path,i|
expect(path).to eq(File.join(*pieces[0..i]))
end
end
end
describe "#flush" do
it "should reset its stat reference" do
FileUtils.touch(path)
stat1 = file.stat
expect(file.stat).to equal(stat1)
file.flush
expect(file.stat).not_to equal(stat1)
end
end
describe "#initialize" do
it "should remove a trailing slash from the title to create the path" do
title = File.expand_path("/abc/\n\tdef/")
file = described_class.new(:title => title)
expect(file[:path]).to eq(title)
end
it "should allow a single slash for a title and create the path" do
title = File.expand_path("/")
file = described_class.new(:title => title)
expect(file[:path]).to eq(title)
end
it "should allow multiple slashes for a title and create the path" do
title = File.expand_path("/") + "//"
file = described_class.new(:title => title)
expect(file[:path]).to eq(File.expand_path("/"))
end
it "should set a desired 'ensure' value if none is set and 'content' is set" do
file = described_class.new(:path => path, :content => "/foo/bar")
expect(file[:ensure]).to eq(:file)
end
it "should set a desired 'ensure' value if none is set and 'target' is set", :if => described_class.defaultprovider.feature?(:manages_symlinks) do
file = described_class.new(:path => path, :target => File.expand_path(__FILE__))
expect(file[:ensure]).to eq(:link)
end
describe "marking parameters as sensitive" do
it "marks sensitive, content, and ensure as sensitive when source is sensitive" do
resource = Puppet::Resource.new(:file, make_absolute("/tmp/foo"), :parameters => {:source => make_absolute('/tmp/bar')}, :sensitive_parameters => [:source])
file = described_class.new(resource)
expect(file.parameter(:source).sensitive).to eq true
expect(file.property(:content).sensitive).to eq true
expect(file.property(:ensure).sensitive).to eq true
end
it "marks ensure as sensitive when content is sensitive" do
resource = Puppet::Resource.new(:file, make_absolute("/tmp/foo"), :parameters => {:content => 'hello world!'}, :sensitive_parameters => [:content])
file = described_class.new(resource)
expect(file.property(:ensure).sensitive).to eq true
end
end
end
describe "#mark_children_for_purging" do
it "should set each child's ensure to absent" do
paths = %w[foo bar baz]
children = {}
paths.each do |child|
children[child] = described_class.new(:path => File.join(path, child), :ensure => :present)
end
file.mark_children_for_purging(children)
expect(children.length).to eq(3)
children.values.each do |child|
expect(child[:ensure]).to eq(:absent)
end
end
it "should skip children which have a source" do
child = described_class.new(:path => path, :ensure => :present, :source => File.expand_path(__FILE__))
file.mark_children_for_purging('foo' => child)
expect(child[:ensure]).to eq(:present)
end
end
describe "#newchild" do
it "should create a new resource relative to the parent" do
child = file.newchild('bar')
expect(child).to be_a(described_class)
expect(child[:path]).to eq(File.join(file[:path], 'bar'))
end
{
:ensure => :present,
:recurse => true,
:recurselimit => 5,
:target => "some_target",
:source => File.expand_path("some_source"),
}.each do |param, value|
it "should omit the #{param} parameter", :if => described_class.defaultprovider.feature?(:manages_symlinks) do
# Make a new file, because we have to set the param at initialization
# or it wouldn't be copied regardless.
file = described_class.new(:path => path, param => value)
child = file.newchild('bar')
expect(child[param]).not_to eq(value)
end
end
it "should copy all of the parent resource's 'should' values that were set at initialization" do
parent = described_class.new(:path => path, :owner => 'root', :group => 'wheel')
child = parent.newchild("my/path")
expect(child[:owner]).to eq('root')
expect(child[:group]).to eq('wheel')
end
it "should not copy default values to the new child" do
child = file.newchild("my/path")
expect(child.original_parameters).not_to include(:backup)
end
it "should not copy values to the child which were set by the source" do
source = File.expand_path(__FILE__)
file[:source] = source
metadata = double('metadata', :owner => "root", :group => "root", :mode => '0755', :ftype => "file", :checksum => "{md5}whatever", :checksum_type => "md5", :source => source)
allow(file.parameter(:source)).to receive(:metadata).and_return(metadata)
file.parameter(:source).copy_source_values
expect(file.class).to receive(:new) do |arg|
expect(arg[:group]).to be_nil
end
file.newchild("my/path")
end
end
describe "#purge?" do
it "should return false if purge is not set" do
expect(file).to_not be_purge
end
it "should return true if purge is set to true" do
file[:purge] = true
expect(file).to be_purge
end
it "should return false if purge is set to false" do
file[:purge] = false
expect(file).to_not be_purge
end
end
describe "#recurse" do
let(:name) { 'bar' }
let(:child) { double('puppet_type_file') }
before do
file[:recurse] = true
@metadata = Puppet::FileServing::Metadata
end
describe "and a source is set" do
it "should pass the already-discovered resources to recurse_remote" do
file[:source] = File.expand_path(__FILE__)
allow(child).to receive(:[]).with(:path).and_return(name)
allow(file).to receive(:recurse_local).and_return({name => child})
expect(file).to receive(:recurse_remote).with({name => child}).and_return([])
file.recurse
end
end
describe "and a target is set" do
it "should use recurse_link" do
file[:target] = File.expand_path(__FILE__)
allow(child).to receive(:[]).with(:path).and_return(name)
allow(file).to receive(:recurse_local).and_return({name => child})
expect(file).to receive(:recurse_link).with({name => child}).and_return([])
file.recurse
end
end
it "should use recurse_local if recurse is not remote" do
expect(file).to receive(:recurse_local).and_return({})
file.recurse
end
it "should not use recurse_local if recurse is remote" do
file[:recurse] = :remote
expect(file).not_to receive(:recurse_local)
file.recurse
end
it "should return the generated resources as an array sorted by file path" do
one = double('one', :[] => "/one")
two = double('two', :[] => "/one/two")
three = double('three', :[] => "/three")
expect(file).to receive(:recurse_local).and_return(:one => one, :two => two, :three => three)
expect(file.recurse).to eq([one, two, three])
end
describe "and purging is enabled" do
before do
file[:purge] = true
end
it "should mark each file for removal" do
local = described_class.new(:path => path, :ensure => :present)
expect(file).to receive(:recurse_local).and_return("local" => local)
file.recurse
expect(local[:ensure]).to eq(:absent)
end
it "should not remove files that exist in the remote repository" do
pending("FIXME: This test has been broken since it was introduced in c189b46e3f1 because of = vs ==")
file[:source] = File.expand_path(__FILE__)
expect(file).to receive(:recurse_local).and_return({})
remote = described_class.new(:path => path, :source => File.expand_path(__FILE__), :ensure => :present)
expect(file).to receive(:recurse_remote).with(hash_including("remote" => remote))
file.recurse
expect(remote[:ensure]).not_to eq(:absent)
end
end
end
describe "#remove_less_specific_files" do
it "should remove any nested files that are already in the catalog" do
foo = described_class.new :path => File.join(file[:path], 'foo')
bar = described_class.new :path => File.join(file[:path], 'bar')
baz = described_class.new :path => File.join(file[:path], 'baz')
catalog.add_resource(foo)
catalog.add_resource(bar)
expect(file.remove_less_specific_files([foo, bar, baz])).to eq([baz])
end
end
describe "#recurse?" do
it "should be true if recurse is true" do
file[:recurse] = true
expect(file).to be_recurse
end
it "should be true if recurse is remote" do
file[:recurse] = :remote
expect(file).to be_recurse
end
it "should be false if recurse is false" do
file[:recurse] = false
expect(file).to_not be_recurse
end
end
describe "#recurse_link" do
before do
@first = double('first', :relative_path => "first", :full_path => "/my/first", :ftype => "directory")
@second = double('second', :relative_path => "second", :full_path => "/my/second", :ftype => "file")
@resource = double('file', :[]= => nil)
end
it "should pass its target to the :perform_recursion method" do
file[:target] = "mylinks"
expect(file).to receive(:perform_recursion).with("mylinks").and_return([@first])
allow(file).to receive(:newchild).and_return(@resource)
file.recurse_link({})
end
it "should ignore the recursively-found '.' file and configure the top-level file to create a directory" do
allow(@first).to receive(:relative_path).and_return(".")
file[:target] = "mylinks"
expect(file).to receive(:perform_recursion).with("mylinks").and_return([@first])
expect(file).not_to receive(:newchild)
expect(file).to receive(:[]=).with(:ensure, :directory)
file.recurse_link({})
end
it "should create a new child resource for each generated metadata instance's relative path that doesn't already exist in the children hash" do
expect(file).to receive(:perform_recursion).and_return([@first, @second])
expect(file).to receive(:newchild).with(@first.relative_path).and_return(@resource)
file.recurse_link("second" => @resource)
end
it "should not create a new child resource for paths that already exist in the children hash" do
expect(file).to receive(:perform_recursion).and_return([@first])
expect(file).not_to receive(:newchild)
file.recurse_link("first" => @resource)
end
it "should set the target to the full path of discovered file and set :ensure to :link if the file is not a directory", :if => described_class.defaultprovider.feature?(:manages_symlinks) do
allow(file).to receive(:perform_recursion).and_return([@first, @second])
file.recurse_link("first" => @resource, "second" => file)
expect(file[:ensure]).to eq(:link)
expect(file[:target]).to eq("/my/second")
end
it "should :ensure to :directory if the file is a directory" do
allow(file).to receive(:perform_recursion).and_return([@first, @second])
file.recurse_link("first" => file, "second" => @resource)
expect(file[:ensure]).to eq(:directory)
end
it "should return a hash with both created and existing resources with the relative paths as the hash keys" do
expect(file).to receive(:perform_recursion).and_return([@first, @second])
allow(file).to receive(:newchild).and_return(file)
expect(file.recurse_link("second" => @resource)).to eq({"second" => @resource, "first" => file})
end
end
describe "#recurse_local" do
before do
@metadata = double('metadata', :relative_path => "my/file")
end
it "should pass its path to the :perform_recursion method" do
expect(file).to receive(:perform_recursion).with(file[:path]).and_return([@metadata])
allow(file).to receive(:newchild)
file.recurse_local
end
it "should return an empty hash if the recursion returns nothing" do
expect(file).to receive(:perform_recursion).and_return(nil)
expect(file.recurse_local).to eq({})
end
it "should create a new child resource with each generated metadata instance's relative path" do
expect(file).to receive(:perform_recursion).and_return([@metadata])
expect(file).to receive(:newchild).with(@metadata.relative_path).and_return("fiebar")
file.recurse_local
end
it "should not create a new child resource for the '.' directory" do
allow(@metadata).to receive(:relative_path).and_return(".")
expect(file).to receive(:perform_recursion).and_return([@metadata])
expect(file).not_to receive(:newchild)
file.recurse_local
end
it "should return a hash of the created resources with the relative paths as the hash keys" do
expect(file).to receive(:perform_recursion).and_return([@metadata])
expect(file).to receive(:newchild).with("my/file").and_return("fiebar")
expect(file.recurse_local).to eq({"my/file" => "fiebar"})
end
it "should set checksum_type to none if this file checksum is none" do
file[:checksum] = :none
expect(Puppet::FileServing::Metadata.indirection).to receive(:search).with(anything, hash_including(checksum_type: :none)).and_return([@metadata])
expect(file).to receive(:newchild).with("my/file").and_return("fiebar")
file.recurse_local
end
end
describe "#recurse_remote" do
let(:my) { File.expand_path('/my') }
before do
file[:source] = "puppet://foo/bar"
@first = Puppet::FileServing::Metadata.new(my, :relative_path => "first")
@second = Puppet::FileServing::Metadata.new(my, :relative_path => "second")
allow(@first).to receive(:ftype).and_return("directory")
allow(@second).to receive(:ftype).and_return("directory")
@parameter = double('property', :metadata= => nil)
@resource = double('file', :[]= => nil, :parameter => @parameter)
end
it "should pass its source to the :perform_recursion method" do
data = Puppet::FileServing::Metadata.new(File.expand_path("/whatever"), :relative_path => "foobar")
expect(file).to receive(:perform_recursion).with("puppet://foo/bar").and_return([data])
allow(file).to receive(:newchild).and_return(@resource)
file.recurse_remote({})
end
it "should not recurse when the remote file is not a directory" do
data = Puppet::FileServing::Metadata.new(File.expand_path("/whatever"), :relative_path => ".")
allow(data).to receive(:ftype).and_return("file")
expect(file).to receive(:perform_recursion).with("puppet://foo/bar").and_return([data])
expect(file).not_to receive(:newchild)
file.recurse_remote({})
end
it "should set the source of each returned file to the searched-for URI plus the found relative path" do
expect(@first).to receive(:source=).with(File.join("puppet://foo/bar", @first.relative_path))
expect(file).to receive(:perform_recursion).and_return([@first])
allow(file).to receive(:newchild).and_return(@resource)
file.recurse_remote({})
end
it "should create a new resource for any relative file paths that do not already have a resource" do
allow(file).to receive(:perform_recursion).and_return([@first])
expect(file).to receive(:newchild).with("first").and_return(@resource)
expect(file.recurse_remote({})).to eq({"first" => @resource})
end
it "should not create a new resource for any relative file paths that do already have a resource" do
allow(file).to receive(:perform_recursion).and_return([@first])
expect(file).not_to receive(:newchild)
file.recurse_remote("first" => @resource)
end
it "should set the source of each resource to the source of the metadata" do
allow(file).to receive(:perform_recursion).and_return([@first])
allow(@resource).to receive(:[]=)
expect(@resource).to receive(:[]=).with(:source, File.join("puppet://foo/bar", @first.relative_path))
file.recurse_remote("first" => @resource)
end
it "should set the checksum parameter based on the metadata" do
allow(file).to receive(:perform_recursion).and_return([@first])
allow(@resource).to receive(:[]=)
expect(@resource).to receive(:[]=).with(:checksum, "sha256")
file.recurse_remote("first" => @resource)
end
it "should store the metadata in the source property for each resource so the source does not have to requery the metadata" do
allow(file).to receive(:perform_recursion).and_return([@first])
expect(@resource).to receive(:parameter).with(:source).and_return(@parameter)
expect(@parameter).to receive(:metadata=).with(@first)
file.recurse_remote("first" => @resource)
end
it "should not create a new resource for the '.' file" do
allow(@first).to receive(:relative_path).and_return(".")
allow(file).to receive(:perform_recursion).and_return([@first])
expect(file).not_to receive(:newchild)
file.recurse_remote({})
end
it "should store the metadata in the main file's source property if the relative path is '.'" do
allow(@first).to receive(:relative_path).and_return(".")
allow(file).to receive(:perform_recursion).and_return([@first])
expect(file.parameter(:source)).to receive(:metadata=).with(@first)
file.recurse_remote("first" => @resource)
end
it "should update the main file's checksum parameter if the relative path is '.'" do
allow(@first).to receive(:relative_path).and_return(".")
allow(file).to receive(:perform_recursion).and_return([@first])
allow(file).to receive(:[]=)
expect(file). to receive(:[]=).with(:checksum, "sha256")
file.recurse_remote("first" => @resource)
end
describe "and multiple sources are provided" do
let(:sources) do
h = {}
%w{/a /b /c /d}.each do |key|
h[key] = Puppet::Util.uri_unescape(Puppet::Util.path_to_uri(File.expand_path(key)).to_s)
end
h
end
describe "and :sourceselect is set to :first" do
it "should create file instances for the results for the first source to return any values" do
data = Puppet::FileServing::Metadata.new(File.expand_path("/whatever"), :relative_path => "foobar")
file[:source] = sources.keys.sort.map { |key| File.expand_path(key) }
expect(file).to receive(:perform_recursion).with(sources['/a']).and_return(nil)
expect(file).to receive(:perform_recursion).with(sources['/b']).and_return([])
expect(file).to receive(:perform_recursion).with(sources['/c']).and_return([data])
expect(file).not_to receive(:perform_recursion).with(sources['/d'])
expect(file).to receive(:newchild).with("foobar").and_return(@resource)
file.recurse_remote({})
end
end
describe "and :sourceselect is set to :all" do
before do
file[:sourceselect] = :all
end
it "should return every found file that is not in a previous source" do
klass = Puppet::FileServing::Metadata
file[:source] = abs_path = %w{/a /b /c /d}.map {|f| File.expand_path(f) }
allow(file).to receive(:newchild).and_return(@resource)
one = [klass.new(abs_path[0], :relative_path => "a")]
expect(file).to receive(:perform_recursion).with(sources['/a']).and_return(one)
expect(file).to receive(:newchild).with("a").and_return(@resource)
two = [klass.new(abs_path[1], :relative_path => "a"), klass.new(abs_path[1], :relative_path => "b")]
expect(file).to receive(:perform_recursion).with(sources['/b']).and_return(two)
expect(file).to receive(:newchild).with("b").and_return(@resource)
three = [klass.new(abs_path[2], :relative_path => "a"), klass.new(abs_path[2], :relative_path => "c")]
expect(file).to receive(:perform_recursion).with(sources['/c']).and_return(three)
expect(file).to receive(:newchild).with("c").and_return(@resource)
expect(file).to receive(:perform_recursion).with(sources['/d']).and_return([])
file.recurse_remote({})
end
end
end
end
describe "#perform_recursion", :uses_checksums => true do
it "should use Metadata to do its recursion" do
expect(Puppet::FileServing::Metadata.indirection).to receive(:search)
file.perform_recursion(file[:path])
end
it "should use the provided path as the key to the search" do
expect(Puppet::FileServing::Metadata.indirection).to receive(:search).with("/foo", anything)
file.perform_recursion("/foo")
end
it "should return the results of the metadata search" do
expect(Puppet::FileServing::Metadata.indirection).to receive(:search).and_return("foobar")
expect(file.perform_recursion(file[:path])).to eq("foobar")
end
it "should pass its recursion value to the search" do
file[:recurse] = true
expect(Puppet::FileServing::Metadata.indirection).to receive(:search).with(anything, hash_including(recurse: true))
file.perform_recursion(file[:path])
end
it "should pass true if recursion is remote" do
file[:recurse] = :remote
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | true |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/type/group_spec.rb | spec/unit/type/group_spec.rb | require 'spec_helper'
describe Puppet::Type.type(:group) do
before do
@class = Puppet::Type.type(:group)
end
it "should have a system_groups feature" do
expect(@class.provider_feature(:system_groups)).not_to be_nil
end
it 'should default to `present`' do
expect(@class.new(:name => "foo")[:ensure]).to eq(:present)
end
it 'should set ensure to whatever is passed in' do
expect(@class.new(:name => "foo", :ensure => 'absent')[:ensure]).to eq(:absent)
end
describe "when validating attributes" do
[:name, :allowdupe].each do |param|
it "should have a #{param} parameter" do
expect(@class.attrtype(param)).to eq(:param)
end
end
[:ensure, :gid].each do |param|
it "should have a #{param} property" do
expect(@class.attrtype(param)).to eq(:property)
end
end
it "should convert gids provided as strings into integers" do
expect(@class.new(:name => "foo", :gid => "15")[:gid]).to eq(15)
end
it "should accepts gids provided as integers" do
expect(@class.new(:name => "foo", :gid => 15)[:gid]).to eq(15)
end
end
it "should have a boolean method for determining if duplicates are allowed" do
expect(@class.new(:name => "foo")).to respond_to "allowdupe?"
end
it "should have a boolean method for determining if system groups are allowed" do
expect(@class.new(:name => "foo")).to respond_to "system?"
end
it "should call 'create' to create the group" do
group = @class.new(:name => "foo", :ensure => :present)
expect(group.provider).to receive(:create)
group.parameter(:ensure).sync
end
it "should call 'delete' to remove the group" do
group = @class.new(:name => "foo", :ensure => :absent)
expect(group.provider).to receive(:delete)
group.parameter(:ensure).sync
end
it "delegates the existence check to its provider" do
provider = @class.provide(:testing) do
def exists?
true
end
end
provider_instance = provider.new
type = @class.new(:name => "group", :provider => provider_instance)
expect(type.exists?).to eq(true)
end
describe "should delegate :members implementation to the provider:" do
let (:provider) do
@class.provide(:testing) do
has_features :manages_members
def members
[]
end
def members_insync?(current, should)
current == should
end
def members_to_s(values)
values.map { |v| "#{v} ()" }.join(', ')
end
end
end
let (:provider_instance) { provider.new }
let (:type) { @class.new(:name => "group", :provider => provider_instance, :members => ['user1']) }
it "insync? calls members_insync?" do
expect(type.property(:members).insync?(['user1'])).to be_truthy
end
it "is_to_s and should_to_s call members_to_s" do
expect(type.property(:members).is_to_s('user1')).to eq('user1 ()')
expect(type.property(:members).should_to_s('user1,user2')).to eq('user1 (), user2 ()')
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/type/filebucket_spec.rb | spec/unit/type/filebucket_spec.rb | require 'spec_helper'
describe Puppet::Type.type(:filebucket) do
include PuppetSpec::Files
describe "when validating attributes" do
%w{name server port path}.each do |attr|
it "should have a '#{attr}' parameter" do
expect(Puppet::Type.type(:filebucket).attrtype(attr.intern)).to eq(:param)
end
end
it "should have its 'name' attribute set as its namevar" do
expect(Puppet::Type.type(:filebucket).key_attributes).to eq([:name])
end
end
it "should use the clientbucketdir as the path by default path" do
Puppet.settings[:clientbucketdir] = "/my/bucket"
expect(Puppet::Type.type(:filebucket).new(:name => "main")[:path]).to eq(Puppet[:clientbucketdir])
end
it "should not have a default port" do
Puppet.settings[:serverport] = 50
expect(Puppet::Type.type(:filebucket).new(:name => "main")[:port]).to eq(nil)
end
it "should not have a default server" do
Puppet.settings[:server] = "myserver"
expect(Puppet::Type.type(:filebucket).new(:name => "main")[:server]).to eq(nil)
end
it "be local by default" do
bucket = Puppet::Type.type(:filebucket).new :name => "main"
expect(bucket.bucket).to be_local
end
describe "path" do
def bucket(hash)
Puppet::Type.type(:filebucket).new({:name => 'main'}.merge(hash))
end
it "should accept false as a value" do
expect { bucket(:path => false) }.not_to raise_error
end
it "should accept true as a value" do
expect { bucket(:path => true) }.not_to raise_error
end
it "should fail when given an array of values" do
expect { bucket(:path => ['one', 'two']) }.
to raise_error Puppet::Error, /only have one filebucket path/
end
%w{one ../one one/two}.each do |path|
it "should fail if given a relative path of #{path.inspect}" do
expect { bucket(:path => path) }.
to raise_error Puppet::Error, /Filebucket paths must be absolute/
end
end
it "should succeed if given an absolute path" do
expect { bucket(:path => make_absolute('/tmp/bucket')) }.not_to raise_error
end
it "not be local if path is false" do
expect(bucket(:path => false).bucket).not_to be_local
end
it "be local if both a path and a server are specified" do
expect(bucket(:server => "puppet", :path => make_absolute("/my/path")).bucket).to be_local
end
end
describe "when creating the filebucket" do
before do
@bucket = double('bucket', :name= => nil)
end
it "should use any provided path" do
path = make_absolute("/foo/bar")
bucket = Puppet::Type.type(:filebucket).new :name => "main", :path => path
expect(Puppet::FileBucket::Dipper).to receive(:new).with({:Path => path}).and_return(@bucket)
bucket.bucket
end
it "should use any provided server and port" do
bucket = Puppet::Type.type(:filebucket).new :name => "main", :server => "myserv", :port => "myport", :path => false
expect(Puppet::FileBucket::Dipper).to receive(:new).with({:Server => "myserv", :Port => "myport"}).and_return(@bucket)
bucket.bucket
end
it "should not try to guess server or port if the path is unset and no server is provided" do
Puppet.settings[:server] = "myserv"
Puppet.settings[:server_list] = ['server_list_0', 'server_list_1']
expect(Puppet::FileBucket::Dipper).to receive(:new).with({:Server => nil, :Port => nil}).and_return(@bucket)
bucket = Puppet::Type.type(:filebucket).new :name => "main", :path => false
bucket.bucket
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/type/package_spec.rb | spec/unit/type/package_spec.rb | require 'spec_helper'
describe Puppet::Type.type(:package) do
before do
allow(Process).to receive(:euid).and_return(0)
allow(Puppet::Util::Storage).to receive(:store)
end
it "should have a :reinstallable feature that requires the :reinstall method" do
expect(Puppet::Type.type(:package).provider_feature(:reinstallable).methods).to eq([:reinstall])
end
it "should have an :installable feature that requires the :install method" do
expect(Puppet::Type.type(:package).provider_feature(:installable).methods).to eq([:install])
end
it "should have an :uninstallable feature that requires the :uninstall method" do
expect(Puppet::Type.type(:package).provider_feature(:uninstallable).methods).to eq([:uninstall])
end
it "should have an :upgradeable feature that requires :update and :latest methods" do
expect(Puppet::Type.type(:package).provider_feature(:upgradeable).methods).to eq([:update, :latest])
end
it "should have a :purgeable feature that requires the :purge latest method" do
expect(Puppet::Type.type(:package).provider_feature(:purgeable).methods).to eq([:purge])
end
it "should have a :versionable feature" do
expect(Puppet::Type.type(:package).provider_feature(:versionable)).not_to be_nil
end
it "should have a :supports_flavors feature" do
expect(Puppet::Type.type(:package).provider_feature(:supports_flavors)).not_to be_nil
end
it "should have a :package_settings feature that requires :package_settings_insync?, :package_settings and :package_settings=" do
expect(Puppet::Type.type(:package).provider_feature(:package_settings).methods).to eq([:package_settings_insync?, :package_settings, :package_settings=])
end
it "should default to being installed" do
pkg = Puppet::Type.type(:package).new(:name => "yay", :provider => :apt)
expect(pkg.should(:ensure)).to eq(:present)
end
describe "when validating attributes" do
[:name, :source, :instance, :status, :adminfile, :responsefile, :configfiles, :category, :platform, :root, :vendor, :description, :allowcdrom, :allow_virtual, :reinstall_on_refresh].each do |param|
it "should have a #{param} parameter" do
expect(Puppet::Type.type(:package).attrtype(param)).to eq(:param)
end
end
it "should have an ensure property" do
expect(Puppet::Type.type(:package).attrtype(:ensure)).to eq(:property)
end
it "should have a package_settings property" do
expect(Puppet::Type.type(:package).attrtype(:package_settings)).to eq(:property)
end
it "should have a flavor property" do
expect(Puppet::Type.type(:package).attrtype(:flavor)).to eq(:property)
end
end
describe "when validating attribute values" do
before :each do
@provider = double(
'provider',
:class => Puppet::Type.type(:package).defaultprovider,
:clear => nil,
:validate_source => nil
)
allow(Puppet::Type.type(:package).defaultprovider).to receive(:new).and_return(@provider)
end
after :each do
Puppet::Type.type(:package).defaultprovider = nil
end
it "should support :present as a value to :ensure" do
Puppet::Type.type(:package).new(:name => "yay", :ensure => :present)
end
it "should alias :installed to :present as a value to :ensure" do
pkg = Puppet::Type.type(:package).new(:name => "yay", :ensure => :installed)
expect(pkg.should(:ensure)).to eq(:present)
end
it "should support :absent as a value to :ensure" do
Puppet::Type.type(:package).new(:name => "yay", :ensure => :absent)
end
it "should support :purged as a value to :ensure if the provider has the :purgeable feature" do
expect(@provider).to receive(:satisfies?).with([:purgeable]).and_return(true)
Puppet::Type.type(:package).new(:name => "yay", :ensure => :purged)
end
it "should not support :purged as a value to :ensure if the provider does not have the :purgeable feature" do
expect(@provider).to receive(:satisfies?).with([:purgeable]).and_return(false)
expect { Puppet::Type.type(:package).new(:name => "yay", :ensure => :purged) }.to raise_error(Puppet::Error)
end
it "should support :latest as a value to :ensure if the provider has the :upgradeable feature" do
expect(@provider).to receive(:satisfies?).with([:upgradeable]).and_return(true)
Puppet::Type.type(:package).new(:name => "yay", :ensure => :latest)
end
it "should not support :latest as a value to :ensure if the provider does not have the :upgradeable feature" do
expect(@provider).to receive(:satisfies?).with([:upgradeable]).and_return(false)
expect { Puppet::Type.type(:package).new(:name => "yay", :ensure => :latest) }.to raise_error(Puppet::Error)
end
it "should support version numbers as a value to :ensure if the provider has the :versionable feature" do
expect(@provider).to receive(:satisfies?).with([:versionable]).and_return(true)
Puppet::Type.type(:package).new(:name => "yay", :ensure => "1.0")
end
it "should not support version numbers as a value to :ensure if the provider does not have the :versionable feature" do
expect(@provider).to receive(:satisfies?).with([:versionable]).and_return(false)
expect { Puppet::Type.type(:package).new(:name => "yay", :ensure => "1.0") }.to raise_error(Puppet::Error)
end
it "should accept any string as an argument to :source" do
expect { Puppet::Type.type(:package).new(:name => "yay", :source => "stuff") }.to_not raise_error
end
it "should not accept a non-string name" do
expect do
Puppet::Type.type(:package).new(:name => ["error"])
end.to raise_error(Puppet::ResourceError, /Name must be a String/)
end
end
module PackageEvaluationTesting
def setprops(properties)
allow(@provider).to receive(:properties).and_return(properties)
end
end
describe Puppet::Type.type(:package) do
before :each do
@provider = double(
'provider',
:class => Puppet::Type.type(:package).defaultprovider,
:clear => nil,
:satisfies? => true,
:name => :mock,
:validate_source => nil
)
allow(Puppet::Type.type(:package).defaultprovider).to receive(:new).and_return(@provider)
allow(Puppet::Type.type(:package).defaultprovider).to receive(:instances).and_return([])
@package = Puppet::Type.type(:package).new(:name => "yay")
@catalog = Puppet::Resource::Catalog.new
@catalog.add_resource(@package)
end
describe Puppet::Type.type(:package), "when it should be purged" do
include PackageEvaluationTesting
before { @package[:ensure] = :purged }
it "should do nothing if it is :purged" do
expect(@provider).to receive(:properties).and_return(:ensure => :purged).at_least(:once)
@catalog.apply
end
[:absent, :installed, :present, :latest].each do |state|
it "should purge if it is #{state.to_s}" do
allow(@provider).to receive(:properties).and_return(:ensure => state)
expect(@provider).to receive(:purge)
@catalog.apply
end
end
end
describe Puppet::Type.type(:package), "when it should be absent" do
include PackageEvaluationTesting
before { @package[:ensure] = :absent }
[:purged, :absent].each do |state|
it "should do nothing if it is #{state.to_s}" do
expect(@provider).to receive(:properties).and_return(:ensure => state).at_least(:once)
@catalog.apply
end
end
[:installed, :present, :latest].each do |state|
it "should uninstall if it is #{state.to_s}" do
allow(@provider).to receive(:properties).and_return(:ensure => state)
expect(@provider).to receive(:uninstall)
@catalog.apply
end
end
end
describe Puppet::Type.type(:package), "when it should be present" do
include PackageEvaluationTesting
before { @package[:ensure] = :present }
[:present, :latest, "1.0"].each do |state|
it "should do nothing if it is #{state.to_s}" do
expect(@provider).to receive(:properties).and_return(:ensure => state).at_least(:once)
@catalog.apply
end
end
[:purged, :absent].each do |state|
it "should install if it is #{state.to_s}" do
allow(@provider).to receive(:properties).and_return(:ensure => state)
expect(@provider).to receive(:install)
@catalog.apply
end
end
end
describe Puppet::Type.type(:package), "when it should be latest" do
include PackageEvaluationTesting
before { @package[:ensure] = :latest }
[:purged, :absent].each do |state|
it "should upgrade if it is #{state.to_s}" do
allow(@provider).to receive(:properties).and_return(:ensure => state)
expect(@provider).to receive(:update)
@catalog.apply
end
end
it "should upgrade if the current version is not equal to the latest version" do
allow(@provider).to receive(:properties).and_return(:ensure => "1.0")
allow(@provider).to receive(:latest).and_return("2.0")
expect(@provider).to receive(:update)
@catalog.apply
end
it "should do nothing if it is equal to the latest version" do
allow(@provider).to receive(:properties).and_return(:ensure => "1.0")
allow(@provider).to receive(:latest).and_return("1.0")
expect(@provider).not_to receive(:update)
@catalog.apply
end
it "should do nothing if the provider returns :present as the latest version" do
allow(@provider).to receive(:properties).and_return(:ensure => :present)
allow(@provider).to receive(:latest).and_return("1.0")
expect(@provider).not_to receive(:update)
@catalog.apply
end
end
describe Puppet::Type.type(:package), "when it should be a specific version" do
include PackageEvaluationTesting
before { @package[:ensure] = "1.0" }
[:purged, :absent].each do |state|
it "should install if it is #{state.to_s}" do
allow(@provider).to receive(:properties).and_return(:ensure => state)
expect(@package.property(:ensure).insync?(state)).to be_falsey
expect(@provider).to receive(:install)
@catalog.apply
end
end
it "should do nothing if the current version is equal to the desired version" do
allow(@provider).to receive(:properties).and_return(:ensure => "1.0")
expect(@package.property(:ensure).insync?('1.0')).to be_truthy
expect(@provider).not_to receive(:install)
@catalog.apply
end
it "should install if the current version is not equal to the specified version" do
allow(@provider).to receive(:properties).and_return(:ensure => "2.0")
expect(@package.property(:ensure).insync?('2.0')).to be_falsey
expect(@provider).to receive(:install)
@catalog.apply
end
describe "when current value is an array" do
let(:installed_versions) { ["1.0", "2.0", "3.0"] }
before (:each) do
allow(@provider).to receive(:properties).and_return(:ensure => installed_versions)
end
it "should install if value not in the array" do
@package[:ensure] = "1.5"
expect(@package.property(:ensure).insync?(installed_versions)).to be_falsey
expect(@provider).to receive(:install)
@catalog.apply
end
it "should not install if value is in the array" do
@package[:ensure] = "2.0"
expect(@package.property(:ensure).insync?(installed_versions)).to be_truthy
expect(@provider).not_to receive(:install)
@catalog.apply
end
describe "when ensure is set to 'latest'" do
it "should not install if the value is in the array" do
expect(@provider).to receive(:latest).and_return("3.0")
@package[:ensure] = "latest"
expect(@package.property(:ensure).insync?(installed_versions)).to be_truthy
expect(@provider).not_to receive(:install)
@catalog.apply
end
end
end
end
describe Puppet::Type.type(:package), "when responding to refresh" do
include PackageEvaluationTesting
it "should support :true as a value to :reinstall_on_refresh" do
srv = Puppet::Type.type(:package).new(:name => "yay", :reinstall_on_refresh => :true)
expect(srv[:reinstall_on_refresh]).to eq(:true)
end
it "should support :false as a value to :reinstall_on_refresh" do
srv = Puppet::Type.type(:package).new(:name => "yay", :reinstall_on_refresh => :false)
expect(srv[:reinstall_on_refresh]).to eq(:false)
end
it "should specify :false as the default value of :reinstall_on_refresh" do
srv = Puppet::Type.type(:package).new(:name => "yay")
expect(srv[:reinstall_on_refresh]).to eq(:false)
end
[:latest, :present, :installed].each do |state|
it "should reinstall if it should be #{state.to_s} and reinstall_on_refresh is true" do
@package[:ensure] = state
@package[:reinstall_on_refresh] = :true
allow(@provider).to receive(:reinstallable?).and_return(true)
expect(@provider).to receive(:reinstall).once
@package.refresh
end
it "should reinstall if it should be #{state.to_s} and reinstall_on_refresh is false" do
@package[:ensure] = state
@package[:reinstall_on_refresh] = :false
allow(@provider).to receive(:reinstallable?).and_return(true)
expect(@provider).not_to receive(:reinstall)
@package.refresh
end
end
[:purged, :absent].each do |state|
it "should not reinstall if it should be #{state.to_s} and reinstall_on_refresh is true" do
@package[:ensure] = state
allow(@provider).to receive(:reinstallable?).and_return(true)
expect(@provider).not_to receive(:reinstall)
@package.refresh
end
it "should not reinstall if it should be #{state.to_s} and reinstall_on_refresh is false" do
@package[:ensure] = state
allow(@provider).to receive(:reinstallable?).and_return(true)
expect(@provider).not_to receive(:reinstall)
@package.refresh
end
end
end
end
it "should select dnf over yum for dnf supported fedora versions" do
dnf = Puppet::Type.type(:package).provider(:dnf)
yum = Puppet::Type.type(:package).provider(:yum)
allow(Facter).to receive(:value).with('os.family').and_return(:redhat)
allow(Facter).to receive(:value).with('os.name').and_return(:fedora)
allow(Facter).to receive(:value).with('os.release.major').and_return("22")
expect(dnf.specificity).to be > yum.specificity
end
describe "allow_virtual" do
it "defaults to true on platforms that support virtual packages" do
pkg = Puppet::Type.type(:package).new(:name => 'yay', :provider => :yum)
expect(pkg[:allow_virtual]).to eq true
end
it "defaults to false on dpkg provider" do
pkg = Puppet::Type.type(:package).new(:name => 'yay', :provider => :dpkg)
expect(pkg[:allow_virtual]).to be_nil
end
it "defaults to false on platforms that do not support virtual packages" do
pkg = Puppet::Type.type(:package).new(:name => 'yay', :provider => :apple)
expect(pkg[:allow_virtual]).to be_nil
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/type/schedule_spec.rb | spec/unit/type/schedule_spec.rb | require 'spec_helper'
module ScheduleTesting
def diff(unit, incr, method, count)
diff = Time.now.to_i.send(method, incr * count)
Time.at(diff)
end
def day(method, count)
diff(:hour, 3600 * 24, method, count)
end
def hour(method, count)
diff(:hour, 3600, method, count)
end
def min(method, count)
diff(:min, 60, method, count)
end
end
describe Puppet::Type.type(:schedule) do
include ScheduleTesting
before :each do
Puppet[:ignoreschedules] = false
@schedule = Puppet::Type.type(:schedule).new(:name => "testing")
end
describe Puppet::Type.type(:schedule) do
it "should apply to device" do
expect(@schedule).to be_appliable_to_device
end
it "should apply to host" do
expect(@schedule).to be_appliable_to_host
end
it "should default to :distance for period-matching" do
expect(@schedule[:periodmatch]).to eq(:distance)
end
it "should default to a :repeat of 1" do
expect(@schedule[:repeat]).to eq(1)
end
it "should never match when the period is :never" do
@schedule[:period] = :never
expect(@schedule).to_not be_match
end
end
describe Puppet::Type.type(:schedule), "when producing default schedules" do
%w{hourly daily weekly monthly never}.each do |period|
period = period.to_sym
it "should produce a #{period} schedule with the period set appropriately" do
schedules = Puppet::Type.type(:schedule).mkdefaultschedules
expect(schedules.find { |s| s[:name] == period.to_s and s[:period] == period }).to be_instance_of(Puppet::Type.type(:schedule))
end
end
it "should not produce default schedules when default_schedules is false" do
Puppet[:default_schedules] = false
schedules = Puppet::Type.type(:schedule).mkdefaultschedules
expect(schedules).to be_empty
end
it "should produce a schedule named puppet with a period of hourly and a repeat of 2" do
schedules = Puppet::Type.type(:schedule).mkdefaultschedules
expect(schedules.find { |s|
s[:name] == "puppet" and s[:period] == :hourly and s[:repeat] == 2
}).to be_instance_of(Puppet::Type.type(:schedule))
end
end
describe Puppet::Type.type(:schedule), "when matching ranges" do
before do
allow(Time).to receive(:now).and_return(Time.local(2011, "may", 23, 11, 0, 0))
end
it "should match when the start time is before the current time and the end time is after the current time" do
@schedule[:range] = "10:59:50 - 11:00:10"
expect(@schedule).to be_match
end
it "should not match when the start time is after the current time" do
@schedule[:range] = "11:00:05 - 11:00:10"
expect(@schedule).to_not be_match
end
it "should not match when the end time is previous to the current time" do
@schedule[:range] = "10:59:50 - 10:59:55"
expect(@schedule).to_not be_match
end
it "should not match the current time fails between an array of ranges" do
@schedule[:range] = ["4-6", "20-23"]
expect(@schedule).to_not be_match
end
it "should match the lower array of ranges" do
@schedule[:range] = ["9-11", "14-16"]
expect(@schedule).to be_match
end
it "should match the upper array of ranges" do
@schedule[:range] = ["11:30 - 6", "11-12"]
expect(@schedule).to be_match
end
end
describe Puppet::Type.type(:schedule), "when matching ranges with abbreviated time specifications" do
before do
allow(Time).to receive(:now).and_return(Time.local(2011, "may", 23, 11, 45, 59))
end
it "should match when just an hour is specified" do
@schedule[:range] = "11-12"
expect(@schedule).to be_match
end
it "should not match when the ending hour is the current hour" do
@schedule[:range] = "10-11"
expect(@schedule).to_not be_match
end
it "should not match when the ending minute is the current minute" do
@schedule[:range] = "10:00 - 11:45"
expect(@schedule).to_not be_match
end
end
describe Puppet::Type.type(:schedule), "when matching ranges with abbreviated time specifications, edge cases part 1" do
before do
allow(Time).to receive(:now).and_return(Time.local(2011, "may", 23, 11, 00, 00))
end
it "should match when the current time is the start of the range using hours" do
@schedule[:range] = "11 - 12"
expect(@schedule).to be_match
end
it "should match when the current time is the end of the range using hours" do
@schedule[:range] = "10 - 11"
expect(@schedule).to be_match
end
it "should match when the current time is the start of the range using hours and minutes" do
@schedule[:range] = "11:00 - 12:00"
expect(@schedule).to be_match
end
it "should match when the current time is the end of the range using hours and minutes" do
@schedule[:range] = "10:00 - 11:00"
expect(@schedule).to be_match
end
end
describe Puppet::Type.type(:schedule), "when matching ranges with abbreviated time specifications, edge cases part 2" do
before do
allow(Time).to receive(:now).and_return(Time.local(2011, "may", 23, 11, 00, 01))
end
it "should match when the current time is just past the start of the range using hours" do
@schedule[:range] = "11 - 12"
expect(@schedule).to be_match
end
it "should not match when the current time is just past the end of the range using hours" do
@schedule[:range] = "10 - 11"
expect(@schedule).to_not be_match
end
it "should match when the current time is just past the start of the range using hours and minutes" do
@schedule[:range] = "11:00 - 12:00"
expect(@schedule).to be_match
end
it "should not match when the current time is just past the end of the range using hours and minutes" do
@schedule[:range] = "10:00 - 11:00"
expect(@schedule).to_not be_match
end
end
describe Puppet::Type.type(:schedule), "when matching ranges with abbreviated time specifications, edge cases part 3" do
before do
allow(Time).to receive(:now).and_return(Time.local(2011, "may", 23, 10, 59, 59))
end
it "should not match when the current time is just before the start of the range using hours" do
@schedule[:range] = "11 - 12"
expect(@schedule).to_not be_match
end
it "should match when the current time is just before the end of the range using hours" do
@schedule[:range] = "10 - 11"
expect(@schedule).to be_match
end
it "should not match when the current time is just before the start of the range using hours and minutes" do
@schedule[:range] = "11:00 - 12:00"
expect(@schedule).to_not be_match
end
it "should match when the current time is just before the end of the range using hours and minutes" do
@schedule[:range] = "10:00 - 11:00"
expect(@schedule).to be_match
end
end
describe Puppet::Type.type(:schedule), "when matching ranges spanning days, day 1" do
before do
# Test with the current time at a month's end boundary to ensure we are
# advancing the day properly when we push the ending limit out a day.
# For example, adding 1 to 31 would throw an error instead of advancing
# the date.
allow(Time).to receive(:now).and_return(Time.local(2011, "mar", 31, 22, 30, 0))
end
it "should match when the start time is before current time and the end time is the following day" do
@schedule[:range] = "22:00:00 - 02:00:00"
expect(@schedule).to be_match
end
it "should not match when the current time is outside the range" do
@schedule[:range] = "23:30:00 - 21:00:00"
expect(@schedule).to_not be_match
end
end
describe Puppet::Type.type(:schedule), "when matching ranges spanning days, day 2" do
before do
# Test with the current time at a month's end boundary to ensure we are
# advancing the day properly when we push the ending limit out a day.
# For example, adding 1 to 31 would throw an error instead of advancing
# the date.
allow(Time).to receive(:now).and_return(Time.local(2011, "mar", 31, 1, 30, 0))
end
it "should match when the start time is the day before the current time and the end time is after the current time" do
@schedule[:range] = "22:00:00 - 02:00:00"
expect(@schedule).to be_match
end
it "should not match when the start time is after the current time" do
@schedule[:range] = "02:00:00 - 00:30:00"
expect(@schedule).to_not be_match
end
it "should not match when the end time is before the current time" do
@schedule[:range] = "22:00:00 - 01:00:00"
expect(@schedule).to_not be_match
end
end
describe Puppet::Type.type(:schedule), "when matching hourly by distance" do
before do
@schedule[:period] = :hourly
@schedule[:periodmatch] = :distance
allow(Time).to receive(:now).and_return(Time.local(2011, "may", 23, 11, 0, 0))
end
it "should match when the previous time was an hour ago" do
expect(@schedule).to be_match(hour("-", 1))
end
it "should not match when the previous time was now" do
expect(@schedule).to_not be_match(Time.now)
end
it "should not match when the previous time was 59 minutes ago" do
expect(@schedule).to_not be_match(min("-", 59))
end
end
describe Puppet::Type.type(:schedule), "when matching daily by distance" do
before do
@schedule[:period] = :daily
@schedule[:periodmatch] = :distance
allow(Time).to receive(:now).and_return(Time.local(2011, "may", 23, 11, 0, 0))
end
it "should match when the previous time was one day ago" do
expect(@schedule).to be_match(day("-", 1))
end
it "should not match when the previous time is now" do
expect(@schedule).to_not be_match(Time.now)
end
it "should not match when the previous time was 23 hours ago" do
expect(@schedule).to_not be_match(hour("-", 23))
end
end
describe Puppet::Type.type(:schedule), "when matching weekly by distance" do
before do
@schedule[:period] = :weekly
@schedule[:periodmatch] = :distance
allow(Time).to receive(:now).and_return(Time.local(2011, "may", 23, 11, 0, 0))
end
it "should match when the previous time was seven days ago" do
expect(@schedule).to be_match(day("-", 7))
end
it "should not match when the previous time was now" do
expect(@schedule).to_not be_match(Time.now)
end
it "should not match when the previous time was six days ago" do
expect(@schedule).to_not be_match(day("-", 6))
end
end
describe Puppet::Type.type(:schedule), "when matching monthly by distance" do
before do
@schedule[:period] = :monthly
@schedule[:periodmatch] = :distance
allow(Time).to receive(:now).and_return(Time.local(2011, "may", 23, 11, 0, 0))
end
it "should match when the previous time was 32 days ago" do
expect(@schedule).to be_match(day("-", 32))
end
it "should not match when the previous time was now" do
expect(@schedule).to_not be_match(Time.now)
end
it "should not match when the previous time was 27 days ago" do
expect(@schedule).to_not be_match(day("-", 27))
end
end
describe Puppet::Type.type(:schedule), "when matching hourly by number" do
before do
@schedule[:period] = :hourly
@schedule[:periodmatch] = :number
end
it "should match if the times are one minute apart and the current minute is 0" do
current = Time.utc(2008, 1, 1, 0, 0, 0)
previous = Time.utc(2007, 12, 31, 23, 59, 0)
allow(Time).to receive(:now).and_return(current)
expect(@schedule).to be_match(previous)
end
it "should not match if the times are 59 minutes apart and the current minute is 59" do
current = Time.utc(2009, 2, 1, 12, 59, 0)
previous = Time.utc(2009, 2, 1, 12, 0, 0)
allow(Time).to receive(:now).and_return(current)
expect(@schedule).to_not be_match(previous)
end
end
describe Puppet::Type.type(:schedule), "when matching daily by number" do
before do
@schedule[:period] = :daily
@schedule[:periodmatch] = :number
end
it "should match if the times are one minute apart and the current minute and hour are 0" do
current = Time.utc(2010, "nov", 7, 0, 0, 0)
# Now set the previous time to one minute before that
previous = current - 60
allow(Time).to receive(:now).and_return(current)
expect(@schedule).to be_match(previous)
end
it "should not match if the times are 23 hours and 58 minutes apart and the current hour is 23 and the current minute is 59" do
# Reset the previous time to 00:00:00
previous = Time.utc(2010, "nov", 7, 0, 0, 0)
# Set the current time to 23:59
now = previous + (23 * 3600) + (59 * 60)
allow(Time).to receive(:now).and_return(now)
expect(@schedule).to_not be_match(previous)
end
end
describe Puppet::Type.type(:schedule), "when matching weekly by number" do
before do
@schedule[:period] = :weekly
@schedule[:periodmatch] = :number
end
it "should match if the previous time is prior to the most recent Sunday" do
now = Time.utc(2010, "nov", 11, 0, 0, 0) # Thursday
allow(Time).to receive(:now).and_return(now)
previous = Time.utc(2010, "nov", 6, 23, 59, 59) # Sat
expect(@schedule).to be_match(previous)
end
it "should not match if the previous time is after the most recent Saturday" do
now = Time.utc(2010, "nov", 11, 0, 0, 0) # Thursday
allow(Time).to receive(:now).and_return(now)
previous = Time.utc(2010, "nov", 7, 0, 0, 0) # Sunday
expect(@schedule).to_not be_match(previous)
end
end
describe Puppet::Type.type(:schedule), "when matching monthly by number" do
before do
@schedule[:period] = :monthly
@schedule[:periodmatch] = :number
end
it "should match when the previous time is prior to the first day of this month" do
now = Time.utc(2010, "nov", 8, 00, 59, 59)
allow(Time).to receive(:now).and_return(now)
previous = Time.utc(2010, "oct", 31, 23, 59, 59)
expect(@schedule).to be_match(previous)
end
it "should not match when the previous time is after the last day of last month" do
now = Time.utc(2010, "nov", 8, 00, 59, 59)
allow(Time).to receive(:now).and_return(now)
previous = Time.utc(2010, "nov", 1, 0, 0, 0)
expect(@schedule).to_not be_match(previous)
end
end
describe Puppet::Type.type(:schedule), "when matching with a repeat greater than one" do
before do
@schedule[:period] = :daily
@schedule[:repeat] = 2
allow(Time).to receive(:now).and_return(Time.local(2011, "may", 23, 11, 0, 0))
end
it "should fail if the periodmatch is 'number'" do
@schedule[:periodmatch] = :number
expect {
@schedule[:repeat] = 2
}.to raise_error(Puppet::Error)
end
it "should match if the previous run was further away than the distance divided by the repeat" do
previous = Time.now - (3600 * 13)
expect(@schedule).to be_match(previous)
end
it "should not match if the previous run was closer than the distance divided by the repeat" do
previous = Time.now - (3600 * 11)
expect(@schedule).to_not be_match(previous)
end
end
describe Puppet::Type.type(:schedule), "when matching days of the week" do
before do
# 2011-05-23 is a Monday
allow(Time).to receive(:now).and_return(Time.local(2011, "may", 23, 11, 0, 0))
end
it "should raise an error if the weekday is 'Someday'" do
expect { @schedule[:weekday] = "Someday" }.to raise_error(Puppet::Error)
end
it "should raise an error if the weekday is '7'" do
expect { @schedule[:weekday] = "7" }.to raise_error(Puppet::Error)
end
it "should accept all full weekday names as valid values" do
expect { @schedule[:weekday] = ['Sunday', 'Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday', 'Saturday'] }.not_to raise_error
end
it "should accept all short weekday names as valid values" do
expect { @schedule[:weekday] = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu',
'Fri', 'Sat'] }.not_to raise_error
end
it "should accept all integers 0-6 as valid values" do
expect {@schedule[:weekday] = [0, 1, 2, 3, 4,
5, 6] }.not_to raise_error
end
it "should match if the weekday is 'Monday'" do
@schedule[:weekday] = "Monday"
expect(@schedule.match?).to be_truthy
end
it "should match if the weekday is 'Mon'" do
@schedule[:weekday] = "Mon"
expect(@schedule.match?).to be_truthy
end
it "should match if the weekday is '1'" do
@schedule[:weekday] = "1"
expect(@schedule.match?).to be_truthy
end
it "should match if weekday is 1" do
@schedule[:weekday] = 1
expect(@schedule).to be_match
end
it "should not match if the weekday is Tuesday" do
@schedule[:weekday] = "Tuesday"
expect(@schedule).not_to be_match
end
it "should match if weekday is ['Sun', 'Mon']" do
@schedule[:weekday] = ["Sun", "Mon"]
expect(@schedule.match?).to be_truthy
end
it "should not match if weekday is ['Sun', 'Tue']" do
@schedule[:weekday] = ["Sun", "Tue"]
expect(@schedule).not_to be_match
end
it "should match if the weekday is 'Monday'" do
@schedule[:weekday] = "Monday"
expect(@schedule.match?).to be_truthy
end
it "should match if the weekday is 'Mon'" do
@schedule[:weekday] = "Mon"
expect(@schedule.match?).to be_truthy
end
it "should match if the weekday is '1'" do
@schedule[:weekday] = "1"
expect(@schedule.match?).to be_truthy
end
it "should not match if the weekday is Tuesday" do
@schedule[:weekday] = "Tuesday"
expect(@schedule).not_to be_match
end
it "should match if weekday is ['Sun', 'Mon']" do
@schedule[:weekday] = ["Sun", "Mon"]
expect(@schedule.match?).to be_truthy
end
end
it "should raise an error if the weekday is an int higher than 6" do
expect { @schedule[:weekday] = 7 }.to raise_error(Puppet::ResourceError, /7 is not a valid day of the week/)
end
describe Puppet::Type.type(:schedule), "when matching days of week and ranges spanning days, day 1" do
before do
# Test with ranges and days-of-week both set. 2011-03-31 was a Thursday.
allow(Time).to receive(:now).and_return(Time.local(2011, "mar", 31, 22, 30, 0))
end
it "should match when the range and day of week matches" do
@schedule[:range] = "22:00:00 - 02:00:00"
@schedule[:weekday] = "Thursday"
expect(@schedule).to be_match
end
it "should not match when the range doesn't match even if the day-of-week matches" do
@schedule[:range] = "23:30:00 - 21:00:00"
@schedule[:weekday] = "Thursday"
expect(@schedule).to_not be_match
end
it "should not match when day-of-week doesn't match even if the range matches (1 day later)" do
@schedule[:range] = "22:00:00 - 01:00:00"
@schedule[:weekday] = "Friday"
expect(@schedule).to_not be_match
end
it "should not match when day-of-week doesn't match even if the range matches (1 day earlier)" do
@schedule[:range] = "22:00:00 - 01:00:00"
@schedule[:weekday] = "Wednesday"
expect(@schedule).to_not be_match
end
end
describe Puppet::Type.type(:schedule), "when matching days of week and ranges spanning days, day 2" do
before do
# 2011-03-31 was a Thursday. As the end-time of a day spanning match, that means
# we need to match on Wednesday.
allow(Time).to receive(:now).and_return(Time.local(2011, "mar", 31, 1, 30, 0))
end
it "should match when the range matches and the day of week should match" do
@schedule[:range] = "22:00:00 - 02:00:00"
@schedule[:weekday] = "Wednesday"
expect(@schedule).to be_match
end
it "should not match when the range does not match and the day of week should match" do
@schedule[:range] = "22:00:00 - 01:00:00"
@schedule[:weekday] = "Thursday"
expect(@schedule).to_not be_match
end
it "should not match when the range matches but the day-of-week does not (1 day later)" do
@schedule[:range] = "22:00:00 - 02:00:00"
@schedule[:weekday] = "Thursday"
expect(@schedule).to_not be_match
end
it "should not match when the range matches but the day-of-week does not (1 day later)" do
@schedule[:range] = "22:00:00 - 02:00:00"
@schedule[:weekday] = "Tuesday"
expect(@schedule).to_not be_match
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/type/service_spec.rb | spec/unit/type/service_spec.rb | require 'spec_helper'
def safely_load_service_type
before(:each) do
# We have a :confine block that calls execute in our upstart provider, which fails
# on jruby. Thus, we stub it out here since we don't care to do any assertions on it.
# This is only an issue if you're running these unit tests on a platform where upstart
# is a default provider, like Ubuntu trusty.
allow(Puppet::Util::Execution).to receive(:execute)
Puppet::Type.type(:service)
end
end
test_title = 'Puppet::Type::Service'
describe test_title do
safely_load_service_type
it "should have an :enableable feature that requires the :enable, :disable, and :enabled? methods" do
expect(Puppet::Type.type(:service).provider_feature(:enableable).methods).to eq([:disable, :enable, :enabled?])
end
it "should have a :refreshable feature that requires the :restart method" do
expect(Puppet::Type.type(:service).provider_feature(:refreshable).methods).to eq([:restart])
end
end
describe test_title, "when validating attributes" do
safely_load_service_type
[:name, :binary, :hasstatus, :path, :pattern, :start, :restart, :stop, :status, :hasrestart, :control, :timeout].each do |param|
it "should have a #{param} parameter" do
expect(Puppet::Type.type(:service).attrtype(param)).to eq(:param)
end
end
[:ensure, :enable].each do |param|
it "should have an #{param} property" do
expect(Puppet::Type.type(:service).attrtype(param)).to eq(:property)
end
end
end
describe test_title, "when validating attribute values" do
safely_load_service_type
before do
@provider = double('provider', :class => Puppet::Type.type(:service).defaultprovider, :clear => nil, :controllable? => false)
allow(Puppet::Type.type(:service).defaultprovider).to receive(:new).and_return(@provider)
end
it "should support :running as a value to :ensure" do
Puppet::Type.type(:service).new(:name => "yay", :ensure => :running)
end
it "should support :stopped as a value to :ensure" do
Puppet::Type.type(:service).new(:name => "yay", :ensure => :stopped)
end
it "should alias the value :true to :running in :ensure" do
svc = Puppet::Type.type(:service).new(:name => "yay", :ensure => true)
expect(svc.should(:ensure)).to eq(:running)
end
it "should alias the value :false to :stopped in :ensure" do
svc = Puppet::Type.type(:service).new(:name => "yay", :ensure => false)
expect(svc.should(:ensure)).to eq(:stopped)
end
describe "the enable property" do
before :each do
allow(@provider.class).to receive(:supports_parameter?).and_return(true)
end
describe "for value without required features" do
before :each do
allow(@provider).to receive(:satisfies?)
end
it "should not support :mask as a value" do
expect { Puppet::Type.type(:service).new(:name => "yay", :enable => :mask) }.to raise_error(
Puppet::ResourceError,
/Provider .+ must have features 'maskable' to set 'enable' to 'mask'/
)
end
it "should not support :manual as a value" do
expect { Puppet::Type.type(:service).new(:name => "yay", :enable => :manual) }.to raise_error(
Puppet::ResourceError,
/Provider .+ must have features 'manual_startable' to set 'enable' to 'manual'/
)
end
it "should not support :mask as a value" do
expect { Puppet::Type.type(:service).new(:name => "yay", :enable => :delayed) }.to raise_error(
Puppet::ResourceError,
/Provider .+ must have features 'delayed_startable' to set 'enable' to 'delayed'/
)
end
end
describe "for value with required features" do
before :each do
allow(@provider).to receive(:satisfies?).and_return(:true)
end
it "should support :true as a value" do
srv = Puppet::Type.type(:service).new(:name => "yay", :enable => :true)
expect(srv.should(:enable)).to eq(:true)
end
it "should support :false as a value" do
srv = Puppet::Type.type(:service).new(:name => "yay", :enable => :false)
expect(srv.should(:enable)).to eq(:false)
end
it "should support :mask as a value" do
srv = Puppet::Type.type(:service).new(:name => "yay", :enable => :mask)
expect(srv.should(:enable)).to eq(:mask)
end
it "should support :manual as a value on Windows" do
allow(Puppet::Util::Platform).to receive(:windows?).and_return(true)
srv = Puppet::Type.type(:service).new(:name => "yay", :enable => :manual)
expect(srv.should(:enable)).to eq(:manual)
end
it "should support :delayed as a value on Windows" do
allow(Puppet::Util::Platform).to receive(:windows?).and_return(true)
srv = Puppet::Type.type(:service).new(:name => "yay", :enable => :delayed)
expect(srv.should(:enable)).to eq(:delayed)
end
end
end
describe "the timeout parameter" do
before do
provider_class_with_timeout = Puppet::Type.type(:service).provide(:simple) do
has_features :configurable_timeout
end
allow(Puppet::Type.type(:service)).to receive(:defaultprovider).and_return(provider_class_with_timeout)
end
it "should fail when timeout is not an integer" do
expect { Puppet::Type.type(:service).new(:name => "yay", :timeout => 'foobar') }.to raise_error(Puppet::Error)
end
[-999, -1, 0].each do |int|
it "should not support #{int} as a value to :timeout" do
expect { Puppet::Type.type(:service).new(:name => "yay", :timeout => int) }.to raise_error(Puppet::Error)
end
end
[1, 30, 999].each do |int|
it "should support #{int} as a value to :timeout" do
srv = Puppet::Type.type(:service).new(:name => "yay", :timeout => int)
expect(srv[:timeout]).to eq(int)
end
end
it "should default :timeout to 10 when provider has no default value" do
srv = Puppet::Type.type(:service).new(:name => "yay")
expect(srv[:timeout]).to eq(10)
end
it "should default :timeout to provider given default time when it has one" do
provider_class_with_timeout = Puppet::Type.type(:service).provide(:simple) do
has_features :configurable_timeout
def default_timeout
30
end
end
allow(Puppet::Type.type(:service)).to receive(:defaultprovider).and_return(provider_class_with_timeout)
srv = Puppet::Type.type(:service).new(:name => "yay")
expect(srv[:timeout]).to eq(30)
end
it "should accept string as value" do
srv = Puppet::Type.type(:service).new(:name => "yay", :timeout => "25")
expect(srv[:timeout]).to eq(25)
end
it "should not support values that cannot be converted to Integer such as Array" do
expect { Puppet::Type.type(:service).new(:name => "yay", :timeout => [25]) }.to raise_error(Puppet::Error)
end
end
describe "the service logon credentials" do
before do
provider_class_with_logon_credentials = Puppet::Type.type(:service).provide(:simple) do
has_features :manages_logon_credentials
def logonpassword=(value) end
def logonaccount_insync?(current) end
end
allow(Puppet::Type.type(:service)).to receive(:defaultprovider).and_return(provider_class_with_logon_credentials)
end
describe "the 'logonaccount' property" do
let(:service) {Puppet::Type.type(:service).new(:name => "yay", :logonaccount => 'myUser')}
it "should let superclass implementation resolve insyncness when provider does not respond to the 'logonaccount_insync?' method" do
allow(service.provider).to receive(:respond_to?).with(:logonaccount_insync?).and_return(false)
expect(service.property(:logonaccount).insync?('myUser')).to eq(true)
end
it "should let provider resolve insyncness when provider responds to the 'logonaccount_insync?' method" do
allow(service.provider).to receive(:respond_to?).with(:logonaccount_insync?, any_args).and_return(true)
allow(service.provider).to receive(:logonaccount_insync?).and_return(false)
expect(service.property(:logonaccount).insync?('myUser')).to eq(false)
end
end
describe "the logonpassword parameter" do
it "should fail when logonaccount is not being managed as well" do
expect { Puppet::Type.type(:service).new(:name => "yay", :logonpassword => 'myPass') }.to raise_error(Puppet::Error, /The 'logonaccount' parameter is mandatory when setting 'logonpassword'./)
end
it "should default to empty string when only logonaccount is being managed" do
service = Puppet::Type.type(:service).new(:name => "yay", :logonaccount => 'myUser')
expect { service }.not_to raise_error
expect(service[:logonpassword]).to eq("")
end
it "should default to nil when not even logonaccount is being managed" do
service = Puppet::Type.type(:service).new(:name => "yay")
expect(service[:logonpassword]).to eq(nil)
end
it "should fail when logonpassword includes the ':' character" do
expect { Puppet::Type.type(:service).new(:name => "yay", :logonaccount => 'myUser', :logonpassword => 'my:Pass') }.to raise_error(Puppet::Error, /Passwords cannot include ':'/)
end
end
end
it "should support :true as a value to :hasstatus" do
srv = Puppet::Type.type(:service).new(:name => "yay", :hasstatus => :true)
expect(srv[:hasstatus]).to eq(:true)
end
it "should support :false as a value to :hasstatus" do
srv = Puppet::Type.type(:service).new(:name => "yay", :hasstatus => :false)
expect(srv[:hasstatus]).to eq(:false)
end
it "should specify :true as the default value of hasstatus" do
srv = Puppet::Type.type(:service).new(:name => "yay")
expect(srv[:hasstatus]).to eq(:true)
end
it "should support :true as a value to :hasrestart" do
srv = Puppet::Type.type(:service).new(:name => "yay", :hasrestart => :true)
expect(srv[:hasrestart]).to eq(:true)
end
it "should support :false as a value to :hasrestart" do
srv = Puppet::Type.type(:service).new(:name => "yay", :hasrestart => :false)
expect(srv[:hasrestart]).to eq(:false)
end
it "should allow setting the :enable parameter if the provider has the :enableable feature" do
allow(Puppet::Type.type(:service).defaultprovider).to receive(:supports_parameter?).and_return(true)
expect(Puppet::Type.type(:service).defaultprovider).to receive(:supports_parameter?).with(Puppet::Type.type(:service).attrclass(:enable)).and_return(true)
svc = Puppet::Type.type(:service).new(:name => "yay", :enable => true)
expect(svc.should(:enable)).to eq(:true)
end
it "should not allow setting the :enable parameter if the provider is missing the :enableable feature" do
allow(Puppet::Type.type(:service).defaultprovider).to receive(:supports_parameter?).and_return(true)
expect(Puppet::Type.type(:service).defaultprovider).to receive(:supports_parameter?).with(Puppet::Type.type(:service).attrclass(:enable)).and_return(false)
svc = Puppet::Type.type(:service).new(:name => "yay", :enable => true)
expect(svc.should(:enable)).to be_nil
end
it "should split paths on '#{File::PATH_SEPARATOR}'" do
allow(Puppet::FileSystem).to receive(:exist?).and_return(true)
allow(FileTest).to receive(:directory?).and_return(true)
svc = Puppet::Type.type(:service).new(:name => "yay", :path => "/one/two#{File::PATH_SEPARATOR}/three/four")
expect(svc[:path]).to eq(%w{/one/two /three/four})
end
it "should accept arrays of paths joined by '#{File::PATH_SEPARATOR}'" do
allow(Puppet::FileSystem).to receive(:exist?).and_return(true)
allow(FileTest).to receive(:directory?).and_return(true)
svc = Puppet::Type.type(:service).new(:name => "yay", :path => ["/one#{File::PATH_SEPARATOR}/two", "/three#{File::PATH_SEPARATOR}/four"])
expect(svc[:path]).to eq(%w{/one /two /three /four})
end
end
describe test_title, "when setting default attribute values" do
safely_load_service_type
it "should default to the provider's default path if one is available" do
allow(FileTest).to receive(:directory?).and_return(true)
allow(Puppet::FileSystem).to receive(:exist?).and_return(true)
allow(Puppet::Type.type(:service).defaultprovider).to receive(:respond_to?).and_return(true)
allow(Puppet::Type.type(:service).defaultprovider).to receive(:defpath).and_return("testing")
svc = Puppet::Type.type(:service).new(:name => "other")
expect(svc[:path]).to eq(["testing"])
end
it "should default 'pattern' to the binary if one is provided" do
svc = Puppet::Type.type(:service).new(:name => "other", :binary => "/some/binary")
expect(svc[:pattern]).to eq("/some/binary")
end
it "should default 'pattern' to the name if no pattern is provided" do
svc = Puppet::Type.type(:service).new(:name => "other")
expect(svc[:pattern]).to eq("other")
end
it "should default 'control' to the upcased service name with periods replaced by underscores if the provider supports the 'controllable' feature" do
provider = double('provider', :controllable? => true, :class => Puppet::Type.type(:service).defaultprovider, :clear => nil)
allow(Puppet::Type.type(:service).defaultprovider).to receive(:new).and_return(provider)
svc = Puppet::Type.type(:service).new(:name => "nfs.client")
expect(svc[:control]).to eq("NFS_CLIENT_START")
end
end
describe test_title, "when retrieving the host's current state" do
safely_load_service_type
before do
@service = Puppet::Type.type(:service).new(:name => "yay")
end
it "should use the provider's status to determine whether the service is running" do
expect(@service.provider).to receive(:status).and_return(:yepper)
@service[:ensure] = :running
expect(@service.property(:ensure).retrieve).to eq(:yepper)
end
it "should ask the provider whether it is enabled" do
allow(@service.provider.class).to receive(:supports_parameter?).and_return(true)
expect(@service.provider).to receive(:enabled?).and_return(:yepper)
@service[:enable] = true
expect(@service.property(:enable).retrieve).to eq(:yepper)
end
end
describe test_title, "when changing the host" do
safely_load_service_type
before do
@service = Puppet::Type.type(:service).new(:name => "yay")
end
it "should start the service if it is supposed to be running" do
@service[:ensure] = :running
expect(@service.provider).to receive(:start)
@service.property(:ensure).sync
end
it "should stop the service if it is supposed to be stopped" do
@service[:ensure] = :stopped
expect(@service.provider).to receive(:stop)
@service.property(:ensure).sync
end
it "should enable the service if it is supposed to be enabled" do
allow(@service.provider.class).to receive(:supports_parameter?).and_return(true)
@service[:enable] = true
expect(@service.provider).to receive(:enable)
@service.property(:enable).sync
end
it "should disable the service if it is supposed to be disabled" do
allow(@service.provider.class).to receive(:supports_parameter?).and_return(true)
@service[:enable] = false
expect(@service.provider).to receive(:disable)
@service.property(:enable).sync
end
it "should let superclass implementation resolve insyncness when provider does not respond to the 'enabled_insync?' method" do
allow(@service.provider.class).to receive(:supports_parameter?).and_return(true)
@service[:enable] = true
allow(@service.provider).to receive(:respond_to?).with(:enabled_insync?).and_return(false)
expect(@service.property(:enable).insync?(:true)).to eq(true)
end
it "insyncness should be resolved by provider instead of superclass implementation when provider responds to the 'enabled_insync?' method" do
allow(@service.provider.class).to receive(:supports_parameter?).and_return(true)
@service[:enable] = true
allow(@service.provider).to receive(:respond_to?).with(:enabled_insync?, any_args).and_return(true)
allow(@service.provider).to receive(:enabled_insync?).and_return(false)
expect(@service.property(:enable).insync?(:true)).to eq(false)
end
it "should sync the service's enable state when changing the state of :ensure if :enable is being managed" do
allow(@service.provider.class).to receive(:supports_parameter?).and_return(true)
@service[:enable] = false
@service[:ensure] = :stopped
expect(@service.property(:enable)).to receive(:retrieve).and_return("whatever")
expect(@service.property(:enable)).to receive(:insync?).and_return(false)
expect(@service.property(:enable)).to receive(:sync)
allow(@service.provider).to receive(:stop)
@service.property(:ensure).sync
end
it "should sync the service's logonaccount state when changing the state of :ensure if :logonaccount is being managed" do
allow(@service.provider.class).to receive(:supports_parameter?).and_return(true)
allow(Puppet::Util::Platform).to receive(:windows?).and_return(false)
@service[:ensure] = :stopped
@service[:logonaccount] = 'LocalSystem'
expect(@service.property(:logonaccount)).to receive(:retrieve).and_return("MyUser")
expect(@service.property(:logonaccount)).to receive(:insync?).and_return(false)
expect(@service.property(:logonaccount)).to receive(:sync)
allow(@service.provider).to receive(:stop)
@service.property(:ensure).sync
end
end
describe test_title, "when refreshing the service" do
safely_load_service_type
before do
@service = Puppet::Type.type(:service).new(:name => "yay")
end
it "should restart the service if it is running" do
@service[:ensure] = :running
expect(@service.provider).to receive(:status).and_return(:running)
expect(@service.provider).to receive(:restart)
@service.refresh
end
it "should restart the service if it is running, even if it is supposed to stopped" do
@service[:ensure] = :stopped
expect(@service.provider).to receive(:status).and_return(:running)
expect(@service.provider).to receive(:restart)
@service.refresh
end
it "should not restart the service if it is not running" do
@service[:ensure] = :running
expect(@service.provider).to receive(:status).and_return(:stopped)
@service.refresh
end
it "should add :ensure as a property if it is not being managed" do
expect(@service.provider).to receive(:status).and_return(:running)
expect(@service.provider).to receive(:restart)
@service.refresh
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/type/noop_metaparam_spec.rb | spec/unit/type/noop_metaparam_spec.rb | require 'spec_helper'
require 'puppet/type'
describe Puppet::Type.type(:file).attrclass(:noop) do
include PuppetSpec::Files
before do
allow(Puppet.settings).to receive(:use)
@file = Puppet::Type.newfile :path => make_absolute("/what/ever")
end
it "should accept true as a value" do
expect { @file[:noop] = true }.not_to raise_error
end
it "should accept false as a value" do
expect { @file[:noop] = false }.not_to raise_error
end
describe "when set on a resource" do
it "should default to the :noop setting" do
Puppet[:noop] = true
expect(@file.noop).to eq(true)
end
it "should prefer true values from the attribute" do
@file[:noop] = true
expect(@file.noop).to be_truthy
end
it "should prefer false values from the attribute" do
@file[:noop] = false
expect(@file.noop).to be_falsey
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/type/resources_spec.rb | spec/unit/type/resources_spec.rb | require 'spec_helper'
# A type and provider that can be purged
Puppet::Type.newtype(:purgeable_test) do
ensurable
newparam(:name) {}
end
Puppet::Type.type(:purgeable_test).provide(:purgeable_test) do
def self.instances
[]
end
end
resources = Puppet::Type.type(:resources)
# There are still plenty of tests to port over from test/.
describe resources do
before :each do
described_class.reset_system_users_max_uid!
end
context "when initializing" do
it "should fail if the specified resource type does not exist" do
allow(Puppet::Type).to receive(:type) do
expect(x.to_s.downcase).to eq("resources")
end.and_return(resources)
expect(Puppet::Type).to receive(:type).with("nosuchtype").and_return(nil)
expect { resources.new :name => "nosuchtype" }.to raise_error(Puppet::Error)
end
it "should not fail when the specified resource type exists" do
expect { resources.new :name => "file" }.not_to raise_error
end
it "should set its :resource_type attribute" do
expect(resources.new(:name => "file").resource_type).to eq(Puppet::Type.type(:file))
end
end
context "purge" do
let (:instance) { described_class.new(:name => 'file') }
it "defaults to false" do
expect(instance[:purge]).to be_falsey
end
it "can be set to false" do
instance[:purge] = 'false'
end
it "cannot be set to true for a resource type that does not accept ensure" do
allow(instance.resource_type).to receive(:validproperty?).with(:ensure).and_return(false)
expect { instance[:purge] = 'yes' }.to raise_error Puppet::Error, /Purging is only supported on types that accept 'ensure'/
end
it "cannot be set to true for a resource type that does not have instances" do
allow(instance.resource_type).to receive(:respond_to?).with(:instances).and_return(false)
expect { instance[:purge] = 'yes' }.to raise_error Puppet::Error, /Purging resources of type file is not supported/
end
it "can be set to true for a resource type that has instances and can accept ensure" do
allow(instance.resource_type).to receive(:validproperty?).and_return(true)
expect { instance[:purge] = 'yes' }.to_not raise_error
end
end
context "#check_user purge behaviour" do
context "with unless_system_user => true" do
before do
@res = Puppet::Type.type(:resources).new :name => :user, :purge => true, :unless_system_user => true
@res.catalog = Puppet::Resource::Catalog.new
allow(Puppet::FileSystem).to receive(:exist?).with('/etc/login.defs').and_return(false)
end
it "should never purge hardcoded system users" do
%w{root nobody bin noaccess daemon sys}.each do |sys_user|
expect(@res.user_check(Puppet::Type.type(:user).new(:name => sys_user))).to be_falsey
end
end
it "should not purge system users if unless_system_user => true" do
user_hash = {:name => 'system_user', :uid => 125, :system => true}
user = Puppet::Type.type(:user).new(user_hash)
allow(user).to receive(:retrieve_resource).and_return(Puppet::Resource.new("user", user_hash[:name], :parameters => user_hash))
expect(@res.user_check(user)).to be_falsey
end
it "should purge non-system users if unless_system_user => true" do
user_hash = {:name => 'system_user', :uid => described_class.system_users_max_uid + 1, :system => true}
user = Puppet::Type.type(:user).new(user_hash)
allow(user).to receive(:retrieve_resource).and_return(Puppet::Resource.new("user", user_hash[:name], :parameters => user_hash))
expect(@res.user_check(user)).to be_truthy
end
it "should not purge system users under 600 if unless_system_user => 600" do
res = Puppet::Type.type(:resources).new :name => :user, :purge => true, :unless_system_user => 600
res.catalog = Puppet::Resource::Catalog.new
user_hash = {:name => 'system_user', :uid => 500, :system => true}
user = Puppet::Type.type(:user).new(user_hash)
allow(user).to receive(:retrieve_resource).and_return(Puppet::Resource.new("user", user_hash[:name], :parameters => user_hash))
expect(res.user_check(user)).to be_falsey
end
it "should not purge Windows system users" do
res = Puppet::Type.type(:resources).new :name => :user, :purge => true
res.catalog = Puppet::Resource::Catalog.new
user_hash = {:name => 'Administrator', :uid => 'S-1-5-21-12345-500'}
user = Puppet::Type.type(:user).new(user_hash)
allow(user).to receive(:retrieve_resource).and_return(Puppet::Resource.new("user", user_hash[:name], :parameters => user_hash))
expect(res.user_check(user)).to be_falsey
end
it "should not purge Windows system users" do
res = Puppet::Type.type(:resources).new :name => :user, :purge => true
res.catalog = Puppet::Resource::Catalog.new
user_hash = {:name => 'other', :uid => 'S-1-5-21-12345-1001'}
user = Puppet::Type.type(:user).new(user_hash)
allow(user).to receive(:retrieve_resource).and_return(Puppet::Resource.new("user", user_hash[:name], :parameters => user_hash))
expect(res.user_check(user)).to be_truthy
end
end
%w(FreeBSD OpenBSD).each do |os|
context "on #{os}" do
before :each do
allow(Facter).to receive(:value).with(:kernel).and_return(os)
allow(Facter).to receive(:value).with('os.name').and_return(os)
allow(Facter).to receive(:value).with('os.family').and_return(os)
allow(Puppet::FileSystem).to receive(:exist?).with('/etc/login.defs').and_return(false)
@res = Puppet::Type.type(:resources).new :name => :user, :purge => true, :unless_system_user => true
@res.catalog = Puppet::Resource::Catalog.new
end
it "should not purge system users under 1000" do
user_hash = {:name => 'system_user', :uid => 999}
user = Puppet::Type.type(:user).new(user_hash)
allow(user).to receive(:retrieve_resource).and_return(Puppet::Resource.new("user", user_hash[:name], :parameters => user_hash))
expect(@res.user_check(user)).to be_falsey
end
it "should purge users over 999" do
user_hash = {:name => 'system_user', :uid => 1000}
user = Puppet::Type.type(:user).new(user_hash)
allow(user).to receive(:retrieve_resource).and_return(Puppet::Resource.new("user", user_hash[:name], :parameters => user_hash))
expect(@res.user_check(user)).to be_truthy
end
end
end
context 'with login.defs present' do
before :each do
expect(Puppet::FileSystem).to receive(:exist?).with('/etc/login.defs').and_return(true)
expect(Puppet::FileSystem).to receive(:each_line).with('/etc/login.defs').and_yield(' UID_MIN 1234 # UID_MIN comment ')
@res = Puppet::Type.type(:resources).new :name => :user, :purge => true, :unless_system_user => true
@res.catalog = Puppet::Resource::Catalog.new
end
it 'should not purge a system user' do
user_hash = {:name => 'system_user', :uid => 1233}
user = Puppet::Type.type(:user).new(user_hash)
allow(user).to receive(:retrieve_resource).and_return(Puppet::Resource.new("user", user_hash[:name], :parameters => user_hash))
expect(@res.user_check(user)).to be_falsey
end
it 'should purge a non-system user' do
user_hash = {:name => 'system_user', :uid => 1234}
user = Puppet::Type.type(:user).new(user_hash)
allow(user).to receive(:retrieve_resource).and_return(Puppet::Resource.new("user", user_hash[:name], :parameters => user_hash))
expect(@res.user_check(user)).to be_truthy
end
end
context "with unless_uid" do
context "with a uid array" do
before do
@res = Puppet::Type.type(:resources).new :name => :user, :purge => true, :unless_uid => [15_000, 15_001, 15_002]
@res.catalog = Puppet::Resource::Catalog.new
end
it "should purge uids that are not in a specified array" do
user_hash = {:name => 'special_user', :uid => 25_000}
user = Puppet::Type.type(:user).new(user_hash)
allow(user).to receive(:retrieve_resource).and_return(Puppet::Resource.new("user", user_hash[:name], :parameters => user_hash))
expect(@res.user_check(user)).to be_truthy
end
it "should not purge uids that are in a specified array" do
user_hash = {:name => 'special_user', :uid => 15000}
user = Puppet::Type.type(:user).new(user_hash)
allow(user).to receive(:retrieve_resource).and_return(Puppet::Resource.new("user", user_hash[:name], :parameters => user_hash))
expect(@res.user_check(user)).to be_falsey
end
end
context "with a single integer uid" do
before do
@res = Puppet::Type.type(:resources).new :name => :user, :purge => true, :unless_uid => 15_000
@res.catalog = Puppet::Resource::Catalog.new
end
it "should purge uids that are not specified" do
user_hash = {:name => 'special_user', :uid => 25_000}
user = Puppet::Type.type(:user).new(user_hash)
allow(user).to receive(:retrieve_resource).and_return(Puppet::Resource.new("user", user_hash[:name], :parameters => user_hash))
expect(@res.user_check(user)).to be_truthy
end
it "should not purge uids that are specified" do
user_hash = {:name => 'special_user', :uid => 15_000}
user = Puppet::Type.type(:user).new(user_hash)
allow(user).to receive(:retrieve_resource).and_return(Puppet::Resource.new("user", user_hash[:name], :parameters => user_hash))
expect(@res.user_check(user)).to be_falsey
end
end
context "with a single string uid" do
before do
@res = Puppet::Type.type(:resources).new :name => :user, :purge => true, :unless_uid => '15000'
@res.catalog = Puppet::Resource::Catalog.new
end
it "should purge uids that are not specified" do
user_hash = {:name => 'special_user', :uid => 25_000}
user = Puppet::Type.type(:user).new(user_hash)
allow(user).to receive(:retrieve_resource).and_return(Puppet::Resource.new("user", user_hash[:name], :parameters => user_hash))
expect(@res.user_check(user)).to be_truthy
end
it "should not purge uids that are specified" do
user_hash = {:name => 'special_user', :uid => 15_000}
user = Puppet::Type.type(:user).new(user_hash)
allow(user).to receive(:retrieve_resource).and_return(Puppet::Resource.new("user", user_hash[:name], :parameters => user_hash))
expect(@res.user_check(user)).to be_falsey
end
end
context "with a mixed uid array" do
before do
@res = Puppet::Type.type(:resources).new :name => :user, :purge => true, :unless_uid => ['15000', 16_666]
@res.catalog = Puppet::Resource::Catalog.new
end
it "should not purge ids in the range" do
user_hash = {:name => 'special_user', :uid => 15_000}
user = Puppet::Type.type(:user).new(user_hash)
allow(user).to receive(:retrieve_resource).and_return(Puppet::Resource.new("user", user_hash[:name], :parameters => user_hash))
expect(@res.user_check(user)).to be_falsey
end
it "should not purge specified ids" do
user_hash = {:name => 'special_user', :uid => 16_666}
user = Puppet::Type.type(:user).new(user_hash)
allow(user).to receive(:retrieve_resource).and_return(Puppet::Resource.new("user", user_hash[:name], :parameters => user_hash))
expect(@res.user_check(user)).to be_falsey
end
it "should purge unspecified ids" do
user_hash = {:name => 'special_user', :uid => 17_000}
user = Puppet::Type.type(:user).new(user_hash)
allow(user).to receive(:retrieve_resource).and_return(Puppet::Resource.new("user", user_hash[:name], :parameters => user_hash))
expect(@res.user_check(user)).to be_truthy
end
end
end
end
context "#generate" do
before do
@purgee = Puppet::Type.type(:purgeable_test).new(:name => 'localhost')
@catalog = Puppet::Resource::Catalog.new
end
context "when the catalog contains a purging resource with an alias" do
before do
@resource = Puppet::Type.type(:resources).new(:name => "purgeable_test", :purge => true)
@catalog.add_resource @resource
@catalog.alias(@resource, "purgeable_test_alias")
end
it "should not copy the alias metaparameter" do
allow(Puppet::Type.type(:purgeable_test)).to receive(:instances).and_return([@purgee])
generated = @resource.generate.first
expect(generated[:alias]).to be_nil
end
end
context "when dealing with non-purging resources" do
before do
@resources = Puppet::Type.type(:resources).new(:name => 'purgeable_test')
end
it "should not generate any resource" do
expect(@resources.generate).to be_empty
end
end
context "when the catalog contains a purging resource" do
before do
@resources = Puppet::Type.type(:resources).new(:name => 'purgeable_test', :purge => true)
@purgeable_resource = Puppet::Type.type(:purgeable_test).new(:name => 'localhost')
@catalog.add_resource @resources
end
it "should not generate a duplicate of that resource" do
allow(Puppet::Type.type(:purgeable_test)).to receive(:instances).and_return([@purgee])
@catalog.add_resource @purgee
expect(@resources.generate.collect { |r| r.ref }).not_to include(@purgee.ref)
end
it "should not include the skipped system users" do
res = Puppet::Type.type(:resources).new :name => :user, :purge => true
res.catalog = Puppet::Resource::Catalog.new
root = Puppet::Type.type(:user).new(:name => "root")
expect(Puppet::Type.type(:user)).to receive(:instances).and_return([root])
list = res.generate
names = list.collect { |r| r[:name] }
expect(names).not_to be_include("root")
end
context "when generating a purgeable resource" do
it "should be included in the generated resources" do
allow(Puppet::Type.type(:purgeable_test)).to receive(:instances).and_return([@purgeable_resource])
expect(@resources.generate.collect { |r| r.ref }).to include(@purgeable_resource.ref)
end
context "when the instance's do not have an ensure property" do
it "should not be included in the generated resources" do
@no_ensure_resource = Puppet::Type.type(:exec).new(:name => "#{File.expand_path('/usr/bin/env')} echo")
allow(Puppet::Type.type(:purgeable_test)).to receive(:instances).and_return([@no_ensure_resource])
expect(@resources.generate.collect { |r| r.ref }).not_to include(@no_ensure_resource.ref)
end
end
context "when the instance's ensure property does not accept absent" do
it "should not be included in the generated resources" do
# We have a :confine block that calls execute in our upstart provider, which fails
# on jruby. Thus, we stub it out here since we don't care to do any assertions on it.
# This is only an issue if you're running these unit tests on a platform where upstart
# is a default provider, like Ubuntu trusty.
allow(Puppet::Util::Execution).to receive(:execute)
@no_absent_resource = Puppet::Type.type(:service).new(:name => 'foobar')
allow(Puppet::Type.type(:purgeable_test)).to receive(:instances).and_return([@no_absent_resource])
expect(@resources.generate.collect { |r| r.ref }).not_to include(@no_absent_resource.ref)
end
end
context "when checking the instance fails" do
it "should not be included in the generated resources" do
@purgeable_resource = Puppet::Type.type(:purgeable_test).new(:name => 'foobar')
allow(Puppet::Type.type(:purgeable_test)).to receive(:instances).and_return([@purgeable_resource])
expect(@resources).to receive(:check).with(@purgeable_resource).and_return(false)
expect(@resources.generate.collect { |r| r.ref }).not_to include(@purgeable_resource.ref)
end
end
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/type/stage_spec.rb | spec/unit/type/stage_spec.rb | require 'spec_helper'
describe Puppet::Type.type(:stage) do
it "should have a 'name' parameter'" do
expect(Puppet::Type.type(:stage).new(:name => :foo)[:name]).to eq(:foo)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/type/user_spec.rb | spec/unit/type/user_spec.rb | # encoding: utf-8
require 'spec_helper'
describe Puppet::Type.type(:user) do
before :each do
@provider_class = described_class.provide(:simple) do
has_features :manages_expiry, :manages_password_age, :manages_passwords, :manages_solaris_rbac, :manages_roles, :manages_shell
mk_resource_methods
def create; end
def delete; end
def exists?; get(:ensure) != :absent; end
def flush; end
def self.instances; []; end
end
allow(described_class).to receive(:defaultprovider).and_return(@provider_class)
end
it "should be able to create an instance" do
expect(described_class.new(:name => "foo")).not_to be_nil
end
it "should have an allows_duplicates feature" do
expect(described_class.provider_feature(:allows_duplicates)).not_to be_nil
end
it "should have a manages_homedir feature" do
expect(described_class.provider_feature(:manages_homedir)).not_to be_nil
end
it "should have a manages_passwords feature" do
expect(described_class.provider_feature(:manages_passwords)).not_to be_nil
end
it "should have a manages_solaris_rbac feature" do
expect(described_class.provider_feature(:manages_solaris_rbac)).not_to be_nil
end
it "should have a manages_roles feature" do
expect(described_class.provider_feature(:manages_roles)).not_to be_nil
end
it "should have a manages_expiry feature" do
expect(described_class.provider_feature(:manages_expiry)).not_to be_nil
end
it "should have a manages_password_age feature" do
expect(described_class.provider_feature(:manages_password_age)).not_to be_nil
end
it "should have a system_users feature" do
expect(described_class.provider_feature(:system_users)).not_to be_nil
end
it "should have a manages_shell feature" do
expect(described_class.provider_feature(:manages_shell)).not_to be_nil
end
context "managehome" do
let (:provider) { @provider_class.new(:name => 'foo', :ensure => :absent) }
let (:instance) { described_class.new(:name => 'foo', :provider => provider) }
it "defaults to false" do
expect(instance[:managehome]).to be_falsey
end
it "can be set to false" do
instance[:managehome] = 'false'
end
it "cannot be set to true for a provider that does not manage homedirs" do
allow(provider.class).to receive(:manages_homedir?).and_return(false)
expect { instance[:managehome] = 'yes' }.to raise_error(Puppet::Error, /can not manage home directories/)
end
it "can be set to true for a provider that does manage homedirs" do
allow(provider.class).to receive(:manages_homedir?).and_return(true)
instance[:managehome] = 'yes'
end
end
describe "instances" do
it "should delegate existence questions to its provider" do
@provider = @provider_class.new(:name => 'foo', :ensure => :absent)
instance = described_class.new(:name => "foo", :provider => @provider)
expect(instance.exists?).to eq(false)
@provider.set(:ensure => :present)
expect(instance.exists?).to eq(true)
end
end
properties = [:ensure, :uid, :gid, :home, :comment, :shell, :password, :password_min_age, :password_max_age, :password_warn_days, :groups, :roles, :auths, :profiles, :project, :keys, :expiry]
properties.each do |property|
it "should have a #{property} property" do
expect(described_class.attrclass(property).ancestors).to be_include(Puppet::Property)
end
it "should have documentation for its #{property} property" do
expect(described_class.attrclass(property).doc).to be_instance_of(String)
end
end
list_properties = [:groups, :roles, :auths]
list_properties.each do |property|
it "should have a list '#{property}'" do
expect(described_class.attrclass(property).ancestors).to be_include(Puppet::Property::List)
end
end
it "should have an ordered list 'profiles'" do
expect(described_class.attrclass(:profiles).ancestors).to be_include(Puppet::Property::OrderedList)
end
it "should have key values 'keys'" do
expect(described_class.attrclass(:keys).ancestors).to be_include(Puppet::Property::KeyValue)
end
describe "when retrieving all current values" do
before do
@provider = @provider_class.new(:name => 'foo', :ensure => :present, :uid => 15, :gid => 15)
@user = described_class.new(:name => "foo", :uid => 10, :provider => @provider)
end
it "should return a hash containing values for all set properties" do
@user[:gid] = 10
values = @user.retrieve
[@user.property(:uid), @user.property(:gid)].each { |property| expect(values).to be_include(property) }
end
it "should set all values to :absent if the user is absent" do
expect(@user.property(:ensure)).to receive(:retrieve).and_return(:absent)
expect(@user.property(:uid)).not_to receive(:retrieve)
expect(@user.retrieve[@user.property(:uid)]).to eq(:absent)
end
it "should include the result of retrieving each property's current value if the user is present" do
expect(@user.retrieve[@user.property(:uid)]).to eq(15)
end
end
describe "when managing the ensure property" do
it "should support a :present value" do
expect { described_class.new(:name => 'foo', :ensure => :present) }.to_not raise_error
end
it "should support an :absent value" do
expect { described_class.new(:name => 'foo', :ensure => :absent) }.to_not raise_error
end
it "should call :create on the provider when asked to sync to the :present state" do
@provider = @provider_class.new(:name => 'foo', :ensure => :absent)
expect(@provider).to receive(:create)
described_class.new(:name => 'foo', :ensure => :present, :provider => @provider).parameter(:ensure).sync
end
it "should call :delete on the provider when asked to sync to the :absent state" do
@provider = @provider_class.new(:name => 'foo', :ensure => :present)
expect(@provider).to receive(:delete)
described_class.new(:name => 'foo', :ensure => :absent, :provider => @provider).parameter(:ensure).sync
end
describe "and determining the current state" do
it "should return :present when the provider indicates the user exists" do
@provider = @provider_class.new(:name => 'foo', :ensure => :present)
expect(described_class.new(:name => 'foo', :ensure => :absent, :provider => @provider).parameter(:ensure).retrieve).to eq(:present)
end
it "should return :absent when the provider indicates the user does not exist" do
@provider = @provider_class.new(:name => 'foo', :ensure => :absent)
expect(described_class.new(:name => 'foo', :ensure => :present, :provider => @provider).parameter(:ensure).retrieve).to eq(:absent)
end
end
end
describe "when managing the uid property" do
it "should convert number-looking strings into actual numbers" do
expect(described_class.new(:name => 'foo', :uid => '50')[:uid]).to eq(50)
end
it "should support UIDs as numbers" do
expect(described_class.new(:name => 'foo', :uid => 50)[:uid]).to eq(50)
end
it "should support :absent as a value" do
expect(described_class.new(:name => 'foo', :uid => :absent)[:uid]).to eq(:absent)
end
end
describe "when managing the gid" do
it "should support :absent as a value" do
expect(described_class.new(:name => 'foo', :gid => :absent)[:gid]).to eq(:absent)
end
it "should convert number-looking strings into actual numbers" do
expect(described_class.new(:name => 'foo', :gid => '50')[:gid]).to eq(50)
end
it "should support GIDs specified as integers" do
expect(described_class.new(:name => 'foo', :gid => 50)[:gid]).to eq(50)
end
it "should support groups specified by name" do
expect(described_class.new(:name => 'foo', :gid => 'foo')[:gid]).to eq('foo')
end
describe "when testing whether in sync" do
it "should return true if no 'should' values are set" do
# this is currently not the case because gid has no default value, so we would never even
# call insync? on that property
if param = described_class.new(:name => 'foo').parameter(:gid)
expect(param).to be_safe_insync(500)
end
end
it "should return true if any of the specified groups are equal to the current integer" do
expect(Puppet::Util).to receive(:gid).with("foo").and_return(300)
expect(Puppet::Util).to receive(:gid).with("bar").and_return(500)
expect(described_class.new(:name => 'baz', :gid => [ 'foo', 'bar' ]).parameter(:gid)).to be_safe_insync(500)
end
it "should return false if none of the specified groups are equal to the current integer" do
expect(Puppet::Util).to receive(:gid).with("foo").and_return(300)
expect(Puppet::Util).to receive(:gid).with("bar").and_return(500)
expect(described_class.new(:name => 'baz', :gid => [ 'foo', 'bar' ]).parameter(:gid)).to_not be_safe_insync(700)
end
end
describe "when syncing" do
it "should use the first found, specified group as the desired value and send it to the provider" do
expect(Puppet::Util).to receive(:gid).with("foo").and_return(nil)
expect(Puppet::Util).to receive(:gid).with("bar").and_return(500)
@provider = @provider_class.new(:name => 'foo')
resource = described_class.new(:name => 'foo', :provider => @provider, :gid => [ 'foo', 'bar' ])
expect(@provider).to receive(:gid=).with(500)
resource.parameter(:gid).sync
end
end
end
describe "when managing groups" do
it "should support a singe group" do
expect { described_class.new(:name => 'foo', :groups => 'bar') }.to_not raise_error
end
it "should support multiple groups as an array" do
expect { described_class.new(:name => 'foo', :groups => [ 'bar' ]) }.to_not raise_error
expect { described_class.new(:name => 'foo', :groups => [ 'bar', 'baz' ]) }.to_not raise_error
end
it "should not support a comma separated list" do
expect { described_class.new(:name => 'foo', :groups => 'bar,baz') }.to raise_error(Puppet::Error, /Group names must be provided as an array/)
end
it "should not support an empty string" do
expect { described_class.new(:name => 'foo', :groups => '') }.to raise_error(Puppet::Error, /Group names must not be empty/)
end
describe "when testing is in sync" do
before :each do
# the useradd provider uses a single string to represent groups and so does Puppet::Property::List when converting to should values
@provider = @provider_class.new(:name => 'foo', :groups => 'a,b,e,f')
end
it "should not care about order" do
@property = described_class.new(:name => 'foo', :groups => [ 'a', 'c', 'b' ]).property(:groups)
expect(@property).to be_safe_insync([ 'a', 'b', 'c' ])
expect(@property).to be_safe_insync([ 'a', 'c', 'b' ])
expect(@property).to be_safe_insync([ 'b', 'a', 'c' ])
expect(@property).to be_safe_insync([ 'b', 'c', 'a' ])
expect(@property).to be_safe_insync([ 'c', 'a', 'b' ])
expect(@property).to be_safe_insync([ 'c', 'b', 'a' ])
end
it "should merge current value and desired value if membership minimal" do
@instance = described_class.new(:name => 'foo', :groups => [ 'a', 'c', 'b' ], :provider => @provider)
@instance[:membership] = :minimum
expect(@instance[:groups]).to eq('a,b,c,e,f')
end
it "should not treat a subset of groups insync if membership inclusive" do
@instance = described_class.new(:name => 'foo', :groups => [ 'a', 'c', 'b' ], :provider => @provider)
@instance[:membership] = :inclusive
expect(@instance[:groups]).to eq('a,b,c')
end
end
end
describe "when managing the purge_ssh_keys property" do
context "with valid input" do
['true', :true, true].each do |input|
it "should support #{input} as value" do
expect { described_class.new(:name => 'foo', :purge_ssh_keys => input) }.to_not raise_error
end
end
['false', :false, false].each do |input|
it "should support #{input} as value" do
expect { described_class.new(:name => 'foo', :purge_ssh_keys => input) }.to_not raise_error
end
end
it "should support a String value" do
expect { described_class.new(:name => 'foo', :purge_ssh_keys => File.expand_path('home/foo/.ssh/authorized_keys')) }.to_not raise_error
end
it "should support an Array value" do
expect { described_class.new(:name => 'foo', :purge_ssh_keys => [File.expand_path('home/foo/.ssh/authorized_keys'),
File.expand_path('custom/authorized_keys')]) }.to_not raise_error
end
end
context "with faulty input" do
it "should raise error for relative path" do
expect { described_class.new(:name => 'foo', :purge_ssh_keys => 'home/foo/.ssh/authorized_keys') }.to raise_error(Puppet::ResourceError,
/Paths to keyfiles must be absolute/ )
end
it "should raise error for invalid type" do
expect { described_class.new(:name => 'foo', :purge_ssh_keys => :invalid) }.to raise_error(Puppet::ResourceError,
/purge_ssh_keys must be true, false, or an array of file names/ )
end
it "should raise error for array with relative path" do
expect { described_class.new(:name => 'foo', :purge_ssh_keys => ['home/foo/.ssh/authorized_keys',
File.expand_path('custom/authorized_keys')]) }.to raise_error(Puppet::ResourceError,
/Paths to keyfiles must be absolute/ )
end
it "should raise error for array with invalid type" do
expect { described_class.new(:name => 'foo', :purge_ssh_keys => [:invalid,
File.expand_path('custom/authorized_keys')]) }.to raise_error(Puppet::ResourceError,
/Each entry for purge_ssh_keys must be a string/ )
end
end
context "homedir retrieval" do
it "should accept the home provided" do
expect(Puppet).not_to receive(:debug).with("User 'foo' does not exist")
described_class.new(:name => 'foo', :purge_ssh_keys => true, :home => '/my_home')
end
it "should accept the home provided" do
expect(Dir).to receive(:home).with('foo').and_return('/my_home')
expect(Puppet).not_to receive(:debug).with("User 'foo' does not exist")
described_class.new(:name => 'foo', :purge_ssh_keys => true)
end
it "should output debug message when home directory cannot be retrieved" do
allow(Dir).to receive(:home).with('foo').and_raise(ArgumentError)
expect(Puppet).to receive(:debug).with("User 'foo' does not exist")
described_class.new(:name => 'foo', :purge_ssh_keys => true)
end
end
end
describe "when managing expiry" do
it "should fail if given an invalid date" do
expect { described_class.new(:name => 'foo', :expiry => "200-20-20") }.to raise_error(Puppet::Error, /Expiry dates must be YYYY-MM-DD/)
end
end
describe "when managing minimum password age" do
it "should accept a negative minimum age" do
expect { described_class.new(:name => 'foo', :password_min_age => '-1') }.to_not raise_error
end
it "should fail with an empty minimum age" do
expect { described_class.new(:name => 'foo', :password_min_age => '') }.to raise_error(Puppet::Error, /minimum age must be provided as a number/)
end
end
describe "when managing maximum password age" do
it "should accept a negative maximum age" do
expect { described_class.new(:name => 'foo', :password_max_age => '-1') }.to_not raise_error
end
it "should fail with an empty maximum age" do
expect { described_class.new(:name => 'foo', :password_max_age => '') }.to raise_error(Puppet::Error, /maximum age must be provided as a number/)
end
end
describe "when managing warning password days" do
it "should accept a negative warning days" do
expect { described_class.new(:name => 'foo', :password_warn_days => '-1') }.to_not raise_error
end
it "should fail with an empty warning days" do
expect { described_class.new(:name => 'foo', :password_warn_days => '') }.to raise_error(Puppet::Error, /warning days must be provided as a number/)
end
end
describe "when managing passwords" do
let(:transaction) { Puppet::Transaction.new(Puppet::Resource::Catalog.new, nil, nil) }
let(:harness) { Puppet::Transaction::ResourceHarness.new(transaction) }
let(:provider) { @provider_class.new(:name => 'foo', :ensure => :present) }
let(:resource) { described_class.new(:name => 'foo', :ensure => :present, :password => 'top secret', :provider => provider) }
it "should not include the password in the change log when adding the password" do
status = harness.evaluate(resource)
sync_event = status.events[0]
expect(sync_event.message).not_to include('top secret')
expect(sync_event.message).to eql('changed [redacted] to [redacted]')
end
it "should not include the password in the change log when changing the password" do
resource[:password] = 'super extra classified'
status = harness.evaluate(resource)
sync_event = status.events[0]
expect(sync_event.message).not_to include('super extra classified')
expect(sync_event.message).to eql('changed [redacted] to [redacted]')
end
it "should fail if a ':' is included in the password" do
expect { described_class.new(:name => 'foo', :password => "some:thing") }.to raise_error(Puppet::Error, /Passwords cannot include ':'/)
end
it "should allow the value to be set to :absent" do
expect { described_class.new(:name => 'foo', :password => :absent) }.to_not raise_error
end
end
describe "when managing comment" do
before :each do
@value = 'abcd™'
expect(@value.encoding).to eq(Encoding::UTF_8)
@user = described_class.new(:name => 'foo', :comment => @value)
end
describe "#insync" do
it "should delegate to the provider's #comments_insync? method if defined" do
# useradd subclasses nameservice and thus inherits #comments_insync?
user = described_class.new(:name => 'foo', :comment => @value, :provider => :useradd)
comment_property = user.properties.find {|p| p.name == :comment}
expect(user.provider).to receive(:comments_insync?)
comment_property.insync?('bar')
end
describe "#change_to_s" do
let(:is) { "\u2603" }
let(:should) { "\u06FF" }
let(:comment_property) { @user.properties.find { |p| p.name == :comment } }
context "given is and should strings with incompatible encoding" do
it "should return a formatted string" do
is.force_encoding(Encoding::ASCII_8BIT)
should.force_encoding(Encoding::UTF_8)
expect(Encoding.compatible?(is, should)).to be_falsey
expect(comment_property.change_to_s(is,should)).to match(/changed '\u{E2}\u{98}\u{83}' to '\u{DB}\u{BF}'/)
end
end
context "given is and should strings with compatible encoding" do
it "should return a formatted string" do
is.force_encoding(Encoding::UTF_8)
should.force_encoding(Encoding::UTF_8)
expect(Encoding.compatible?(is, should)).to be_truthy
expect(comment_property.change_to_s(is,should)).to match(/changed '\u{2603}' to '\u{6FF}'/u)
end
end
end
end
end
describe "when manages_solaris_rbac is enabled" do
it "should support a :role value for ensure" do
expect { described_class.new(:name => 'foo', :ensure => :role) }.to_not raise_error
end
end
describe "when user has roles" do
it "should autorequire roles on non-Windows", :unless => Puppet::Util::Platform.windows? do
testuser = described_class.new(:name => "testuser", :roles => ['testrole'] )
testrole = described_class.new(:name => "testrole")
Puppet::Resource::Catalog.new :testing do |conf|
[testuser, testrole].each { |resource| conf.add_resource resource }
end
rel = testuser.autorequire[0]
expect(rel.source.ref).to eq(testrole.ref)
expect(rel.target.ref).to eq(testuser.ref)
end
it "should not autorequire roles on Windows", :if => Puppet::Util::Platform.windows? do
testuser = described_class.new(:name => "testuser", :roles => ['testrole'] )
testrole = described_class.new(:name => "testrole")
Puppet::Resource::Catalog.new :testing do |conf|
[testuser, testrole].each { |resource| conf.add_resource resource }
end
expect(testuser.autorequire).to be_empty
end
it "should sync the user roles when changing the state of :ensure if :roles is being managed" do
user = Puppet::Type.type(:user).new(:name => "myUser", :ensure => :present)
user[:roles] = 'testRole'
allow(user.provider.class).to receive(:supports_parameter?).and_return(true)
expect(user.property(:roles)).to receive(:retrieve).and_return("other")
expect(user.property(:roles)).to receive(:insync?).and_return(false)
expect(user.property(:roles)).to receive(:sync)
allow(user.provider).to receive(:create)
user.property(:ensure).sync
end
end
describe "when setting shell" do
before :each do
@shell_provider_class = described_class.provide(:shell_manager) do
has_features :manages_shell
mk_resource_methods
def create; check_valid_shell;end
def shell=(value); check_valid_shell; end
def delete; end
def exists?; get(:ensure) != :absent; end
def flush; end
def self.instances; []; end
def check_valid_shell; end
end
allow(described_class).to receive(:defaultprovider).and_return(@shell_provider_class)
end
it "should call :check_valid_shell on the provider when changing shell value" do
@provider = @shell_provider_class.new(:name => 'foo', :shell => '/bin/bash', :ensure => :present)
expect(@provider).to receive(:check_valid_shell)
resource = described_class.new(:name => 'foo', :shell => '/bin/zsh', :provider => @provider)
allow(Puppet::Util::Storage).to receive(:load)
allow(Puppet::Util::Storage).to receive(:store)
catalog = Puppet::Resource::Catalog.new
catalog.add_resource resource
catalog.apply
end
it "should call :check_valid_shell on the provider when changing ensure from present to absent" do
@provider = @shell_provider_class.new(:name => 'foo', :shell => '/bin/bash', :ensure => :absent)
expect(@provider).to receive(:check_valid_shell)
resource = described_class.new(:name => 'foo', :shell => '/bin/zsh', :provider => @provider)
allow(Puppet::Util::Storage).to receive(:load)
allow(Puppet::Util::Storage).to receive(:store)
catalog = Puppet::Resource::Catalog.new
catalog.add_resource resource
catalog.apply
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/type/exec_spec.rb | spec/unit/type/exec_spec.rb | require 'spec_helper'
RSpec.describe Puppet::Type.type(:exec) do
include PuppetSpec::Files
def exec_tester(command, exitstatus = 0, rest = {})
allow(Puppet.features).to receive(:root?).and_return(true)
output = rest.delete(:output) || ''
output = Puppet::Util::Execution::ProcessOutput.new(output, exitstatus)
tries = rest[:tries] || 1
type_args = {
:name => command,
:path => @example_path,
:logoutput => false,
:loglevel => :err,
:returns => 0
}.merge(rest)
exec = Puppet::Type.type(:exec).new(type_args)
expect(Puppet::Util::Execution).to receive(:execute) do |cmd, options|
expect(cmd).to eq(command)
expect(options[:override_locale]).to eq(false)
expect(options).to have_key(:custom_environment)
output
end.exactly(tries).times
return exec
end
def exec_stub(options = {})
command = options.delete(:command) || @command
#unless_val = options.delete(:unless) || :true
type_args = {
:name => command,
#:unless => unless_val,
}.merge(options)
# Chicken, meet egg:
# Provider methods have to be stubbed before resource init or checks fail
# We have to set 'unless' in resource init or it can not be marked sensitive correctly.
# So: we create a dummy ahead of time and use 'any_instance' to stub out provider methods.
dummy = Puppet::Type.type(:exec).new(:name => @command)
allow_any_instance_of(dummy.provider.class).to receive(:validatecmd)
allow_any_instance_of(dummy.provider.class).to receive(:checkexe).and_return(true)
pass_status = double('status', :exitstatus => 0, :split => ["pass output"])
fail_status = double('status', :exitstatus => 1, :split => ["fail output"])
allow(Puppet::Util::Execution).to receive(:execute).with(:true, anything).and_return(pass_status)
allow(Puppet::Util::Execution).to receive(:execute).with(:false, anything).and_return(fail_status)
test = Puppet::Type.type(:exec).new(type_args)
Puppet::Util::Log.level = :debug
return test
end
before do
@command = make_absolute('/bin/true whatever')
@executable = make_absolute('/bin/true')
@bogus_cmd = make_absolute('/bogus/cmd')
end
describe "when not stubbing the provider" do
before do
path = tmpdir('path')
ext = Puppet::Util::Platform.windows? ? '.exe' : ''
true_cmd = File.join(path, "true#{ext}")
false_cmd = File.join(path, "false#{ext}")
FileUtils.touch(true_cmd)
FileUtils.touch(false_cmd)
File.chmod(0755, true_cmd)
File.chmod(0755, false_cmd)
@example_path = [path]
end
it "should return :executed_command as its event" do
resource = Puppet::Type.type(:exec).new :command => @command
expect(resource.parameter(:returns).event.name).to eq(:executed_command)
end
describe "when execing" do
it "should use the 'execute' method to exec" do
expect(exec_tester("true").refresh).to eq(:executed_command)
end
it "should report a failure" do
expect { exec_tester('false', 1).refresh }.
to raise_error(Puppet::Error, /^'false' returned 1 instead of/)
end
it "should redact sensitive commands on failure" do
expect { exec_tester('false', 1, :sensitive_parameters => [:command]).refresh }.
to raise_error(Puppet::Error, /^\[command redacted\] returned 1 instead of/)
end
it "should not report a failure if the exit status is specified in a returns array" do
expect { exec_tester("false", 1, :returns => [0, 1]).refresh }.to_not raise_error
end
it "should report a failure if the exit status is not specified in a returns array" do
expect { exec_tester('false', 1, :returns => [0, 100]).refresh }.
to raise_error(Puppet::Error, /^'false' returned 1 instead of/)
end
it "should report redact sensitive commands if the exit status is not specified in a returns array" do
expect { exec_tester('false', 1, :returns => [0, 100], :sensitive_parameters => [:command]).refresh }.
to raise_error(Puppet::Error, /^\[command redacted\] returned 1 instead of/)
end
it "should log the output on success" do
output = "output1\noutput2\n"
exec_tester('false', 0, :output => output, :logoutput => true).refresh
output.split("\n").each do |line|
log = @logs.shift
expect(log.level).to eq(:err)
expect(log.message).to eq(line)
end
end
it "should log the output on failure" do
output = "output1\noutput2\n"
expect { exec_tester('false', 1, :output => output, :logoutput => true).refresh }.
to raise_error(Puppet::Error)
output.split("\n").each do |line|
log = @logs.shift
expect(log.level).to eq(:err)
expect(log.message).to eq(line)
end
end
end
describe "when logoutput=>on_failure is set" do
it "should log the output on failure" do
output = "output1\noutput2\n"
expect { exec_tester('false', 1, :output => output, :logoutput => :on_failure).refresh }.
to raise_error(Puppet::Error, /^'false' returned 1 instead of/)
output.split("\n").each do |line|
log = @logs.shift
expect(log.level).to eq(:err)
expect(log.message).to eq(line)
end
end
it "should redact the sensitive command on failure" do
output = "output1\noutput2\n"
expect { exec_tester('false', 1, :output => output, :logoutput => :on_failure, :sensitive_parameters => [:command]).refresh }.
to raise_error(Puppet::Error, /^\[command redacted\] returned 1 instead of/)
expect(@logs).to include(an_object_having_attributes(level: :err, message: '[output redacted]'))
expect(@logs).to_not include(an_object_having_attributes(message: /output1|output2/))
end
it "should log the output on failure when returns is specified as an array" do
output = "output1\noutput2\n"
expect {
exec_tester('false', 1, :output => output, :returns => [0, 100],
:logoutput => :on_failure).refresh
}.to raise_error(Puppet::Error, /^'false' returned 1 instead of/)
output.split("\n").each do |line|
log = @logs.shift
expect(log.level).to eq(:err)
expect(log.message).to eq(line)
end
end
it "should redact the sensitive command on failure when returns is specified as an array" do
output = "output1\noutput2\n"
expect {
exec_tester('false', 1, :output => output, :returns => [0, 100],
:logoutput => :on_failure, :sensitive_parameters => [:command]).refresh
}.to raise_error(Puppet::Error, /^\[command redacted\] returned 1 instead of/)
expect(@logs).to include(an_object_having_attributes(level: :err, message: '[output redacted]'))
expect(@logs).to_not include(an_object_having_attributes(message: /output1|output2/))
end
it "shouldn't log the output on success" do
exec_tester('true', 0, :output => "a\nb\nc\n", :logoutput => :on_failure).refresh
expect(@logs).to eq([])
end
end
it "shouldn't log the output on success when non-zero exit status is in a returns array" do
exec_tester("true", 100, :output => "a\n", :logoutput => :on_failure, :returns => [1, 100]).refresh
expect(@logs).to eq([])
end
describe "when checks stop execution when debugging" do
[[:unless, :true], [:onlyif, :false]].each do |check, result|
it "should log a message with the command when #{check} is #{result}" do
output = "'#{@command}' won't be executed because of failed check '#{check}'"
test = exec_stub({:command => @command, check => result})
expect(test.check_all_attributes).to eq(false)
expect(@logs).to include(an_object_having_attributes(level: :debug, message: output))
end
it "should log a message with a redacted command and check if #{check} is sensitive" do
output1 = "Executing check '[redacted]'"
output2 = "'[command redacted]' won't be executed because of failed check '#{check}'"
test = exec_stub({:command => @command, check => result, :sensitive_parameters => [check]})
expect(test.check_all_attributes).to eq(false)
expect(@logs).to include(an_object_having_attributes(level: :debug, message: output1))
expect(@logs).to include(an_object_having_attributes(level: :debug, message: output2))
end
end
end
describe " when multiple tries are set," do
it "should repeat the command attempt 'tries' times on failure and produce an error" do
tries = 5
resource = exec_tester("false", 1, :tries => tries, :try_sleep => 0)
expect { resource.refresh }.to raise_error(Puppet::Error)
end
end
end
it "should be able to autorequire files mentioned in the command" do
foo = make_absolute('/bin/foo')
catalog = Puppet::Resource::Catalog.new
tmp = Puppet::Type.type(:file).new(:name => foo)
execer = Puppet::Type.type(:exec).new(:name => foo)
catalog.add_resource tmp
catalog.add_resource execer
dependencies = execer.autorequire(catalog)
expect(dependencies.collect(&:to_s)).to eq([Puppet::Relationship.new(tmp, execer).to_s])
end
it "should be able to autorequire files mentioned in the array command" do
foo = make_absolute('/bin/foo')
catalog = Puppet::Resource::Catalog.new
tmp = Puppet::Type.type(:file).new(:name => foo)
execer = Puppet::Type.type(:exec).new(:name => 'test array', :command => [foo, 'bar'])
catalog.add_resource tmp
catalog.add_resource execer
dependencies = execer.autorequire(catalog)
expect(dependencies.collect(&:to_s)).to eq([Puppet::Relationship.new(tmp, execer).to_s])
end
it "skips autorequire for deferred commands" do
foo = make_absolute('/bin/foo')
catalog = Puppet::Resource::Catalog.new
tmp = Puppet::Type.type(:file).new(:name => foo)
execer = Puppet::Type.type(:exec).new(:name => 'test array', :command => Puppet::Pops::Evaluator::DeferredValue.new(nil))
catalog.add_resource tmp
catalog.add_resource execer
dependencies = execer.autorequire(catalog)
expect(dependencies.collect(&:to_s)).to eq([])
end
describe "when handling the path parameter" do
expect = %w{one two three four}
{ "an array" => expect,
"a path-separator delimited list" => expect.join(File::PATH_SEPARATOR),
"both array and path-separator delimited lists" => ["one", "two#{File::PATH_SEPARATOR}three", "four"],
}.each do |test, input|
it "should accept #{test}" do
type = Puppet::Type.type(:exec).new(:name => @command, :path => input)
expect(type[:path]).to eq(expect)
end
end
describe "on platforms where path separator is not :" do
before :each do
stub_const('File::PATH_SEPARATOR', 'q')
end
it "should use the path separator of the current platform" do
type = Puppet::Type.type(:exec).new(:name => @command, :path => "fooqbarqbaz")
expect(type[:path]).to eq(%w[foo bar baz])
end
end
end
describe "when setting user" do
describe "on POSIX systems", :if => Puppet.features.posix? do
it "should fail if we are not root" do
allow(Puppet.features).to receive(:root?).and_return(false)
expect {
Puppet::Type.type(:exec).new(:name => '/bin/true whatever', :user => 'input')
}.to raise_error Puppet::Error, /Parameter user failed/
end
it "accepts the current user" do
allow(Puppet.features).to receive(:root?).and_return(false)
allow(Etc).to receive(:getpwuid).and_return(Etc::Passwd.new('input'))
type = Puppet::Type.type(:exec).new(:name => '/bin/true whatever', :user => 'input')
expect(type[:user]).to eq('input')
end
['one', 2, 'root', 4294967295, 4294967296].each do |value|
it "should accept '#{value}' as user if we are root" do
allow(Puppet.features).to receive(:root?).and_return(true)
type = Puppet::Type.type(:exec).new(:name => '/bin/true whatever', :user => value)
expect(type[:user]).to eq(value)
end
end
end
describe "on Windows systems", :if => Puppet::Util::Platform.windows? do
before :each do
allow(Puppet.features).to receive(:root?).and_return(true)
end
it "should reject user parameter" do
expect {
Puppet::Type.type(:exec).new(:name => 'c:\windows\notepad.exe', :user => 'input')
}.to raise_error Puppet::Error, /Unable to execute commands as other users on Windows/
end
end
end
describe "when setting group" do
shared_examples_for "exec[:group]" do
['one', 2, 'wheel', 4294967295, 4294967296].each do |value|
it "should accept '#{value}' without error or judgement" do
type = Puppet::Type.type(:exec).new(:name => @command, :group => value)
expect(type[:group]).to eq(value)
end
end
end
describe "when running as root" do
before(:each) do
allow(Puppet.features).to receive(:root?).and_return(true)
end
it_behaves_like "exec[:group]"
end
describe "when not running as root" do
before(:each) do
allow(Puppet.features).to receive(:root?).and_return(false)
end
it_behaves_like "exec[:group]"
end
end
describe "when setting cwd" do
it_should_behave_like "all path parameters", :cwd, :array => false do
def instance(path)
# Specify shell provider so we don't have to care about command validation
Puppet::Type.type(:exec).new(:name => @executable, :cwd => path, :provider => :shell)
end
end
end
shared_examples_for "all exec command parameters" do |param|
array_cmd = ["/bin/example", "*"]
array_cmd = [["/bin/example", "*"]] if [:onlyif, :unless].include?(param)
commands = { "relative" => "example", "absolute" => "/bin/example" }
commands["array"] = array_cmd
commands.sort.each do |name, command|
describe "if command is #{name}" do
before :each do
@param = param
end
def test(command, valid)
if @param == :name then
instance = Puppet::Type.type(:exec).new()
else
instance = Puppet::Type.type(:exec).new(:name => @executable)
end
if valid then
expect(instance.provider).to receive(:validatecmd).and_return(true)
else
expect(instance.provider).to receive(:validatecmd).and_raise(Puppet::Error, "from a stub")
end
instance[@param] = command
end
it "should work if the provider calls the command valid" do
expect { test(command, true) }.to_not raise_error
end
it "should fail if the provider calls the command invalid" do
expect { test(command, false) }.
to raise_error Puppet::Error, /Parameter #{@param} failed on Exec\[.*\]: from a stub/
end
end
end
end
shared_examples_for "all exec command parameters that take arrays" do |param|
[
%w{one two three},
[%w{one -a}, %w{two, -b}, 'three']
].each do |input|
context "when given #{input.inspect} as input" do
let(:resource) { Puppet::Type.type(:exec).new(:name => @executable) }
it "accepts the array when all commands return valid" do
input = %w{one two three}
allow(resource.provider).to receive(:validatecmd).exactly(input.length).times.and_return(true)
resource[param] = input
expect(resource[param]).to eq(input)
end
it "rejects the array when any commands return invalid" do
input = %w{one two three}
allow(resource.provider).to receive(:validatecmd).with(input[0]).and_return(true)
allow(resource.provider).to receive(:validatecmd).with(input[1]).and_raise(Puppet::Error)
expect { resource[param] = input }.to raise_error(Puppet::ResourceError, /Parameter #{param} failed/)
end
it "stops at the first invalid command" do
input = %w{one two three}
allow(resource.provider).to receive(:validatecmd).with(input[0]).and_raise(Puppet::Error)
expect(resource.provider).not_to receive(:validatecmd).with(input[1])
expect(resource.provider).not_to receive(:validatecmd).with(input[2])
expect { resource[param] = input }.to raise_error(Puppet::ResourceError, /Parameter #{param} failed/)
end
end
end
end
describe "when setting command" do
subject { described_class.new(:name => @command) }
it "fails when passed a Hash" do
expect { subject[:command] = {} }.to raise_error Puppet::Error, /Command must be a String or Array<String>/
end
end
describe "when setting refresh" do
it_should_behave_like "all exec command parameters", :refresh
end
describe "for simple parameters" do
before :each do
@exec = Puppet::Type.type(:exec).new(:name => @executable)
end
describe "when setting environment" do
{ "single values" => "foo=bar",
"multiple values" => ["foo=bar", "baz=quux"],
}.each do |name, data|
it "should accept #{name}" do
@exec[:environment] = data
expect(@exec[:environment]).to eq(data)
end
end
{ "single values" => "foo",
"only values" => ["foo", "bar"],
"any values" => ["foo=bar", "baz"]
}.each do |name, data|
it "should reject #{name} without assignment" do
expect { @exec[:environment] = data }.
to raise_error Puppet::Error, /Invalid environment setting/
end
end
end
describe "when setting timeout" do
[0, 0.1, 1, 10, 4294967295].each do |valid|
it "should accept '#{valid}' as valid" do
@exec[:timeout] = valid
expect(@exec[:timeout]).to eq(valid)
end
it "should accept '#{valid}' in an array as valid" do
@exec[:timeout] = [valid]
expect(@exec[:timeout]).to eq(valid)
end
end
['1/2', '', 'foo', '5foo'].each do |invalid|
it "should reject '#{invalid}' as invalid" do
expect { @exec[:timeout] = invalid }.
to raise_error Puppet::Error, /The timeout must be a number/
end
it "should reject '#{invalid}' in an array as invalid" do
expect { @exec[:timeout] = [invalid] }.
to raise_error Puppet::Error, /The timeout must be a number/
end
end
describe 'when timeout is exceeded' do
subject do
ruby_path = Puppet::Util::Execution.ruby_path()
Puppet::Type.type(:exec).new(:name => "#{ruby_path} -e 'sleep 1'", :timeout => '0.1')
end
context 'on POSIX', :unless => Puppet::Util::Platform.windows? || RUBY_PLATFORM == 'java' do
it 'sends a SIGTERM and raises a Puppet::Error' do
expect(Process).to receive(:kill).at_least(:once)
expect { subject.refresh }.to raise_error Puppet::Error, "Command exceeded timeout"
end
end
context 'on Windows', :if => Puppet::Util::Platform.windows? do
it 'raises a Puppet::Error' do
expect { subject.refresh }.to raise_error Puppet::Error, "Command exceeded timeout"
end
end
end
it "should convert timeout to a float" do
command = make_absolute('/bin/false')
resource = Puppet::Type.type(:exec).new :command => command, :timeout => "12"
expect(resource[:timeout]).to be_a(Float)
expect(resource[:timeout]).to eq(12.0)
end
it "should munge negative timeouts to 0.0" do
command = make_absolute('/bin/false')
resource = Puppet::Type.type(:exec).new :command => command, :timeout => "-12.0"
expect(resource.parameter(:timeout).value).to be_a(Float)
expect(resource.parameter(:timeout).value).to eq(0.0)
end
end
describe "when setting tries" do
[1, 10, 4294967295].each do |valid|
it "should accept '#{valid}' as valid" do
@exec[:tries] = valid
expect(@exec[:tries]).to eq(valid)
end
if "REVISIT: too much test log spam" == "a good thing" then
it "should accept '#{valid}' in an array as valid" do
pending "inconsistent, but this is not supporting arrays, unlike timeout"
@exec[:tries] = [valid]
expect(@exec[:tries]).to eq(valid)
end
end
end
[-3.5, -1, 0, 0.2, '1/2', '1_000_000', '+12', '', 'foo'].each do |invalid|
it "should reject '#{invalid}' as invalid" do
expect { @exec[:tries] = invalid }.
to raise_error Puppet::Error, /Tries must be an integer/
end
if "REVISIT: too much test log spam" == "a good thing" then
it "should reject '#{invalid}' in an array as invalid" do
pending "inconsistent, but this is not supporting arrays, unlike timeout"
expect { @exec[:tries] = [invalid] }.
to raise_error Puppet::Error, /Tries must be an integer/
end
end
end
end
describe "when setting try_sleep" do
[0, 0.2, 1, 10, 4294967295].each do |valid|
it "should accept '#{valid}' as valid" do
@exec[:try_sleep] = valid
expect(@exec[:try_sleep]).to eq(valid)
end
if "REVISIT: too much test log spam" == "a good thing" then
it "should accept '#{valid}' in an array as valid" do
pending "inconsistent, but this is not supporting arrays, unlike timeout"
@exec[:try_sleep] = [valid]
expect(@exec[:try_sleep]).to eq(valid)
end
end
end
{ -3.5 => "cannot be a negative number",
-1 => "cannot be a negative number",
'1/2' => 'must be a number',
'1_000_000' => 'must be a number',
'+12' => 'must be a number',
'' => 'must be a number',
'foo' => 'must be a number',
}.each do |invalid, error|
it "should reject '#{invalid}' as invalid" do
expect { @exec[:try_sleep] = invalid }.
to raise_error Puppet::Error, /try_sleep #{error}/
end
if "REVISIT: too much test log spam" == "a good thing" then
it "should reject '#{invalid}' in an array as invalid" do
pending "inconsistent, but this is not supporting arrays, unlike timeout"
expect { @exec[:try_sleep] = [invalid] }.
to raise_error Puppet::Error, /try_sleep #{error}/
end
end
end
end
describe "when setting refreshonly" do
[:true, :false].each do |value|
it "should accept '#{value}'" do
@exec[:refreshonly] = value
expect(@exec[:refreshonly]).to eq(value)
end
end
[1, 0, "1", "0", "yes", "y", "no", "n"].each do |value|
it "should reject '#{value}'" do
expect { @exec[:refreshonly] = value }.
to raise_error(Puppet::Error,
/Invalid value #{value.inspect}\. Valid values are true, false/
)
end
end
end
end
describe "when setting creates" do
it_should_behave_like "all path parameters", :creates, :array => true do
def instance(path)
# Specify shell provider so we don't have to care about command validation
Puppet::Type.type(:exec).new(:name => @executable, :creates => path, :provider => :shell)
end
end
end
describe "when setting unless" do
it_should_behave_like "all exec command parameters", :unless
it_should_behave_like "all exec command parameters that take arrays", :unless
end
describe "when setting onlyif" do
it_should_behave_like "all exec command parameters", :onlyif
it_should_behave_like "all exec command parameters that take arrays", :onlyif
end
describe "#check" do
before :each do
@test = Puppet::Type.type(:exec).new(:name => @executable)
end
describe ":refreshonly" do
{ :true => false, :false => true }.each do |input, result|
it "should return '#{result}' when given '#{input}'" do
@test[:refreshonly] = input
expect(@test.check_all_attributes).to eq(result)
end
end
end
describe ":creates" do
before :each do
@exist = tmpfile('exist')
FileUtils.touch(@exist)
@unexist = tmpfile('unexist')
end
context "with a single item" do
it "should run when the item does not exist" do
@test[:creates] = @unexist
expect(@test.check_all_attributes).to eq(true)
end
it "should not run when the item exists" do
@test[:creates] = @exist
expect(@test.check_all_attributes).to eq(false)
end
end
context "with an array with one item" do
it "should run when the item does not exist" do
@test[:creates] = [@unexist]
expect(@test.check_all_attributes).to eq(true)
end
it "should not run when the item exists" do
@test[:creates] = [@exist]
expect(@test.check_all_attributes).to eq(false)
end
end
context "with an array with multiple items" do
it "should run when all items do not exist" do
@test[:creates] = [@unexist] * 3
expect(@test.check_all_attributes).to eq(true)
end
it "should not run when one item exists" do
@test[:creates] = [@unexist, @exist, @unexist]
expect(@test.check_all_attributes).to eq(false)
end
it "should not run when all items exist" do
@test[:creates] = [@exist] * 3
end
end
context "when creates is being checked" do
it "should be logged to debug when the path does exist" do
Puppet::Util::Log.level = :debug
@test[:creates] = @exist
expect(@test.check_all_attributes).to eq(false)
expect(@logs).to include(an_object_having_attributes(level: :debug, message: "Checking that 'creates' path '#{@exist}' exists"))
end
it "should be logged to debug when the path does not exist" do
Puppet::Util::Log.level = :debug
@test[:creates] = @unexist
expect(@test.check_all_attributes).to eq(true)
expect(@logs).to include(an_object_having_attributes(level: :debug, message: "Checking that 'creates' path '#{@unexist}' exists"))
end
end
end
{ :onlyif => { :pass => false, :fail => true },
:unless => { :pass => true, :fail => false },
}.each do |param, sense|
describe ":#{param}" do
before :each do
@pass = make_absolute("/magic/pass")
@fail = make_absolute("/magic/fail")
@pass_status = double('status', :exitstatus => sense[:pass] ? 0 : 1)
@fail_status = double('status', :exitstatus => sense[:fail] ? 0 : 1)
allow(@test.provider).to receive(:checkexe).and_return(true)
[true, false].each do |check|
allow(@test.provider).to receive(:run).with(@pass, check).
and_return(['test output', @pass_status])
allow(@test.provider).to receive(:run).with(@fail, check).
and_return(['test output', @fail_status])
end
end
context "with a single item" do
it "should run if the command exits non-zero" do
@test[param] = @fail
expect(@test.check_all_attributes).to eq(true)
end
it "should not run if the command exits zero" do
@test[param] = @pass
expect(@test.check_all_attributes).to eq(false)
end
end
context "with an array with a single item" do
it "should run if the command exits non-zero" do
@test[param] = [@fail]
expect(@test.check_all_attributes).to eq(true)
end
it "should not run if the command exits zero" do
@test[param] = [@pass]
expect(@test.check_all_attributes).to eq(false)
end
end
context "with an array with multiple items" do
it "should run if all the commands exits non-zero" do
@test[param] = [@fail] * 3
expect(@test.check_all_attributes).to eq(true)
end
it "should not run if one command exits zero" do
@test[param] = [@pass, @fail, @pass]
expect(@test.check_all_attributes).to eq(false)
end
it "should not run if all command exits zero" do
@test[param] = [@pass] * 3
expect(@test.check_all_attributes).to eq(false)
end
end
context 'with an array of arrays with multiple items' do
before do
[true, false].each do |check|
allow(@test.provider).to receive(:run).with([@pass, '--flag'], check).
and_return(['test output', @pass_status])
allow(@test.provider).to receive(:run).with([@fail, '--flag'], check).
and_return(['test output', @fail_status])
allow(@test.provider).to receive(:run).with([@pass], check).
and_return(['test output', @pass_status])
allow(@test.provider).to receive(:run).with([@fail], check).
and_return(['test output', @fail_status])
end
end
it "runs if all the commands exits non-zero" do
@test[param] = [[@fail, '--flag'], [@fail], [@fail, '--flag']]
expect(@test.check_all_attributes).to eq(true)
end
it "does not run if one command exits zero" do
@test[param] = [[@pass, '--flag'], [@pass], [@fail, '--flag']]
expect(@test.check_all_attributes).to eq(false)
end
it "does not run if all command exits zero" do
@test[param] = [[@pass, '--flag'], [@pass], [@pass, '--flag']]
expect(@test.check_all_attributes).to eq(false)
end
end
it "should emit output to debug" do
Puppet::Util::Log.level = :debug
@test[param] = @fail
expect(@test.check_all_attributes).to eq(true)
expect(@logs.shift.message).to eq("test output")
end
it "should not emit output to debug if sensitive is true" do
Puppet::Util::Log.level = :debug
@test[param] = @fail
allow(@test.parameters[param]).to receive(:sensitive).and_return(true)
expect(@test.check_all_attributes).to eq(true)
expect(@logs).not_to include(an_object_having_attributes(level: :debug, message: "test output"))
expect(@logs).to include(an_object_having_attributes(level: :debug, message: "[output redacted]"))
end
end
end
end
describe "#retrieve" do
before :each do
@exec_resource = Puppet::Type.type(:exec).new(:name => @bogus_cmd)
end
it "should return :notrun when check_all_attributes returns true" do
allow(@exec_resource).to receive(:check_all_attributes).and_return(true)
expect(@exec_resource.retrieve[:returns]).to eq(:notrun)
end
it "should return default exit code 0 when check_all_attributes returns false" do
allow(@exec_resource).to receive(:check_all_attributes).and_return(false)
expect(@exec_resource.retrieve[:returns]).to eq(['0'])
end
it "should return the specified exit code when check_all_attributes returns false" do
allow(@exec_resource).to receive(:check_all_attributes).and_return(false)
@exec_resource[:returns] = 42
expect(@exec_resource.retrieve[:returns]).to eq(["42"])
end
end
describe "#output" do
before :each do
@exec_resource = Puppet::Type.type(:exec).new(:name => @bogus_cmd)
end
it "should return the provider's run output" do
provider = double('provider')
status = double('process_status')
allow(status).to receive(:exitstatus).and_return("0")
expect(provider).to receive(:run).and_return(["silly output", status])
allow(@exec_resource).to receive(:provider).and_return(provider)
@exec_resource.refresh
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | true |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/type/whit_spec.rb | spec/unit/type/whit_spec.rb | require 'spec_helper'
whit = Puppet::Type.type(:whit)
describe whit do
it "should stringify in a way that users will regognise" do
expect(whit.new(:name => "Foo::Bar").to_s).to eq("Foo::Bar")
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/type/component_spec.rb | spec/unit/type/component_spec.rb | require 'spec_helper'
component = Puppet::Type.type(:component)
describe component do
it "should have a :name attribute" do
expect(component.attrclass(:name)).not_to be_nil
end
it "should use Class as its type when a normal string is provided as the title" do
expect(component.new(:name => "bar").ref).to eq("Class[Bar]")
end
it "should always produce a resource reference string as its title" do
expect(component.new(:name => "bar").title).to eq("Class[Bar]")
end
it "should have a reference string equivalent to its title" do
comp = component.new(:name => "Foo[bar]")
expect(comp.title).to eq(comp.ref)
end
it "should not fail when provided an invalid value" do
comp = component.new(:name => "Foo[bar]")
expect { comp[:yayness] = "ey" }.not_to raise_error
end
it "should return previously provided invalid values" do
comp = component.new(:name => "Foo[bar]")
comp[:yayness] = "eh"
expect(comp[:yayness]).to eq("eh")
end
it "should correctly support metaparameters" do
comp = component.new(:name => "Foo[bar]", :require => "Foo[bar]")
expect(comp.parameter(:require)).to be_instance_of(component.attrclass(:require))
end
describe "when building up the path" do
it "should produce the class name if the component models a class" do
expect(component.new(:name => "Class[foo]").pathbuilder).to eq(["Foo"])
end
it "should produce the class name even for the class named main" do
expect(component.new(:name => "Class[main]").pathbuilder).to eq(["Main"])
end
it "should produce a resource reference if the component does not model a class" do
expect(component.new(:name => "Foo[bar]").pathbuilder).to eq(["Foo[bar]"])
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.