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/pops/parser/parse_calls_spec.rb | spec/unit/pops/parser/parse_calls_spec.rb | require 'spec_helper'
require 'puppet/pops'
# relative to this spec file (./) does not work as this file is loaded by rspec
require File.join(File.dirname(__FILE__), '/parser_rspec_helper')
describe "egrammar parsing function calls" do
include ParserRspecHelper
context "When parsing calls as statements" do
context "in top level scope" do
it "foo()" do
expect(dump(parse("foo()"))).to eq("(invoke foo)")
end
it "notice bar" do
expect(dump(parse("notice bar"))).to eq("(invoke notice bar)")
end
it "notice(bar)" do
expect(dump(parse("notice bar"))).to eq("(invoke notice bar)")
end
it "foo(bar)" do
expect(dump(parse("foo(bar)"))).to eq("(invoke foo bar)")
end
it "notice {a=>2}" do
expect(dump(parse("notice {a => 2}"))).to eq("(invoke notice ({} ('a' 2)))")
end
it 'notice a=>2' do
expect{parse('notice a => 2')}.to raise_error(/Syntax error at '=>'/)
end
it "foo(bar,)" do
expect(dump(parse("foo(bar,)"))).to eq("(invoke foo bar)")
end
it "foo(bar, fum,)" do
expect(dump(parse("foo(bar,fum,)"))).to eq("(invoke foo bar fum)")
end
it 'foo(a=>1)' do
expect(dump(parse('foo(a=>1)'))).to eq('(invoke foo ({} (a 1)))')
end
it 'foo(a=>1, b=>2)' do
expect(dump(parse('foo(a=>1, b=>2)'))).to eq('(invoke foo ({} (a 1) (b 2)))')
end
it 'foo({a=>1, b=>2})' do
expect(dump(parse('foo({a=>1, b=>2})'))).to eq('(invoke foo ({} (a 1) (b 2)))')
end
it 'foo({a=>1}, b=>2)' do
expect(dump(parse('foo({a=>1}, b=>2)'))).to eq('(invoke foo ({} (a 1)) ({} (b 2)))')
end
it 'foo(a=>1, {b=>2})' do
expect(dump(parse('foo(a=>1, {b=>2})'))).to eq('(invoke foo ({} (a 1)) ({} (b 2)))')
end
it "notice fqdn_rand(30)" do
expect(dump(parse("notice fqdn_rand(30)"))).to eq('(invoke notice (call fqdn_rand 30))')
end
it "notice type(42)" do
expect(dump(parse("notice type(42)"))).to eq('(invoke notice (call type 42))')
end
it "is required to place the '(' on the same line as the name of the function to recognize it as arguments in call" do
expect(dump(parse("notice foo\n(42)"))).to eq("(block\n (invoke notice foo)\n 42\n)")
end
end
context "in nested scopes" do
it "if true { foo() }" do
expect(dump(parse("if true {foo()}"))).to eq("(if true\n (then (invoke foo)))")
end
it "if true { notice bar}" do
expect(dump(parse("if true {notice bar}"))).to eq("(if true\n (then (invoke notice bar)))")
end
end
end
context "When parsing calls as expressions" do
it "$a = foo()" do
expect(dump(parse("$a = foo()"))).to eq("(= $a (call foo))")
end
it "$a = foo(bar)" do
expect(dump(parse("$a = foo()"))).to eq("(= $a (call foo))")
end
# For egrammar where a bare word can be a "statement"
it "$a = foo bar # illegal, must have parentheses" do
expect(dump(parse("$a = foo bar"))).to eq("(block\n (= $a foo)\n bar\n)")
end
context "in nested scopes" do
it "if true { $a = foo() }" do
expect(dump(parse("if true { $a = foo()}"))).to eq("(if true\n (then (= $a (call foo))))")
end
it "if true { $a= foo(bar)}" do
expect(dump(parse("if true {$a = foo(bar)}"))).to eq("(if true\n (then (= $a (call foo bar))))")
end
end
end
context "When parsing method calls" do
it "$a.foo" do
expect(dump(parse("$a.foo"))).to eq("(call-method (. $a foo))")
end
it "$a.foo || { }" do
expect(dump(parse("$a.foo || { }"))).to eq("(call-method (. $a foo) (lambda ()))")
end
it "$a.foo |$x| { }" do
expect(dump(parse("$a.foo |$x|{ }"))).to eq("(call-method (. $a foo) (lambda (parameters x) ()))")
end
it "$a.foo |$x|{ }" do
expect(dump(parse("$a.foo |$x|{ $b = $x}"))).to eq([
"(call-method (. $a foo) (lambda (parameters x) (block",
" (= $b $x)",
")))"
].join("\n"))
end
it "notice 42.type()" do
expect(dump(parse("notice 42.type()"))).to eq('(invoke notice (call-method (. 42 type)))')
end
it 'notice Hash.assert_type(a => 42)' do
expect(dump(parse('notice Hash.assert_type(a => 42)'))).to eq('(invoke notice (call-method (. Hash assert_type) ({} (a 42))))')
end
it "notice 42.type(detailed)" do
expect(dump(parse("notice 42.type(detailed)"))).to eq('(invoke notice (call-method (. 42 type) detailed))')
end
it "is required to place the '(' on the same line as the name of the method to recognize it as arguments in call" do
expect(dump(parse("notice 42.type\n(detailed)"))).to eq("(block\n (invoke notice (call-method (. 42 type)))\n detailed\n)")
end
end
context "When parsing an illegal argument list" do
it "raises an error if argument list is not for a call" do
expect do
parse("$a = 10, 3")
end.to raise_error(/illegal comma/)
end
it "raises an error if argument list is for a potential call not allowed without parentheses" do
expect do
parse("foo 10, 3")
end.to raise_error(/attempt to pass argument list to the function 'foo' which cannot be called without parentheses/)
end
it "does no raise an error for an argument list to an allowed call" do
expect do
parse("notice 10, 3")
end.to_not raise_error()
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/parser/evaluating_parser_spec.rb | spec/unit/pops/parser/evaluating_parser_spec.rb | require 'spec_helper'
require 'puppet/pops'
require 'puppet_spec/pops'
require 'puppet_spec/scope'
describe 'The Evaluating Parser' do
include PuppetSpec::Pops
include PuppetSpec::Scope
let(:acceptor) { Puppet::Pops::Validation::Acceptor.new() }
let(:scope) { s = create_test_scope_for_node(node); s }
let(:node) { 'node.example.com' }
def quote(x)
Puppet::Pops::Parser::EvaluatingParser.quote(x)
end
def evaluator()
Puppet::Pops::Parser::EvaluatingParser.new()
end
def evaluate(s)
evaluator.evaluate(scope, quote(s))
end
def test(x)
expect(evaluator.evaluate_string(scope, quote(x))).to eq(x)
end
def test_interpolate(x, y)
scope['a'] = 'expansion'
expect(evaluator.evaluate_string(scope, quote(x))).to eq(y)
end
context 'when evaluating' do
it 'should produce an empty string with no change' do
test('')
end
it 'should produce a normal string with no change' do
test('A normal string')
end
it 'should produce a string with newlines with no change' do
test("A\nnormal\nstring")
end
it 'should produce a string with escaped newlines with no change' do
test("A\\nnormal\\nstring")
end
it 'should produce a string containing quotes without change' do
test('This " should remain untouched')
end
it 'should produce a string containing escaped quotes without change' do
test('This \" should remain untouched')
end
it 'should expand ${a} variables' do
test_interpolate('This ${a} was expanded', 'This expansion was expanded')
end
it 'should expand quoted ${a} variables' do
test_interpolate('This "${a}" was expanded', 'This "expansion" was expanded')
end
it 'should not expand escaped ${a}' do
test_interpolate('This \${a} was not expanded', 'This ${a} was not expanded')
end
it 'should expand $a variables' do
test_interpolate('This $a was expanded', 'This expansion was expanded')
end
it 'should expand quoted $a variables' do
test_interpolate('This "$a" was expanded', 'This "expansion" was expanded')
end
it 'should not expand escaped $a' do
test_interpolate('This \$a was not expanded', 'This $a was not expanded')
end
it 'should produce an single space from a \s' do
test_interpolate("\\s", ' ')
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/pops/parser/parse_containers_spec.rb | spec/unit/pops/parser/parse_containers_spec.rb | require 'spec_helper'
require 'puppet/pops'
# relative to this spec file (./) does not work as this file is loaded by rspec
require File.join(File.dirname(__FILE__), '/parser_rspec_helper')
describe "egrammar parsing containers" do
include ParserRspecHelper
context "When parsing file scope" do
it "$a = 10 $b = 20" do
expect(dump(parse("$a = 10 $b = 20"))).to eq([
"(block",
" (= $a 10)",
" (= $b 20)",
")"
].join("\n"))
end
it "$a = 10" do
expect(dump(parse("$a = 10"))).to eq("(= $a 10)")
end
end
context "When parsing class" do
it "class foo {}" do
expect(dump(parse("class foo {}"))).to eq("(class foo ())")
end
it "class foo { class bar {} }" do
expect(dump(parse("class foo { class bar {}}"))).to eq([
"(class foo (block",
" (class foo::bar ())",
"))"
].join("\n"))
end
it "class foo::bar {}" do
expect(dump(parse("class foo::bar {}"))).to eq("(class foo::bar ())")
end
it "class foo inherits bar {}" do
expect(dump(parse("class foo inherits bar {}"))).to eq("(class foo (inherits bar) ())")
end
it "class foo($a) {}" do
expect(dump(parse("class foo($a) {}"))).to eq("(class foo (parameters a) ())")
end
it "class foo($a, $b) {}" do
expect(dump(parse("class foo($a, $b) {}"))).to eq("(class foo (parameters a b) ())")
end
it "class foo($a, $b=10) {}" do
expect(dump(parse("class foo($a, $b=10) {}"))).to eq("(class foo (parameters a (= b 10)) ())")
end
it "class foo($a, $b) inherits belgo::bar {}" do
expect(dump(parse("class foo($a, $b) inherits belgo::bar{}"))).to eq("(class foo (inherits belgo::bar) (parameters a b) ())")
end
it "class foo {$a = 10 $b = 20}" do
expect(dump(parse("class foo {$a = 10 $b = 20}"))).to eq([
"(class foo (block",
" (= $a 10)",
" (= $b 20)",
"))"
].join("\n"))
end
context "it should handle '3x weirdness'" do
it "class class {} # a class named 'class'" do
# Not as much weird as confusing that it is possible to name a class 'class'. Can have
# a very confusing effect when resolving relative names, getting the global hardwired "Class"
# instead of some foo::class etc.
# This was allowed in 3.x.
expect { parse("class class {}") }.to raise_error(/'class' keyword not allowed at this location/)
end
it "class default {} # a class named 'default'" do
# The weirdness here is that a class can inherit 'default' but not declare a class called default.
# (It will work with relative names i.e. foo::default though). The whole idea with keywords as
# names is flawed to begin with - it generally just a very bad idea.
expect { parse("class default {}") }.to raise_error(Puppet::ParseError)
end
it "class 'foo' {} # a string as class name" do
# A common error is to put quotes around the class name, the parser should provide the error message at the right location
# See PUP-7471
expect { parse("class 'foo' {}") }.to raise_error(/A quoted string is not valid as a name here \(line: 1, column: 7\)/)
end
it "class foo::default {} # a nested name 'default'" do
expect(dump(parse("class foo::default {}"))).to eq("(class foo::default ())")
end
it "class class inherits default {} # inherits default" do
expect { parse("class class inherits default {}") }.to raise_error(/'class' keyword not allowed at this location/)
end
it "class foo inherits class" do
expect { parse("class foo inherits class {}") }.to raise_error(/'class' keyword not allowed at this location/)
end
end
context 'it should allow keywords as attribute names' do
['and', 'case', 'class', 'default', 'define', 'else', 'elsif', 'if', 'in', 'inherits', 'node', 'or',
'undef', 'unless', 'type', 'attr', 'function', 'private', 'plan', 'apply'].each do |keyword|
it "such as #{keyword}" do
expect { parse("class x ($#{keyword}){} class { x: #{keyword} => 1 }") }.to_not raise_error
end
end
end
end
context "When the parser parses define" do
it "define foo {}" do
expect(dump(parse("define foo {}"))).to eq("(define foo ())")
end
it "class foo { define bar {}}" do
expect(dump(parse("class foo {define bar {}}"))).to eq([
"(class foo (block",
" (define foo::bar ())",
"))"
].join("\n"))
end
it "define foo { define bar {}}" do
# This is illegal, but handled as part of validation
expect(dump(parse("define foo { define bar {}}"))).to eq([
"(define foo (block",
" (define bar ())",
"))"
].join("\n"))
end
it "define foo::bar {}" do
expect(dump(parse("define foo::bar {}"))).to eq("(define foo::bar ())")
end
it "define foo($a) {}" do
expect(dump(parse("define foo($a) {}"))).to eq("(define foo (parameters a) ())")
end
it "define foo($a, $b) {}" do
expect(dump(parse("define foo($a, $b) {}"))).to eq("(define foo (parameters a b) ())")
end
it "define foo($a, $b=10) {}" do
expect(dump(parse("define foo($a, $b=10) {}"))).to eq("(define foo (parameters a (= b 10)) ())")
end
it "define foo {$a = 10 $b = 20}" do
expect(dump(parse("define foo {$a = 10 $b = 20}"))).to eq([
"(define foo (block",
" (= $a 10)",
" (= $b 20)",
"))"
].join("\n"))
end
context "it should handle '3x weirdness'" do
it "define class {} # a define named 'class'" do
# This is weird because Class already exists, and instantiating this define will probably not
# work
expect { parse("define class {}") }.to raise_error(/'class' keyword not allowed at this location/)
end
it "define default {} # a define named 'default'" do
# Check unwanted ability to define 'default'.
# The expression below is not allowed (which is good).
expect { parse("define default {}") }.to raise_error(Puppet::ParseError)
end
end
context 'it should allow keywords as attribute names' do
['and', 'case', 'class', 'default', 'define', 'else', 'elsif', 'if', 'in', 'inherits', 'node', 'or',
'undef', 'unless', 'type', 'attr', 'function', 'private', 'plan', 'apply'].each do |keyword|
it "such as #{keyword}" do
expect {parse("define x ($#{keyword}){} x { y: #{keyword} => 1 }")}.to_not raise_error
end
end
end
end
context "When parsing node" do
it "node foo {}" do
expect(dump(parse("node foo {}"))).to eq("(node (matches 'foo') ())")
end
it "node foo, {} # trailing comma" do
expect(dump(parse("node foo, {}"))).to eq("(node (matches 'foo') ())")
end
it "node kermit.example.com {}" do
expect(dump(parse("node kermit.example.com {}"))).to eq("(node (matches 'kermit.example.com') ())")
end
it "node kermit . example . com {}" do
expect(dump(parse("node kermit . example . com {}"))).to eq("(node (matches 'kermit.example.com') ())")
end
it "node foo, x::bar, default {}" do
expect(dump(parse("node foo, x::bar, default {}"))).to eq("(node (matches 'foo' 'x::bar' :default) ())")
end
it "node 'foo' {}" do
expect(dump(parse("node 'foo' {}"))).to eq("(node (matches 'foo') ())")
end
it "node foo inherits x::bar {}" do
expect(dump(parse("node foo inherits x::bar {}"))).to eq("(node (matches 'foo') (parent 'x::bar') ())")
end
it "node foo inherits 'bar' {}" do
expect(dump(parse("node foo inherits 'bar' {}"))).to eq("(node (matches 'foo') (parent 'bar') ())")
end
it "node foo inherits default {}" do
expect(dump(parse("node foo inherits default {}"))).to eq("(node (matches 'foo') (parent :default) ())")
end
it "node /web.*/ {}" do
expect(dump(parse("node /web.*/ {}"))).to eq("(node (matches /web.*/) ())")
end
it "node /web.*/, /do\.wop.*/, and.so.on {}" do
expect(dump(parse("node /web.*/, /do\.wop.*/, 'and.so.on' {}"))).to eq("(node (matches /web.*/ /do\.wop.*/ 'and.so.on') ())")
end
it "node wat inherits /apache.*/ {}" do
expect(dump(parse("node wat inherits /apache.*/ {}"))).to eq("(node (matches 'wat') (parent /apache.*/) ())")
end
it "node foo inherits bar {$a = 10 $b = 20}" do
expect(dump(parse("node foo inherits bar {$a = 10 $b = 20}"))).to eq([
"(node (matches 'foo') (parent 'bar') (block",
" (= $a 10)",
" (= $b 20)",
"))"
].join("\n"))
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/parser/parse_lambda_spec.rb | spec/unit/pops/parser/parse_lambda_spec.rb | require 'spec_helper'
require 'puppet/pops'
require_relative 'parser_rspec_helper'
describe 'egrammar parsing lambda definitions' do
include ParserRspecHelper
context 'without return type' do
it 'f() |$x| { 1 }' do
expect(dump(parse('f() |$x| { 1 }'))).to eq("(invoke f (lambda (parameters x) (block\n 1\n)))")
end
end
context 'with return type' do
it 'f() |$x| >> Integer { 1 }' do
expect(dump(parse('f() |$x| >> Integer { 1 }'))).to eq("(invoke f (lambda (parameters x) (return_type Integer) (block\n 1\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/pops/parser/parse_conditionals_spec.rb | spec/unit/pops/parser/parse_conditionals_spec.rb | require 'spec_helper'
require 'puppet/pops'
# relative to this spec file (./) does not work as this file is loaded by rspec
require File.join(File.dirname(__FILE__), '/parser_rspec_helper')
describe "egrammar parsing conditionals" do
include ParserRspecHelper
context "When parsing if statements" do
it "if true { $a = 10 }" do
expect(dump(parse("if true { $a = 10 }"))).to eq("(if true\n (then (= $a 10)))")
end
it "if true { $a = 10 } else {$a = 20}" do
expect(dump(parse("if true { $a = 10 } else {$a = 20}"))).to eq(
["(if true",
" (then (= $a 10))",
" (else (= $a 20)))"].join("\n")
)
end
it "if true { $a = 10 } elsif false { $a = 15} else {$a = 20}" do
expect(dump(parse("if true { $a = 10 } elsif false { $a = 15} else {$a = 20}"))).to eq(
["(if true",
" (then (= $a 10))",
" (else (if false",
" (then (= $a 15))",
" (else (= $a 20)))))"].join("\n")
)
end
it "if true { $a = 10 $b = 10 } else {$a = 20}" do
expect(dump(parse("if true { $a = 10 $b = 20} else {$a = 20}"))).to eq([
"(if true",
" (then (block",
" (= $a 10)",
" (= $b 20)",
" ))",
" (else (= $a 20)))"
].join("\n"))
end
it "allows a parenthesized conditional expression" do
expect(dump(parse("if (true) { 10 }"))).to eq("(if true\n (then 10))")
end
it "allows a parenthesized elsif conditional expression" do
expect(dump(parse("if true { 10 } elsif (false) { 20 }"))).to eq(
["(if true",
" (then 10)",
" (else (if false",
" (then 20))))"].join("\n")
)
end
end
context "When parsing unless statements" do
it "unless true { $a = 10 }" do
expect(dump(parse("unless true { $a = 10 }"))).to eq("(unless true\n (then (= $a 10)))")
end
it "unless true { $a = 10 } else {$a = 20}" do
expect(dump(parse("unless true { $a = 10 } else {$a = 20}"))).to eq(
["(unless true",
" (then (= $a 10))",
" (else (= $a 20)))"].join("\n")
)
end
it "allows a parenthesized conditional expression" do
expect(dump(parse("unless (true) { 10 }"))).to eq("(unless true\n (then 10))")
end
it "unless true { $a = 10 } elsif false { $a = 15} else {$a = 20} # is illegal" do
expect { parse("unless true { $a = 10 } elsif false { $a = 15} else {$a = 20}")}.to raise_error(Puppet::ParseError)
end
end
context "When parsing selector expressions" do
it "$a = $b ? banana => fruit " do
expect(dump(parse("$a = $b ? banana => fruit"))).to eq(
"(= $a (? $b (banana => fruit)))"
)
end
it "$a = $b ? { banana => fruit}" do
expect(dump(parse("$a = $b ? { banana => fruit }"))).to eq(
"(= $a (? $b (banana => fruit)))"
)
end
it "does not fail on a trailing blank line" do
expect(dump(parse("$a = $b ? { banana => fruit }\n\n"))).to eq(
"(= $a (? $b (banana => fruit)))"
)
end
it "$a = $b ? { banana => fruit, grape => berry }" do
expect(dump(parse("$a = $b ? {banana => fruit, grape => berry}"))).to eq(
"(= $a (? $b (banana => fruit) (grape => berry)))"
)
end
it "$a = $b ? { banana => fruit, grape => berry, default => wat }" do
expect(dump(parse("$a = $b ? {banana => fruit, grape => berry, default => wat}"))).to eq(
"(= $a (? $b (banana => fruit) (grape => berry) (:default => wat)))"
)
end
it "$a = $b ? { default => wat, banana => fruit, grape => berry, }" do
expect(dump(parse("$a = $b ? {default => wat, banana => fruit, grape => berry}"))).to eq(
"(= $a (? $b (:default => wat) (banana => fruit) (grape => berry)))"
)
end
it '1+2 ? 3 => yes' do
expect(dump(parse("1+2 ? 3 => yes"))).to eq(
"(? (+ 1 2) (3 => yes))"
)
end
it 'true and 1+2 ? 3 => yes' do
expect(dump(parse("true and 1+2 ? 3 => yes"))).to eq(
"(&& true (? (+ 1 2) (3 => yes)))"
)
end
end
context "When parsing case statements" do
it "case $a { a : {}}" do
expect(dump(parse("case $a { a : {}}"))).to eq(
["(case $a",
" (when (a) (then ())))"
].join("\n")
)
end
it "allows a parenthesized value expression" do
expect(dump(parse("case ($a) { a : {}}"))).to eq(
["(case $a",
" (when (a) (then ())))"
].join("\n")
)
end
it "case $a { /.*/ : {}}" do
expect(dump(parse("case $a { /.*/ : {}}"))).to eq(
["(case $a",
" (when (/.*/) (then ())))"
].join("\n")
)
end
it "case $a { a, b : {}}" do
expect(dump(parse("case $a { a, b : {}}"))).to eq(
["(case $a",
" (when (a b) (then ())))"
].join("\n")
)
end
it "case $a { a, b : {} default : {}}" do
expect(dump(parse("case $a { a, b : {} default : {}}"))).to eq(
["(case $a",
" (when (a b) (then ()))",
" (when (:default) (then ())))"
].join("\n")
)
end
it "case $a { a : {$b = 10 $c = 20}}" do
expect(dump(parse("case $a { a : {$b = 10 $c = 20}}"))).to eq(
["(case $a",
" (when (a) (then (block",
" (= $b 10)",
" (= $c 20)",
" ))))"
].join("\n")
)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/pops/parser/parsing_typed_parameters_spec.rb | spec/unit/pops/parser/parsing_typed_parameters_spec.rb | require 'spec_helper'
require 'puppet/pops'
require 'puppet/pops/evaluator/evaluator_impl'
require 'puppet_spec/pops'
require 'puppet_spec/scope'
require 'puppet/parser/e4_parser_adapter'
# relative to this spec file (./) does not work as this file is loaded by rspec
#require File.join(File.dirname(__FILE__), '/evaluator_rspec_helper')
describe 'Puppet::Pops::Evaluator::EvaluatorImpl' do
include PuppetSpec::Pops
include PuppetSpec::Scope
let(:parser) { Puppet::Pops::Parser::EvaluatingParser.new }
context "captures-rest parameter" do
it 'is allowed in lambda when placed last' do
source = <<-CODE
foo() |$a, *$b| { $a + $b[0] }
CODE
expect do
parser.parse_string(source, __FILE__)
end.to_not raise_error()
end
it 'allows a type annotation' do
source = <<-CODE
foo() |$a, Integer *$b| { $a + $b[0] }
CODE
expect do
parser.parse_string(source, __FILE__)
end.to_not raise_error()
end
it 'is not allowed in lambda except last' do
source = <<-CODE
foo() |*$a, $b| { $a + $b[0] }
CODE
expect do
parser.parse_string(source, __FILE__)
end.to raise_error(Puppet::ParseError, /Parameter \$a is not last, and has 'captures rest'/)
end
it 'is not allowed in define' do
source = <<-CODE
define foo(*$a) { }
CODE
expect do
parser.parse_string(source, __FILE__)
end.to raise_error(Puppet::ParseError, /Parameter \$a has 'captures rest' - not supported in a 'define'/)
end
it 'is not allowed in class' do
source = <<-CODE
class foo(*$a) { }
CODE
expect do
parser.parse_string(source, __FILE__)
end.to raise_error(Puppet::ParseError, /Parameter \$a has 'captures rest' - not supported in a Host Class Definition/)
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/pops/parser/parse_resource_spec.rb | spec/unit/pops/parser/parse_resource_spec.rb | require 'spec_helper'
require 'puppet/pops'
# relative to this spec file (./) does not work as this file is loaded by rspec
require File.join(File.dirname(__FILE__), '/parser_rspec_helper')
describe "egrammar parsing resource declarations" do
include ParserRspecHelper
context "When parsing regular resource" do
["File", "file"].each do |word|
it "#{word} { 'title': }" do
expect(dump(parse("#{word} { 'title': }"))).to eq([
"(resource #{word}",
" ('title'))"
].join("\n"))
end
it "#{word} { 'title': path => '/somewhere', mode => '0777'}" do
expect(dump(parse("#{word} { 'title': path => '/somewhere', mode => '0777'}"))).to eq([
"(resource #{word}",
" ('title'",
" (path => '/somewhere')",
" (mode => '0777')))"
].join("\n"))
end
it "#{word} { 'title': path => '/somewhere', }" do
expect(dump(parse("#{word} { 'title': path => '/somewhere', }"))).to eq([
"(resource #{word}",
" ('title'",
" (path => '/somewhere')))"
].join("\n"))
end
it "#{word} { 'title': , }" do
expect(dump(parse("#{word} { 'title': , }"))).to eq([
"(resource #{word}",
" ('title'))"
].join("\n"))
end
it "#{word} { 'title': ; }" do
expect(dump(parse("#{word} { 'title': ; }"))).to eq([
"(resource #{word}",
" ('title'))"
].join("\n"))
end
it "#{word} { 'title': ; 'other_title': }" do
expect(dump(parse("#{word} { 'title': ; 'other_title': }"))).to eq([
"(resource #{word}",
" ('title')",
" ('other_title'))"
].join("\n"))
end
# PUP-2898, trailing ';'
it "#{word} { 'title': ; 'other_title': ; }" do
expect(dump(parse("#{word} { 'title': ; 'other_title': ; }"))).to eq([
"(resource #{word}",
" ('title')",
" ('other_title'))"
].join("\n"))
end
it "#{word} { 'title1': path => 'x'; 'title2': path => 'y'}" do
expect(dump(parse("#{word} { 'title1': path => 'x'; 'title2': path => 'y'}"))).to eq([
"(resource #{word}",
" ('title1'",
" (path => 'x'))",
" ('title2'",
" (path => 'y')))",
].join("\n"))
end
it "#{word} { title: * => {mode => '0777'} }" do
expect(dump(parse("#{word} { title: * => {mode => '0777'}}"))).to eq([
"(resource #{word}",
" (title",
" (* => ({} (mode '0777')))))"
].join("\n"))
end
end
end
context "When parsing (type based) resource defaults" do
it "File { }" do
expect(dump(parse("File { }"))).to eq("(resource-defaults File)")
end
it "File { mode => '0777' }" do
expect(dump(parse("File { mode => '0777'}"))).to eq([
"(resource-defaults File",
" (mode => '0777'))"
].join("\n"))
end
it "File { * => {mode => '0777'} } (even if validated to be illegal)" do
expect(dump(parse("File { * => {mode => '0777'}}"))).to eq([
"(resource-defaults File",
" (* => ({} (mode '0777'))))"
].join("\n"))
end
end
context "When parsing resource override" do
it "File['x'] { }" do
expect(dump(parse("File['x'] { }"))).to eq("(override (slice File 'x'))")
end
it "File['x'] { x => 1 }" do
expect(dump(parse("File['x'] { x => 1}"))).to eq([
"(override (slice File 'x')",
" (x => 1))"
].join("\n"))
end
it "File['x', 'y'] { x => 1 }" do
expect(dump(parse("File['x', 'y'] { x => 1}"))).to eq([
"(override (slice File ('x' 'y'))",
" (x => 1))"
].join("\n"))
end
it "File['x'] { x => 1, y => 2 }" do
expect(dump(parse("File['x'] { x => 1, y=> 2}"))).to eq([
"(override (slice File 'x')",
" (x => 1)",
" (y => 2))"
].join("\n"))
end
it "File['x'] { x +> 1 }" do
expect(dump(parse("File['x'] { x +> 1}"))).to eq([
"(override (slice File 'x')",
" (x +> 1))"
].join("\n"))
end
it "File['x'] { * => {mode => '0777'} } (even if validated to be illegal)" do
expect(dump(parse("File['x'] { * => {mode => '0777'}}"))).to eq([
"(override (slice File 'x')",
" (* => ({} (mode '0777'))))"
].join("\n"))
end
end
context "When parsing virtual and exported resources" do
it "parses exported @@file { 'title': }" do
expect(dump(parse("@@file { 'title': }"))).to eq("(exported-resource file\n ('title'))")
end
it "parses virtual @file { 'title': }" do
expect(dump(parse("@file { 'title': }"))).to eq("(virtual-resource file\n ('title'))")
end
it "nothing before the title colon is a syntax error" do
expect do
parse("@file {: mode => '0777' }")
end.to raise_error(/Syntax error/)
end
it "raises error for user error; not a resource" do
# The expression results in VIRTUAL, CALL FUNCTION('file', HASH) since the resource body has
# no title.
expect do
parse("@file { mode => '0777' }")
end.to raise_error(/Virtual \(@\) can only be applied to a Resource Expression/)
end
it "parses global defaults with @ (even if validated to be illegal)" do
expect(dump(parse("@File { mode => '0777' }"))).to eq([
"(virtual-resource-defaults File",
" (mode => '0777'))"
].join("\n"))
end
it "parses global defaults with @@ (even if validated to be illegal)" do
expect(dump(parse("@@File { mode => '0777' }"))).to eq([
"(exported-resource-defaults File",
" (mode => '0777'))"
].join("\n"))
end
it "parses override with @ (even if validated to be illegal)" do
expect(dump(parse("@File[foo] { mode => '0777' }"))).to eq([
"(virtual-override (slice File foo)",
" (mode => '0777'))"
].join("\n"))
end
it "parses override combined with @@ (even if validated to be illegal)" do
expect(dump(parse("@@File[foo] { mode => '0777' }"))).to eq([
"(exported-override (slice File foo)",
" (mode => '0777'))"
].join("\n"))
end
end
context "When parsing class resource" do
it "class { 'cname': }" do
expect(dump(parse("class { 'cname': }"))).to eq([
"(resource class",
" ('cname'))"
].join("\n"))
end
it "@class { 'cname': }" do
expect(dump(parse("@class { 'cname': }"))).to eq([
"(virtual-resource class",
" ('cname'))"
].join("\n"))
end
it "@@class { 'cname': }" do
expect(dump(parse("@@class { 'cname': }"))).to eq([
"(exported-resource class",
" ('cname'))"
].join("\n"))
end
it "class { 'cname': x => 1, y => 2}" do
expect(dump(parse("class { 'cname': x => 1, y => 2}"))).to eq([
"(resource class",
" ('cname'",
" (x => 1)",
" (y => 2)))"
].join("\n"))
end
it "class { 'cname1': x => 1; 'cname2': y => 2}" do
expect(dump(parse("class { 'cname1': x => 1; 'cname2': y => 2}"))).to eq([
"(resource class",
" ('cname1'",
" (x => 1))",
" ('cname2'",
" (y => 2)))",
].join("\n"))
end
end
context "reported issues in 3.x" do
it "should not screw up on brackets in title of resource #19632" do
expect(dump(parse('notify { "thisisa[bug]": }'))).to eq([
"(resource notify",
" ('thisisa[bug]'))",
].join("\n"))
end
end
context "When parsing Relationships" do
it "File[a] -> File[b]" do
expect(dump(parse("File[a] -> File[b]"))).to eq("(-> (slice File a) (slice File b))")
end
it "File[a] <- File[b]" do
expect(dump(parse("File[a] <- File[b]"))).to eq("(<- (slice File a) (slice File b))")
end
it "File[a] ~> File[b]" do
expect(dump(parse("File[a] ~> File[b]"))).to eq("(~> (slice File a) (slice File b))")
end
it "File[a] <~ File[b]" do
expect(dump(parse("File[a] <~ File[b]"))).to eq("(<~ (slice File a) (slice File b))")
end
it "Should chain relationships" do
expect(dump(parse("a -> b -> c"))).to eq(
"(-> (-> a b) c)"
)
end
it "Should chain relationships" do
expect(dump(parse("File[a] -> File[b] ~> File[c] <- File[d] <~ File[e]"))).to eq(
"(<~ (<- (~> (-> (slice File a) (slice File b)) (slice File c)) (slice File d)) (slice File e))"
)
end
it "should create relationships between collects" do
expect(dump(parse("File <| mode == 0644 |> -> File <| mode == 0755 |>"))).to eq(
"(-> (collect File\n (<| |> (== mode 0644))) (collect File\n (<| |> (== mode 0755))))"
)
end
end
context "When parsing collection" do
context "of virtual resources" do
it "File <| |>" do
expect(dump(parse("File <| |>"))).to eq("(collect File\n (<| |>))")
end
end
context "of exported resources" do
it "File <<| |>>" do
expect(dump(parse("File <<| |>>"))).to eq("(collect File\n (<<| |>>))")
end
end
context "queries are parsed with correct precedence" do
it "File <| tag == 'foo' |>" do
expect(dump(parse("File <| tag == 'foo' |>"))).to eq("(collect File\n (<| |> (== tag 'foo')))")
end
it "File <| tag == 'foo' and mode != '0777' |>" do
expect(dump(parse("File <| tag == 'foo' and mode != '0777' |>"))).to eq("(collect File\n (<| |> (&& (== tag 'foo') (!= mode '0777'))))")
end
it "File <| tag == 'foo' or mode != '0777' |>" do
expect(dump(parse("File <| tag == 'foo' or mode != '0777' |>"))).to eq("(collect File\n (<| |> (|| (== tag 'foo') (!= mode '0777'))))")
end
it "File <| tag == 'foo' or tag == 'bar' and mode != '0777' |>" do
expect(dump(parse("File <| tag == 'foo' or tag == 'bar' and mode != '0777' |>"))).to eq(
"(collect File\n (<| |> (|| (== tag 'foo') (&& (== tag 'bar') (!= mode '0777')))))"
)
end
it "File <| (tag == 'foo' or tag == 'bar') and mode != '0777' |>" do
expect(dump(parse("File <| (tag == 'foo' or tag == 'bar') and mode != '0777' |>"))).to eq(
"(collect File\n (<| |> (&& (|| (== tag 'foo') (== tag 'bar')) (!= mode '0777'))))"
)
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/pops/parser/parse_basic_expressions_spec.rb | spec/unit/pops/parser/parse_basic_expressions_spec.rb | require 'spec_helper'
require 'puppet/pops'
# relative to this spec file (./) does not work as this file is loaded by rspec
require File.join(File.dirname(__FILE__), '/parser_rspec_helper')
describe "egrammar parsing basic expressions" do
include ParserRspecHelper
context "When the parser parses arithmetic" do
context "with Integers" do
it "$a = 2 + 2" do; expect(dump(parse("$a = 2 + 2"))).to eq("(= $a (+ 2 2))") ; end
it "$a = 7 - 3" do; expect(dump(parse("$a = 7 - 3"))).to eq("(= $a (- 7 3))") ; end
it "$a = 6 * 3" do; expect(dump(parse("$a = 6 * 3"))).to eq("(= $a (* 6 3))") ; end
it "$a = 6 / 3" do; expect(dump(parse("$a = 6 / 3"))).to eq("(= $a (/ 6 3))") ; end
it "$a = 6 % 3" do; expect(dump(parse("$a = 6 % 3"))).to eq("(= $a (% 6 3))") ; end
it "$a = -(6/3)" do; expect(dump(parse("$a = -(6/3)"))).to eq("(= $a (- (/ 6 3)))") ; end
it "$a = -6/3" do; expect(dump(parse("$a = -6/3"))).to eq("(= $a (/ (- 6) 3))") ; end
it "$a = 8 >> 1 " do; expect(dump(parse("$a = 8 >> 1"))).to eq("(= $a (>> 8 1))") ; end
it "$a = 8 << 1 " do; expect(dump(parse("$a = 8 << 1"))).to eq("(= $a (<< 8 1))") ; end
end
context "with Floats" do
it "$a = 2.2 + 2.2" do; expect(dump(parse("$a = 2.2 + 2.2"))).to eq("(= $a (+ 2.2 2.2))") ; end
it "$a = 7.7 - 3.3" do; expect(dump(parse("$a = 7.7 - 3.3"))).to eq("(= $a (- 7.7 3.3))") ; end
it "$a = 6.1 * 3.1" do; expect(dump(parse("$a = 6.1 - 3.1"))).to eq("(= $a (- 6.1 3.1))") ; end
it "$a = 6.6 / 3.3" do; expect(dump(parse("$a = 6.6 / 3.3"))).to eq("(= $a (/ 6.6 3.3))") ; end
it "$a = -(6.0/3.0)" do; expect(dump(parse("$a = -(6.0/3.0)"))).to eq("(= $a (- (/ 6.0 3.0)))") ; end
it "$a = -6.0/3.0" do; expect(dump(parse("$a = -6.0/3.0"))).to eq("(= $a (/ (- 6.0) 3.0))") ; end
it "$a = 3.14 << 2" do; expect(dump(parse("$a = 3.14 << 2"))).to eq("(= $a (<< 3.14 2))") ; end
it "$a = 3.14 >> 2" do; expect(dump(parse("$a = 3.14 >> 2"))).to eq("(= $a (>> 3.14 2))") ; end
end
context "with hex and octal Integer values" do
it "$a = 0xAB + 0xCD" do; expect(dump(parse("$a = 0xAB + 0xCD"))).to eq("(= $a (+ 0xAB 0xCD))") ; end
it "$a = 0777 - 0333" do; expect(dump(parse("$a = 0777 - 0333"))).to eq("(= $a (- 0777 0333))") ; end
end
context "with strings requiring boxing to Numeric" do
# Test that numbers in string form does not turn into numbers
it "$a = '2' + '2'" do; expect(dump(parse("$a = '2' + '2'"))).to eq("(= $a (+ '2' '2'))") ; end
it "$a = '2.2' + '0.2'" do; expect(dump(parse("$a = '2.2' + '0.2'"))).to eq("(= $a (+ '2.2' '0.2'))") ; end
it "$a = '0xab' + '0xcd'" do; expect(dump(parse("$a = '0xab' + '0xcd'"))).to eq("(= $a (+ '0xab' '0xcd'))") ; end
it "$a = '0777' + '0333'" do; expect(dump(parse("$a = '0777' + '0333'"))).to eq("(= $a (+ '0777' '0333'))") ; end
end
context "precedence should be correct" do
it "$a = 1 + 2 * 3" do; expect(dump(parse("$a = 1 + 2 * 3"))).to eq("(= $a (+ 1 (* 2 3)))"); end
it "$a = 1 + 2 % 3" do; expect(dump(parse("$a = 1 + 2 % 3"))).to eq("(= $a (+ 1 (% 2 3)))"); end
it "$a = 1 + 2 / 3" do; expect(dump(parse("$a = 1 + 2 / 3"))).to eq("(= $a (+ 1 (/ 2 3)))"); end
it "$a = 1 + 2 << 3" do; expect(dump(parse("$a = 1 + 2 << 3"))).to eq("(= $a (<< (+ 1 2) 3))"); end
it "$a = 1 + 2 >> 3" do; expect(dump(parse("$a = 1 + 2 >> 3"))).to eq("(= $a (>> (+ 1 2) 3))"); end
end
context "parentheses alter precedence" do
it "$a = (1 + 2) * 3" do; expect(dump(parse("$a = (1 + 2) * 3"))).to eq("(= $a (* (+ 1 2) 3))"); end
it "$a = (1 + 2) / 3" do; expect(dump(parse("$a = (1 + 2) / 3"))).to eq("(= $a (/ (+ 1 2) 3))"); end
end
end
context "When the evaluator performs boolean operations" do
context "using operators AND OR NOT" do
it "$a = true and true" do; expect(dump(parse("$a = true and true"))).to eq("(= $a (&& true true))"); end
it "$a = true or true" do; expect(dump(parse("$a = true or true"))).to eq("(= $a (|| true true))") ; end
it "$a = !true" do; expect(dump(parse("$a = !true"))).to eq("(= $a (! true))") ; end
end
context "precedence should be correct" do
it "$a = false or true and true" do
expect(dump(parse("$a = false or true and true"))).to eq("(= $a (|| false (&& true true)))")
end
it "$a = (false or true) and true" do
expect(dump(parse("$a = (false or true) and true"))).to eq("(= $a (&& (|| false true) true))")
end
it "$a = !true or true and true" do
expect(dump(parse("$a = !false or true and true"))).to eq("(= $a (|| (! false) (&& true true)))")
end
end
# Possibly change to check of literal expressions
context "on values requiring boxing to Boolean" do
it "'x' == true" do
expect(dump(parse("! 'x'"))).to eq("(! 'x')")
end
it "'' == false" do
expect(dump(parse("! ''"))).to eq("(! '')")
end
it ":undef == false" do
expect(dump(parse("! undef"))).to eq("(! :undef)")
end
end
end
context "When parsing comparisons" do
context "of string values" do
it "$a = 'a' == 'a'" do; expect(dump(parse("$a = 'a' == 'a'"))).to eq("(= $a (== 'a' 'a'))") ; end
it "$a = 'a' != 'a'" do; expect(dump(parse("$a = 'a' != 'a'"))).to eq("(= $a (!= 'a' 'a'))") ; end
it "$a = 'a' < 'b'" do; expect(dump(parse("$a = 'a' < 'b'"))).to eq("(= $a (< 'a' 'b'))") ; end
it "$a = 'a' > 'b'" do; expect(dump(parse("$a = 'a' > 'b'"))).to eq("(= $a (> 'a' 'b'))") ; end
it "$a = 'a' <= 'b'" do; expect(dump(parse("$a = 'a' <= 'b'"))).to eq("(= $a (<= 'a' 'b'))") ; end
it "$a = 'a' >= 'b'" do; expect(dump(parse("$a = 'a' >= 'b'"))).to eq("(= $a (>= 'a' 'b'))") ; end
end
context "of integer values" do
it "$a = 1 == 1" do; expect(dump(parse("$a = 1 == 1"))).to eq("(= $a (== 1 1))") ; end
it "$a = 1 != 1" do; expect(dump(parse("$a = 1 != 1"))).to eq("(= $a (!= 1 1))") ; end
it "$a = 1 < 2" do; expect(dump(parse("$a = 1 < 2"))).to eq("(= $a (< 1 2))") ; end
it "$a = 1 > 2" do; expect(dump(parse("$a = 1 > 2"))).to eq("(= $a (> 1 2))") ; end
it "$a = 1 <= 2" do; expect(dump(parse("$a = 1 <= 2"))).to eq("(= $a (<= 1 2))") ; end
it "$a = 1 >= 2" do; expect(dump(parse("$a = 1 >= 2"))).to eq("(= $a (>= 1 2))") ; end
end
context "of regular expressions (parse errors)" do
# Not supported in concrete syntax
it "$a = /.*/ == /.*/" do
expect(dump(parse("$a = /.*/ == /.*/"))).to eq("(= $a (== /.*/ /.*/))")
end
it "$a = /.*/ != /a.*/" do
expect(dump(parse("$a = /.*/ != /.*/"))).to eq("(= $a (!= /.*/ /.*/))")
end
end
end
context "When parsing Regular Expression matching" do
it "$a = 'a' =~ /.*/" do; expect(dump(parse("$a = 'a' =~ /.*/"))).to eq("(= $a (=~ 'a' /.*/))") ; end
it "$a = 'a' =~ '.*'" do; expect(dump(parse("$a = 'a' =~ '.*'"))).to eq("(= $a (=~ 'a' '.*'))") ; end
it "$a = 'a' !~ /b.*/" do; expect(dump(parse("$a = 'a' !~ /b.*/"))).to eq("(= $a (!~ 'a' /b.*/))") ; end
it "$a = 'a' !~ 'b.*'" do; expect(dump(parse("$a = 'a' !~ 'b.*'"))).to eq("(= $a (!~ 'a' 'b.*'))") ; end
end
context "When parsing unfold" do
it "$a = *[1,2]" do; expect(dump(parse("$a = *[1,2]"))).to eq("(= $a (unfold ([] 1 2)))") ; end
it "$a = *1" do; expect(dump(parse("$a = *1"))).to eq("(= $a (unfold 1))") ; end
it "$a = *[1,a => 2]" do; expect(dump(parse("$a = *[1,a => 2]"))).to eq("(= $a (unfold ([] 1 ({} (a 2)))))") ; end
end
context "When parsing Lists" do
it "$a = []" do
expect(dump(parse("$a = []"))).to eq("(= $a ([]))")
end
it "$a = [1]" do
expect(dump(parse("$a = [1]"))).to eq("(= $a ([] 1))")
end
it "$a = [1,2,3]" do
expect(dump(parse("$a = [1,2,3]"))).to eq("(= $a ([] 1 2 3))")
end
it "$a = [1,a => 2]" do
expect(dump(parse("$a = [1,a => 2]"))).to eq('(= $a ([] 1 ({} (a 2))))')
end
it "$a = [1,a => 2, 3]" do
expect(dump(parse("$a = [1,a => 2, 3]"))).to eq('(= $a ([] 1 ({} (a 2)) 3))')
end
it "$a = [1,a => 2, b => 3]" do
expect(dump(parse("$a = [1,a => 2, b => 3]"))).to eq('(= $a ([] 1 ({} (a 2) (b 3))))')
end
it "$a = [1,a => 2, b => 3, 4]" do
expect(dump(parse("$a = [1,a => 2, b => 3, 4]"))).to eq('(= $a ([] 1 ({} (a 2) (b 3)) 4))')
end
it "$a = [{ x => y }, a => 2, b => 3, { z => p }]" do
expect(dump(parse("$a = [{ x => y }, a => 2, b => 3, { z => p }]"))).to eq('(= $a ([] ({} (x y)) ({} (a 2) (b 3)) ({} (z p))))')
end
it "[...[...[]]] should create nested arrays without trouble" do
expect(dump(parse("$a = [1,[2.0, 2.1, [2.2]],[3.0, 3.1]]"))).to eq("(= $a ([] 1 ([] 2.0 2.1 ([] 2.2)) ([] 3.0 3.1)))")
end
it "$a = [2 + 2]" do
expect(dump(parse("$a = [2+2]"))).to eq("(= $a ([] (+ 2 2)))")
end
it "$a [1,2,3] == [1,2,3]" do
expect(dump(parse("$a = [1,2,3] == [1,2,3]"))).to eq("(= $a (== ([] 1 2 3) ([] 1 2 3)))")
end
it "calculates the text length of an empty array" do
expect(parse("[]").model.body.length).to eq(2)
expect(parse("[ ]").model.body.length).to eq(3)
end
{
'keyword' => %w(type function),
}.each_pair do |word_type, words|
words.each do |word|
it "allows the #{word_type} '#{word}' in a list" do
expect(dump(parse("$a = [#{word}]"))).to(eq("(= $a ([] '#{word}'))"))
end
it "allows the #{word_type} '#{word}' as a key in a hash" do
expect(dump(parse("$a = {#{word}=>'x'}"))).to(eq("(= $a ({} ('#{word}' 'x')))"))
end
it "allows the #{word_type} '#{word}' as a value in a hash" do
expect(dump(parse("$a = {'x'=>#{word}}"))).to(eq("(= $a ({} ('x' '#{word}')))"))
end
end
end
end
context "When parsing indexed access" do
it "$a = $b[2]" do
expect(dump(parse("$a = $b[2]"))).to eq("(= $a (slice $b 2))")
end
it "$a = $b[2,]" do
expect(dump(parse("$a = $b[2,]"))).to eq("(= $a (slice $b 2))")
end
it "$a = [1, 2, 3][2]" do
expect(dump(parse("$a = [1,2,3][2]"))).to eq("(= $a (slice ([] 1 2 3) 2))")
end
it '$a = [1, 2, 3][a => 2]' do
expect(dump(parse('$a = [1,2,3][a => 2]'))).to eq('(= $a (slice ([] 1 2 3) ({} (a 2))))')
end
it "$a = {'a' => 1, 'b' => 2}['b']" do
expect(dump(parse("$a = {'a'=>1,'b' =>2}[b]"))).to eq("(= $a (slice ({} ('a' 1) ('b' 2)) b))")
end
end
context 'When parsing type aliases' do
it 'type A = B' do
expect(dump(parse('type A = B'))).to eq('(type-alias A B)')
end
it 'type A = B[]' do
expect{parse('type A = B[]')}.to raise_error(/Syntax error at '\]'/)
end
it 'type A = B[,]' do
expect{parse('type A = B[,]')}.to raise_error(/Syntax error at ','/)
end
it 'type A = B[C]' do
expect(dump(parse('type A = B[C]'))).to eq('(type-alias A (slice B C))')
end
it 'type A = B[C,]' do
expect(dump(parse('type A = B[C,]'))).to eq('(type-alias A (slice B C))')
end
it 'type A = B[C,D]' do
expect(dump(parse('type A = B[C,D]'))).to eq('(type-alias A (slice B (C D)))')
end
it 'type A = B[C,D,]' do
expect(dump(parse('type A = B[C,D,]'))).to eq('(type-alias A (slice B (C D)))')
end
end
context "When parsing assignments" do
it "Should allow simple assignment" do
expect(dump(parse("$a = 10"))).to eq("(= $a 10)")
end
it "Should allow append assignment" do
expect(dump(parse("$a += 10"))).to eq("(+= $a 10)")
end
it "Should allow without assignment" do
expect(dump(parse("$a -= 10"))).to eq("(-= $a 10)")
end
it "Should allow chained assignment" do
expect(dump(parse("$a = $b = 10"))).to eq("(= $a (= $b 10))")
end
it "Should allow chained assignment with expressions" do
expect(dump(parse("$a = 1 + ($b = 10)"))).to eq("(= $a (+ 1 (= $b 10)))")
end
end
context "When parsing Hashes" do
it "should create a Hash when evaluating a LiteralHash" do
expect(dump(parse("$a = {'a'=>1,'b'=>2}"))).to eq("(= $a ({} ('a' 1) ('b' 2)))")
end
it "$a = {...{...{}}} should create nested hashes without trouble" do
expect(dump(parse("$a = {'a'=>1,'b'=>{'x'=>2.1,'y'=>2.2}}"))).to eq("(= $a ({} ('a' 1) ('b' ({} ('x' 2.1) ('y' 2.2)))))")
end
it "$a = {'a'=> 2 + 2} should evaluate values in entries" do
expect(dump(parse("$a = {'a'=>2+2}"))).to eq("(= $a ({} ('a' (+ 2 2))))")
end
it "$a = {'a'=> 1, 'b'=>2} == {'a'=> 1, 'b'=>2}" do
expect(dump(parse("$a = {'a'=>1,'b'=>2} == {'a'=>1,'b'=>2}"))).to eq("(= $a (== ({} ('a' 1) ('b' 2)) ({} ('a' 1) ('b' 2))))")
end
it "$a = {'a'=> 1, 'b'=>2} != {'x'=> 1, 'y'=>3}" do
expect(dump(parse("$a = {'a'=>1,'b'=>2} != {'a'=>1,'b'=>2}"))).to eq("(= $a (!= ({} ('a' 1) ('b' 2)) ({} ('a' 1) ('b' 2))))")
end
it "$a = 'a' => 1" do
expect{parse("$a = 'a' => 1")}.to raise_error(/Syntax error at '=>'/)
end
it "$a = { 'a' => 'b' => 1 }" do
expect{parse("$a = { 'a' => 'b' => 1 }")}.to raise_error(/Syntax error at '=>'/)
end
it "calculates the text length of an empty hash" do
expect(parse("{}").model.body.length).to eq(2)
expect(parse("{ }").model.body.length).to eq(3)
end
end
context "When parsing the 'in' operator" do
it "with integer in a list" do
expect(dump(parse("$a = 1 in [1,2,3]"))).to eq("(= $a (in 1 ([] 1 2 3)))")
end
it "with string key in a hash" do
expect(dump(parse("$a = 'a' in {'x'=>1, 'a'=>2, 'y'=> 3}"))).to eq("(= $a (in 'a' ({} ('x' 1) ('a' 2) ('y' 3))))")
end
it "with substrings of a string" do
expect(dump(parse("$a = 'ana' in 'bananas'"))).to eq("(= $a (in 'ana' 'bananas'))")
end
it "with sublist in a list" do
expect(dump(parse("$a = [2,3] in [1,2,3]"))).to eq("(= $a (in ([] 2 3) ([] 1 2 3)))")
end
end
context "When parsing string interpolation" do
it "should interpolate a bare word as a variable name, \"${var}\"" do
expect(dump(parse("$a = \"$var\""))).to eq("(= $a (cat (str $var)))")
end
it "should interpolate a variable in a text expression, \"${$var}\"" do
expect(dump(parse("$a = \"${$var}\""))).to eq("(= $a (cat (str $var)))")
end
it "should interpolate a variable, \"yo${var}yo\"" do
expect(dump(parse("$a = \"yo${var}yo\""))).to eq("(= $a (cat 'yo' (str $var) 'yo'))")
end
it "should interpolate any expression in a text expression, \"${$var*2}\"" do
expect(dump(parse("$a = \"yo${$var+2}yo\""))).to eq("(= $a (cat 'yo' (str (+ $var 2)) 'yo'))")
end
it "should not interpolate names as variable in expression, \"${notvar*2}\"" do
expect(dump(parse("$a = \"yo${notvar+2}yo\""))).to eq("(= $a (cat 'yo' (str (+ notvar 2)) 'yo'))")
end
it "should interpolate name as variable in access expression, \"${var[0]}\"" do
expect(dump(parse("$a = \"yo${var[0]}yo\""))).to eq("(= $a (cat 'yo' (str (slice $var 0)) 'yo'))")
end
it "should interpolate name as variable in method call, \"${var.foo}\"" do
expect(dump(parse("$a = \"yo${$var.foo}yo\""))).to eq("(= $a (cat 'yo' (str (call-method (. $var foo))) 'yo'))")
end
it "should interpolate name as variable in method call, \"${var.foo}\"" do
expect(dump(parse("$a = \"yo${var.foo}yo\""))).to eq("(= $a (cat 'yo' (str (call-method (. $var foo))) 'yo'))")
expect(dump(parse("$a = \"yo${var.foo.bar}yo\""))).to eq("(= $a (cat 'yo' (str (call-method (. (call-method (. $var foo)) bar))) 'yo'))")
end
it "should interpolate interpolated expressions with a variable, \"yo${\"$var\"}yo\"" do
expect(dump(parse("$a = \"yo${\"$var\"}yo\""))).to eq("(= $a (cat 'yo' (str (cat (str $var))) 'yo'))")
end
it "should interpolate interpolated expressions with an expression, \"yo${\"${$var+2}\"}yo\"" do
expect(dump(parse("$a = \"yo${\"${$var+2}\"}yo\""))).to eq("(= $a (cat 'yo' (str (cat (str (+ $var 2)))) 'yo'))")
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/pops/parser/parser_spec.rb | spec/unit/pops/parser/parser_spec.rb | require 'spec_helper'
require 'puppet/pops'
describe Puppet::Pops::Parser::Parser do
it "should instantiate a parser" do
parser = Puppet::Pops::Parser::Parser.new()
expect(parser.class).to eq(Puppet::Pops::Parser::Parser)
end
it "should parse a code string and return a model" do
parser = Puppet::Pops::Parser::Parser.new()
model = parser.parse_string("$a = 10").model
expect(model.class).to eq(Puppet::Pops::Model::Program)
expect(model.body.class).to eq(Puppet::Pops::Model::AssignmentExpression)
end
it "should accept empty input and return a model" do
parser = Puppet::Pops::Parser::Parser.new()
model = parser.parse_string("").model
expect(model.class).to eq(Puppet::Pops::Model::Program)
expect(model.body.class).to eq(Puppet::Pops::Model::Nop)
end
it "should accept empty input containing only comments and report location at end of input" do
parser = Puppet::Pops::Parser::Parser.new()
model = parser.parse_string("# comment\n").model
expect(model.class).to eq(Puppet::Pops::Model::Program)
expect(model.body.class).to eq(Puppet::Pops::Model::Nop)
expect(model.body.offset).to eq(10)
expect(model.body.length).to eq(0)
end
it "should give single resource expressions the correct offset inside an if/else statement" do
parser = Puppet::Pops::Parser::Parser.new()
model = parser.parse_string(<<-EOF).model
class firewall {
if(true) {
service { 'if service':
ensure => stopped
}
} else {
service { 'else service':
ensure => running
}
}
}
EOF
then_service = model.body.body.statements[0].then_expr
expect(then_service.class).to eq(Puppet::Pops::Model::ResourceExpression)
expect(then_service.offset).to eq(34)
else_service = model.body.body.statements[0].else_expr
expect(else_service.class).to eq(Puppet::Pops::Model::ResourceExpression)
expect(else_service.offset).to eq(106)
end
it "should give block expressions and their contained resources the correct offset inside an if/else statement" do
parser = Puppet::Pops::Parser::Parser.new()
model = parser.parse_string(<<-EOF).model
class firewall {
if(true) {
service { 'if service 1':
ensure => running
}
service { 'if service 2':
ensure => stopped
}
} else {
service { 'else service 1':
ensure => running
}
service { 'else service 2':
ensure => stopped
}
}
}
EOF
if_expr = model.body.body.statements[0]
block_expr = model.body.body.statements[0].then_expr
expect(if_expr.class).to eq(Puppet::Pops::Model::IfExpression)
expect(if_expr.offset).to eq(19)
expect(block_expr.class).to eq(Puppet::Pops::Model::BlockExpression)
expect(block_expr.offset).to eq(28)
expect(block_expr.statements[0].class).to eq(Puppet::Pops::Model::ResourceExpression)
expect(block_expr.statements[0].offset).to eq(34)
expect(block_expr.statements[1].class).to eq(Puppet::Pops::Model::ResourceExpression)
expect(block_expr.statements[1].offset).to eq(98)
block_expr = model.body.body.statements[0].else_expr
expect(block_expr.class).to eq(Puppet::Pops::Model::BlockExpression)
expect(block_expr.offset).to eq(166)
expect(block_expr.statements[0].class).to eq(Puppet::Pops::Model::ResourceExpression)
expect(block_expr.statements[0].offset).to eq(172)
expect(block_expr.statements[1].class).to eq(Puppet::Pops::Model::ResourceExpression)
expect(block_expr.statements[1].offset).to eq(238)
end
it "should give single resource expressions the correct offset inside an unless/else statement" do
parser = Puppet::Pops::Parser::Parser.new()
model = parser.parse_string(<<-EOF).model
class firewall {
unless(true) {
service { 'if service':
ensure => stopped
}
} else {
service { 'else service':
ensure => running
}
}
}
EOF
then_service = model.body.body.statements[0].then_expr
expect(then_service.class).to eq(Puppet::Pops::Model::ResourceExpression)
expect(then_service.offset).to eq(38)
else_service = model.body.body.statements[0].else_expr
expect(else_service.class).to eq(Puppet::Pops::Model::ResourceExpression)
expect(else_service.offset).to eq(110)
end
it "should give block expressions and their contained resources the correct offset inside an unless/else statement" do
parser = Puppet::Pops::Parser::Parser.new()
model = parser.parse_string(<<-EOF).model
class firewall {
unless(true) {
service { 'if service 1':
ensure => running
}
service { 'if service 2':
ensure => stopped
}
} else {
service { 'else service 1':
ensure => running
}
service { 'else service 2':
ensure => stopped
}
}
}
EOF
if_expr = model.body.body.statements[0]
block_expr = model.body.body.statements[0].then_expr
expect(if_expr.class).to eq(Puppet::Pops::Model::UnlessExpression)
expect(if_expr.offset).to eq(19)
expect(block_expr.class).to eq(Puppet::Pops::Model::BlockExpression)
expect(block_expr.offset).to eq(32)
expect(block_expr.statements[0].class).to eq(Puppet::Pops::Model::ResourceExpression)
expect(block_expr.statements[0].offset).to eq(38)
expect(block_expr.statements[1].class).to eq(Puppet::Pops::Model::ResourceExpression)
expect(block_expr.statements[1].offset).to eq(102)
block_expr = model.body.body.statements[0].else_expr
expect(block_expr.class).to eq(Puppet::Pops::Model::BlockExpression)
expect(block_expr.offset).to eq(170)
expect(block_expr.statements[0].class).to eq(Puppet::Pops::Model::ResourceExpression)
expect(block_expr.statements[0].offset).to eq(176)
expect(block_expr.statements[1].class).to eq(Puppet::Pops::Model::ResourceExpression)
expect(block_expr.statements[1].offset).to eq(242)
end
it "multi byte characters in a comment are counted as individual bytes" do
parser = Puppet::Pops::Parser::Parser.new()
model = parser.parse_string("# \u{0400}comment\n").model
expect(model.class).to eq(Puppet::Pops::Model::Program)
expect(model.body.class).to eq(Puppet::Pops::Model::Nop)
expect(model.body.offset).to eq(12)
expect(model.body.length).to eq(0)
end
it "should raise an error with position information when error is raised from within parser" do
parser = Puppet::Pops::Parser::Parser.new()
the_error = nil
begin
parser.parse_string("File [1] { }", 'fakefile.pp')
rescue Puppet::ParseError => e
the_error = e
end
expect(the_error).to be_a(Puppet::ParseError)
expect(the_error.file).to eq('fakefile.pp')
expect(the_error.line).to eq(1)
expect(the_error.pos).to eq(6)
end
it "should raise an error with position information when error is raised on token" do
parser = Puppet::Pops::Parser::Parser.new()
the_error = nil
begin
parser.parse_string(<<-EOF, 'fakefile.pp')
class whoops($a,$b,$c) {
$d = "oh noes", "b"
}
EOF
rescue Puppet::ParseError => e
the_error = e
end
expect(the_error).to be_a(Puppet::ParseError)
expect(the_error.file).to eq('fakefile.pp')
expect(the_error.line).to eq(2)
expect(the_error.pos).to eq(17)
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/pops/parser/parse_functions_spec.rb | spec/unit/pops/parser/parse_functions_spec.rb | require 'spec_helper'
require 'puppet/pops'
require_relative 'parser_rspec_helper'
describe 'egrammar parsing function definitions' do
include ParserRspecHelper
context 'without return type' do
it 'function foo() { 1 }' do
expect(dump(parse('function foo() { 1 }'))).to eq("(function foo (block\n 1\n))")
end
end
context 'with return type' do
it 'function foo() >> Integer { 1 }' do
expect(dump(parse('function foo() >> Integer { 1 }'))).to eq("(function foo (return_type Integer) (block\n 1\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/pops/parser/pn_parser_spec.rb | spec/unit/pops/parser/pn_parser_spec.rb | require 'spec_helper'
require 'puppet/pops'
require 'puppet/pops/pn'
module Puppet::Pops
module Parser
describe 'Puppet::Pops::Parser::PNParser' do
context 'parses the text' do
it '"true" to PN::Literal(true)' do
expect(PNParser.new.parse('true')).to eql(lit(true))
end
it '"false" to PN::Literal(false)' do
expect(PNParser.new.parse('false')).to eql(lit(false))
end
it '"nil" to PN::Literal(nil)' do
expect(PNParser.new.parse('nil')).to eql(lit(nil))
end
it '"123" to PN::Literal(123)' do
expect(PNParser.new.parse('123')).to eql(lit(123))
end
it '"-123" to PN::Literal(-123)' do
expect(PNParser.new.parse('-123')).to eql(lit(-123))
end
it '"123.45" to PN::Literal(123.45)' do
expect(PNParser.new.parse('123.45')).to eql(lit(123.45))
end
it '"-123.45" to PN::Literal(-123.45)' do
expect(PNParser.new.parse('-123.45')).to eql(lit(-123.45))
end
it '"123.45e12" to PN::Literal(123.45e12)' do
expect(PNParser.new.parse('123.45e12')).to eql(lit(123.45e12))
end
it '"123.45e+12" to PN::Literal(123.45e+12)' do
expect(PNParser.new.parse('123.45e+12')).to eql(lit(123.45e+12))
end
it '"123.45e-12" to PN::Literal(123.45e-12)' do
expect(PNParser.new.parse('123.45e-12')).to eql(lit(123.45e-12))
end
it '"hello" to PN::Literal("hello")' do
expect(PNParser.new.parse('"hello"')).to eql(lit('hello'))
end
it '"\t" to PN::Literal("\t")' do
expect(PNParser.new.parse('"\t"')).to eql(lit("\t"))
end
it '"\r" to PN::Literal("\r")' do
expect(PNParser.new.parse('"\r"')).to eql(lit("\r"))
end
it '"\n" to PN::Literal("\n")' do
expect(PNParser.new.parse('"\n"')).to eql(lit("\n"))
end
it '"\"" to PN::Literal("\"")' do
expect(PNParser.new.parse('"\""')).to eql(lit('"'))
end
it '"\\\\" to PN::Literal("\\")' do
expect(PNParser.new.parse('"\\\\"')).to eql(lit("\\"))
end
it '"\o024" to PN::Literal("\u{14}")' do
expect(PNParser.new.parse('"\o024"')).to eql(lit("\u{14}"))
end
end
it 'parses elements enclosed in brackets to a PN::List' do
expect(PNParser.new.parse('[1 "2" true false nil]')).to eql(PN::List.new([lit(1), lit('2'), lit(true), lit(false), lit(nil)]))
end
it 'parses elements enclosed in parenthesis to a PN::Call' do
expect(PNParser.new.parse('(+ 1 2)')).to eql(PN::Call.new('+', lit(1), lit(2)))
end
it 'parses entries enclosed in curly braces to a PN::Map' do
expect(PNParser.new.parse('{:a 1 :b "2" :c true}')).to eql(PN::Map.new([entry('a', 1), entry('b', '2'), entry('c', true)]))
end
def entry(k, v)
PN::Entry.new(k, lit(v))
end
def lit(v)
PN::Literal.new(v)
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/pops/serialization/to_stringified_spec.rb | spec/unit/pops/serialization/to_stringified_spec.rb | require 'spec_helper'
require 'puppet_spec/compiler'
describe 'ToStringifiedConverter' do
include PuppetSpec::Compiler
after(:all) { Puppet::Pops::Loaders.clear }
let(:env) { Puppet::Node::Environment.create(:testing, []) }
let(:loaders) { Puppet::Pops::Loaders.new(env) }
let(:node) { Puppet::Node.new(env, environment: env) }
def transform(v)
Puppet::Pops::Serialization::ToStringifiedConverter.convert(v)
end
def eval_transform(source)
Puppet.override(:current_environment => env, :loaders => loaders) do
transform(evaluate(source: source, node: node))
end
end
it 'converts undef to to nil' do
expect(transform(nil)).to be_nil
expect(eval_transform('undef')).to be_nil
end
it "converts literal default to the string 'default'" do
expect(transform(:default)).to eq('default')
expect(eval_transform('default')).to eq('default')
end
it "does not convert an integer" do
expect(transform(42)).to eq(42)
end
it "does not convert a float" do
expect(transform(3.14)).to eq(3.14)
end
it "does not convert a boolean" do
expect(transform(true)).to be(true)
expect(transform(false)).to be(false)
end
it "does not convert a string (that is free from encoding issues)" do
expect(transform("hello")).to eq("hello")
end
it "converts a regexp to a string" do
expect(transform(/this|that.*/)).to eq("/this|that.*/")
expect(eval_transform('/this|that.*/')).to eq("/this|that.*/")
end
it 'handles a string with an embedded single quote' do
expect(transform("ta'phoenix")).to eq("ta'phoenix")
end
it 'handles a string with embedded double quotes' do
expect(transform('he said "hi"')).to eq("he said \"hi\"")
end
it 'converts a user defined object to its string representation including attributes' do
result = evaluate(code: "type Car = Object[attributes=>{regnbr => String}]", source: "Car(abc123)")
expect(transform(result)).to eq("Car({'regnbr' => 'abc123'})")
end
it 'converts a Deferred object to its string representation including attributes' do
expect(eval_transform("Deferred(func, [1,2,3])")).to eq("Deferred({'name' => 'func', 'arguments' => [1, 2, 3]})")
end
it 'converts a Sensitive to type + redacted plus id' do
sensitive = evaluate(source: "Sensitive('hush')")
id = sensitive.object_id
expect(transform(sensitive)).to eq("#<Sensitive [value redacted]:#{id}>")
end
it 'converts a Timestamp to String' do
expect(eval_transform("Timestamp('2018-09-03T19:45:33.697066000 UTC')")).to eq("2018-09-03T19:45:33.697066000 UTC")
end
it 'does not convert an array' do
expect(transform([1,2,3])).to eq([1,2,3])
end
it 'converts the content of an array - for example a Sensitive value' do
sensitive = evaluate(source: "Sensitive('hush')")
id = sensitive.object_id
expect(transform([sensitive])).to eq(["#<Sensitive [value redacted]:#{id}>"])
end
it 'converts the content of a hash - for example a Sensitive value' do
sensitive = evaluate(source: "Sensitive('hush')")
id = sensitive.object_id
expect(transform({'x' => sensitive})).to eq({'x' => "#<Sensitive [value redacted]:#{id}>"})
end
it 'does not convert a hash' do
expect(transform({'a' => 10, 'b' => 20})).to eq({'a' => 10, 'b' => 20})
end
it 'converts non Data compliant hash key to string' do
expect(transform({['funky', 'key'] => 10})).to eq({'["funky", "key"]' => 10})
end
it 'converts reserved __ptype hash key to different string' do
expect(transform({'__ptype' => 10})).to eq({'reserved key: __ptype' => 10})
end
it 'converts reserved __pvalue hash key to different string' do
expect(transform({'__pvalue' => 10})).to eq({'reserved key: __pvalue' => 10})
end
it 'converts a Binary to Base64 string' do
expect(eval_transform("Binary('hello', '%s')")).to eq("aGVsbG8=")
end
it 'converts an ASCII-8BIT String to Base64 String' do
binary_string = "\x02\x03\x04hello".force_encoding('ascii-8bit')
expect(transform(binary_string)).to eq("AgMEaGVsbG8=")
end
it 'converts Runtime (alien) object to its to_s' do
class Alien
end
an_alien = Alien.new
expect(transform(an_alien)).to eq(an_alien.to_s)
end
it 'converts a runtime Symbol to String' do
expect(transform(:symbolic)).to eq("symbolic")
end
it 'converts a datatype (such as Integer[0,10]) to its puppet source string form' do
expect(eval_transform("Integer[0,100]")).to eq("Integer[0, 100]")
end
it 'converts a user defined datatype (such as Car) to its puppet source string form' do
result = evaluate(code: "type Car = Object[attributes=>{regnbr => String}]", source: "Car")
expect(transform(result)).to eq("Car")
end
it 'converts a self referencing user defined datatype by using named references for cyclic entries' do
result = evaluate(code: "type Tree = Array[Variant[String, Tree]]", source: "Tree")
expect(transform(result)).to eq("Tree = Array[Variant[String, Tree]]")
end
it 'converts illegal char sequence in an encoding to Unicode Illegal' do
invalid_sequence = [0xc2, 0xc2].pack("c*").force_encoding(Encoding::UTF_8)
expect(transform(invalid_sequence)).to eq("��")
end
it 'does not convert unassigned char - glyph is same for all unassigned' do
unassigned = [243, 176, 128, 128].pack("C*").force_encoding(Encoding::UTF_8)
expect(transform(unassigned)).to eq("")
end
it 'converts ProcessOutput objects to string' do
object = Puppet::Util::Execution::ProcessOutput.new('object', 0)
expect(transform(object)).to be_instance_of(String)
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/pops/serialization/to_from_hr_spec.rb | spec/unit/pops/serialization/to_from_hr_spec.rb | require 'spec_helper'
require 'puppet/pops'
module Puppet::Pops
module Serialization
describe 'Passing values through ToDataConverter/FromDataConverter' do
let(:dumper) { Model::ModelTreeDumper.new }
let(:io) { StringIO.new }
let(:parser) { Parser::EvaluatingParser.new }
let(:env) { Puppet::Node::Environment.create(:testing, []) }
let(:loaders) { Puppet::Pops::Loaders.new(env) }
let(:loader) { loaders.find_loader(nil) }
let(:to_converter) { ToDataConverter.new(:rich_data => true) }
let(:from_converter) { FromDataConverter.new(:loader => loader) }
before(:each) do
Puppet.lookup(:environments).clear_all
Puppet.push_context(:loaders => loaders, :current_environment => env)
end
after(:each) do
Puppet.pop_context
end
def write(value)
io.reopen
value = to_converter.convert(value)
expect(Types::TypeFactory.data).to be_instance(value)
io << [value].to_json
io.rewind
end
def write_raw(value)
io.reopen
expect(Types::TypeFactory.data).to be_instance(value)
io << [value].to_json
io.rewind
end
def read
from_converter.convert(::JSON.parse(io.read)[0])
end
def parse(string)
parser.parse_string(string, '/home/tester/experiments/manifests/init.pp')
end
context 'can write and read a' do
it 'String' do
val = 'the value'
write(val)
val2 = read
expect(val2).to be_a(String)
expect(val2).to eql(val)
end
it 'Integer' do
val = 32
write(val)
val2 = read
expect(val2).to be_a(Integer)
expect(val2).to eql(val)
end
it 'Float' do
val = 32.45
write(val)
val2 = read
expect(val2).to be_a(Float)
expect(val2).to eql(val)
end
it 'true' do
val = true
write(val)
val2 = read
expect(val2).to be_a(TrueClass)
expect(val2).to eql(val)
end
it 'false' do
val = false
write(val)
val2 = read
expect(val2).to be_a(FalseClass)
expect(val2).to eql(val)
end
it 'nil' do
val = nil
write(val)
val2 = read
expect(val2).to be_a(NilClass)
expect(val2).to eql(val)
end
it 'Regexp' do
val = /match me/
write(val)
val2 = read
expect(val2).to be_a(Regexp)
expect(val2).to eql(val)
end
it 'Sensitive' do
sval = 'the sensitive value'
val = Types::PSensitiveType::Sensitive.new(sval)
write(val)
val2 = read
expect(val2).to be_a(Types::PSensitiveType::Sensitive)
expect(val2.unwrap).to eql(sval)
end
it 'Timespan' do
val = Time::Timespan.from_fields(false, 3, 12, 40, 31, 123)
write(val)
val2 = read
expect(val2).to be_a(Time::Timespan)
expect(val2).to eql(val)
end
it 'Timestamp' do
val = Time::Timestamp.now
write(val)
val2 = read
expect(val2).to be_a(Time::Timestamp)
expect(val2).to eql(val)
end
it 'Version' do
# It does succeed on rare occasions, so we need to repeat
val = SemanticPuppet::Version.parse('1.2.3-alpha2')
write(val)
val2 = read
expect(val2).to be_a(SemanticPuppet::Version)
expect(val2).to eql(val)
end
it 'VersionRange' do
# It does succeed on rare occasions, so we need to repeat
val = SemanticPuppet::VersionRange.parse('>=1.2.3-alpha2 <1.2.4')
write(val)
val2 = read
expect(val2).to be_a(SemanticPuppet::VersionRange)
expect(val2).to eql(val)
end
it 'Binary' do
val = Types::PBinaryType::Binary.from_base64('w5ZzdGVuIG1lZCByw7ZzdGVuCg==')
write(val)
val2 = read
expect(val2).to be_a(Types::PBinaryType::Binary)
expect(val2).to eql(val)
end
it 'ACII_8BIT String as Binary' do
val = Types::PBinaryType::Binary.from_base64('w5ZzdGVuIG1lZCByw7ZzdGVuCg==')
strval = val.binary_buffer
write(strval)
val2 = read
expect(val2).to be_a(Types::PBinaryType::Binary)
expect(val2).to eql(val)
end
it 'URI' do
val = URI('http://bob:ewing@dallas.example.com:8080/oil/baron?crude=cash#leftovers')
write(val)
val2 = read
expect(val2).to be_a(URI)
expect(val2).to eql(val)
end
it 'Sensitive with rich data' do
sval = Time::Timestamp.now
val = Types::PSensitiveType::Sensitive.new(sval)
write(val)
val2 = read
expect(val2).to be_a(Types::PSensitiveType::Sensitive)
expect(val2.unwrap).to be_a(Time::Timestamp)
expect(val2.unwrap).to eql(sval)
end
it 'Hash with Symbol keys' do
val = { :one => 'one', :two => 'two' }
write(val)
val2 = read
expect(val2).to be_a(Hash)
expect(val2).to eql(val)
end
it 'Hash with Integer keys' do
val = { 1 => 'one', 2 => 'two' }
write(val)
val2 = read
expect(val2).to be_a(Hash)
expect(val2).to eql(val)
end
it 'A Hash that references itself' do
val = {}
val['myself'] = val
write(val)
val2 = read
expect(val2).to be_a(Hash)
expect(val2['myself']).to equal(val2)
end
end
context 'can write and read' do
include_context 'types_setup'
all_types.each do |t|
it "the default for type #{t.name}" do
val = t::DEFAULT
write(val)
val2 = read
expect(val2).to be_a(t)
expect(val2).to eql(val)
end
end
context 'a parameterized' do
it 'String' do
val = Types::TypeFactory.string(Types::TypeFactory.range(1, :default))
write(val)
val2 = read
expect(val2).to be_a(Types::PStringType)
expect(val2).to eql(val)
end
it 'Regex' do
val = Types::TypeFactory.regexp(/foo/)
write(val)
val2 = read
expect(val2).to be_a(Types::PRegexpType)
expect(val2).to eql(val)
end
it 'Collection' do
val = Types::TypeFactory.collection(Types::TypeFactory.range(0, 20))
write(val)
val2 = read
expect(val2).to be_a(Types::PCollectionType)
expect(val2).to eql(val)
end
it 'Array' do
val = Types::TypeFactory.array_of(Types::TypeFactory.integer, Types::TypeFactory.range(0, 20))
write(val)
val2 = read
expect(val2).to be_a(Types::PArrayType)
expect(val2).to eql(val)
end
it 'Hash' do
val = Types::TypeFactory.hash_kv(Types::TypeFactory.string, Types::TypeFactory.integer, Types::TypeFactory.range(0, 20))
write(val)
val2 = read
expect(val2).to be_a(Types::PHashType)
expect(val2).to eql(val)
end
it 'Variant' do
val = Types::TypeFactory.variant(Types::TypeFactory.string, Types::TypeFactory.range(1, :default))
write(val)
val2 = read
expect(val2).to be_a(Types::PVariantType)
expect(val2).to eql(val)
end
it 'Object' do
val = Types::TypeParser.singleton.parse('Pcore::StringType', loader)
write(val)
val2 = read
expect(val2).to be_a(Types::PObjectType)
expect(val2).to eql(val)
end
context 'ObjectType' do
let(:type) do
Types::PObjectType.new({
'name' => 'MyType',
'type_parameters' => {
'x' => Types::PIntegerType::DEFAULT
},
'attributes' => {
'x' => Types::PIntegerType::DEFAULT
}
})
end
it 'with preserved parameters' do
val = type.create(34)._pcore_type
write(val)
val2 = read
expect(val2).to be_a(Types::PObjectTypeExtension)
expect(val2).to eql(val)
end
it 'with POjbectTypeExtension type being converted' do
val = { 'ObjectExtension' => type.create(34) }
expect(to_converter.convert(val))
.to eq({"ObjectExtension"=>{"__ptype"=>"MyType", "x"=>34}})
end
end
end
it 'Array of rich data' do
# Sensitive omitted because it doesn't respond to ==
val = [
Time::Timespan.from_fields(false, 3, 12, 40, 31, 123),
Time::Timestamp.now,
SemanticPuppet::Version.parse('1.2.3-alpha2'),
SemanticPuppet::VersionRange.parse('>=1.2.3-alpha2 <1.2.4'),
Types::PBinaryType::Binary.from_base64('w5ZzdGVuIG1lZCByw7ZzdGVuCg==')
]
write(val)
val2 = read
expect(val2).to eql(val)
end
it 'Hash of rich data' do
# Sensitive omitted because it doesn't respond to ==
val = {
'duration' => Time::Timespan.from_fields(false, 3, 12, 40, 31, 123),
'time' => Time::Timestamp.now,
'version' => SemanticPuppet::Version.parse('1.2.3-alpha2'),
'range' => SemanticPuppet::VersionRange.parse('>=1.2.3-alpha2 <1.2.4'),
'binary' => Types::PBinaryType::Binary.from_base64('w5ZzdGVuIG1lZCByw7ZzdGVuCg==')
}
write(val)
val2 = read
expect(val2).to eql(val)
end
context 'an AST model' do
it "Locator" do
val = Parser::Locator::Locator19.new('here is some text', '/tmp/foo', [5])
write(val)
val2 = read
expect(val2).to be_a(Parser::Locator::Locator19)
expect(val2).to eql(val)
end
it 'nested Expression' do
expr = parse(<<-CODE)
$rootgroup = $os['family'] ? {
'Solaris' => 'wheel',
/(Darwin|FreeBSD)/ => 'wheel',
default => 'root',
}
file { '/etc/passwd':
ensure => file,
owner => 'root',
group => $rootgroup,
}
CODE
write(expr)
expr2 = read
expect(dumper.dump(expr)).to eq(dumper.dump(expr2))
end
end
context 'PuppetObject' do
before(:each) do
class DerivedArray < Array
include Types::PuppetObject
def self._pcore_type
@type
end
def self.register_ptype(loader, ir)
@type = Pcore.create_object_type(loader, ir, DerivedArray, 'DerivedArray', nil, 'values' => Types::PArrayType::DEFAULT)
.resolve(loader)
end
def initialize(values)
concat(values)
end
def values
Array.new(self)
end
end
class DerivedHash < Hash
include Types::PuppetObject
def self._pcore_type
@type
end
def self.register_ptype(loader, ir)
@type = Pcore.create_object_type(loader, ir, DerivedHash, 'DerivedHash', nil, '_pcore_init_hash' => Types::PHashType::DEFAULT)
.resolve(loader)
end
def initialize(_pcore_init_hash)
merge!(_pcore_init_hash)
end
def _pcore_init_hash
result = {}
result.merge!(self)
result
end
end
end
after(:each) do
x = Puppet::Pops::Serialization
x.send(:remove_const, :DerivedArray) if x.const_defined?(:DerivedArray)
x.send(:remove_const, :DerivedHash) if x.const_defined?(:DerivedHash)
end
it 'derived from Array' do
DerivedArray.register_ptype(loader, loaders.implementation_registry)
# Sensitive omitted because it doesn't respond to ==
val = DerivedArray.new([
Time::Timespan.from_fields(false, 3, 12, 40, 31, 123),
Time::Timestamp.now,
SemanticPuppet::Version.parse('1.2.3-alpha2'),
SemanticPuppet::VersionRange.parse('>=1.2.3-alpha2 <1.2.4'),
Types::PBinaryType::Binary.from_base64('w5ZzdGVuIG1lZCByw7ZzdGVuCg==')
])
write(val)
val2 = read
expect(val2).to eql(val)
end
it 'derived from Hash' do
DerivedHash.register_ptype(loader, loaders.implementation_registry)
# Sensitive omitted because it doesn't respond to ==
val = DerivedHash.new({
'duration' => Time::Timespan.from_fields(false, 3, 12, 40, 31, 123),
'time' => Time::Timestamp.now,
'version' => SemanticPuppet::Version.parse('1.2.3-alpha2'),
'range' => SemanticPuppet::VersionRange.parse('>=1.2.3-alpha2 <1.2.4'),
'binary' => Types::PBinaryType::Binary.from_base64('w5ZzdGVuIG1lZCByw7ZzdGVuCg==')
})
write(val)
val2 = read
expect(val2).to eql(val)
end
end
end
context 'deserializing an instance whose Object type was serialized by reference' do
let(:to_converter) { ToDataConverter.new(:type_by_reference => true, :rich_data => true) }
let(:type) do
Types::PObjectType.new({
'name' => 'MyType',
'attributes' => {
'x' => Types::PIntegerType::DEFAULT
}
})
end
context 'fails when deserializer is unaware of the referenced type' do
it 'fails by default' do
write(type.create(32))
# Should fail since no loader knows about 'MyType'
expect{ read }.to raise_error(Puppet::Error, 'No implementation mapping found for Puppet Type MyType')
end
it 'succeeds and produces a hash when a read __ptype key is something other than a string or a hash' do
# i.e. this is for content that is not produced by ToDataHash - writing on-the-wire-format directly
# to test that it does not crash.
write_raw({'__ptype' => 10, 'x'=> 32})
expect(read).to eql({'__ptype'=>10, 'x'=>32})
end
context "succeeds but produces an rich_type hash when deserializer has 'allow_unresolved' set to true" do
let(:from_converter) { FromDataConverter.new(:allow_unresolved => true) }
it do
write(type.create(32))
expect(read).to eql({'__ptype'=>'MyType', 'x'=>32})
end
end
end
it 'succeeds when deserializer is aware of the referenced type' do
obj = type.create(32)
write(obj)
expect(loaders.find_loader(nil)).to receive(:load).with(:type, 'mytype').and_return(type)
expect(read).to eql(obj)
end
end
context 'with rich_data set to false' do
before :each do
# strict mode off so behavior is not stubbed
Puppet[:strict] = :warning
end
let(:to_converter) { ToDataConverter.new(:message_prefix => 'Test Hash', :rich_data => false) }
let(:logs) { [] }
let(:warnings) { logs.select { |log| log.level == :warning }.map { |log| log.message } }
it 'A Hash with Symbol keys is converted to hash with String keys with warning' do
val = { :one => 'one', :two => 'two' }
Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do
write(val)
val2 = read
expect(val2).to be_a(Hash)
expect(val2).to eql({ 'one' => 'one', 'two' => 'two' })
end
expect(warnings).to eql([
"Test Hash contains a hash with a Symbol key. It will be converted to the String 'one'",
"Test Hash contains a hash with a Symbol key. It will be converted to the String 'two'"])
end
it 'A Hash with Version keys is converted to hash with String keys with warning' do
val = { SemanticPuppet::Version.parse('1.0.0') => 'one', SemanticPuppet::Version.parse('2.0.0') => 'two' }
Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do
write(val)
val2 = read
expect(val2).to be_a(Hash)
expect(val2).to eql({ '1.0.0' => 'one', '2.0.0' => 'two' })
end
expect(warnings).to eql([
"Test Hash contains a hash with a SemanticPuppet::Version key. It will be converted to the String '1.0.0'",
"Test Hash contains a hash with a SemanticPuppet::Version key. It will be converted to the String '2.0.0'"])
end
it 'A Hash with rich data is not converted and raises error by default' do
Puppet[:strict] = :error
expect do
val = { SemanticPuppet::Version.parse('1.0.0') => 'one', SemanticPuppet::Version.parse('2.0.0') => 'two' }
write(val)
end.to raise_error(/Evaluation Error: Test Hash contains a hash with a SemanticPuppet::Version key. It will be converted to the String '1.0.0'/)
end
context 'and symbol_as_string is set to true' do
let(:to_converter) { ToDataConverter.new(:rich_data => false, :symbol_as_string => true) }
it 'A Hash with Symbol keys is silently converted to hash with String keys' do
val = { :one => 'one', :two => 'two' }
Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do
write(val)
val2 = read
expect(val2).to be_a(Hash)
expect(val2).to eql({ 'one' => 'one', 'two' => 'two' })
end
expect(warnings).to be_empty
end
it 'A Hash with Symbol values is silently converted to hash with String values' do
val = { 'one' => :one, 'two' => :two }
Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do
write(val)
val2 = read
expect(val2).to be_a(Hash)
expect(val2).to eql({ 'one' => 'one', 'two' => 'two' })
end
expect(warnings).to be_empty
end
it 'A Hash with default values will have the values converted to string with a warning' do
val = { 'key' => :default }
Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do
write(val)
val2 = read
expect(val2).to be_a(Hash)
expect(val2).to eql({ 'key' => 'default' })
end
expect(warnings).to eql(["['key'] contains the special value default. It will be converted to the String 'default'"])
end
end
end
context 'with rich_data is set to true' do
let(:to_converter) { ToDataConverter.new(:message_prefix => 'Test Hash', :rich_data => true) }
let(:logs) { [] }
let(:warnings) { logs.select { |log| log.level == :warning }.map { |log| log.message } }
context 'and symbol_as_string is set to true' do
let(:to_converter) { ToDataConverter.new(:rich_data => true, :symbol_as_string => true) }
it 'A Hash with Symbol keys is silently converted to hash with String keys' do
val = { :one => 'one', :two => 'two' }
Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do
write(val)
val2 = read
expect(val2).to be_a(Hash)
expect(val2).to eql({ 'one' => 'one', 'two' => 'two' })
end
expect(warnings).to be_empty
end
it 'A Hash with Symbol values is silently converted to hash with String values' do
val = { 'one' => :one, 'two' => :two }
Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do
write(val)
val2 = read
expect(val2).to be_a(Hash)
expect(val2).to eql({ 'one' => 'one', 'two' => 'two' })
end
expect(warnings).to be_empty
end
it 'A Hash with __ptype, __pvalue keys will not be taken as a pcore meta tag' do
val = { '__ptype' => 42, '__pvalue' => 43 }
Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do
write(val)
val2 = read
expect(val2).to be_a(Hash)
expect(val2).to eql({ '__ptype' => 42, '__pvalue' => 43 })
end
expect(warnings).to be_empty
end
it 'A Hash with default values will not loose type information' do
val = { 'key' => :default }
Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do
write(val)
val2 = read
expect(val2).to be_a(Hash)
expect(val2).to eql({ 'key' => :default })
end
expect(warnings).to be_empty
end
end
end
context 'with local_reference set to false' do
let(:to_converter) { ToDataConverter.new(:local_reference => false) }
it 'A self referencing value will trigger an endless recursion error' do
val = {}
val['myself'] = val
expect { write(val) }.to raise_error(/Endless recursion detected when attempting to serialize value of class Hash/)
end
end
context 'will fail when' do
it 'the value of a type description is something other than a String or a Hash' do
expect do
from_converter.convert({ '__ptype' => { '__ptype' => 'Pcore::TimestampType', '__pvalue' => 12345 }})
end.to raise_error(/Cannot create a Pcore::TimestampType from a Integer/)
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/pops/serialization/packer_spec.rb | spec/unit/pops/serialization/packer_spec.rb | require 'spec_helper'
require 'puppet/pops/serialization'
module Puppet::Pops
module Serialization
[JSON].each do |packer_module|
describe "the Puppet::Pops::Serialization when using #{packer_module.name}" do
let(:io) { StringIO.new }
let(:reader_class) { packer_module::Reader }
let(:writer_class) { packer_module::Writer }
def write(*values)
io.reopen
serializer = writer_class.new(io)
values.each { |val| serializer.write(val) }
serializer.finish
io.rewind
end
def read(count = nil)
@deserializer = reader_class.new(io)
count.nil? ? @deserializer.read : Array.new(count) { @deserializer.read }
end
context 'can write and read a' do
it 'String' do
val = 'the value'
write(val)
val2 = read
expect(val2).to be_a(String)
expect(val2).to eql(val)
end
it 'positive Integer' do
val = 2**63-1
write(val)
val2 = read
expect(val2).to be_a(Integer)
expect(val2).to eql(val)
end
it 'negative Integer' do
val = -2**63
write(val)
val2 = read
expect(val2).to be_a(Integer)
expect(val2).to eql(val)
end
it 'Float' do
val = 32.45
write(val)
val2 = read
expect(val2).to be_a(Float)
expect(val2).to eql(val)
end
it 'true' do
val = true
write(val)
val2 = read
expect(val2).to be_a(TrueClass)
expect(val2).to eql(val)
end
it 'false' do
val = false
write(val)
val2 = read
expect(val2).to be_a(FalseClass)
expect(val2).to eql(val)
end
it 'nil' do
val = nil
write(val)
val2 = read
expect(val2).to be_a(NilClass)
expect(val2).to eql(val)
end
it 'Regexp' do
val = /match me/
write(val)
val2 = read
expect(val2).to be_a(Regexp)
expect(val2).to eql(val)
end
it 'Timespan' do
val = Time::Timespan.from_fields(false, 3, 12, 40, 31, 123)
write(val)
val2 = read
expect(val2).to be_a(Time::Timespan)
expect(val2).to eql(val)
end
it 'Timestamp' do
val = Time::Timestamp.now
write(val)
val2 = read
expect(val2).to be_a(Time::Timestamp)
expect(val2).to eql(val)
end
it 'Version' do
val = SemanticPuppet::Version.parse('1.2.3-alpha2')
write(val)
val2 = read
expect(val2).to be_a(SemanticPuppet::Version)
expect(val2).to eql(val)
end
it 'VersionRange' do
val = SemanticPuppet::VersionRange.parse('>=1.2.3-alpha2 <1.2.4')
write(val)
val2 = read
expect(val2).to be_a(SemanticPuppet::VersionRange)
expect(val2).to eql(val)
end
it 'Binary' do
val = Types::PBinaryType::Binary.from_base64('w5ZzdGVuIG1lZCByw7ZzdGVuCg==')
write(val)
val2 = read
expect(val2).to be_a(Types::PBinaryType::Binary)
expect(val2).to eql(val)
end
it 'URI' do
val = URI('http://bob:ewing@dallas.example.com:8080/oil/baron?crude=cash#leftovers')
write(val)
val2 = read
expect(val2).to be_a(URI)
expect(val2).to eql(val)
end
end
context 'will fail on attempts to write' do
it 'Integer larger than 2**63-1' do
expect { write(2**63) }.to raise_error(SerializationError, 'Integer out of bounds')
end
it 'Integer smaller than -2**63' do
expect { write(-2**63-1) }.to raise_error(SerializationError, 'Integer out of bounds')
end
it 'objects unknown to Puppet serialization' do
expect { write("".class) }.to raise_error(SerializationError, 'Unable to serialize a Class')
end
end
it 'should be able to write and read primitives using tabulation' do
val = 'the value'
write(val, val)
expect(read(2)).to eql([val, val])
expect(@deserializer.primitive_count).to eql(1)
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/pops/serialization/serialization_spec.rb | spec/unit/pops/serialization/serialization_spec.rb | require 'spec_helper'
require 'puppet/pops'
module Puppet::Pops
module Serialization
[JSON].each do |packer_module|
describe "the Puppet::Pops::Serialization over #{packer_module.name}" do
let!(:dumper) { Model::ModelTreeDumper.new }
let(:io) { StringIO.new }
let(:parser) { Parser::EvaluatingParser.new }
let(:env) { Puppet::Node::Environment.create(:testing, []) }
let(:loaders) { Puppet::Pops::Loaders.new(env) }
let(:loader) { loaders.find_loader(nil) }
let(:reader_class) { packer_module::Reader }
let(:writer_class) { packer_module::Writer }
let(:serializer) { Serializer.new(writer_class.new(io)) }
let(:deserializer) { Deserializer.new(reader_class.new(io), loaders.find_loader(nil)) }
before(:each) do
Puppet.push_context(:loaders => loaders, :current_environment => env)
end
after(:each) do
Puppet.pop_context()
end
def write(*values)
io.reopen
values.each { |val| serializer.write(val) }
serializer.finish
io.rewind
end
def read
deserializer.read
end
def parse(string)
parser.parse_string(string, '/home/tester/experiments/manifests/init.pp')
end
context 'can write and read a' do
it 'String' do
val = 'the value'
write(val)
val2 = read
expect(val2).to be_a(String)
expect(val2).to eql(val)
end
it 'Integer' do
val = 32
write(val)
val2 = read
expect(val2).to be_a(Integer)
expect(val2).to eql(val)
end
it 'Float' do
val = 32.45
write(val)
val2 = read
expect(val2).to be_a(Float)
expect(val2).to eql(val)
end
it 'true' do
val = true
write(val)
val2 = read
expect(val2).to be_a(TrueClass)
expect(val2).to eql(val)
end
it 'false' do
val = false
write(val)
val2 = read
expect(val2).to be_a(FalseClass)
expect(val2).to eql(val)
end
it 'nil' do
val = nil
write(val)
val2 = read
expect(val2).to be_a(NilClass)
expect(val2).to eql(val)
end
it 'Regexp' do
val = /match me/
write(val)
val2 = read
expect(val2).to be_a(Regexp)
expect(val2).to eql(val)
end
it 'Sensitive' do
sval = 'the sensitive value'
val = Types::PSensitiveType::Sensitive.new(sval)
write(val)
val2 = read
expect(val2).to be_a(Types::PSensitiveType::Sensitive)
expect(val2.unwrap).to eql(sval)
end
it 'Timespan' do
val = Time::Timespan.from_fields(false, 3, 12, 40, 31, 123)
write(val)
val2 = read
expect(val2).to be_a(Time::Timespan)
expect(val2).to eql(val)
end
it 'Timestamp' do
val = Time::Timestamp.now
write(val)
val2 = read
expect(val2).to be_a(Time::Timestamp)
expect(val2).to eql(val)
end
it 'Version' do
# It does succeed on rare occasions, so we need to repeat
val = SemanticPuppet::Version.parse('1.2.3-alpha2')
write(val)
val2 = read
expect(val2).to be_a(SemanticPuppet::Version)
expect(val2).to eql(val)
end
it 'VersionRange' do
# It does succeed on rare occasions, so we need to repeat
val = SemanticPuppet::VersionRange.parse('>=1.2.3-alpha2 <1.2.4')
write(val)
val2 = read
expect(val2).to be_a(SemanticPuppet::VersionRange)
expect(val2).to eql(val)
end
it 'Binary' do
val = Types::PBinaryType::Binary.from_base64('w5ZzdGVuIG1lZCByw7ZzdGVuCg==')
write(val)
val2 = read
expect(val2).to be_a(Types::PBinaryType::Binary)
expect(val2).to eql(val)
end
it 'URI' do
val = URI('http://bob:ewing@dallas.example.com:8080/oil/baron?crude=cash#leftovers')
write(val)
val2 = read
expect(val2).to be_a(URI)
expect(val2).to eql(val)
end
it 'Sensitive with rich data' do
sval = Time::Timestamp.now
val = Types::PSensitiveType::Sensitive.new(sval)
write(val)
val2 = read
expect(val2).to be_a(Types::PSensitiveType::Sensitive)
expect(val2.unwrap).to be_a(Time::Timestamp)
expect(val2.unwrap).to eql(sval)
end
end
context 'can write and read' do
include_context 'types_setup'
all_types.each do |t|
it "the default for type #{t.name}" do
val = t::DEFAULT
write(val)
val2 = read
expect(val2).to be_a(t)
expect(val2).to eql(val)
end
end
context 'a parameterized' do
it 'String' do
val = Types::TypeFactory.string(Types::TypeFactory.range(1, :default))
write(val)
val2 = read
expect(val2).to be_a(Types::PStringType)
expect(val2).to eql(val)
end
it 'Regex' do
val = Types::TypeFactory.regexp(/foo/)
write(val)
val2 = read
expect(val2).to be_a(Types::PRegexpType)
expect(val2).to eql(val)
end
it 'Collection' do
val = Types::TypeFactory.collection(Types::TypeFactory.range(0, 20))
write(val)
val2 = read
expect(val2).to be_a(Types::PCollectionType)
expect(val2).to eql(val)
end
it 'Array' do
val = Types::TypeFactory.array_of(Types::TypeFactory.integer, Types::TypeFactory.range(0, 20))
write(val)
val2 = read
expect(val2).to be_a(Types::PArrayType)
expect(val2).to eql(val)
end
it 'Hash' do
val = Types::TypeFactory.hash_kv(Types::TypeFactory.string, Types::TypeFactory.integer, Types::TypeFactory.range(0, 20))
write(val)
val2 = read
expect(val2).to be_a(Types::PHashType)
expect(val2).to eql(val)
end
it 'Variant' do
val = Types::TypeFactory.variant(Types::TypeFactory.string, Types::TypeFactory.range(1, :default))
write(val)
val2 = read
expect(val2).to be_a(Types::PVariantType)
expect(val2).to eql(val)
end
it 'Object' do
val = Types::TypeParser.singleton.parse('Pcore::StringType', loader)
write(val)
val2 = read
expect(val2).to be_a(Types::PObjectType)
expect(val2).to eql(val)
end
context 'ObjectType' do
let(:type) do
Types::PObjectType.new({
'name' => 'MyType',
'type_parameters' => {
'x' => Types::PIntegerType::DEFAULT
},
'attributes' => {
'x' => Types::PIntegerType::DEFAULT
}
})
end
it 'with preserved parameters' do
val = type.create(34)._pcore_type
write(val)
val2 = read
expect(val2).to be_a(Types::PObjectTypeExtension)
expect(val2).to eql(val)
end
end
end
it 'Array of rich data' do
# Sensitive omitted because it doesn't respond to ==
val = [
Time::Timespan.from_fields(false, 3, 12, 40, 31, 123),
Time::Timestamp.now,
SemanticPuppet::Version.parse('1.2.3-alpha2'),
SemanticPuppet::VersionRange.parse('>=1.2.3-alpha2 <1.2.4'),
Types::PBinaryType::Binary.from_base64('w5ZzdGVuIG1lZCByw7ZzdGVuCg==')
]
write(val)
val2 = read
expect(val2).to eql(val)
end
it 'Hash of rich data' do
# Sensitive omitted because it doesn't respond to ==
val = {
'duration' => Time::Timespan.from_fields(false, 3, 12, 40, 31, 123),
'time' => Time::Timestamp.now,
'version' => SemanticPuppet::Version.parse('1.2.3-alpha2'),
'range' => SemanticPuppet::VersionRange.parse('>=1.2.3-alpha2 <1.2.4'),
'binary' => Types::PBinaryType::Binary.from_base64('w5ZzdGVuIG1lZCByw7ZzdGVuCg==')
}
write(val)
val2 = read
expect(val2).to eql(val)
end
context 'an AST model' do
it "Locator" do
val = Parser::Locator::Locator19.new('here is some text', '/tmp/foo', [5])
write(val)
val2 = read
expect(val2).to be_a(Parser::Locator::Locator19)
expect(val2).to eql(val)
end
it 'nested Expression' do
expr = parse(<<-CODE)
$rootgroup = $os['family'] ? {
'Solaris' => 'wheel',
/(Darwin|FreeBSD)/ => 'wheel',
default => 'root',
}
file { '/etc/passwd':
ensure => file,
owner => 'root',
group => $rootgroup,
}
CODE
write(expr)
expr2 = read
expect(dumper.dump(expr)).to eq(dumper.dump(expr2))
end
end
context 'PuppetObject' do
before(:each) do
class DerivedArray < Array
include Types::PuppetObject
def self._pcore_type
@type
end
def self.register_ptype(loader, ir)
@type = Pcore.create_object_type(loader, ir, DerivedArray, 'DerivedArray', nil, 'values' => Types::PArrayType::DEFAULT)
.resolve(loader)
end
def initialize(values)
concat(values)
end
def values
Array.new(self)
end
end
class DerivedHash < Hash
include Types::PuppetObject
def self._pcore_type
@type
end
def self.register_ptype(loader, ir)
@type = Pcore.create_object_type(loader, ir, DerivedHash, 'DerivedHash', nil, '_pcore_init_hash' => Types::PHashType::DEFAULT)
.resolve(loader)
end
def initialize(_pcore_init_hash)
merge!(_pcore_init_hash)
end
def _pcore_init_hash
result = {}
result.merge!(self)
result
end
end
end
after(:each) do
x = Puppet::Pops::Serialization
x.send(:remove_const, :DerivedArray) if x.const_defined?(:DerivedArray)
x.send(:remove_const, :DerivedHash) if x.const_defined?(:DerivedHash)
end
it 'derived from Array' do
DerivedArray.register_ptype(loader, loaders.implementation_registry)
# Sensitive omitted because it doesn't respond to ==
val = DerivedArray.new([
Time::Timespan.from_fields(false, 3, 12, 40, 31, 123),
Time::Timestamp.now,
SemanticPuppet::Version.parse('1.2.3-alpha2'),
SemanticPuppet::VersionRange.parse('>=1.2.3-alpha2 <1.2.4'),
Types::PBinaryType::Binary.from_base64('w5ZzdGVuIG1lZCByw7ZzdGVuCg==')
])
write(val)
val2 = read
expect(val2).to eql(val)
end
it 'derived from Hash' do
DerivedHash.register_ptype(loader, loaders.implementation_registry)
# Sensitive omitted because it doesn't respond to ==
val = DerivedHash.new({
'duration' => Time::Timespan.from_fields(false, 3, 12, 40, 31, 123),
'time' => Time::Timestamp.now,
'version' => SemanticPuppet::Version.parse('1.2.3-alpha2'),
'range' => SemanticPuppet::VersionRange.parse('>=1.2.3-alpha2 <1.2.4'),
'binary' => Types::PBinaryType::Binary.from_base64('w5ZzdGVuIG1lZCByw7ZzdGVuCg==')
})
write(val)
val2 = read
expect(val2).to eql(val)
end
end
end
context 'deserializing an instance whose Object type was serialized by reference' do
let(:serializer) { Serializer.new(writer_class.new(io), :type_by_reference => true) }
let(:type) do
Types::PObjectType.new({
'name' => 'MyType',
'attributes' => {
'x' => Types::PIntegerType::DEFAULT
}
})
end
it 'fails when deserializer is unaware of the referenced type' do
write(type.create(32))
# Should fail since no loader knows about 'MyType'
expect{ read }.to raise_error(Puppet::Error, 'No implementation mapping found for Puppet Type MyType')
end
it 'succeeds when deserializer is aware of the referenced type' do
obj = type.create(32)
write(obj)
expect(loaders.find_loader(nil)).to receive(:load).with(:type, 'mytype').and_return(type)
expect(read).to eql(obj)
end
end
context 'When debugging' do
let(:debug_io) { StringIO.new }
let(:writer) { reader_class.new(io, { :debug_io => debug_io, :tabulate => false, :verbose => true }) }
it 'can write and read an AST expression' do
expr = parse(<<-CODE)
$rootgroup = $os['family'] ? {
'Solaris' => 'wheel',
/(Darwin|FreeBSD)/ => 'wheel',
default => 'root',
}
file { '/etc/passwd':
ensure => file,
owner => 'root',
group => $rootgroup,
}
CODE
write(expr)
expr2 = read
expect(dumper.dump(expr)).to eq(dumper.dump(expr2))
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/external/pson_spec.rb | spec/unit/external/pson_spec.rb | # Encoding: UTF-8
require 'spec_helper'
describe 'PSON', if: Puppet.features.pson? do
{
'foo' => '"foo"',
1 => '1',
"\x80" => "\"\x80\"",
[] => '[]'
}.each do |str, expect|
it "should be able to encode #{str.inspect}" do
got = str.to_pson
if got.respond_to? :force_encoding
expect(got.force_encoding('binary')).to eq(expect.force_encoding('binary'))
else
expect(got).to eq(expect)
end
end
end
it "should be able to handle arbitrary binary data" do
bin_string = (1..20000).collect { |i| ((17*i+13*i*i) % 255).chr }.join
parsed = PSON.parse(%Q{{ "type": "foo", "data": #{bin_string.to_pson} }})["data"]
if parsed.respond_to? :force_encoding
parsed.force_encoding('binary')
bin_string.force_encoding('binary')
end
expect(parsed).to eq(bin_string)
end
it "should be able to handle UTF8 that isn't a real unicode character" do
s = ["\355\274\267"]
expect(PSON.parse( [s].to_pson )).to eq([s])
end
it "should be able to handle UTF8 for \\xFF" do
s = ["\xc3\xbf"]
expect(PSON.parse( [s].to_pson )).to eq([s])
end
it "should be able to handle invalid UTF8 bytes" do
s = ["\xc3\xc3"]
expect(PSON.parse( [s].to_pson )).to eq([s])
end
it "should be able to parse JSON containing UTF-8 characters in strings" do
s = '{ "foö": "bár" }'
expect { PSON.parse s }.not_to raise_error
end
it 'ignores "document_type" during parsing' do
text = '{"data":{},"document_type":"Node"}'
expect(PSON.parse(text)).to eq({"data" => {}, "document_type" => "Node"})
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/application/face_base_spec.rb | spec/unit/application/face_base_spec.rb | require 'spec_helper'
require 'puppet/application/face_base'
require 'tmpdir'
class Puppet::Application::FaceBase::Basetest < Puppet::Application::FaceBase
end
describe Puppet::Application::FaceBase do
let :app do
app = Puppet::Application::FaceBase::Basetest.new
allow(app.command_line).to receive(:subcommand_name).and_return('subcommand')
allow(Puppet::Util::Log).to receive(:newdestination)
app
end
after :each do
app.class.clear_everything_for_tests
end
describe "#find_global_settings_argument" do
it "should not match --ca to --ca-location" do
option = double('ca option', :optparse_args => ["--ca"])
expect(Puppet.settings).to receive(:each).and_yield(:ca, option)
expect(app.find_global_settings_argument("--ca-location")).to be_nil
end
end
describe "#parse_options" do
before :each do
allow(app.command_line).to receive(:args).and_return(%w{})
end
describe "with just an action" do
before(:each) do
# We have to stub Signal.trap to avoid a crazy mess where we take
# over signal handling and make it impossible to cancel the test
# suite run.
#
# It would be nice to fix this elsewhere, but it is actually hard to
# capture this in rspec 2.5 and all. :( --daniel 2011-04-08
allow(Signal).to receive(:trap)
allow(app.command_line).to receive(:args).and_return(%w{foo})
app.preinit
app.parse_options
end
it "should set the face based on the type" do
expect(app.face.name).to eq(:basetest)
end
it "should find the action" do
expect(app.action).to be
expect(app.action.name).to eq(:foo)
end
end
it "should stop if the first thing found is not an action" do
allow(app.command_line).to receive(:args).and_return(%w{banana count_args})
expect { app.run }.to exit_with(1)
expect(@logs.map(&:message)).to eq(["'basetest' has no 'banana' action. See `puppet help basetest`."])
end
it "should use the default action if not given any arguments" do
allow(app.command_line).to receive(:args).and_return([])
action = double(:options => [], :render_as => nil)
expect(Puppet::Face[:basetest, '0.0.1']).to receive(:get_default_action).and_return(action)
allow(app).to receive(:main)
app.run
expect(app.action).to eq(action)
expect(app.arguments).to eq([ { } ])
end
it "should use the default action if not given a valid one" do
allow(app.command_line).to receive(:args).and_return(%w{bar})
action = double(:options => [], :render_as => nil)
expect(Puppet::Face[:basetest, '0.0.1']).to receive(:get_default_action).and_return(action)
allow(app).to receive(:main)
app.run
expect(app.action).to eq(action)
expect(app.arguments).to eq([ 'bar', { } ])
end
it "should have no action if not given a valid one and there is no default action" do
allow(app.command_line).to receive(:args).and_return(%w{bar})
expect(Puppet::Face[:basetest, '0.0.1']).to receive(:get_default_action).and_return(nil)
allow(app).to receive(:main)
expect { app.run }.to exit_with(1)
expect(@logs.first.message).to match(/has no 'bar' action./)
end
[%w{something_I_cannot_do},
%w{something_I_cannot_do argument}].each do |input|
it "should report unknown actions nicely" do
allow(app.command_line).to receive(:args).and_return(input)
expect(Puppet::Face[:basetest, '0.0.1']).to receive(:get_default_action).and_return(nil)
allow(app).to receive(:main)
expect { app.run }.to exit_with(1)
expect(@logs.first.message).to match(/has no 'something_I_cannot_do' action/)
end
end
[%w{something_I_cannot_do --unknown-option},
%w{something_I_cannot_do argument --unknown-option}].each do |input|
it "should report unknown actions even if there are unknown options" do
allow(app.command_line).to receive(:args).and_return(input)
expect(Puppet::Face[:basetest, '0.0.1']).to receive(:get_default_action).and_return(nil)
allow(app).to receive(:main)
expect { app.run }.to exit_with(1)
expect(@logs.first.message).to match(/has no 'something_I_cannot_do' action/)
end
end
it "should report a sensible error when options with = fail" do
allow(app.command_line).to receive(:args).and_return(%w{--action=bar foo})
expect { app.preinit; app.parse_options }.
to raise_error(OptionParser::InvalidOption, /invalid option: --action/)
end
it "should fail if an action option is before the action" do
allow(app.command_line).to receive(:args).and_return(%w{--action foo})
expect { app.preinit; app.parse_options }.
to raise_error(OptionParser::InvalidOption, /invalid option: --action/)
end
it "should fail if an unknown option is before the action" do
allow(app.command_line).to receive(:args).and_return(%w{--bar foo})
expect { app.preinit; app.parse_options }.
to raise_error(OptionParser::InvalidOption, /invalid option: --bar/)
end
it "should fail if an unknown option is after the action" do
allow(app.command_line).to receive(:args).and_return(%w{foo --bar})
expect { app.preinit; app.parse_options }.
to raise_error(OptionParser::InvalidOption, /invalid option: --bar/)
end
it "should accept --bar as an argument to a mandatory option after action" do
allow(app.command_line).to receive(:args).and_return(%w{foo --mandatory --bar})
app.preinit
app.parse_options
expect(app.action.name).to eq(:foo)
expect(app.options).to eq({ :mandatory => "--bar" })
end
it "should accept --bar as an argument to a mandatory option before action" do
allow(app.command_line).to receive(:args).and_return(%w{--mandatory --bar foo})
app.preinit
app.parse_options
expect(app.action.name).to eq(:foo)
expect(app.options).to eq({ :mandatory => "--bar" })
end
it "should not skip when --foo=bar is given" do
allow(app.command_line).to receive(:args).and_return(%w{--mandatory=bar --bar foo})
expect { app.preinit; app.parse_options }.
to raise_error(OptionParser::InvalidOption, /invalid option: --bar/)
end
it "does not skip when a puppet global setting is given as one item" do
allow(app.command_line).to receive(:args).and_return(%w{--confdir=/tmp/puppet foo})
app.preinit
app.parse_options
expect(app.action.name).to eq(:foo)
expect(app.options).to eq({})
end
it "does not skip when a puppet global setting is given as two items" do
allow(app.command_line).to receive(:args).and_return(%w{--confdir /tmp/puppet foo})
app.preinit
app.parse_options
expect(app.action.name).to eq(:foo)
expect(app.options).to eq({})
end
it "should not add :debug to the application-level options" do
allow(app.command_line).to receive(:args).and_return(%w{--confdir /tmp/puppet foo --debug})
app.preinit
app.parse_options
expect(app.action.name).to eq(:foo)
expect(app.options).to eq({})
end
it "should not add :verbose to the application-level options" do
allow(app.command_line).to receive(:args).and_return(%w{--confdir /tmp/puppet foo --verbose})
app.preinit
app.parse_options
expect(app.action.name).to eq(:foo)
expect(app.options).to eq({})
end
{ "boolean options before" => %w{--trace foo},
"boolean options after" => %w{foo --trace}
}.each do |name, args|
it "should accept global boolean settings #{name} the action" do
allow(app.command_line).to receive(:args).and_return(args)
Puppet.settings.initialize_global_settings(args)
app.preinit
app.parse_options
expect(Puppet[:trace]).to be_truthy
end
end
{ "before" => %w{--syslogfacility user1 foo},
" after" => %w{foo --syslogfacility user1}
}.each do |name, args|
it "should accept global settings with arguments #{name} the action" do
allow(app.command_line).to receive(:args).and_return(args)
Puppet.settings.initialize_global_settings(args)
app.preinit
app.parse_options
expect(Puppet[:syslogfacility]).to eq("user1")
end
end
it "should handle application-level options" do
allow(app.command_line).to receive(:args).and_return(%w{--verbose return_true})
app.preinit
app.parse_options
expect(app.face.name).to eq(:basetest)
end
end
describe "#setup" do
it "should remove the action name from the arguments" do
allow(app.command_line).to receive(:args).and_return(%w{--mandatory --bar foo})
app.preinit
app.parse_options
app.setup
expect(app.arguments).to eq([{ :mandatory => "--bar" }])
end
it "should pass positional arguments" do
myargs = %w{--mandatory --bar foo bar baz quux}
allow(app.command_line).to receive(:args).and_return(myargs)
app.preinit
app.parse_options
app.setup
expect(app.arguments).to eq(['bar', 'baz', 'quux', { :mandatory => "--bar" }])
end
end
describe "#main" do
before :each do
allow(app).to receive(:puts) # don't dump text to screen.
app.face = Puppet::Face[:basetest, '0.0.1']
app.action = app.face.get_action(:foo)
app.arguments = ["myname", "myarg"]
end
it "should send the specified verb and name to the face" do
expect(app.face).to receive(:foo).with(*app.arguments)
expect { app.main }.to exit_with(0)
end
it "should lookup help when it cannot do anything else" do
app.action = nil
expect(Puppet::Face[:help, :current]).to receive(:help).with(:basetest)
expect { app.main }.to exit_with(1)
end
it "should use its render method to render any result" do
expect(app).to receive(:render).with(app.arguments.length + 1, ["myname", "myarg"])
expect { app.main }.to exit_with(0)
end
it "should issue a deprecation warning if the face is deprecated" do
# since app is shared across examples, stub to avoid affecting shared context
allow(app.face).to receive(:deprecated?).and_return(true)
expect(app.face).to receive(:foo).with(*app.arguments)
expect(Puppet).to receive(:deprecation_warning).with(/'puppet basetest' is deprecated/)
expect { app.main }.to exit_with(0)
end
it "should not issue a deprecation warning if the face is not deprecated" do
expect(Puppet).not_to receive(:deprecation_warning)
# since app is shared across examples, stub to avoid affecting shared context
allow(app.face).to receive(:deprecated?).and_return(false)
expect(app.face).to receive(:foo).with(*app.arguments)
expect { app.main }.to exit_with(0)
end
end
describe "error reporting" do
before :each do
allow(app).to receive(:puts) # don't dump text to screen.
app.render_as = :json
app.face = Puppet::Face[:basetest, '0.0.1']
app.arguments = [{}] # we always have options in there...
end
it "should exit 0 when the action returns true" do
app.action = app.face.get_action :return_true
expect { app.main }.to exit_with(0)
end
it "should exit 0 when the action returns false" do
app.action = app.face.get_action :return_false
expect { app.main }.to exit_with(0)
end
it "should exit 0 when the action returns nil" do
app.action = app.face.get_action :return_nil
expect { app.main }.to exit_with(0)
end
it "should exit non-0 when the action raises" do
app.action = app.face.get_action :return_raise
expect { app.main }.not_to exit_with(0)
end
it "should use the exit code set by the action" do
app.action = app.face.get_action :with_specific_exit_code
expect { app.main }.to exit_with(5)
end
end
describe "#render" do
before :each do
app.face = Puppet::Interface.new('basetest', '0.0.1')
app.action = Puppet::Interface::Action.new(app.face, :foo)
end
context "default rendering" do
before :each do app.setup end
["hello", 1, 1.0].each do |input|
it "should just return a #{input.class.name}" do
expect(app.render(input, {})).to eq(input)
end
end
[[1, 2], ["one"], [{ 1 => 1 }]].each do |input|
it "should render Array as one item per line" do
expect(app.render(input, {})).to eq(input.collect { |item| item.to_s + "\n" }.join(''))
end
end
it "should render a non-trivially-keyed Hash with using pretty printed JSON" do
hash = { [1,2] => 3, [2,3] => 5, [3,4] => 7 }
expect(app.render(hash, {})).to eq(Puppet::Util::Json.dump(hash, :pretty => true).chomp)
end
it "should render a {String,Numeric}-keyed Hash into a table" do
object = Object.new
hash = { "one" => 1, "two" => [], "three" => {}, "four" => object,
5 => 5, 6.0 => 6 }
# Gotta love ASCII-betical sort order. Hope your objects are better
# structured for display than my test one is. --daniel 2011-04-18
expect(app.render(hash, {})).to eq <<EOT
5 5
6.0 6
four #{Puppet::Util::Json.dump(object).chomp}
one 1
three {}
two []
EOT
end
it "should render a hash nicely with a multi-line value" do
pending "Moving to PSON rather than PP makes this unsupportable."
hash = {
"number" => { "1" => '1' * 40, "2" => '2' * 40, '3' => '3' * 40 },
"text" => { "a" => 'a' * 40, 'b' => 'b' * 40, 'c' => 'c' * 40 }
}
expect(app.render(hash, {})).to eq <<EOT
number {"1"=>"1111111111111111111111111111111111111111",
"2"=>"2222222222222222222222222222222222222222",
"3"=>"3333333333333333333333333333333333333333"}
text {"a"=>"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"b"=>"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
"c"=>"cccccccccccccccccccccccccccccccccccccccc"}
EOT
end
describe "when setting the rendering method" do
after do
# need to reset the when_rendering block so that other tests can set it later
app.action.instance_variable_set("@when_rendering", {})
end
it "should invoke the action rendering hook while rendering" do
app.action.set_rendering_method_for(:console, proc { |value| "bi-winning!" })
expect(app.render("bi-polar?", {})).to eq("bi-winning!")
end
it "should invoke the action rendering hook with args and options while rendering" do
app.action.instance_variable_set("@when_rendering", {})
app.action.when_invoked = proc { |name, options| 'just need to match arity for rendering' }
app.action.set_rendering_method_for(
:console,
proc { |value, name, options| "I'm #{name}, no wait, I'm #{options[:altername]}" }
)
expect(app.render("bi-polar?", ['bob', {:altername => 'sue'}])).to eq("I'm bob, no wait, I'm sue")
end
end
it "should render JSON when asked for json" do
app.render_as = :json
json = app.render({ :one => 1, :two => 2 }, {})
expect(json).to match(/"one":\s*1\b/)
expect(json).to match(/"two":\s*2\b/)
expect(JSON.parse(json)).to eq({ "one" => 1, "two" => 2 })
end
end
it "should fail early if asked to render an invalid format" do
allow(app.command_line).to receive(:args).and_return(%w{--render-as interpretive-dance return_true})
# We shouldn't get here, thanks to the exception, and our expectation on
# it, but this helps us fail if that slips up and all. --daniel 2011-04-27
expect(Puppet::Face[:help, :current]).not_to receive(:help)
expect(Puppet).to receive(:send_log).with(:err, "Could not parse application options: I don't know how to render 'interpretive-dance'")
expect { app.run }.to exit_with(1)
end
it "should work if asked to render json" do
allow(app.command_line).to receive(:args).and_return(%w{count_args a b c --render-as json})
expect {
app.run
}.to exit_with(0)
.and output(/3/).to_stdout
end
it "should invoke when_rendering hook 's' when asked to render-as 's'" do
allow(app.command_line).to receive(:args).and_return(%w{with_s_rendering_hook --render-as s})
app.action = app.face.get_action(:with_s_rendering_hook)
expect {
app.run
}.to exit_with(0)
.and output(/you invoked the 's' rendering hook/).to_stdout
end
end
describe "#help" do
it "should generate help for --help" do
allow(app.command_line).to receive(:args).and_return(%w{--help})
expect(Puppet::Face[:help, :current]).to receive(:help)
expect { app.run }.to exit_with(0)
end
it "should generate help for -h" do
allow(app.command_line).to receive(:args).and_return(%w{-h})
expect(Puppet::Face[:help, :current]).to receive(:help)
expect { app.run }.to exit_with(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/application/agent_spec.rb | spec/unit/application/agent_spec.rb | require 'spec_helper'
require 'puppet/agent'
require 'puppet/application/agent'
require 'puppet/daemon'
class TestAgentClientClass
def initialize(transaction_uuid = nil, job_id = nil); end
def run(options = {}); end
end
describe Puppet::Application::Agent do
include PuppetSpec::Files
let(:machine) { double(ensure_client_certificate: nil) }
before :each do
@puppetd = Puppet::Application[:agent]
@client = TestAgentClientClass.new
allow(TestAgentClientClass).to receive(:new).and_return(@client)
@agent = Puppet::Agent.new(TestAgentClientClass, false)
allow(Puppet::Agent).to receive(:new).and_return(@agent)
Puppet[:pidfile] = tmpfile('pidfile')
@daemon = Puppet::Daemon.new(@agent, Puppet::Util::Pidlock.new(Puppet[:pidfile]))
allow(@daemon).to receive(:daemonize)
allow(@daemon).to receive(:stop)
# simulate one run so we don't infinite looptwo runs of the agent, then return so we don't infinite loop
allow(@daemon).to receive(:run_event_loop) do
@agent.run(splay: false)
end
allow(Puppet::Daemon).to receive(:new).and_return(@daemon)
Puppet[:daemonize] = false
@puppetd.preinit
allow(Puppet::Util::Log).to receive(:newdestination)
allow(Puppet::Node.indirection).to receive(:terminus_class=)
allow(Puppet::Node.indirection).to receive(:cache_class=)
allow(Puppet::Node::Facts.indirection).to receive(:terminus_class=)
allow(Puppet.settings).to receive(:use)
allow(Puppet::SSL::StateMachine).to receive(:new).and_return(machine)
end
it "should operate in agent run_mode" do
expect(@puppetd.class.run_mode.name).to eq(:agent)
end
it "should declare a main command" do
expect(@puppetd).to respond_to(:main)
end
it "should declare a onetime command" do
expect(@puppetd).to respond_to(:onetime)
end
it "should declare a fingerprint command" do
expect(@puppetd).to respond_to(:fingerprint)
end
it "should declare a preinit block" do
expect(@puppetd).to respond_to(:preinit)
end
describe "in preinit" do
it "should catch INT" do
expect(Signal).to receive(:trap).with(:INT)
@puppetd.preinit
end
it "should init fqdn to nil" do
@puppetd.preinit
expect(@puppetd.options[:fqdn]).to be_nil
end
it "should init serve to []" do
@puppetd.preinit
expect(@puppetd.options[:serve]).to eq([])
end
it "should use SHA256 as default digest algorithm" do
@puppetd.preinit
expect(@puppetd.options[:digest]).to eq('SHA256')
end
it "should not fingerprint by default" do
@puppetd.preinit
expect(@puppetd.options[:fingerprint]).to be_falsey
end
it "should init waitforcert to nil" do
@puppetd.preinit
expect(@puppetd.options[:waitforcert]).to be_nil
end
end
describe "when handling options" do
[:enable, :debug, :fqdn, :test, :verbose, :digest].each do |option|
it "should declare handle_#{option} method" do
expect(@puppetd).to respond_to("handle_#{option}".to_sym)
end
it "should store argument value when calling handle_#{option}" do
@puppetd.send("handle_#{option}".to_sym, 'arg')
expect(@puppetd.options[option]).to eq('arg')
end
end
describe "when handling --disable" do
it "should set disable to true" do
@puppetd.handle_disable('')
expect(@puppetd.options[:disable]).to eq(true)
end
it "should store disable message" do
@puppetd.handle_disable('message')
expect(@puppetd.options[:disable_message]).to eq('message')
end
end
it "should log the agent start time" do
expect(@puppetd.options[:start_time]).to be_a(Time)
end
it "should set waitforcert to 0 with --onetime and if --waitforcert wasn't given" do
allow(@client).to receive(:run).and_return(2)
Puppet[:onetime] = true
expect(Puppet::SSL::StateMachine).to receive(:new).with(hash_including(waitforcert: 0)).and_return(machine)
expect { execute_agent }.to exit_with 0
end
it "should use supplied waitforcert when --onetime is specified" do
allow(@client).to receive(:run).and_return(2)
Puppet[:onetime] = true
@puppetd.handle_waitforcert(60)
expect(Puppet::SSL::StateMachine).to receive(:new).with(hash_including(waitforcert: 60)).and_return(machine)
expect { execute_agent }.to exit_with 0
end
it "should use a default value for waitforcert when --onetime and --waitforcert are not specified" do
allow(@client).to receive(:run).and_return(2)
expect(Puppet::SSL::StateMachine).to receive(:new).with(hash_including(waitforcert: 120)).and_return(machine)
execute_agent
end
it "should register ssl OIDs" do
expect(Puppet::SSL::StateMachine).to receive(:new).with(hash_including(waitforcert: 120)).and_return(machine)
expect(Puppet::SSL::Oids).to receive(:register_puppet_oids)
execute_agent
end
it "should use the waitforcert setting when checking for a signed certificate" do
Puppet[:waitforcert] = 10
expect(Puppet::SSL::StateMachine).to receive(:new).with(hash_including(waitforcert: 10)).and_return(machine)
execute_agent
end
it "should set the log destination with --logdest" do
expect(Puppet::Log).to receive(:newdestination).with("console")
@puppetd.handle_logdest("console")
end
it "should put the setdest options to true" do
@puppetd.handle_logdest("console")
expect(@puppetd.options[:setdest]).to eq(true)
end
it "should parse the log destination from the command line" do
allow(@puppetd.command_line).to receive(:args).and_return(%w{--logdest /my/file})
expect(Puppet::Util::Log).to receive(:newdestination).with("/my/file")
@puppetd.parse_options
end
it "should store the waitforcert options with --waitforcert" do
@puppetd.handle_waitforcert("42")
expect(@puppetd.options[:waitforcert]).to eq(42)
end
end
describe "during setup" do
before :each do
allow(Puppet).to receive(:info)
Puppet[:libdir] = "/dev/null/lib"
allow(Puppet::Transaction::Report.indirection).to receive(:terminus_class=)
allow(Puppet::Transaction::Report.indirection).to receive(:cache_class=)
allow(Puppet::Resource::Catalog.indirection).to receive(:terminus_class=)
allow(Puppet::Resource::Catalog.indirection).to receive(:cache_class=)
allow(Puppet::Node::Facts.indirection).to receive(:terminus_class=)
end
it "should not run with extra arguments" do
allow(@puppetd.command_line).to receive(:args).and_return(%w{disable})
expect{@puppetd.setup}.to raise_error ArgumentError, /does not take parameters/
end
describe "with --test" do
it "should call setup_test" do
@puppetd.options[:test] = true
expect(@puppetd).to receive(:setup_test)
@puppetd.setup
end
it "should set options[:verbose] to true" do
@puppetd.setup_test
expect(@puppetd.options[:verbose]).to eq(true)
end
it "should set options[:onetime] to true" do
Puppet[:onetime] = false
@puppetd.setup_test
expect(Puppet[:onetime]).to eq(true)
end
it "should set options[:detailed_exitcodes] to true" do
@puppetd.setup_test
expect(@puppetd.options[:detailed_exitcodes]).to eq(true)
end
end
it "should call setup_logs" do
expect(@puppetd).to receive(:setup_logs)
@puppetd.setup
end
describe "when setting up logs" do
before :each do
allow(Puppet::Util::Log).to receive(:newdestination)
end
it "should set log level to debug if --debug was passed" do
@puppetd.options[:debug] = true
@puppetd.setup_logs
expect(Puppet::Util::Log.level).to eq(:debug)
end
it "should set log level to info if --verbose was passed" do
@puppetd.options[:verbose] = true
@puppetd.setup_logs
expect(Puppet::Util::Log.level).to eq(:info)
end
[:verbose, :debug].each do |level|
it "should set console as the log destination with level #{level}" do
@puppetd.options[level] = true
allow(Puppet::Util::Log).to receive(:newdestination)
expect(Puppet::Util::Log).to receive(:newdestination).with(:console).exactly(:once)
@puppetd.setup_logs
end
end
it "should set a default log destination if no --logdest" do
@puppetd.options[:setdest] = false
expect(Puppet::Util::Log).to receive(:setup_default)
@puppetd.setup_logs
end
end
it "should print puppet config if asked to in Puppet config" do
Puppet[:configprint] = "plugindest"
expect(Puppet.settings).to receive(:print_configs).and_return(true)
expect { execute_agent }.to exit_with 0
end
it "should exit after printing puppet config if asked to in Puppet config" do
path = make_absolute('/my/path')
Puppet[:modulepath] = path
Puppet[:configprint] = "modulepath"
expect_any_instance_of(Puppet::Settings).to receive(:puts).with(path)
expect { execute_agent }.to exit_with 0
end
it "should use :main, :puppetd, and :ssl" do
expect(Puppet.settings).to receive(:use).with(:main, :agent, :ssl)
@puppetd.setup
end
it "should setup an agent in fingerprint mode" do
@puppetd.options[:fingerprint] = true
expect(@puppetd).not_to receive(:setup_agent)
@puppetd.setup
end
it "should tell the report handler to use REST" do
expect(Puppet::Transaction::Report.indirection).to receive(:terminus_class=).with(:rest)
@puppetd.setup
end
it "should tell the report handler to cache locally as yaml" do
expect(Puppet::Transaction::Report.indirection).to receive(:cache_class=).with(:yaml)
@puppetd.setup
end
it "should default catalog_terminus setting to 'rest'" do
@puppetd.initialize_app_defaults
expect(Puppet[:catalog_terminus]).to eq(:rest)
end
it "should default node_terminus setting to 'rest'" do
@puppetd.initialize_app_defaults
expect(Puppet[:node_terminus]).to eq(:rest)
end
it "has an application default :catalog_cache_terminus setting of 'json'" do
expect(Puppet::Resource::Catalog.indirection).to receive(:cache_class=).with(:json)
@puppetd.initialize_app_defaults
@puppetd.setup
end
it "should tell the catalog cache class based on the :catalog_cache_terminus setting" do
Puppet[:catalog_cache_terminus] = "yaml"
expect(Puppet::Resource::Catalog.indirection).to receive(:cache_class=).with(:yaml)
@puppetd.initialize_app_defaults
@puppetd.setup
end
it "should not set catalog cache class if :catalog_cache_terminus is explicitly nil" do
Puppet[:catalog_cache_terminus] = nil
expect(Puppet::Resource::Catalog.indirection).not_to receive(:cache_class=)
@puppetd.initialize_app_defaults
@puppetd.setup
end
it "should default facts_terminus setting to 'facter'" do
@puppetd.initialize_app_defaults
expect(Puppet[:facts_terminus]).to eq(:facter)
end
it "should create an agent" do
allow(Puppet::Agent).to receive(:new).with(Puppet::Configurer)
@puppetd.setup
end
[:enable, :disable].each do |action|
it "should delegate to enable_disable_client if we #{action} the agent" do
@puppetd.options[action] = true
expect(@puppetd).to receive(:enable_disable_client).with(@agent)
@puppetd.setup
end
end
describe "when enabling or disabling agent" do
[:enable, :disable].each do |action|
it "should call client.#{action}" do
@puppetd.options[action] = true
expect(@agent).to receive(action)
expect { execute_agent }.to exit_with 0
end
end
it "should pass the disable message when disabling" do
@puppetd.options[:disable] = true
@puppetd.options[:disable_message] = "message"
expect(@agent).to receive(:disable).with("message")
expect { execute_agent }.to exit_with 0
end
it "should pass the default disable message when disabling without a message" do
@puppetd.options[:disable] = true
@puppetd.options[:disable_message] = nil
expect(@agent).to receive(:disable).with("reason not specified")
expect { execute_agent }.to exit_with 0
end
end
it "should inform the daemon about our agent if :client is set to 'true'" do
@puppetd.options[:client] = true
execute_agent
expect(@daemon.agent).to eq(@agent)
end
it "should daemonize if needed" do
allow(Puppet::Util::Platform).to receive(:windows?).and_return(false)
Puppet[:daemonize] = true
allow(Signal).to receive(:trap)
expect(@daemon).to receive(:daemonize)
execute_agent
end
it "should wait for a certificate" do
Puppet[:waitforcert] = 123
expect(Puppet::SSL::StateMachine).to receive(:new).with(hash_including(waitforcert: 123)).and_return(machine)
execute_agent
end
describe "when setting up for fingerprint" do
before(:each) do
@puppetd.options[:fingerprint] = true
end
it "should not setup as an agent" do
expect(@puppetd).not_to receive(:setup_agent)
@puppetd.setup
end
it "should not create an agent" do
expect(Puppet::Agent).not_to receive(:new).with(Puppet::Configurer)
@puppetd.setup
end
it "should not daemonize" do
expect(@daemon).not_to receive(:daemonize)
@puppetd.setup
end
end
describe "when configuring agent for catalog run" do
it "should set should_fork as true when running normally" do
expect(Puppet::Agent).to receive(:new).with(anything, true)
@puppetd.setup
end
it "should not set should_fork as false for --onetime" do
Puppet[:onetime] = true
expect(Puppet::Agent).to receive(:new).with(anything, false)
@puppetd.setup
end
end
end
describe "when running" do
before :each do
@puppetd.options[:fingerprint] = false
end
it "should dispatch to fingerprint if --fingerprint is used" do
@puppetd.options[:fingerprint] = true
expect(@puppetd).to receive(:fingerprint)
execute_agent
end
it "should dispatch to onetime if --onetime is used" do
Puppet[:onetime] = true
expect(@puppetd).to receive(:onetime)
execute_agent
end
it "should dispatch to main if --onetime and --fingerprint are not used" do
Puppet[:onetime] = false
expect(@puppetd).to receive(:main)
execute_agent
end
describe "with --onetime" do
before :each do
allow(@agent).to receive(:run).and_return(:report)
Puppet[:onetime] = true
@puppetd.options[:client] = :client
@puppetd.options[:detailed_exitcodes] = false
end
it "should setup traps" do
expect(@daemon).to receive(:set_signal_traps)
expect { execute_agent }.to exit_with 0
end
it "should let the agent run" do
expect(@agent).to receive(:run).and_return(:report)
expect { execute_agent }.to exit_with 0
end
it "should run the agent with the supplied job_id" do
@puppetd.options[:job_id] = 'special id'
expect(@agent).to receive(:run).with(hash_including(:job_id => 'special id')).and_return(:report)
expect { execute_agent }.to exit_with 0
end
it "should stop the daemon" do
expect(@daemon).to receive(:stop).with({:exit => false})
expect { execute_agent }.to exit_with 0
end
describe "and --detailed-exitcodes" do
before :each do
@puppetd.options[:detailed_exitcodes] = true
end
it "should exit with agent computed exit status" do
Puppet[:noop] = false
allow(@agent).to receive(:run).and_return(666)
expect { execute_agent }.to exit_with 666
end
it "should exit with the agent's exit status, even if --noop is set." do
Puppet[:noop] = true
allow(@agent).to receive(:run).and_return(666)
expect { execute_agent }.to exit_with 666
end
end
end
describe "with --fingerprint" do
before :each do
@puppetd.options[:fingerprint] = true
@puppetd.options[:digest] = :MD5
end
def expected_fingerprint(name, x509)
digest = OpenSSL::Digest.new(name).hexdigest(x509.to_der)
digest.scan(/../).join(':').upcase
end
it "should fingerprint the certificate if it exists" do
cert = cert_fixture('signed.pem')
allow_any_instance_of(Puppet::X509::CertProvider).to receive(:load_client_cert).and_return(cert)
expect(@puppetd).to receive(:puts).with("(MD5) #{expected_fingerprint('md5', cert)}")
@puppetd.fingerprint
end
it "should fingerprint the request if it exists" do
request = request_fixture('request.pem')
allow_any_instance_of(Puppet::X509::CertProvider).to receive(:load_client_cert).and_return(nil)
allow_any_instance_of(Puppet::X509::CertProvider).to receive(:load_request).and_return(request)
expect(@puppetd).to receive(:puts).with("(MD5) #{expected_fingerprint('md5', request)}")
@puppetd.fingerprint
end
it "should print an error to stderr if neither exist" do
allow_any_instance_of(Puppet::X509::CertProvider).to receive(:load_client_cert).and_return(nil)
allow_any_instance_of(Puppet::X509::CertProvider).to receive(:load_request).and_return(nil)
expect {
@puppetd.fingerprint
}.to exit_with(1)
.and output(/Fingerprint asked but neither the certificate, nor the certificate request have been issued/).to_stderr
end
it "should log an error if an exception occurs" do
allow_any_instance_of(Puppet::X509::CertProvider).to receive(:load_client_cert).and_raise(Puppet::Error, "Invalid PEM")
expect {
@puppetd.fingerprint
}.to exit_with(1)
expect(@logs).to include(an_object_having_attributes(message: /Failed to generate fingerprint: Invalid PEM/))
end
end
describe "without --onetime and --fingerprint" do
before :each do
allow(Puppet).to receive(:notice)
end
it "should start our daemon" do
expect(@daemon).to receive(:start)
execute_agent
end
end
end
describe "when starting in daemon mode on non-windows", :unless => Puppet.features.microsoft_windows? do
before :each do
allow(Puppet).to receive(:notice)
Puppet[:daemonize] = true
allow(Puppet::SSL::StateMachine).to receive(:new).and_return(machine)
end
it "should not print config in default mode" do
execute_agent
expect(@logs).to be_empty
end
it "should print config in debug mode" do
@puppetd.options[:debug] = true
execute_agent
expect(@logs).to include(an_object_having_attributes(level: :debug, message: /agent_catalog_run_lockfile=/))
end
end
def execute_agent
@puppetd.setup
@puppetd.run_command
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/application/device_spec.rb | spec/unit/application/device_spec.rb | require 'spec_helper'
require 'ostruct'
require 'puppet/application/apply'
require 'puppet/application/device'
require 'puppet/configurer'
require 'puppet/util/network_device/config'
describe Puppet::Application::Device do
include PuppetSpec::Files
let(:device) do
dev = Puppet::Application[:device]
allow(dev).to receive(:trap)
allow(Signal).to receive(:trap)
dev.preinit
dev
end
let(:ssl_context) { instance_double(Puppet::SSL::SSLContext, 'ssl_context') }
let(:state_machine) { instance_double(Puppet::SSL::StateMachine, 'state machine') }
before do
allow(Puppet::Node::Facts.indirection).to receive(:terminus_class=)
allow(Puppet::Node.indirection).to receive(:cache_class=)
allow(Puppet::Node.indirection).to receive(:terminus_class=)
allow(Puppet::Resource::Catalog.indirection).to receive(:cache_class=)
allow(Puppet::Resource::Catalog.indirection).to receive(:terminus_class=)
allow(Puppet::Transaction::Report.indirection).to receive(:terminus_class=)
allow(Puppet::Util::Log).to receive(:newdestination)
allow(state_machine).to receive(:ensure_client_certificate).and_return(ssl_context)
allow(Puppet::SSL::StateMachine).to receive(:new).and_return(state_machine)
end
it "operates in agent run_mode" do
expect(device.class.run_mode.name).to eq(:agent)
end
it "declares a main command" do
expect(device).to respond_to(:main)
end
it "declares a preinit block" do
expect(device).to respond_to(:preinit)
end
describe "in preinit" do
before do
end
it "catches INT" do
device
expect(Signal).to have_received(:trap).with(:INT)
end
it "inits waitforcert to nil" do
expect(device.options[:waitforcert]).to be_nil
end
it "inits target to nil" do
expect(device.options[:target]).to be_nil
end
end
describe "when handling options" do
before do
Puppet[:certname] = 'device.example.com'
allow(device.command_line).to receive(:args).and_return([])
end
[:centrallogging, :debug, :verbose,].each do |option|
it "should declare handle_#{option} method" do
expect(device).to respond_to("handle_#{option}".to_sym)
end
it "should store argument value when calling handle_#{option}" do
allow(device.options).to receive(:[]=).with(option, 'arg')
device.send("handle_#{option}".to_sym, 'arg')
end
end
context 'when setting --onetime' do
before do
Puppet[:onetime] = true
end
context 'without --waitforcert' do
it "defaults waitforcert to 0" do
device.setup_context
expect(Puppet::SSL::StateMachine).to have_received(:new).with(hash_including(waitforcert: 0))
end
end
context 'with --waitforcert=60' do
it "uses supplied waitforcert" do
device.handle_waitforcert(60)
device.setup_context
expect(Puppet::SSL::StateMachine).to have_received(:new).with(hash_including(waitforcert: 60))
end
end
end
context 'without setting --onetime' do
before do
Puppet[:onetime] = false
end
it "uses a default value for waitforcert when --onetime and --waitforcert are not specified" do
device.setup_context
expect(Puppet::SSL::StateMachine).to have_received(:new).with(hash_including(waitforcert: 120))
end
it "uses the waitforcert setting when checking for a signed certificate" do
Puppet[:waitforcert] = 10
device.setup_context
expect(Puppet::SSL::StateMachine).to have_received(:new).with(hash_including(waitforcert: 10))
end
end
it "sets the log destination with --logdest" do
allow(device.options).to receive(:[]=).with(:setdest, anything)
expect(Puppet::Log).to receive(:newdestination).with("console")
device.handle_logdest("console")
end
it "puts the setdest options to true" do
expect(device.options).to receive(:[]=).with(:setdest, true)
device.handle_logdest("console")
end
it "parses the log destination from the command line" do
allow(device.command_line).to receive(:args).and_return(%w{--logdest /my/file})
expect(Puppet::Util::Log).to receive(:newdestination).with("/my/file")
device.parse_options
end
it "stores the waitforcert options with --waitforcert" do
expect(device.options).to receive(:[]=).with(:waitforcert,42)
device.handle_waitforcert("42")
end
it "sets args[:Port] with --port" do
device.handle_port("42")
expect(device.args[:Port]).to eq("42")
end
it "stores the target options with --target" do
expect(device.options).to receive(:[]=).with(:target,'test123')
device.handle_target('test123')
end
it "stores the resource options with --resource" do
expect(device.options).to receive(:[]=).with(:resource,true)
device.handle_resource(true)
end
it "stores the facts options with --facts" do
expect(device.options).to receive(:[]=).with(:facts,true)
device.handle_facts(true)
end
it "should register ssl OIDs" do
expect(Puppet::SSL::Oids).to receive(:register_puppet_oids)
device.setup
end
end
describe "during setup" do
before do
allow(device.options).to receive(:[])
Puppet[:libdir] = "/dev/null/lib"
end
it "calls setup_logs" do
expect(device).to receive(:setup_logs)
device.setup
end
describe "when setting up logs" do
before do
allow(Puppet::Util::Log).to receive(:newdestination)
end
it "sets log level to debug if --debug was passed" do
allow(device.options).to receive(:[]).with(:debug).and_return(true)
device.setup_logs
expect(Puppet::Util::Log.level).to eq(:debug)
end
it "sets log level to info if --verbose was passed" do
allow(device.options).to receive(:[]).with(:verbose).and_return(true)
device.setup_logs
expect(Puppet::Util::Log.level).to eq(:info)
end
[:verbose, :debug].each do |level|
it "should set console as the log destination with level #{level}" do
allow(device.options).to receive(:[]).with(level).and_return(true)
expect(Puppet::Util::Log).to receive(:newdestination).with(:console)
device.setup_logs
end
end
it "sets a default log destination if no --logdest" do
allow(device.options).to receive(:[]).with(:setdest).and_return(false)
expect(Puppet::Util::Log).to receive(:setup_default)
device.setup_logs
end
end
it "sets a central log destination with --centrallogs" do
allow(device.options).to receive(:[]).with(:centrallogs).and_return(true)
Puppet[:server] = "puppet.example.com"
allow(Puppet::Util::Log).to receive(:newdestination).with(:syslog)
expect(Puppet::Util::Log).to receive(:newdestination).with("puppet.example.com")
device.setup
end
it "uses :main, :agent, :device and :ssl config" do
expect(Puppet.settings).to receive(:use).with(:main, :agent, :device, :ssl)
device.setup
end
it "tells the report handler to use REST" do
device.setup
expect(Puppet::Transaction::Report.indirection).to have_received(:terminus_class=).with(:rest)
end
it "defaults the catalog_terminus setting to 'rest'" do
device.initialize_app_defaults
expect(Puppet[:catalog_terminus]).to eq(:rest)
end
it "defaults the node_terminus setting to 'rest'" do
device.initialize_app_defaults
expect(Puppet[:node_terminus]).to eq(:rest)
end
it "has an application default :catalog_cache_terminus setting of 'json'" do
expect(Puppet::Resource::Catalog.indirection).to receive(:cache_class=).with(:json)
device.initialize_app_defaults
device.setup
end
it "tells the catalog cache class based on the :catalog_cache_terminus setting" do
Puppet[:catalog_cache_terminus] = "yaml"
expect(Puppet::Resource::Catalog.indirection).to receive(:cache_class=).with(:yaml)
device.initialize_app_defaults
device.setup
end
it "does not set catalog cache class if :catalog_cache_terminus is explicitly nil" do
Puppet[:catalog_cache_terminus] = nil
expect(Puppet::Resource::Catalog.indirection).not_to receive(:cache_class=)
device.initialize_app_defaults
device.setup
end
it "defaults the facts_terminus setting to 'network_device'" do
device.initialize_app_defaults
expect(Puppet[:facts_terminus]).to eq(:network_device)
end
end
describe "when initializing SSL" do
it "creates a new ssl host" do
allow(device.options).to receive(:[]).with(:waitforcert).and_return(123)
device.setup_context
expect(Puppet::SSL::StateMachine).to have_received(:new).with(hash_including(waitforcert: 123))
end
end
describe "when running" do
let(:device_hash) { {} }
let(:plugin_handler) { instance_double(Puppet::Configurer::PluginHandler, 'plugin_handler') }
before do
allow(device.options).to receive(:[]).with(:fingerprint).and_return(false)
allow(Puppet).to receive(:notice)
allow(device.options).to receive(:[]).with(:detailed_exitcodes).and_return(false)
allow(device.options).to receive(:[]).with(:target).and_return(nil)
allow(device.options).to receive(:[]).with(:apply).and_return(nil)
allow(device.options).to receive(:[]).with(:facts).and_return(false)
allow(device.options).to receive(:[]).with(:resource).and_return(false)
allow(device.options).to receive(:[]).with(:to_yaml).and_return(false)
allow(device.options).to receive(:[]).with(:libdir).and_return(nil)
allow(device.options).to receive(:[]).with(:client)
allow(device.command_line).to receive(:args).and_return([])
allow(Puppet::Util::NetworkDevice::Config).to receive(:devices).and_return(device_hash)
allow(Puppet::Configurer::PluginHandler).to receive(:new).and_return(plugin_handler)
end
it "dispatches to main" do
allow(device).to receive(:main)
device.run_command
end
it "errors if resource is requested without target" do
allow(device.options).to receive(:[]).with(:resource).and_return(true)
expect { device.main }.to raise_error(RuntimeError, "resource command requires target")
end
it "errors if facts is requested without target" do
allow(device.options).to receive(:[]).with(:facts).and_return(true)
expect { device.main }.to raise_error(RuntimeError, "facts command requires target")
end
it "gets the device list" do
expect(Puppet::Util::NetworkDevice::Config).to receive(:devices).and_return(device_hash)
expect { device.main }.to exit_with 1
end
it "errors when an invalid target parameter is passed" do
allow(device.options).to receive(:[]).with(:target).and_return('bla')
expect(Puppet).not_to receive(:info).with(/starting applying configuration to/)
expect { device.main }.to raise_error(RuntimeError, /Target device \/ certificate 'bla' not found in .*\.conf/)
end
it "errors if target is passed and the apply path is incorrect" do
allow(device.options).to receive(:[]).with(:apply).and_return('file.pp')
allow(device.options).to receive(:[]).with(:target).and_return('device1')
expect(File).to receive(:file?).and_return(false)
expect { device.main }.to raise_error(RuntimeError, /does not exist, cannot apply/)
end
it "exits if the device list is empty" do
expect { device.main }.to exit_with 1
end
context 'with some devices configured' do
let(:configurer) { instance_double(Puppet::Configurer, 'configurer') }
let(:device_hash) {
{
"device1" => OpenStruct.new(:name => "device1", :url => "ssh://user:pass@testhost", :provider => "cisco"),
"device2" => OpenStruct.new(:name => "device2", :url => "https://user:pass@testhost/some/path", :provider => "rest"),
}
}
before do
Puppet[:vardir] = make_absolute("/dummy")
Puppet[:confdir] = make_absolute("/dummy")
Puppet[:certname] = "certname"
allow(Puppet).to receive(:[]=)
allow(Puppet.settings).to receive(:use)
allow(device).to receive(:setup_context)
allow(Puppet::Util::NetworkDevice).to receive(:init)
allow(configurer).to receive(:run)
allow(Puppet::Configurer).to receive(:new).and_return(configurer)
allow(Puppet::FileSystem).to receive(:exist?)
allow(Puppet::FileSystem).to receive(:symlink)
allow(Puppet::FileSystem).to receive(:dir_mkpath).and_return(true)
allow(Puppet::FileSystem).to receive(:dir_exist?).and_return(true)
allow(plugin_handler).to receive(:download_plugins)
end
it "sets ssldir relative to the global confdir" do
expect(Puppet).to receive(:[]=).with(:ssldir, make_absolute("/dummy/devices/device1/ssl"))
expect { device.main }.to exit_with 1
end
it "sets vardir to the device vardir" do
expect(Puppet).to receive(:[]=).with(:vardir, make_absolute("/dummy/devices/device1"))
expect { device.main }.to exit_with 1
end
it "sets confdir to the device confdir" do
expect(Puppet).to receive(:[]=).with(:confdir, make_absolute("/dummy/devices/device1"))
expect { device.main }.to exit_with 1
end
it "sets certname to the device certname" do
expect(Puppet).to receive(:[]=).with(:certname, "device1")
expect(Puppet).to receive(:[]=).with(:certname, "device2")
expect { device.main }.to exit_with 1
end
context 'with --target=device1' do
it "symlinks the ssl directory if it doesn't exist" do
allow(device.options).to receive(:[]).with(:target).and_return('device1')
allow(Puppet::FileSystem).to receive(:exist?).and_return(false)
expect(Puppet::FileSystem).to receive(:symlink).with(Puppet[:ssldir], File.join(Puppet[:confdir], 'ssl')).and_return(true)
expect { device.main }.to exit_with 1
end
it "creates the device confdir under the global confdir" do
allow(device.options).to receive(:[]).with(:target).and_return('device1')
allow(Puppet::FileSystem).to receive(:dir_exist?).and_return(false)
expect(Puppet::FileSystem).to receive(:dir_mkpath).with(Puppet[:ssldir]).and_return(true)
expect { device.main }.to exit_with 1
end
it "manages the specified target" do
allow(device.options).to receive(:[]).with(:target).and_return('device1')
expect(URI).to receive(:parse).with("ssh://user:pass@testhost")
expect(URI).not_to receive(:parse).with("https://user:pass@testhost/some/path")
expect { device.main }.to exit_with 1
end
end
context 'when running --resource' do
before do
allow(device.options).to receive(:[]).with(:resource).and_return(true)
allow(device.options).to receive(:[]).with(:target).and_return('device1')
end
it "raises an error if no type is given" do
allow(device.command_line).to receive(:args).and_return([])
expect(Puppet).to receive(:log_exception) { |e| expect(e.message).to eq("You must specify the type to display") }
expect { device.main }.to exit_with 1
end
it "raises an error if the type is not found" do
allow(device.command_line).to receive(:args).and_return(['nope'])
expect(Puppet).to receive(:log_exception) { |e| expect(e.message).to eq("Could not find type nope") }
expect { device.main }.to exit_with 1
end
it "retrieves all resources of a type" do
allow(device.command_line).to receive(:args).and_return(['user'])
expect(Puppet::Resource.indirection).to receive(:search).with('user/', {}).and_return([])
expect { device.main }.to exit_with 0
end
it "retrieves named resources of a type" do
resource = Puppet::Type.type(:user).new(:name => "jim").to_resource
allow(device.command_line).to receive(:args).and_return(['user', 'jim'])
expect(Puppet::Resource.indirection).to receive(:find).with('user/jim').and_return(resource)
expect(device).to receive(:puts).with("user { 'jim':\n ensure => 'absent',\n}")
expect { device.main }.to exit_with 0
end
it "outputs resources as YAML" do
resources = [
Puppet::Type.type(:user).new(:name => "title").to_resource,
]
allow(device.options).to receive(:[]).with(:to_yaml).and_return(true)
allow(device.command_line).to receive(:args).and_return(['user'])
expect(Puppet::Resource.indirection).to receive(:search).with('user/', {}).and_return(resources)
expect(device).to receive(:puts).with("---\nuser:\n title:\n ensure: absent\n")
expect { device.main }.to exit_with 0
end
end
context 'when running --facts' do
before do
allow(device.options).to receive(:[]).with(:facts).and_return(true)
allow(device.options).to receive(:[]).with(:target).and_return('device1')
end
it "retrieves facts" do
indirection_fact_values = {"os"=> {"name" => "cisco_ios"},"clientcert"=>"3750"}
indirection_facts = Puppet::Node::Facts.new("nil", indirection_fact_values)
expect(Puppet::Node::Facts.indirection).to receive(:find).with(nil, anything()).and_return(indirection_facts)
expect(device).to receive(:puts).with(/name.*3750.*\n.*values.*\n.*os.*\n.*name.*cisco_ios/)
expect { device.main }.to exit_with 0
end
end
context 'when running in agent mode' do
it "makes sure all the required folders and files are created" do
expect(Puppet.settings).to receive(:use).with(:main, :agent, :ssl).twice
expect { device.main }.to exit_with 1
end
it "initializes the device singleton" do
expect(Puppet::Util::NetworkDevice).to receive(:init).with(device_hash["device1"]).ordered
expect(Puppet::Util::NetworkDevice).to receive(:init).with(device_hash["device2"]).ordered
expect { device.main }.to exit_with 1
end
it "retrieves plugins and print the device url scheme, host, and port" do
allow(Puppet).to receive(:info)
expect(plugin_handler).to receive(:download_plugins).twice
expect(Puppet).to receive(:info).with("starting applying configuration to device1 at ssh://testhost")
expect(Puppet).to receive(:info).with("starting applying configuration to device2 at https://testhost:443/some/path")
expect { device.main }.to exit_with 1
end
it "setups the SSL context before pluginsync" do
expect(device).to receive(:setup_context).ordered
expect(plugin_handler).to receive(:download_plugins).ordered
expect(device).to receive(:setup_context).ordered
expect(plugin_handler).to receive(:download_plugins).ordered
expect { device.main }.to exit_with 1
end
it "launches a configurer for this device" do
expect(configurer).to receive(:run).twice
expect { device.main }.to exit_with 1
end
it "exits 1 when configurer raises error" do
expect(configurer).to receive(:run).and_raise(Puppet::Error).ordered
expect(configurer).to receive(:run).and_return(0).ordered
expect { device.main }.to exit_with 1
end
it "exits 0 when run happens without puppet errors but with failed run" do
allow(configurer).to receive(:run).and_return(6, 2)
expect { device.main }.to exit_with 0
end
it "makes the Puppet::Pops::Loaders available" do
expect(configurer).to receive(:run).with({:network_device => true, :pluginsync => false}) do
fail('Loaders not available') unless Puppet.lookup(:loaders) { nil }.is_a?(Puppet::Pops::Loaders)
true
end.and_return(6, 2)
expect { device.main }.to exit_with 0
end
it "exits 2 when --detailed-exitcodes and successful runs" do
allow(device.options).to receive(:[]).with(:detailed_exitcodes).and_return(true)
allow(configurer).to receive(:run).and_return(0, 2)
expect { device.main }.to exit_with 2
end
it "exits 1 when --detailed-exitcodes and failed parse" do
allow(Puppet::Configurer).to receive(:new).and_return(configurer)
allow(device.options).to receive(:[]).with(:detailed_exitcodes).and_return(true)
allow(configurer).to receive(:run).and_return(6, 1)
expect { device.main }.to exit_with 7
end
it "exits 6 when --detailed-exitcodes and failed run" do
allow(Puppet::Configurer).to receive(:new).and_return(configurer)
allow(device.options).to receive(:[]).with(:detailed_exitcodes).and_return(true)
allow(configurer).to receive(:run).and_return(6, 2)
expect { device.main }.to exit_with 6
end
[:vardir, :confdir].each do |setting|
it "resets the #{setting} setting after the run" do
all_devices = Set.new(device_hash.keys.map do |device_name| make_absolute("/dummy/devices/#{device_name}") end)
found_devices = Set.new()
# a block to use in a few places later to validate the updated settings
p = Proc.new do |my_setting, my_value|
expect(all_devices).to include(my_value)
found_devices.add(my_value)
end
all_devices.size.times do
## one occurrence of set / run / set("/dummy") for each device
expect(Puppet).to receive(:[]=, &p).with(setting, anything).ordered
expect(configurer).to receive(:run).ordered
expect(Puppet).to receive(:[]=).with(setting, make_absolute("/dummy")).ordered
end
expect { device.main }.to exit_with 1
expect(found_devices).to eq(all_devices)
end
end
it "resets the certname setting after the run" do
all_devices = Set.new(device_hash.keys)
found_devices = Set.new()
# a block to use in a few places later to validate the updated settings
p = Proc.new do |my_setting, my_value|
expect(all_devices).to include(my_value)
found_devices.add(my_value)
end
allow(Puppet).to receive(:[]=)
all_devices.size.times do
## one occurrence of set / run / set("certname") for each device
expect(Puppet).to receive(:[]=, &p).with(:certname, anything).ordered
expect(configurer).to receive(:run).ordered
expect(Puppet).to receive(:[]=).with(:certname, "certname").ordered
end
expect { device.main }.to exit_with 1
# make sure that we were called with each of the defined devices
expect(found_devices).to eq(all_devices)
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/application/apply_spec.rb | spec/unit/application/apply_spec.rb | require 'spec_helper'
require 'puppet/application/apply'
require 'puppet/file_bucket/dipper'
require 'puppet/configurer'
require 'fileutils'
describe Puppet::Application::Apply do
include PuppetSpec::Files
before :each do
@apply = Puppet::Application[:apply]
Puppet[:reports] = "none"
end
[:debug,:loadclasses,:test,:verbose,:use_nodes,:detailed_exitcodes,:catalog].each do |option|
it "should store argument value when calling handle_#{option}" do
expect(@apply.options).to receive(:[]=).with(option, 'arg')
@apply.send("handle_#{option}".to_sym, 'arg')
end
end
it "should handle write_catalog_summary" do
@apply.send(:handle_write_catalog_summary, true)
expect(Puppet[:write_catalog_summary]).to eq(true)
end
it "should set the code to the provided code when :execute is used" do
expect(@apply.options).to receive(:[]=).with(:code, 'arg')
@apply.send("handle_execute".to_sym, 'arg')
end
describe "when applying options" do
it "should set the log destination with --logdest" do
expect(Puppet::Log).to receive(:newdestination).with("console")
@apply.handle_logdest("console")
end
it "should set the setdest options to true" do
expect(@apply.options).to receive(:[]=).with(:setdest,true)
@apply.handle_logdest("console")
end
end
describe "during setup" do
before :each do
allow(Puppet::Log).to receive(:newdestination)
allow(Puppet::FileBucket::Dipper).to receive(:new)
allow(STDIN).to receive(:read)
allow(Puppet::Transaction::Report.indirection).to receive(:cache_class=)
end
describe "with --test" do
it "should set options[:verbose] to true" do
@apply.setup_test
expect(@apply.options[:verbose]).to eq(true)
end
it "should set options[:show_diff] to true" do
Puppet.settings.override_default(:show_diff, false)
@apply.setup_test
expect(Puppet[:show_diff]).to eq(true)
end
it "should set options[:detailed_exitcodes] to true" do
@apply.setup_test
expect(@apply.options[:detailed_exitcodes]).to eq(true)
end
end
it "should set console as the log destination if logdest option wasn't provided" do
expect(Puppet::Log).to receive(:newdestination).with(:console)
@apply.setup
end
it "sets the log destination if logdest is provided via settings" do
expect(Puppet::Log).to receive(:newdestination).with("set_via_config")
Puppet[:logdest] = "set_via_config"
@apply.setup
end
it "should set INT trap" do
expect(Signal).to receive(:trap).with(:INT)
@apply.setup
end
it "should set log level to debug if --debug was passed" do
@apply.options[:debug] = true
@apply.setup
expect(Puppet::Log.level).to eq(:debug)
end
it "should set log level to info if --verbose was passed" do
@apply.options[:verbose] = true
@apply.setup
expect(Puppet::Log.level).to eq(:info)
end
it "should print puppet config if asked to in Puppet config" do
allow(Puppet.settings).to receive(:print_configs?).and_return(true)
expect(Puppet.settings).to receive(:print_configs).and_return(true)
expect { @apply.setup }.to exit_with 0
end
it "should exit after printing puppet config if asked to in Puppet config" do
allow(Puppet.settings).to receive(:print_configs?).and_return(true)
expect { @apply.setup }.to exit_with 1
end
it "should use :main, :puppetd, and :ssl" do
expect(Puppet.settings).to receive(:use).with(:main, :agent, :ssl)
@apply.setup
end
it "should tell the report handler to cache locally as yaml" do
expect(Puppet::Transaction::Report.indirection).to receive(:cache_class=).with(:yaml)
@apply.setup
end
it "configures a profiler when profiling is enabled" do
Puppet[:profile] = true
@apply.setup
expect(Puppet::Util::Profiler.current).to satisfy do |ps|
ps.any? {|p| p.is_a? Puppet::Util::Profiler::WallClock }
end
end
it "does not have a profiler if profiling is disabled" do
Puppet[:profile] = false
@apply.setup
expect(Puppet::Util::Profiler.current.length).to be 0
end
it "should set default_file_terminus to `file_server` to be local" do
expect(@apply.app_defaults[:default_file_terminus]).to eq(:file_server)
end
end
describe "when executing" do
it "should dispatch to 'apply' if it was called with a catalog" do
@apply.options[:catalog] = "foo"
expect(@apply).to receive(:apply)
@apply.run_command
end
it "should dispatch to main otherwise" do
allow(@apply).to receive(:options).and_return({})
expect(@apply).to receive(:main)
@apply.run_command
end
describe "the main command" do
before :each do
Puppet[:prerun_command] = ''
Puppet[:postrun_command] = ''
Puppet::Node.indirection.terminus_class = :memory
Puppet::Node.indirection.cache_class = :memory
facts = Puppet::Node::Facts.new(Puppet[:node_name_value])
Puppet::Node::Facts.indirection.save(facts)
@node = Puppet::Node.new(Puppet[:node_name_value])
Puppet::Node.indirection.save(@node)
@catalog = Puppet::Resource::Catalog.new("testing", Puppet.lookup(:environments).get(Puppet[:environment]))
allow(@catalog).to receive(:to_ral).and_return(@catalog)
allow(Puppet::Resource::Catalog.indirection).to receive(:find).and_return(@catalog)
allow(STDIN).to receive(:read)
@transaction = double('transaction')
allow(@catalog).to receive(:apply).and_return(@transaction)
allow(Puppet::Util::Storage).to receive(:load)
allow_any_instance_of(Puppet::Configurer).to receive(:save_last_run_summary) # to prevent it from trying to write files
end
after :each do
Puppet::Node::Facts.indirection.reset_terminus_class
Puppet::Node::Facts.indirection.cache_class = nil
end
around :each do |example|
Puppet.override(:current_environment =>
Puppet::Node::Environment.create(:production, [])) do
example.run
end
end
it "should set the code to run from --code" do
@apply.options[:code] = "code to run"
expect(Puppet).to receive(:[]=).with(:code,"code to run")
expect { @apply.run }.to exit_with(0).and output(anything).to_stdout
end
it "should set the code to run from STDIN if no arguments" do
@apply.command_line.args = []
allow(STDIN).to receive(:read).and_return("code to run")
expect(Puppet).to receive(:[]=).with(:code,"code to run")
expect { @apply.run }.to exit_with(0).and output(anything).to_stdout
end
it "should raise an error if a file is passed on command line and the file does not exist" do
noexist = tmpfile('noexist.pp')
@apply.command_line.args << noexist
expect {
@apply.run
}.to exit_with(1)
.and output(anything).to_stdout
.and output(/Could not find file #{noexist}/).to_stderr
end
it "should set the manifest to the first file and warn other files will be skipped" do
manifest = tmpfile('starwarsIV')
FileUtils.touch(manifest)
@apply.command_line.args << manifest << 'starwarsI' << 'starwarsII'
expect {
@apply.run
}.to exit_with(0)
.and output(anything).to_stdout
.and output(/Warning: Only one file can be applied per run. Skipping starwarsI, starwarsII/).to_stderr
end
it "should splay" do
expect(@apply).to receive(:splay)
expect {
@apply.run
}.to exit_with(0).and output(anything).to_stdout
end
it "should exit with 1 if we can't find the node" do
expect(Puppet::Node.indirection).to receive(:find).and_return(nil)
expect { @apply.run }.to exit_with(1).and output(/Could not find node/).to_stderr
end
it "should load custom classes if loadclasses" do
@apply.options[:loadclasses] = true
classfile = tmpfile('classfile')
File.open(classfile, 'w') { |c| c.puts 'class' }
Puppet[:classfile] = classfile
expect(@node).to receive(:classes=).with(['class'])
expect { @apply.run }.to exit_with(0).and output(anything).to_stdout
end
it "should compile the catalog" do
expect(Puppet::Resource::Catalog.indirection).to receive(:find).and_return(@catalog)
expect { @apply.run }.to exit_with(0).and output(anything).to_stdout
end
it 'should called the DeferredResolver to resolve any Deferred values' do
expect(Puppet::Pops::Evaluator::DeferredResolver).to receive(:resolve_and_replace).with(any_args)
expect { @apply.run }.to exit_with(0).and output(anything).to_stdout
end
it 'should make the Puppet::Pops::Loaders available when applying the compiled catalog' do
expect(Puppet::Resource::Catalog.indirection).to receive(:find).and_return(@catalog)
expect(@apply).to receive(:apply_catalog) do |catalog|
expect(@catalog).to eq(@catalog)
fail('Loaders not found') unless Puppet.lookup(:loaders) { nil }.is_a?(Puppet::Pops::Loaders)
true
end.and_return(0)
expect { @apply.run }.to exit_with(0).and output(anything).to_stdout
end
it "should transform the catalog to ral" do
expect(@catalog).to receive(:to_ral).and_return(@catalog)
expect { @apply.run }.to exit_with(0).and output(anything).to_stdout
end
it "should finalize the catalog" do
expect(@catalog).to receive(:finalize)
expect { @apply.run }.to exit_with(0).and output(anything).to_stdout
end
it "should not save the classes or resource file by default" do
expect(@catalog).not_to receive(:write_class_file)
expect(@catalog).not_to receive(:write_resource_file)
expect { @apply.run }.to exit_with(0).and output(anything).to_stdout
end
it "should save the classes and resources files when requested on the command line using dashes" do
expect(@catalog).to receive(:write_class_file).once
expect(@catalog).to receive(:write_resource_file).once
# dashes are parsed by the application's OptionParser
@apply.command_line.args = ['--write-catalog-summary']
expect { @apply.run }.to exit_with(0).and output(anything).to_stdout
end
it "should save the classes and resources files when requested on the command line using underscores" do
expect(@catalog).to receive(:write_class_file).once
expect(@catalog).to receive(:write_resource_file).once
# underscores are parsed by the settings PuppetOptionParser
@apply.command_line.args = ['--write_catalog_summary']
Puppet.initialize_settings(['--write_catalog_summary'])
expect { @apply.run }.to exit_with(0).and output(anything).to_stdout
end
it "should save the classes and resources files when specified as a setting" do
Puppet[:write_catalog_summary] = true
expect(@catalog).to receive(:write_class_file).once
expect(@catalog).to receive(:write_resource_file).once
expect { @apply.run }.to exit_with(0).and output(anything).to_stdout
end
it "should call the prerun and postrun commands on a Configurer instance" do
expect_any_instance_of(Puppet::Configurer).to receive(:execute_prerun_command).and_return(true)
expect_any_instance_of(Puppet::Configurer).to receive(:execute_postrun_command).and_return(true)
expect { @apply.run }.to exit_with(0).and output(anything).to_stdout
end
it "should apply the catalog" do
expect(@catalog).to receive(:apply).and_return(double('transaction'))
expect { @apply.run }.to exit_with(0).and output(anything).to_stdout
end
it "should save the last run summary" do
Puppet[:noop] = false
report = Puppet::Transaction::Report.new
allow(Puppet::Transaction::Report).to receive(:new).and_return(report)
expect_any_instance_of(Puppet::Configurer).to receive(:save_last_run_summary).with(report)
expect { @apply.run }.to exit_with(0).and output(anything).to_stdout
end
describe "when using node_name_fact" do
before :each do
@facts = Puppet::Node::Facts.new(Puppet[:node_name_value], 'my_name_fact' => 'other_node_name')
Puppet::Node::Facts.indirection.save(@facts)
@node = Puppet::Node.new('other_node_name')
Puppet::Node.indirection.save(@node)
Puppet[:node_name_fact] = 'my_name_fact'
end
it "should set the facts name based on the node_name_fact" do
expect { @apply.run }.to exit_with(0).and output(anything).to_stdout
expect(@facts.name).to eq('other_node_name')
end
it "should set the node_name_value based on the node_name_fact" do
expect { @apply.run }.to exit_with(0).and output(anything).to_stdout
expect(Puppet[:node_name_value]).to eq('other_node_name')
end
it "should merge in our node the loaded facts" do
@facts.values.merge!('key' => 'value')
expect { @apply.run }.to exit_with(0).and output(anything).to_stdout
expect(@node.parameters['key']).to eq('value')
end
it "should exit if we can't find the facts" do
expect(Puppet::Node::Facts.indirection).to receive(:find).and_return(nil)
expect { @apply.run }.to exit_with(1).and output(/Could not find facts/).to_stderr
end
end
describe "with detailed_exitcodes" do
before :each do
@apply.options[:detailed_exitcodes] = true
end
it "should exit with report's computed exit status" do
Puppet[:noop] = false
allow_any_instance_of(Puppet::Transaction::Report).to receive(:exit_status).and_return(666)
expect { @apply.run }.to exit_with(666).and output(anything).to_stdout
end
it "should exit with report's computed exit status, even if --noop is set" do
Puppet[:noop] = true
allow_any_instance_of(Puppet::Transaction::Report).to receive(:exit_status).and_return(666)
expect { @apply.run }.to exit_with(666).and output(anything).to_stdout
end
it "should always exit with 0 if option is disabled" do
Puppet[:noop] = false
report = double('report', :exit_status => 666)
allow(@transaction).to receive(:report).and_return(report)
expect { @apply.run }.to exit_with(0).and output(anything).to_stdout
end
it "should always exit with 0 if --noop" do
Puppet[:noop] = true
report = double('report', :exit_status => 666)
allow(@transaction).to receive(:report).and_return(report)
expect { @apply.run }.to exit_with(0).and output(anything).to_stdout
end
end
end
describe "the 'apply' command" do
# We want this memoized, and to be able to adjust the content, so we
# have to do it ourselves.
def temporary_catalog(content = '"something"')
@tempfile = Tempfile.new('catalog.json')
@tempfile.write(content)
@tempfile.close
@tempfile.path
end
let(:default_format) { Puppet::Resource::Catalog.default_format }
it "should read the catalog in from disk if a file name is provided" do
@apply.options[:catalog] = temporary_catalog
catalog = Puppet::Resource::Catalog.new("testing", Puppet::Node::Environment::NONE)
allow(Puppet::Resource::Catalog).to receive(:convert_from).with(default_format, '"something"').and_return(catalog)
@apply.apply
end
it "should read the catalog in from stdin if '-' is provided" do
@apply.options[:catalog] = "-"
expect($stdin).to receive(:read).and_return('"something"')
catalog = Puppet::Resource::Catalog.new("testing", Puppet::Node::Environment::NONE)
allow(Puppet::Resource::Catalog).to receive(:convert_from).with(default_format, '"something"').and_return(catalog)
@apply.apply
end
it "should deserialize the catalog from the default format" do
@apply.options[:catalog] = temporary_catalog
allow(Puppet::Resource::Catalog).to receive(:default_format).and_return(:rot13_piglatin)
catalog = Puppet::Resource::Catalog.new("testing", Puppet::Node::Environment::NONE)
allow(Puppet::Resource::Catalog).to receive(:convert_from).with(:rot13_piglatin,'"something"').and_return(catalog)
@apply.apply
end
it "should fail helpfully if deserializing fails" do
@apply.options[:catalog] = temporary_catalog('something syntactically invalid')
expect { @apply.apply }.to raise_error(Puppet::Error)
end
it "should convert the catalog to a RAL catalog and use a Configurer instance to apply it" do
@apply.options[:catalog] = temporary_catalog
catalog = Puppet::Resource::Catalog.new("testing", Puppet::Node::Environment::NONE)
allow(Puppet::Resource::Catalog).to receive(:convert_from).with(default_format, '"something"').and_return(catalog)
expect(catalog).to receive(:to_ral).and_return("mycatalog")
configurer = double('configurer')
expect(Puppet::Configurer).to receive(:new).and_return(configurer)
expect(configurer).to receive(:run).
with(:catalog => "mycatalog", :pluginsync => false)
@apply.apply
end
it 'should make the Puppet::Pops::Loaders available when applying a catalog' do
@apply.options[:catalog] = temporary_catalog
catalog = Puppet::Resource::Catalog.new("testing", Puppet::Node::Environment::NONE)
expect(@apply).to receive(:read_catalog) do |arg|
expect(arg).to eq('"something"')
fail('Loaders not found') unless Puppet.lookup(:loaders) { nil }.is_a?(Puppet::Pops::Loaders)
true
end.and_return(catalog)
expect(@apply).to receive(:apply_catalog) do |cat|
expect(cat).to eq(catalog)
fail('Loaders not found') unless Puppet.lookup(:loaders) { nil }.is_a?(Puppet::Pops::Loaders)
true
end
expect { @apply.apply }.not_to raise_error
end
it "should call the DeferredResolver to resolve Deferred values" do
@apply.options[:catalog] = temporary_catalog
allow(Puppet::Resource::Catalog).to receive(:default_format).and_return(:rot13_piglatin)
catalog = Puppet::Resource::Catalog.new("testing", Puppet::Node::Environment::NONE)
allow(Puppet::Resource::Catalog).to receive(:convert_from).with(:rot13_piglatin, '"something"').and_return(catalog)
expect(Puppet::Pops::Evaluator::DeferredResolver).to receive(:resolve_and_replace).with(any_args)
@apply.apply
end
end
end
describe "when really executing" do
let(:testfile) { tmpfile('secret_file_name') }
let(:resourcefile) { tmpfile('resourcefile') }
let(:classfile) { tmpfile('classfile') }
it "should not expose sensitive data in the relationship file" do
@apply.options[:code] = <<-CODE
$secret = Sensitive('cat #{testfile}')
exec { 'do it':
command => $secret,
path => '/bin/'
}
CODE
Puppet.settings[:write_catalog_summary] = true
Puppet.settings[:resourcefile] = resourcefile
Puppet.settings[:classfile] = classfile
#We don't actually need the resource to do anything, we are using it's properties in other parts of the workflow.
allow_any_instance_of(Puppet::Type.type(:exec).defaultprovider).to receive(:which).and_return('cat')
allow(Puppet::Util::Execution).to receive(:execute).and_return(double(exitstatus: 0, output: ''))
expect { @apply.run }.to exit_with(0).and output(%r{Exec\[do it\]/returns: executed successfully}).to_stdout
result = File.read(resourcefile)
expect(result).not_to match(/secret_file_name/)
expect(result).to match(/do it/)
end
end
describe "apply_catalog" do
it "should call the configurer with the catalog" do
catalog = "I am a catalog"
expect_any_instance_of(Puppet::Configurer).to receive(:run).
with(:catalog => catalog, :pluginsync => false)
@apply.send(:apply_catalog, catalog)
end
end
it "should honor the catalog_cache_terminus setting" do
Puppet.settings[:catalog_cache_terminus] = "json"
expect(Puppet::Resource::Catalog.indirection).to receive(:cache_class=).with(:json)
@apply.initialize_app_defaults
@apply.setup
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/application/filebucket_spec.rb | spec/unit/application/filebucket_spec.rb | require 'spec_helper'
require 'puppet/application/filebucket'
require 'puppet/file_bucket/dipper'
describe Puppet::Application::Filebucket do
before :each do
@filebucket = Puppet::Application[:filebucket]
end
it "should declare a get command" do
expect(@filebucket).to respond_to(:get)
end
it "should declare a backup command" do
expect(@filebucket).to respond_to(:backup)
end
it "should declare a restore command" do
expect(@filebucket).to respond_to(:restore)
end
it "should declare a diff command" do
expect(@filebucket).to respond_to(:diff)
end
it "should declare a list command" do
expect(@filebucket).to respond_to(:list)
end
[:bucket, :debug, :local, :remote, :verbose, :fromdate, :todate].each do |option|
it "should declare handle_#{option} method" do
expect(@filebucket).to respond_to("handle_#{option}".to_sym)
end
it "should store argument value when calling handle_#{option}" do
expect(@filebucket.options).to receive(:[]=).with("#{option}".to_sym, 'arg')
@filebucket.send("handle_#{option}".to_sym, 'arg')
end
end
describe "during setup" do
before :each do
allow(Puppet::Log).to receive(:newdestination)
allow(Puppet::FileBucket::Dipper).to receive(:new)
allow(@filebucket.options).to receive(:[])
end
it "should set console as the log destination" do
expect(Puppet::Log).to receive(:newdestination).with(:console)
@filebucket.setup
end
it "should trap INT" do
expect(Signal).to receive(:trap).with(:INT)
@filebucket.setup
end
it "should set log level to debug if --debug was passed" do
allow(@filebucket.options).to receive(:[]).with(:debug).and_return(true)
@filebucket.setup
expect(Puppet::Log.level).to eq(:debug)
end
it "should set log level to info if --verbose was passed" do
allow(@filebucket.options).to receive(:[]).with(:verbose).and_return(true)
@filebucket.setup
expect(Puppet::Log.level).to eq(:info)
end
it "should print puppet config if asked to in Puppet config" do
allow(Puppet.settings).to receive(:print_configs?).and_return(true)
expect(Puppet.settings).to receive(:print_configs).and_return(true)
expect { @filebucket.setup }.to exit_with 0
end
it "should exit after printing puppet config if asked to in Puppet config" do
allow(Puppet.settings).to receive(:print_configs?).and_return(true)
expect { @filebucket.setup }.to exit_with 1
end
describe "with local bucket" do
let(:path) { File.expand_path("path") }
before :each do
allow(@filebucket.options).to receive(:[]).with(:local).and_return(true)
end
it "should create a client with the default bucket if none passed" do
Puppet[:clientbucketdir] = path
Puppet[:bucketdir] = path + "2"
expect(Puppet::FileBucket::Dipper).to receive(:new).with(hash_including(Path: path))
@filebucket.setup
end
it "should create a local Dipper with the given bucket" do
allow(@filebucket.options).to receive(:[]).with(:bucket).and_return(path)
expect(Puppet::FileBucket::Dipper).to receive(:new).with(hash_including(Path: path))
@filebucket.setup
end
end
describe "with remote bucket" do
it "should create a remote Client to the configured server" do
Puppet[:server] = "puppet.reductivelabs.com"
expect(Puppet::FileBucket::Dipper).to receive(:new).with(hash_including(Server: "puppet.reductivelabs.com"))
@filebucket.setup
end
it "should default to the first good server_list entry if server_list is set" do
stub_request(:get, "https://foo:8140/status/v1/simple/server").to_return(status: 200)
Puppet[:server_list] = "foo,bar,baz"
expect(Puppet::FileBucket::Dipper).to receive(:new).with(hash_including(Server: "foo"))
@filebucket.setup
end
it "should walk server_list until it finds a good entry" do
stub_request(:get, "https://foo:8140/status/v1/simple/server").to_return(status: 502)
stub_request(:get, "https://bar:8140/status/v1/simple/server").to_return(status: 200)
Puppet[:server_list] = "foo,bar,baz"
expect(Puppet::FileBucket::Dipper).to receive(:new).with(hash_including(Server: "bar"))
@filebucket.setup
end
# FileBucket catches any exceptions raised, logs them, then just exits
it "raises an error if there are no functional servers in server_list" do
stub_request(:get, "https://foo:8140/status/v1/simple/server").to_return(status: 404)
stub_request(:get, "https://bar:8140/status/v1/simple/server").to_return(status: 404)
stub_request(:get, "https://foo:8140/status/v1/simple/master").to_return(status: 404)
stub_request(:get, "https://bar:8140/status/v1/simple/master").to_return(status: 404)
Puppet[:server] = 'horacio'
Puppet[:server_list] = "foo,bar"
expect{@filebucket.setup}.to exit_with(1)
end
it "should fall back to server if server_list is empty" do
Puppet[:server_list] = ""
expect(Puppet::FileBucket::Dipper).to receive(:new).with(hash_including(Server: "puppet"))
@filebucket.setup
end
it "should take both the server and port specified in server_list" do
stub_request(:get, "https://foo:632/status/v1/simple/server").to_return(status: 200)
Puppet[:server_list] = "foo:632,bar:6215,baz:351"
expect(Puppet::FileBucket::Dipper).to receive(:new).with({ :Server => "foo", :Port => 632 })
@filebucket.setup
end
end
end
describe "when running" do
before :each do
allow(Puppet::Log).to receive(:newdestination)
allow(Puppet::FileBucket::Dipper).to receive(:new)
allow(@filebucket.options).to receive(:[])
@client = double('client')
allow(Puppet::FileBucket::Dipper).to receive(:new).and_return(@client)
@filebucket.setup
end
it "should use the first non-option parameter as the dispatch" do
allow(@filebucket.command_line).to receive(:args).and_return(['get'])
expect(@filebucket).to receive(:get)
@filebucket.run_command
end
describe "the command get" do
before :each do
allow(@filebucket).to receive(:print)
allow(@filebucket).to receive(:args).and_return([])
end
it "should call the client getfile method" do
expect(@client).to receive(:getfile)
@filebucket.get
end
it "should call the client getfile method with the given digest" do
digest = 'DEADBEEF'
allow(@filebucket).to receive(:args).and_return([digest])
expect(@client).to receive(:getfile).with(digest)
@filebucket.get
end
it "should print the file content" do
allow(@client).to receive(:getfile).and_return("content")
expect(@filebucket).to receive(:print).and_return("content")
@filebucket.get
end
end
describe "the command backup" do
it "should fail if no arguments are specified" do
allow(@filebucket).to receive(:args).and_return([])
expect { @filebucket.backup }.to raise_error(RuntimeError, /You must specify a file to back up/)
end
it "should call the client backup method for each given parameter" do
allow(@filebucket).to receive(:puts)
allow(Puppet::FileSystem).to receive(:exist?).and_return(true)
allow(FileTest).to receive(:readable?).and_return(true)
allow(@filebucket).to receive(:args).and_return(["file1", "file2"])
expect(@client).to receive(:backup).with("file1")
expect(@client).to receive(:backup).with("file2")
@filebucket.backup
end
end
describe "the command restore" do
it "should call the client getfile method with the given digest" do
digest = 'DEADBEEF'
file = 'testfile'
allow(@filebucket).to receive(:args).and_return([file, digest])
expect(@client).to receive(:restore).with(file, digest)
@filebucket.restore
end
end
describe "the command diff" do
it "should call the client diff method with 2 given checksums" do
digest_a = 'DEADBEEF'
digest_b = 'BEEF'
allow(Puppet::FileSystem).to receive(:exist?).and_return(false)
allow(@filebucket).to receive(:args).and_return([digest_a, digest_b])
expect(@client).to receive(:diff).with(digest_a, digest_b, nil, nil)
@filebucket.diff
end
it "should call the client diff with a path if the second argument is a file" do
digest_a = 'DEADBEEF'
digest_b = 'BEEF'
allow(Puppet::FileSystem).to receive(:exist?).with(digest_a).and_return(false)
allow(Puppet::FileSystem).to receive(:exist?).with(digest_b).and_return(true)
allow(@filebucket).to receive(:args).and_return([digest_a, digest_b])
expect(@client).to receive(:diff).with(digest_a, nil, nil, digest_b)
@filebucket.diff
end
it "should call the client diff with a path if the first argument is a file" do
digest_a = 'DEADBEEF'
digest_b = 'BEEF'
allow(Puppet::FileSystem).to receive(:exist?).with(digest_a).and_return(true)
allow(Puppet::FileSystem).to receive(:exist?).with(digest_b).and_return(false)
allow(@filebucket).to receive(:args).and_return([digest_a, digest_b])
expect(@client).to receive(:diff).with(nil, digest_b, digest_a, nil)
@filebucket.diff
end
it "should call the clien diff with paths if the both arguments are files" do
digest_a = 'DEADBEEF'
digest_b = 'BEEF'
allow(Puppet::FileSystem).to receive(:exist?).with(digest_a).and_return(true)
allow(Puppet::FileSystem).to receive(:exist?).with(digest_b).and_return(true)
allow(@filebucket).to receive(:args).and_return([digest_a, digest_b])
expect(@client).to receive(:diff).with(nil, nil, digest_a, digest_b)
@filebucket.diff
end
it "should fail if only one checksum is given" do
digest_a = 'DEADBEEF'
allow(@filebucket).to receive(:args).and_return([digest_a])
expect { @filebucket.diff }.to raise_error Puppet::Error
end
end
describe "the command list" do
it "should call the client list method with nil dates" do
expect(@client).to receive(:list).with(nil, nil)
@filebucket.list
end
it "should call the client list method with the given dates" do
# 3 Hours ago
threehours = 60*60*3
fromdate = (Time.now - threehours).strftime("%F %T")
# 1 Hour ago
onehour = 60*60
todate = (Time.now - onehour).strftime("%F %T")
allow(@filebucket.options).to receive(:[]).with(:fromdate).and_return(fromdate)
allow(@filebucket.options).to receive(:[]).with(:todate).and_return(todate)
expect(@client).to receive(:list).with(fromdate, todate)
@filebucket.list
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/application/indirection_base_spec.rb | spec/unit/application/indirection_base_spec.rb | require 'spec_helper'
require 'puppet/util/command_line'
require 'puppet/application/indirection_base'
require 'puppet/indirector/face'
########################################################################
# Stub for testing; the names are critical, sadly. --daniel 2011-03-30
class Puppet::Application::TestIndirection < Puppet::Application::IndirectionBase
end
########################################################################
describe Puppet::Application::IndirectionBase do
before :all do
@face = Puppet::Indirector::Face.define(:test_indirection, '0.0.1') do
summary "fake summary"
copyright "Puppet Labs", 2011
license "Apache 2 license; see COPYING"
end
# REVISIT: This horror is required because we don't allow anything to be
# :current except for if it lives on, and is loaded from, disk. --daniel 2011-03-29
@face.instance_variable_set('@version', :current)
Puppet::Face.register(@face)
end
after :all do
# Delete the face so that it doesn't interfere with other specs
Puppet::Interface::FaceCollection.instance_variable_get(:@faces).delete Puppet::Interface::FaceCollection.underscorize(@face.name)
end
it "should accept a terminus command line option" do
# It would be nice not to have to stub this, but whatever... writing an
# entire indirection stack would cause us more grief. --daniel 2011-03-31
terminus = double("test indirection terminus")
allow(terminus).to receive(:name).and_return(:test_indirection)
allow(terminus).to receive(:terminus_class=)
allow(terminus).to receive(:save)
allow(terminus).to receive(:reset_terminus_class)
expect(Puppet::Indirector::Indirection).to receive(:instance).
with(:test_indirection).and_return(terminus)
command_line = Puppet::Util::CommandLine.new("puppet", %w{test_indirection --terminus foo save bar})
application = Puppet::Application::TestIndirection.new(command_line)
expect {
application.run
}.to exit_with 0
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/application/describe_spec.rb | spec/unit/application/describe_spec.rb | require 'spec_helper'
require 'puppet/application/describe'
describe Puppet::Application::Describe do
let(:describe) { Puppet::Application[:describe] }
it "lists all types" do
describe.command_line.args << '--list'
expect {
describe.run
}.to output(/These are the types known to puppet:/).to_stdout
end
it "describes a single type" do
describe.command_line.args << 'exec'
expect {
describe.run
}.to output(/exec.*====.*Executes external commands/m).to_stdout
end
it "describes multiple types" do
describe.command_line.args.concat(['exec', 'file'])
expect {
describe.run
}.to output(/Executes external commands.*Manages files, including their content, ownership, and permissions./m).to_stdout
end
it "describes parameters for the type by default" do
describe.command_line.args << 'exec'
expect {
describe.run
}.to output(/Parameters\n----------/m).to_stdout
end
it "lists parameter names, but excludes description in short mode" do
describe.command_line.args.concat(['exec', '-s'])
expect {
describe.run
}.to output(/Parameters.*command, creates, cwd/m).to_stdout
end
it "outputs providers for the type" do
describe.command_line.args.concat(['exec', '--providers'])
expect {
describe.run
}.to output(/Providers.*#{Regexp.escape('**posix**')}.*#{Regexp.escape('**windows**')}/m).to_stdout
end
it "lists metaparameters for a type" do
describe.command_line.args.concat(['exec', '--meta'])
expect {
describe.run
}.to output(/Meta Parameters.*#{Regexp.escape('**notify**')}/m).to_stdout
end
it "outputs no documentation if the summary is missing" do
Puppet::Type.newtype(:describe_test) {}
describe.command_line.args << '--list'
expect {
describe.run
}.to output(/#{Regexp.escape("describe_test - .. no documentation ..")}/).to_stdout
end
it "outputs the first short sentence ending in a dot" do
Puppet::Type.newtype(:describe_test) do
@doc = "ends in a dot."
end
describe.command_line.args << '--list'
expect {
describe.run
}.to output(/#{Regexp.escape("describe_test - ends in a dot\n")}/).to_stdout
end
it "outputs the first short sentence missing a dot" do
Puppet::Type.newtype(:describe_test) do
@doc = "missing a dot"
end
describe.command_line.args << '--list'
expect {
describe.run
}.to output(/describe_test - missing a dot\n/).to_stdout
end
it "truncates long summaries ending in a dot" do
Puppet::Type.newtype(:describe_test) do
@doc = "This sentence is more than 45 characters and ends in a dot."
end
describe.command_line.args << '--list'
expect {
describe.run
}.to output(/#{Regexp.escape("describe_test - This sentence is more than 45 characters and ...")}/).to_stdout
end
it "truncates long summaries missing a dot" do
Puppet::Type.newtype(:describe_test) do
@doc = "This sentence is more than 45 characters and is missing a dot"
end
describe.command_line.args << '--list'
expect {
describe.run
}.to output(/#{Regexp.escape("describe_test - This sentence is more than 45 characters and ...")}/).to_stdout
end
it "formats text with long non-space runs without garbling" do
f = Formatter.new(76)
teststring = <<TESTSTRING
. 12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890 nick@magpie.puppetlabs.lan
**this part should not repeat!**
TESTSTRING
expected_result = <<EXPECTED
.
1234567890123456789012345678901234567890123456789012345678901234567890123456
7890123456789012345678901234567890 nick@magpie.puppetlabs.lan
**this part should not repeat!**
EXPECTED
result = f.wrap(teststring, {:indent => 0, :scrub => true})
expect(result).to eql(expected_result)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/application/facts_spec.rb | spec/unit/application/facts_spec.rb | require 'spec_helper'
require 'puppet/application/facts'
describe Puppet::Application::Facts do
let(:app) { Puppet::Application[:facts] }
let(:values) { {"filesystems" => "apfs,autofs,devfs", "macaddress" => "64:52:11:22:03:2e"} }
before :each do
Puppet::Node::Facts.indirection.terminus_class = :memory
end
it "returns facts for a given node" do
facts = Puppet::Node::Facts.new('whatever', values)
Puppet::Node::Facts.indirection.save(facts)
app.command_line.args = %w{find whatever --render-as yaml}
# due to PUP-10105 we emit the class tag when we shouldn't
expected = Regexp.new(<<~END)
--- !ruby/object:Puppet::Node::Facts
name: whatever
values:
filesystems: apfs,autofs,devfs
macaddress: "64:52:11:22:03:2e"
END
expect {
app.run
}.to exit_with(0)
.and output(expected).to_stdout
end
it "returns facts for the current node when the name is omitted" do
facts = Puppet::Node::Facts.new(Puppet[:certname], values)
Puppet::Node::Facts.indirection.save(facts)
app.command_line.args = %w{find --render-as yaml}
# due to PUP-10105 we emit the class tag when we shouldn't
expected = Regexp.new(<<~END)
--- !ruby/object:Puppet::Node::Facts
name: #{Puppet[:certname]}
values:
filesystems: apfs,autofs,devfs
macaddress: "64:52:11:22:03:2e"
END
expect {
app.run
}.to exit_with(0)
.and output(expected).to_stdout
end
context 'when show action is called' do
let(:expected) { <<~END }
{
"filesystems": "apfs,autofs,devfs",
"macaddress": "64:52:11:22:03:2e",
"implementation": "#{Puppet.implementation}",
"clientcert": "#{Puppet.settings[:certname]}",
"clientversion": "#{Puppet.version}",
"clientnoop": false
}
END
before :each do
Puppet::Node::Facts.indirection.terminus_class = :facter
allow(Facter).to receive(:resolve).and_return(values)
app.command_line.args = %w{show}
end
it 'correctly displays facts with default formatting' do
expect {
app.run
}.to exit_with(0)
.and output(expected).to_stdout
end
it 'displays a single fact value' do
app.command_line.args << 'filesystems' << '--value-only'
expect {
app.run
}.to exit_with(0)
.and output("apfs,autofs,devfs\n").to_stdout
end
it "warns and ignores value-only when multiple fact names are specified" do
app.command_line.args << 'filesystems' << 'macaddress' << 'implementation' << 'clientcert' << 'clientversion' << 'clientnoop' << '--value-only'
expect {
app.run
}.to exit_with(0)
.and output(expected).to_stdout
.and output(/it can only be used when querying for a single fact/).to_stderr
end
{
"type_hash" => [{'a' => 2}, "{\n \"a\": 2\n}"],
"type_empty_hash" => [{}, "{\n}"],
"type_array" => [[], "[\n\n]"],
"type_string" => ["str", "str"],
"type_int" => [1, "1"],
"type_float" => [1.0, "1.0"],
"type_true" => [true, "true"],
"type_false" => [false, "false"],
"type_nil" => [nil, ""],
"type_sym" => [:sym, "sym"]
}.each_pair do |name, values|
it "renders '#{name}' as '#{values.last}'" do
fact_value = values.first
fact_output = values.last
allow(Facter).to receive(:resolve).and_return({name => fact_value})
app.command_line.args << name << '--value-only'
expect {
app.run
}.to exit_with(0)
.and output("#{fact_output}\n").to_stdout
end
end
end
context 'when default action is called' do
let(:expected) { <<~END }
---
filesystems: apfs,autofs,devfs
macaddress: 64:52:11:22:03:2e
implementation: #{Puppet.implementation}
clientcert: #{Puppet.settings[:certname]}
clientversion: #{Puppet.version}
clientnoop: false
END
before :each do
Puppet::Node::Facts.indirection.terminus_class = :facter
allow(Facter).to receive(:resolve).and_return(values)
app.command_line.args = %w{--render-as yaml}
end
it 'calls show action' do
expect {
app.run
}.to exit_with(0)
.and output(expected).to_stdout
expect(app.action.name).to eq(:show)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/application/ssl_spec.rb | spec/unit/application/ssl_spec.rb | require 'spec_helper'
require 'puppet/application/ssl'
require 'openssl'
require 'puppet/test_ca'
describe Puppet::Application::Ssl, unless: Puppet::Util::Platform.jruby? do
include PuppetSpec::Files
let(:ssl) do
app = Puppet::Application[:ssl]
app.options[:verbose] = true
app.setup_logs
app
end
let(:name) { 'ssl-client' }
before :all do
@ca = Puppet::TestCa.new
@ca_cert = @ca.ca_cert
@crl = @ca.ca_crl
@host = @ca.generate('ssl-client', {})
end
before do
Puppet.settings.use(:main)
Puppet[:certname] = name
Puppet[:vardir] = tmpdir("ssl_testing")
# Host assumes ca cert and crl are present
File.write(Puppet[:localcacert], @ca_cert.to_pem)
File.write(Puppet[:hostcrl], @crl.to_pem)
# Setup our ssl client
File.write(Puppet[:hostprivkey], @host[:private_key].to_pem)
File.write(Puppet[:hostpubkey], @host[:private_key].public_key.to_pem)
end
def expects_command_to_pass(expected_output = nil)
expect {
ssl.run_command
}.to output(expected_output).to_stdout
end
def expects_command_to_fail(message)
expect {
expect {
ssl.run_command
}.to raise_error(Puppet::Error, message)
}.to output(/.*/).to_stdout
end
shared_examples_for 'an ssl action' do
it 'downloads the CA bundle first when missing' do
File.delete(Puppet[:localcacert])
stub_request(:get, %r{puppet-ca/v1/certificate/ca}).to_return(status: 200, body: @ca.ca_cert.to_pem)
stub_request(:put, %r{puppet-ca/v1/certificate_request/#{name}}).to_return(status: 200)
stub_request(:get, %r{puppet-ca/v1/certificate/#{name}}).to_return(status: 200, body: @host[:cert].to_pem)
expects_command_to_pass
expect(File.read(Puppet[:localcacert])).to eq(@ca.ca_cert.to_pem)
end
it 'downloads the CRL bundle first when missing' do
File.delete(Puppet[:hostcrl])
stub_request(:get, %r{puppet-ca/v1/certificate_revocation_list/ca}).to_return(status: 200, body: @crl.to_pem)
stub_request(:put, %r{puppet-ca/v1/certificate_request/#{name}}).to_return(status: 200)
stub_request(:get, %r{puppet-ca/v1/certificate/#{name}}).to_return(status: 200, body: @host[:cert].to_pem)
expects_command_to_pass
expect(File.read(Puppet[:hostcrl])).to eq(@crl.to_pem)
end
end
it 'uses the agent run mode' do
# make sure the ssl app resolves certname, server, etc
# the same way the agent application does
expect(ssl.class.run_mode.name).to eq(:agent)
end
context 'when generating help' do
it 'prints a message when an unknown action is specified' do
ssl.command_line.args << 'whoops'
expects_command_to_fail(/Unknown action 'whoops'/)
end
it 'prints a message requiring an action to be specified' do
expects_command_to_fail(/An action must be specified/)
end
end
context 'when submitting a CSR' do
let(:csr_path) { Puppet[:hostcsr] }
before do
ssl.command_line.args << 'submit_request'
end
it_behaves_like 'an ssl action'
it 'generates an RSA private key' do
File.unlink(Puppet[:hostprivkey])
stub_request(:put, %r{puppet-ca/v1/certificate_request/#{name}}).to_return(status: 200)
stub_request(:get, %r{puppet-ca/v1/certificate/#{name}}).to_return(status: 404)
expects_command_to_pass(%r{Submitted certificate request for '#{name}' to https://.*})
end
it 'generates an EC private key' do
Puppet[:key_type] = 'ec'
File.unlink(Puppet[:hostprivkey])
stub_request(:put, %r{puppet-ca/v1/certificate_request/#{name}}).to_return(status: 200)
stub_request(:get, %r{puppet-ca/v1/certificate/#{name}}).to_return(status: 404)
expects_command_to_pass(%r{Submitted certificate request for '#{name}' to https://.*})
end
it 'registers OIDs' do
stub_request(:put, %r{puppet-ca/v1/certificate_request/#{name}}).to_return(status: 200)
stub_request(:get, %r{puppet-ca/v1/certificate/#{name}}).to_return(status: 404)
expect(Puppet::SSL::Oids).to receive(:register_puppet_oids)
expects_command_to_pass(%r{Submitted certificate request for '#{name}' to https://.*})
end
it 'submits the CSR and saves it locally' do
stub_request(:put, %r{puppet-ca/v1/certificate_request/#{name}}).to_return(status: 200)
stub_request(:get, %r{puppet-ca/v1/certificate/#{name}}).to_return(status: 404)
expects_command_to_pass(%r{Submitted certificate request for '#{name}' to https://.*})
expect(Puppet::FileSystem).to be_exist(csr_path)
end
it 'detects when a CSR with the same public key has already been submitted' do
stub_request(:put, %r{puppet-ca/v1/certificate_request/#{name}}).to_return(status: 200)
stub_request(:get, %r{puppet-ca/v1/certificate/#{name}}).to_return(status: 404)
expects_command_to_pass(%r{Submitted certificate request for '#{name}' to https://.*})
stub_request(:get, %r{puppet-ca/v1/certificate/#{name}}).to_return(status: 404)
expects_command_to_pass
end
it 'downloads the certificate when autosigning is enabled' do
stub_request(:put, %r{puppet-ca/v1/certificate_request/#{name}}).to_return(status: 200)
stub_request(:get, %r{puppet-ca/v1/certificate/#{name}}).to_return(status: 200, body: @host[:cert].to_pem)
expects_command_to_pass(%r{Submitted certificate request for '#{name}' to https://.*})
expect(Puppet::FileSystem).to be_exist(Puppet[:hostcert])
expect(Puppet::FileSystem).to_not be_exist(csr_path)
end
it 'accepts dns alt names' do
Puppet[:dns_alt_names] = 'majortom'
stub_request(:put, %r{puppet-ca/v1/certificate_request/#{name}}).to_return(status: 200)
stub_request(:get, %r{puppet-ca/v1/certificate/#{name}}).to_return(status: 404)
expects_command_to_pass
csr = Puppet::SSL::CertificateRequest.new(name)
csr.read(csr_path)
expect(csr.subject_alt_names).to include('DNS:majortom')
end
end
context 'when generating a CSR' do
let(:csr_path) { Puppet[:hostcsr] }
let(:requestdir) { Puppet[:requestdir] }
before do
ssl.command_line.args << 'generate_request'
end
it 'generates an RSA private key' do
File.unlink(Puppet[:hostprivkey])
expects_command_to_pass(%r{Generated certificate request in '#{csr_path}'})
end
it 'generates an EC private key' do
Puppet[:key_type] = 'ec'
File.unlink(Puppet[:hostprivkey])
expects_command_to_pass(%r{Generated certificate request in '#{csr_path}'})
end
it 'registers OIDs' do
expect(Puppet::SSL::Oids).to receive(:register_puppet_oids)
expects_command_to_pass(%r{Generated certificate request in '#{csr_path}'})
end
it 'saves the CSR locally' do
expects_command_to_pass(%r{Generated certificate request in '#{csr_path}'})
expect(Puppet::FileSystem).to be_exist(csr_path)
end
it 'accepts dns alt names' do
Puppet[:dns_alt_names] = 'majortom'
expects_command_to_pass
csr = Puppet::SSL::CertificateRequest.new(name)
csr.read(csr_path)
expect(csr.subject_alt_names).to include('DNS:majortom')
end
end
context 'when downloading a certificate' do
before do
ssl.command_line.args << 'download_cert'
end
it_behaves_like 'an ssl action'
it 'downloads a new cert' do
stub_request(:get, %r{puppet-ca/v1/certificate/#{name}}).to_return(status: 200, body: @host[:cert].to_pem)
expects_command_to_pass(%r{Downloaded certificate '#{name}' with fingerprint .*})
expect(File.read(Puppet[:hostcert])).to eq(@host[:cert].to_pem)
end
it 'overwrites an existing cert' do
File.write(Puppet[:hostcert], "existing certificate")
stub_request(:get, %r{puppet-ca/v1/certificate/#{name}}).to_return(status: 200, body: @host[:cert].to_pem)
expects_command_to_pass(%r{Downloaded certificate '#{name}' with fingerprint .*})
expect(File.read(Puppet[:hostcert])).to eq(@host[:cert].to_pem)
end
it "reports an error if the downloaded cert's public key doesn't match our private key" do
File.write(Puppet[:hostcert], "existing cert")
# generate a new host key, whose public key doesn't match the cert
private_key = OpenSSL::PKey::RSA.new(512)
File.write(Puppet[:hostprivkey], private_key.to_pem)
File.write(Puppet[:hostpubkey], private_key.public_key.to_pem)
stub_request(:get, %r{puppet-ca/v1/certificate/#{name}}).to_return(status: 200, body: @host[:cert].to_pem)
expects_command_to_fail(
%r{^Failed to download certificate: The certificate for 'CN=ssl-client' does not match its private key}
)
end
it "prints a message if there isn't a cert to download" do
stub_request(:get, %r{puppet-ca/v1/certificate/#{name}}).to_return(status: 404)
expects_command_to_fail(/The certificate for '#{name}' has not yet been signed/)
end
end
context 'when verifying' do
before do
ssl.command_line.args << 'verify'
File.write(Puppet[:hostcert], @host[:cert].to_pem)
end
it 'reports if the key is missing' do
File.delete(Puppet[:hostprivkey])
expects_command_to_fail(/The private key is missing from/)
end
it 'reports if the cert is missing' do
File.delete(Puppet[:hostcert])
expects_command_to_fail(/The client certificate is missing from/)
end
it 'reports if the key and cert are mismatched' do
# generate new keys
private_key = OpenSSL::PKey::RSA.new(512)
public_key = private_key.public_key
File.write(Puppet[:hostprivkey], private_key.to_pem)
File.write(Puppet[:hostpubkey], public_key.to_pem)
expects_command_to_fail(%r{The certificate for 'CN=ssl-client' does not match its private key})
end
it 'reports if the cert verification fails' do
# generate a new CA to force an error
new_ca = Puppet::TestCa.new
File.write(Puppet[:localcacert], new_ca.ca_cert.to_pem)
# and CRL for that CA
File.write(Puppet[:hostcrl], new_ca.ca_crl.to_pem)
expects_command_to_fail(%r{Invalid signature for certificate 'CN=ssl-client'})
end
it 'reports when verification succeeds' do
expects_command_to_pass(%r{Verified client certificate 'CN=ssl-client' fingerprint})
end
it 'reports when verification succeeds with a password protected private key' do
FileUtils.cp(File.join(PuppetSpec::FIXTURE_DIR, 'ssl', 'encrypted-key.pem'), Puppet[:hostprivkey])
FileUtils.cp(File.join(PuppetSpec::FIXTURE_DIR, 'ssl', 'signed.pem'), Puppet[:hostcert])
# To verify the client cert we need the root and intermediate certs and crls.
# We don't need to do this with `ssl-client` cert above, because it is issued
# directly from the generated TestCa above.
File.open(Puppet[:localcacert], 'w') do |f|
f.write(File.read(File.join(PuppetSpec::FIXTURE_DIR, 'ssl', 'ca.pem')))
f.write(File.read(File.join(PuppetSpec::FIXTURE_DIR, 'ssl', 'intermediate.pem')))
end
File.open(Puppet[:hostcrl], 'w') do |f|
f.write(File.read(File.join(PuppetSpec::FIXTURE_DIR, 'ssl', 'crl.pem')))
f.write(File.read(File.join(PuppetSpec::FIXTURE_DIR, 'ssl', 'intermediate-crl.pem')))
end
Puppet[:passfile] = file_containing('passfile', '74695716c8b6')
expects_command_to_pass(%r{Verified client certificate 'CN=signed' fingerprint})
end
it 'reports if the private key password is incorrect' do
FileUtils.cp(File.join(PuppetSpec::FIXTURE_DIR, 'ssl', 'encrypted-key.pem'), Puppet[:hostprivkey])
FileUtils.cp(File.join(PuppetSpec::FIXTURE_DIR, 'ssl', 'signed.pem'), Puppet[:hostcert])
Puppet[:passfile] = file_containing('passfile', 'wrongpassword')
expects_command_to_fail(/Failed to load private key for host 'ssl-client'/)
end
end
context 'when cleaning' do
before do
ssl.command_line.args << 'clean'
end
it 'deletes the hostcert' do
File.write(Puppet[:hostcert], @host[:cert].to_pem)
expects_command_to_pass(%r{Removed certificate #{Puppet[:cert]}})
end
it 'deletes the private key' do
File.write(Puppet[:hostprivkey], @host[:private_key].to_pem)
expects_command_to_pass(%r{Removed private key #{Puppet[:hostprivkey]}})
end
it 'deletes the public key' do
File.write(Puppet[:hostpubkey], @host[:private_key].public_key.to_pem)
expects_command_to_pass(%r{Removed public key #{Puppet[:hostpubkey]}})
end
it 'deletes the request' do
path = Puppet[:hostcsr]
File.write(path, @host[:csr].to_pem)
expects_command_to_pass(%r{Removed certificate request #{path}})
end
it 'deletes the passfile' do
FileUtils.touch(Puppet[:passfile])
expects_command_to_pass(%r{Removed private key password file #{Puppet[:passfile]}})
end
it 'skips files that do not exist' do
File.delete(Puppet[:hostprivkey])
expect {
ssl.run_command
}.to_not output(%r{Removed private key #{Puppet[:hostprivkey]}}).to_stdout
end
it "raises if we fail to retrieve server's cert that we're about to clean" do
Puppet[:certname] = name
Puppet[:server] = name
stub_request(:get, %r{puppet-ca/v1/certificate/#{name}}).to_raise(Errno::ECONNREFUSED)
expects_command_to_fail(%r{Failed to connect to the CA to determine if certificate #{name} has been cleaned})
end
it 'raises if we have extra args' do
ssl.command_line.args << 'hostname.example.biz'
expects_command_to_fail(/Extra arguments detected: hostname.example.biz/)
end
context 'when deleting local CA' do
before do
ssl.command_line.args << '--localca'
ssl.parse_options
end
it 'deletes the local CA cert' do
File.write(Puppet[:localcacert], @ca_cert.to_pem)
expects_command_to_pass(%r{Removed local CA certificate #{Puppet[:localcacert]}})
end
it 'deletes the local CRL' do
File.write(Puppet[:hostcrl], @crl.to_pem)
expects_command_to_pass(%r{Removed local CRL #{Puppet[:hostcrl]}})
end
end
context 'on the puppetserver host' do
before :each do
Puppet[:certname] = 'puppetserver'
Puppet[:server] = 'puppetserver'
end
it "prints an error when the CA is local and the CA has not cleaned its cert" do
stub_request(:get, %r{puppet-ca/v1/certificate/puppetserver}).to_return(status: 200, body: @host[:cert].to_pem)
expects_command_to_fail(%r{The certificate puppetserver must be cleaned from the CA first})
end
it "cleans the cert when the CA is local and the CA has already cleaned its cert" do
File.write(Puppet[:hostcert], @host[:cert].to_pem)
stub_request(:get, %r{puppet-ca/v1/certificate/puppetserver}).to_return(status: 404)
expects_command_to_pass(%r{Removed certificate .*puppetserver.pem})
end
it "cleans the cert when run on a puppetserver that isn't the CA" do
File.write(Puppet[:hostcert], @host[:cert].to_pem)
Puppet[:ca_server] = 'caserver'
expects_command_to_pass(%r{Removed certificate .*puppetserver.pem})
end
end
context 'when cleaning a device' do
before do
ssl.command_line.args = ['clean', '--target', 'device.example.com']
ssl.parse_options
end
it 'deletes the device certificate' do
device_cert_path = File.join(Puppet[:devicedir], 'device.example.com', 'ssl', 'certs')
device_cert_file = File.join(device_cert_path, 'device.example.com.pem')
FileUtils.mkdir_p(device_cert_path)
File.write(device_cert_file, 'device.example.com')
expects_command_to_pass(%r{Removed certificate #{device_cert_file}})
end
end
end
context 'when bootstrapping' do
before do
ssl.command_line.args << 'bootstrap'
end
it 'registers the OIDs' do
expect_any_instance_of(Puppet::SSL::StateMachine).to receive(:ensure_client_certificate).and_return(
double('ssl_context')
)
expect(Puppet::SSL::Oids).to receive(:register_puppet_oids)
expects_command_to_pass
end
it 'returns an SSLContext with the loaded CA certs, CRLs, private key and client cert' do
expect_any_instance_of(Puppet::SSL::StateMachine).to receive(:ensure_client_certificate).and_return(
double('ssl_context')
)
expects_command_to_pass
end
end
context 'when showing' do
before do
ssl.command_line.args << 'show'
File.write(Puppet[:hostcert], @host[:cert].to_pem)
end
it 'reports if the key is missing' do
File.delete(Puppet[:hostprivkey])
expects_command_to_fail(/The private key is missing from/)
end
it 'reports if the cert is missing' do
File.delete(Puppet[:hostcert])
expects_command_to_fail(/The client certificate is missing from/)
end
it 'prints certificate information' do
expects_command_to_pass(@host[:cert].to_text)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/application/lookup_spec.rb | spec/unit/application/lookup_spec.rb | require 'spec_helper'
require 'puppet/application/lookup'
require 'puppet/pops/lookup'
describe Puppet::Application::Lookup do
def run_lookup(lookup)
capture = StringIO.new
saved_stdout = $stdout
begin
$stdout = capture
expect { lookup.run_command }.to exit_with(0)
ensure
$stdout = saved_stdout
end
# Drop end of line and an optional yaml end of document
capture.string.gsub(/\n(\.\.\.\n)?\Z/m, '')
end
context "when running with incorrect command line options" do
let (:lookup) { Puppet::Application[:lookup] }
it "errors if no keys are given via the command line" do
lookup.options[:node] = 'dantooine.local'
expected_error = "No keys were given to lookup."
expect { lookup.run_command }.to raise_error(RuntimeError, expected_error)
end
it "does not allow invalid arguments for '--merge'" do
lookup.options[:node] = 'dantooine.local'
lookup.options[:merge] = 'something_bad'
allow(lookup.command_line).to receive(:args).and_return(['atton', 'kreia'])
expected_error = "The --merge option only accepts 'first', 'hash', 'unique', or 'deep'\nRun 'puppet lookup --help' for more details"
expect { lookup.run_command }.to raise_error(RuntimeError, expected_error)
end
it "does not allow deep merge options if '--merge' was not set to deep" do
lookup.options[:node] = 'dantooine.local'
lookup.options[:merge_hash_arrays] = true
lookup.options[:merge] = 'hash'
allow(lookup.command_line).to receive(:args).and_return(['atton', 'kreia'])
expected_error = "The options --knock-out-prefix, --sort-merged-arrays, and --merge-hash-arrays are only available with '--merge deep'\nRun 'puppet lookup --help' for more details"
expect { lookup.run_command }.to raise_error(RuntimeError, expected_error)
end
end
context "when running with correct command line options" do
let (:lookup) { Puppet::Application[:lookup] }
it "calls the lookup method with the correct arguments" do
lookup.options[:node] = 'dantooine.local'
lookup.options[:render_as] = :s;
lookup.options[:merge_hash_arrays] = true
lookup.options[:merge] = 'deep'
allow(lookup.command_line).to receive(:args).and_return(['atton', 'kreia'])
allow(lookup).to receive(:generate_scope).and_yield('scope')
expected_merge = { "strategy" => "deep", "sort_merged_arrays" => false, "merge_hash_arrays" => true }
expect(Puppet::Pops::Lookup).to receive(:lookup).with(['atton', 'kreia'], nil, nil, false, expected_merge, anything).and_return('rand')
expect(run_lookup(lookup)).to eql("rand")
end
%w(first unique hash deep).each do |opt|
it "accepts --merge #{opt}" do
lookup.options[:node] = 'dantooine.local'
lookup.options[:merge] = opt
lookup.options[:render_as] = :s
allow(lookup.command_line).to receive(:args).and_return(['atton', 'kreia'])
allow(lookup).to receive(:generate_scope).and_yield('scope')
allow(Puppet::Pops::Lookup).to receive(:lookup).and_return('rand')
expect(run_lookup(lookup)).to eql("rand")
end
end
it "prints the value found by lookup" do
lookup.options[:node] = 'dantooine.local'
lookup.options[:render_as] = :s
allow(lookup.command_line).to receive(:args).and_return(['atton', 'kreia'])
allow(lookup).to receive(:generate_scope).and_yield('scope')
allow(Puppet::Pops::Lookup).to receive(:lookup).and_return('rand')
expect(run_lookup(lookup)).to eql("rand")
end
end
context 'when given a valid configuration' do
let (:lookup) { Puppet::Application[:lookup] }
# There is a fully configured 'sample' environment in fixtures at this location
let(:environmentpath) { File.absolute_path(File.join(my_fixture_dir(), '../environments')) }
let(:facts) { Puppet::Node::Facts.new("facts", {}) }
let(:node) { Puppet::Node.new("testnode", :facts => facts, :environment => 'production') }
let(:expected_json_hash) {
{
'branches' =>
[
{
'branches'=>
[
{
'key'=>'lookup_options',
'event'=>'not_found',
'type'=>'data_provider',
'name'=>'Global Data Provider (hiera configuration version 5)'
},
{
'branches'=>
[
{
'branches'=>
[
{
'key' => 'lookup_options',
'value' => {'a'=>'first'},
'event'=>'found',
'type'=>'path',
'original_path'=>'common.yaml',
'path'=>"#{environmentpath}/production/data/common.yaml"
}
],
'type'=>'data_provider',
'name'=>'Hierarchy entry "Common"'
}
],
'type'=>'data_provider',
'name'=>'Environment Data Provider (hiera configuration version 5)'
}
],
'key'=>'lookup_options',
'type'=>'root'
},
{
'branches'=>
[
{
'key'=>'a',
'event'=>'not_found',
'type'=>'data_provider',
'name'=>'Global Data Provider (hiera configuration version 5)'
},
{
'branches'=>
[
{
'branches'=>
[
{
'key'=>'a',
'value'=>'This is A',
'event'=>'found',
'type'=>'path',
'original_path'=>'common.yaml',
'path'=>"#{environmentpath}/production/data/common.yaml"
}
],
'type'=>'data_provider',
'name'=>'Hierarchy entry "Common"'
}
],
'type'=>'data_provider',
'name'=>'Environment Data Provider (hiera configuration version 5)'
}
],
'key'=>'a',
'type'=>'root'
}
]
}
}
let(:expected_yaml_hash) {
{
:branches =>
[
{
:branches=>
[
{
:key=>'lookup_options',
:event=>:not_found,
:type=>:data_provider,
:name=>'Global Data Provider (hiera configuration version 5)'
},
{
:branches=>
[
{
:branches=>
[
{
:key => 'lookup_options',
:value => {'a'=>'first'},
:event=>:found,
:type=>:path,
:original_path=>'common.yaml',
:path=>"#{environmentpath}/production/data/common.yaml"
}
],
:type=>:data_provider,
:name=>'Hierarchy entry "Common"'
}
],
:type=>:data_provider,
:name=>'Environment Data Provider (hiera configuration version 5)'
}
],
:key=>'lookup_options',
:type=>:root
},
{
:branches=>
[
{
:key=>'a',
:event=>:not_found,
:type=>:data_provider,
:name=>'Global Data Provider (hiera configuration version 5)'
},
{
:branches=>
[
{
:branches=>
[
{
:key=>'a',
:value=>'This is A',
:event=>:found,
:type=>:path,
:original_path=>'common.yaml',
:path=>"#{environmentpath}/production/data/common.yaml"
}
],
:type=>:data_provider,
:name=>'Hierarchy entry "Common"'
}
],
:type=>:data_provider,
:name=>'Environment Data Provider (hiera configuration version 5)'
}
],
:key=>'a',
:type=>:root
}
]
}
}
around(:each) do |example|
# Initialize settings to get a full compile as close as possible to a real
# environment load
Puppet.settings.initialize_global_settings
loader = Puppet::Environments::Directories.new(environmentpath, [])
Puppet.override(:environments => loader) do
example.run
end
end
it '--explain produces human readable text by default and does not produce output to debug logger' do
lookup.options[:node] = node
lookup.options[:explain] = true
allow(lookup.command_line).to receive(:args).and_return(['a'])
logs = []
Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do
expect(run_lookup(lookup)).to eql(<<-EXPLANATION.chomp)
Searching for "lookup_options"
Global Data Provider (hiera configuration version 5)
No such key: "lookup_options"
Environment Data Provider (hiera configuration version 5)
Hierarchy entry "Common"
Path "#{environmentpath}/production/data/common.yaml"
Original path: "common.yaml"
Found key: "lookup_options" value: {
"a" => "first"
}
Searching for "a"
Global Data Provider (hiera configuration version 5)
No such key: "a"
Environment Data Provider (hiera configuration version 5)
Hierarchy entry "Common"
Path "#{environmentpath}/production/data/common.yaml"
Original path: "common.yaml"
Found key: "a" value: "This is A"
EXPLANATION
end
expect(logs.any? { |log| log.level == :debug }).to be_falsey
end
it '--debug using multiple interpolation functions produces output to the logger' do
lookup.options[:node] = node
allow(lookup.command_line).to receive(:args).and_return(['ab'])
Puppet.debug = true
logs = []
begin
Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do
expect { lookup.run_command }.to output(<<-VALUE.unindent).to_stdout
--- This is A and This is B
...
VALUE
end
rescue SystemExit => e
expect(e.status).to eq(0)
end
logs = logs.select { |log| log.level == :debug }.map { |log| log.message }
expect(logs).to include(/Found key: "ab" value: "This is A and This is B"/)
end
it '--explain produces human readable text by default and --debug produces the same output to debug logger' do
lookup.options[:node] = node
lookup.options[:explain] = true
allow(lookup.command_line).to receive(:args).and_return(['a'])
Puppet.debug = true
logs = []
Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do
expect(run_lookup(lookup)).to eql(<<-EXPLANATION.chomp)
Searching for "lookup_options"
Global Data Provider (hiera configuration version 5)
No such key: "lookup_options"
Environment Data Provider (hiera configuration version 5)
Hierarchy entry "Common"
Path "#{environmentpath}/production/data/common.yaml"
Original path: "common.yaml"
Found key: "lookup_options" value: {
"a" => "first"
}
Searching for "a"
Global Data Provider (hiera configuration version 5)
No such key: "a"
Environment Data Provider (hiera configuration version 5)
Hierarchy entry "Common"
Path "#{environmentpath}/production/data/common.yaml"
Original path: "common.yaml"
Found key: "a" value: "This is A"
EXPLANATION
end
logs = logs.select { |log| log.level == :debug }.map { |log| log.message }
expect(logs).to include(<<-EXPLANATION.chomp)
Lookup of 'a'
Searching for "lookup_options"
Global Data Provider (hiera configuration version 5)
No such key: "lookup_options"
Environment Data Provider (hiera configuration version 5)
Hierarchy entry "Common"
Path "#{environmentpath}/production/data/common.yaml"
Original path: "common.yaml"
Found key: "lookup_options" value: {
"a" => "first"
}
Searching for "a"
Global Data Provider (hiera configuration version 5)
No such key: "a"
Environment Data Provider (hiera configuration version 5)
Hierarchy entry "Common"
Path "#{environmentpath}/production/data/common.yaml"
Original path: "common.yaml"
Found key: "a" value: "This is A"
EXPLANATION
end
it '--explain-options produces human readable text of a hash merge' do
lookup.options[:node] = node
lookup.options[:explain_options] = true
expect(run_lookup(lookup)).to eql(<<-EXPLANATION.chomp)
Merge strategy hash
Global Data Provider (hiera configuration version 5)
No such key: "lookup_options"
Environment Data Provider (hiera configuration version 5)
Hierarchy entry "Common"
Path "#{environmentpath}/production/data/common.yaml"
Original path: "common.yaml"
Found key: "lookup_options" value: {
"a" => "first"
}
Merged result: {
"a" => "first"
}
EXPLANATION
end
it '--explain-options produces human readable text of a hash merge and --debug produces the same output to debug logger' do
lookup.options[:node] = node
lookup.options[:explain_options] = true
Puppet.debug = true
logs = []
Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do
expect(run_lookup(lookup)).to eql(<<-EXPLANATION.chomp)
Merge strategy hash
Global Data Provider (hiera configuration version 5)
No such key: "lookup_options"
Environment Data Provider (hiera configuration version 5)
Hierarchy entry "Common"
Path "#{environmentpath}/production/data/common.yaml"
Original path: "common.yaml"
Found key: "lookup_options" value: {
"a" => "first"
}
Merged result: {
"a" => "first"
}
EXPLANATION
logs = logs.select { |log| log.level == :debug }.map { |log| log.message }
expect(logs).to include(<<-EXPLANATION.chomp)
Lookup of '__global__'
Merge strategy hash
Global Data Provider (hiera configuration version 5)
No such key: "lookup_options"
Environment Data Provider (hiera configuration version 5)
Hierarchy entry "Common"
Path "#{environmentpath}/production/data/common.yaml"
Original path: "common.yaml"
Found key: "lookup_options" value: {
"a" => "first"
}
Merged result: {
"a" => "first"
}
EXPLANATION
end
end
it '--explain produces human readable text of a hash merge when using both --explain and --explain-options' do
lookup.options[:node] = node
lookup.options[:explain] = true
lookup.options[:explain_options] = true
allow(lookup.command_line).to receive(:args).and_return(['a'])
expect(run_lookup(lookup)).to eql(<<-EXPLANATION.chomp)
Searching for "lookup_options"
Global Data Provider (hiera configuration version 5)
No such key: "lookup_options"
Environment Data Provider (hiera configuration version 5)
Hierarchy entry "Common"
Path "#{environmentpath}/production/data/common.yaml"
Original path: "common.yaml"
Found key: "lookup_options" value: {
"a" => "first"
}
Searching for "a"
Global Data Provider (hiera configuration version 5)
No such key: "a"
Environment Data Provider (hiera configuration version 5)
Hierarchy entry "Common"
Path "#{environmentpath}/production/data/common.yaml"
Original path: "common.yaml"
Found key: "a" value: "This is A"
EXPLANATION
end
it 'can produce a yaml explanation' do
lookup.options[:node] = node
lookup.options[:explain] = true
lookup.options[:render_as] = :yaml
allow(lookup.command_line).to receive(:args).and_return(['a'])
output = run_lookup(lookup)
expect(Puppet::Util::Yaml.safe_load(output, [Symbol])).to eq(expected_yaml_hash)
end
it 'can produce a json explanation' do
lookup.options[:node] = node
lookup.options[:explain] = true
lookup.options[:render_as] = :json
allow(lookup.command_line).to receive(:args).and_return(['a'])
output = run_lookup(lookup)
expect(JSON.parse(output)).to eq(expected_json_hash)
end
it 'can access values using dotted keys' do
lookup.options[:node] = node
lookup.options[:render_as] = :json
allow(lookup.command_line).to receive(:args).and_return(['d.one.two.three'])
output = run_lookup(lookup)
expect(JSON.parse("[#{output}]")).to eq(['the value'])
end
it 'can access values using quoted dotted keys' do
lookup.options[:node] = node
lookup.options[:render_as] = :json
allow(lookup.command_line).to receive(:args).and_return(['"e.one.two.three"'])
output = run_lookup(lookup)
expect(JSON.parse("[#{output}]")).to eq(['the value'])
end
it 'can access values using mix of dotted keys and quoted dotted keys' do
lookup.options[:node] = node
lookup.options[:render_as] = :json
allow(lookup.command_line).to receive(:args).and_return(['"f.one"."two.three".1'])
output = run_lookup(lookup)
expect(JSON.parse("[#{output}]")).to eq(['second value'])
end
context 'the global scope' do
include PuppetSpec::Files
it "is unaffected by global variables unless '--compile' is used" do
# strict mode is off so behavior this test is trying to check isn't stubbed out
Puppet[:strict_variables] = false
Puppet[:strict] = :warning
lookup.options[:node] = node
lookup.options[:render_as] = :s
allow(lookup.command_line).to receive(:args).and_return(['c'])
expect(run_lookup(lookup)).to eql("This is")
end
it "is affected by global variables when '--compile' is used" do
lookup.options[:node] = node
lookup.options[:compile] = true
lookup.options[:render_as] = :s
allow(lookup.command_line).to receive(:args).and_return(['c'])
expect(run_lookup(lookup)).to eql("This is C from site.pp")
end
it 'receives extra facts in top scope' do
file_path = file_containing('facts.yaml', <<~CONTENT)
---
cx: ' C from facts'
CONTENT
lookup.options[:node] = node
lookup.options[:fact_file] = file_path
lookup.options[:render_as] = :s
allow(lookup.command_line).to receive(:args).and_return(['c'])
expect(run_lookup(lookup)).to eql("This is C from facts")
end
it 'receives extra facts in the facts hash' do
file_path = file_containing('facts.yaml', <<~CONTENT)
---
cx: ' G from facts'
CONTENT
lookup.options[:node] = node
lookup.options[:fact_file] = file_path
lookup.options[:render_as] = :s
allow(lookup.command_line).to receive(:args).and_return(['g'])
expect(run_lookup(lookup)).to eql("This is G from facts in facts hash")
end
it 'looks up server facts' do
lookup.options[:node] = node
lookup.options[:render_as] = :s
allow(lookup.command_line).to receive(:args).and_return(['h'])
expect(run_lookup(lookup)).to eql("server version is #{Puppet.version}")
end
describe 'when retrieving given facts' do
before do
lookup.options[:node] = node
allow(lookup.command_line).to receive(:args).and_return(['g'])
end
it 'loads files with yaml extension as yaml on first try' do
file_path = file_containing('facts.yaml', <<~CONTENT)
---
cx: ' G from facts'
CONTENT
lookup.options[:fact_file] = file_path
expect(Puppet::Util::Yaml).to receive(:safe_load_file).with(file_path, []).and_call_original
run_lookup(lookup)
end
it 'loads files with yml extension as yaml on first try' do
file_path = file_containing('facts.yml', <<~CONTENT)
---
cx: ' G from facts'
CONTENT
lookup.options[:fact_file] = file_path
expect(Puppet::Util::Yaml).to receive(:safe_load_file).with(file_path, []).and_call_original
run_lookup(lookup)
end
it 'loads files with json extension as json on first try' do
file_path = file_containing('facts.json', <<~CONTENT)
{
"cx": " G from facts"
}
CONTENT
lookup.options[:fact_file] = file_path
expect(Puppet::Util::Json).to receive(:load_file).with(file_path, {}).and_call_original
run_lookup(lookup)
end
it 'detects file format accordingly even with random file extension' do
file_path = file_containing('facts.txt', <<~CONTENT)
{
"cx": " G from facts"
}
CONTENT
lookup.options[:fact_file] = file_path
expect(Puppet::Util::Json).to receive(:load_file_if_valid).with(file_path).and_call_original
expect(Puppet::Util::Yaml).not_to receive(:safe_load_file_if_valid).with(file_path)
run_lookup(lookup)
end
it 'detects file without extension as json due to valid contents' do
file_path = file_containing('facts', <<~CONTENT)
{
"cx": " G from facts"
}
CONTENT
lookup.options[:fact_file] = file_path
expect(Puppet::Util::Json).to receive(:load_file_if_valid).with(file_path).and_call_original
expect(Puppet::Util::Yaml).not_to receive(:safe_load_file_if_valid).with(file_path)
run_lookup(lookup)
end
it 'detects file without extension as yaml due to valid contents' do
file_path = file_containing('facts', <<~CONTENT)
---
cx: ' G from facts'
CONTENT
lookup.options[:fact_file] = file_path
expect(Puppet::Util::Json.load_file_if_valid(file_path)).to be_nil
expect(Puppet::Util::Yaml).to receive(:safe_load_file_if_valid).with(file_path).and_call_original
run_lookup(lookup)
end
it 'raises error due to invalid contents' do
file_path = file_containing('facts.yml', <<~CONTENT)
INVALID CONTENT
CONTENT
lookup.options[:fact_file] = file_path
expect {
lookup.run_command
}.to raise_error(/Incorrectly formatted data in .+ given via the --facts flag \(only accepts yaml and json files\)/)
end
it "fails when a node doesn't have facts" do
lookup.options[:node] = "bad.node"
allow(lookup.command_line).to receive(:args).and_return(['c'])
expected_error = "No facts available for target node: #{lookup.options[:node]}"
expect { lookup.run_command }.to raise_error(RuntimeError, expected_error)
end
it 'raises error due to missing trusted information facts in --facts file' do
file_path = file_containing('facts.yaml', <<~CONTENT)
---
fqdn: some.fqdn.com
CONTENT
lookup.options[:fact_file] = file_path
expect {
lookup.run_command
}.to raise_error(/When overriding any of the hostname,domain,fqdn,clientcert facts with #{file_path} given via the --facts flag, they must all be overridden./)
end
it 'does not fail when all trusted information facts are provided via --facts file' do
file_path = file_containing('facts.yaml', <<~CONTENT)
---
fqdn: some.fqdn.com
hostname: some.hostname
domain: some.domain
clientcert: some.clientcert
CONTENT
lookup.options[:fact_file] = file_path
expect {
lookup.run_command
}.to exit_with(0)
.and output(/This is in facts hash/).to_stdout
end
end
end
context 'using a puppet function as data provider' do
let(:node) { Puppet::Node.new("testnode", :facts => facts, :environment => 'puppet_func_provider') }
it "works OK in the absense of '--compile'" do
# strict mode is off so behavior this test is trying to check isn't stubbed out
Puppet[:strict_variables] = false
Puppet[:strict] = :warning
lookup.options[:node] = node
allow(lookup.command_line).to receive(:args).and_return(['c'])
lookup.options[:render_as] = :s
expect(run_lookup(lookup)).to eql("This is C from data.pp")
end
it "global scope is affected by global variables when '--compile' is used" do
lookup.options[:node] = node
lookup.options[:compile] = true
lookup.options[:render_as] = :s
allow(lookup.command_line).to receive(:args).and_return(['c'])
expect(run_lookup(lookup)).to eql("This is C from site.pp")
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/application/config_spec.rb | spec/unit/application/config_spec.rb | # coding: utf-8
require 'spec_helper'
require 'puppet/application/config'
describe Puppet::Application::Config do
include PuppetSpec::Files
# different UTF-8 widths
# 1-byte A
# 2-byte ۿ - http://www.fileformat.info/info/unicode/char/06ff/index.htm - 0xDB 0xBF / 219 191
# 3-byte ᚠ - http://www.fileformat.info/info/unicode/char/16A0/index.htm - 0xE1 0x9A 0xA0 / 225 154 160
# 4-byte 𠜎 - http://www.fileformat.info/info/unicode/char/2070E/index.htm - 0xF0 0xA0 0x9C 0x8E / 240 160 156 142
MIXED_UTF8 = "A\u06FF\u16A0\u{2070E}" # Aۿᚠ𠜎
let(:app) { Puppet::Application[:config] }
before :each do
Puppet[:config] = tmpfile('config')
end
def initialize_app(args)
app.command_line.args = args
# ensure global defaults are initialized prior to app defaults
Puppet.initialize_settings(args)
end
def read_utf8(path)
File.read(path, :encoding => 'UTF-8')
end
def write_utf8(path, content)
File.write(path, content, 0, :encoding => 'UTF-8')
end
context "when printing" do
it "prints a value" do
initialize_app(%w[print certname])
expect {
app.run
}.to exit_with(0)
.and output(a_string_matching(Puppet[:certname])).to_stdout
end
it "prints a value from a section" do
File.write(Puppet[:config], <<~END)
[main]
external_nodes=none
[server]
external_nodes=exec
END
initialize_app(%w[print external_nodes --section server])
expect {
app.run
}.to exit_with(0)
.and output(a_string_matching('exec')).to_stdout
end
it "doesn't require the environment to exist" do
initialize_app(%w[print certname --environment doesntexist])
expect {
app.run
}.to exit_with(0)
.and output(a_string_matching(Puppet[:certname])).to_stdout
end
end
context "when setting" do
it "sets a value in its config file" do
initialize_app(%w[set certname www.example.com])
expect {
app.run
}.to exit_with(0)
expect(File.read(Puppet[:config])).to eq("[main]\ncertname = www.example.com\n")
end
it "sets a value in the server section" do
initialize_app(%w[set external_nodes exec --section server])
expect {
app.run
}.to exit_with(0)
expect(File.read(Puppet[:config])).to eq("[server]\nexternal_nodes = exec\n")
end
{
%w[certname WWW.EXAMPLE.COM] => /Certificate names must be lower case/,
%w[log_level all] => /Invalid loglevel all/,
%w[disable_warnings true] => /Cannot disable unrecognized warning types 'true'/,
%w[strict on] => /Invalid value 'on' for parameter strict/,
%w[digest_algorithm rot13] => /Invalid value 'rot13' for parameter digest_algorithm/,
%w[http_proxy_password a#b] => /Passwords set in the http_proxy_password setting must be valid as part of a URL/,
}.each_pair do |args, message|
it "rejects #{args.join(' ')}" do
initialize_app(['set', *args])
expect {
app.run
}.to exit_with(1)
.and output(message).to_stderr
end
end
it 'sets unknown settings' do
initialize_app(['set', 'notarealsetting', 'true'])
expect {
app.run
}.to exit_with(0)
expect(File.read(Puppet[:config])).to eq("[main]\nnotarealsetting = true\n")
end
end
context "when deleting" do
it "deletes a value" do
initialize_app(%w[delete external_nodes])
File.write(Puppet[:config], <<~END)
[main]
external_nodes=none
END
expect {
app.run
}.to exit_with(0)
.and output(/Deleted setting from 'main': 'external_nodes=none'/).to_stdout
expect(File.read(Puppet[:config])).to eq("[main]\n")
end
it "warns when deleting a value that isn't set" do
initialize_app(%w[delete external_nodes])
File.write(Puppet[:config], "")
expect {
app.run
}.to exit_with(0)
.and output(a_string_matching("Warning: No setting found in configuration file for section 'main' setting name 'external_nodes'")).to_stderr
expect(File.read(Puppet[:config])).to eq("")
end
it "deletes a value from main" do
initialize_app(%w[delete external_nodes])
File.write(Puppet[:config], <<~END)
[main]
external_nodes=none
END
expect {
app.run
}.to exit_with(0)
.and output(/Deleted setting from 'main': 'external_nodes=none'/).to_stdout
expect(File.read(Puppet[:config])).to eq("[main]\n")
end
it "deletes a value from main a section" do
initialize_app(%w[delete external_nodes --section server])
File.write(Puppet[:config], <<~END)
[main]
external_nodes=none
[server]
external_nodes=exec
END
expect {
app.run
}.to exit_with(0)
.and output(/Deleted setting from 'server': 'external_nodes'/).to_stdout
expect(File.read(Puppet[:config])).to eq("[main]\nexternal_nodes=none\n[server]\n")
end
end
context "when managing UTF-8 values" do
it "reads a UTF-8 value" do
write_utf8(Puppet[:config], <<~EOF)
[main]
tags=#{MIXED_UTF8}
EOF
initialize_app(%w[print tags])
expect {
app.run
}.to exit_with(0)
.and output("#{MIXED_UTF8}\n").to_stdout
end
it "sets a UTF-8 value" do
initialize_app(['set', 'tags', MIXED_UTF8])
expect {
app.run
}.to exit_with(0)
expect(read_utf8(Puppet[:config])).to eq(<<~EOF)
[main]
tags = #{MIXED_UTF8}
EOF
end
it "deletes a UTF-8 value" do
initialize_app(%w[delete tags])
write_utf8(Puppet[:config], <<~EOF)
[main]
tags=#{MIXED_UTF8}
EOF
expect {
app.run
}.to exit_with(0)
.and output(/Deleted setting from 'main': 'tags=#{MIXED_UTF8}'/).to_stdout
expect(read_utf8(Puppet[:config])).to eq(<<~EOF)
[main]
EOF
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/application/doc_spec.rb | spec/unit/application/doc_spec.rb | require 'spec_helper'
require 'puppet/application/doc'
require 'puppet/util/reference'
require 'puppet/util/rdoc'
describe Puppet::Application::Doc do
before :each do
@doc = Puppet::Application[:doc]
allow(@doc).to receive(:puts)
@doc.preinit
allow(Puppet::Util::Log).to receive(:newdestination)
end
it "should declare an other command" do
expect(@doc).to respond_to(:other)
end
it "should declare a rdoc command" do
expect(@doc).to respond_to(:rdoc)
end
it "should declare a fallback for unknown options" do
expect(@doc).to respond_to(:handle_unknown)
end
it "should declare a preinit block" do
expect(@doc).to respond_to(:preinit)
end
describe "in preinit" do
it "should set references to []" do
@doc.preinit
expect(@doc.options[:references]).to eq([])
end
it "should init mode to text" do
@doc.preinit
expect(@doc.options[:mode]).to eq(:text)
end
it "should init format to to_markdown" do
@doc.preinit
expect(@doc.options[:format]).to eq(:to_markdown)
end
end
describe "when handling options" do
[:all, :outputdir, :verbose, :debug, :charset].each do |option|
it "should declare handle_#{option} method" do
expect(@doc).to respond_to("handle_#{option}".to_sym)
end
it "should store argument value when calling handle_#{option}" do
expect(@doc.options).to receive(:[]=).with(option, 'arg')
@doc.send("handle_#{option}".to_sym, 'arg')
end
end
it "should store the format if valid" do
allow(Puppet::Util::Reference).to receive(:method_defined?).with('to_format').and_return(true)
@doc.handle_format('format')
expect(@doc.options[:format]).to eq('to_format')
end
it "should raise an error if the format is not valid" do
allow(Puppet::Util::Reference).to receive(:method_defined?).with('to_format').and_return(false)
expect { @doc.handle_format('format') }.to raise_error(RuntimeError, /Invalid output format/)
end
it "should store the mode if valid" do
allow(Puppet::Util::Reference).to receive(:modes).and_return(double('mode', :include? => true))
@doc.handle_mode('mode')
expect(@doc.options[:mode]).to eq(:mode)
end
it "should store the mode if :rdoc" do
allow(Puppet::Util::Reference.modes).to receive(:include?).with('rdoc').and_return(false)
@doc.handle_mode('rdoc')
expect(@doc.options[:mode]).to eq(:rdoc)
end
it "should raise an error if the mode is not valid" do
allow(Puppet::Util::Reference.modes).to receive(:include?).with('unknown').and_return(false)
expect { @doc.handle_mode('unknown') }.to raise_error(RuntimeError, /Invalid output mode/)
end
it "should list all references on list and exit" do
reference = double('reference')
ref = double('ref')
allow(Puppet::Util::Reference).to receive(:references).and_return([reference])
expect(Puppet::Util::Reference).to receive(:reference).with(reference).and_return(ref)
expect(ref).to receive(:doc)
expect { @doc.handle_list(nil) }.to exit_with 0
end
it "should add reference to references list with --reference" do
@doc.options[:references] = [:ref1]
@doc.handle_reference('ref2')
expect(@doc.options[:references]).to eq([:ref1,:ref2])
end
end
describe "during setup" do
before :each do
allow(Puppet::Log).to receive(:newdestination)
allow(@doc.command_line).to receive(:args).and_return([])
end
it "should default to rdoc mode if there are command line arguments" do
allow(@doc.command_line).to receive(:args).and_return(["1"])
allow(@doc).to receive(:setup_rdoc)
@doc.setup
expect(@doc.options[:mode]).to eq(:rdoc)
end
it "should call setup_rdoc in rdoc mode" do
@doc.options[:mode] = :rdoc
expect(@doc).to receive(:setup_rdoc)
@doc.setup
end
it "should call setup_reference if not rdoc" do
@doc.options[:mode] = :test
expect(@doc).to receive(:setup_reference)
@doc.setup
end
describe "configuring logging" do
before :each do
allow(Puppet::Util::Log).to receive(:newdestination)
end
describe "with --debug" do
before do
@doc.options[:debug] = true
end
it "should set log level to debug" do
@doc.setup
expect(Puppet::Util::Log.level).to eq(:debug)
end
it "should set log destination to console" do
expect(Puppet::Util::Log).to receive(:newdestination).with(:console)
@doc.setup
end
end
describe "with --verbose" do
before do
@doc.options[:verbose] = true
end
it "should set log level to info" do
@doc.setup
expect(Puppet::Util::Log.level).to eq(:info)
end
it "should set log destination to console" do
expect(Puppet::Util::Log).to receive(:newdestination).with(:console)
@doc.setup
end
end
describe "without --debug or --verbose" do
before do
@doc.options[:debug] = false
@doc.options[:verbose] = false
end
it "should set log level to warning" do
@doc.setup
expect(Puppet::Util::Log.level).to eq(:warning)
end
it "should set log destination to console" do
expect(Puppet::Util::Log).to receive(:newdestination).with(:console)
@doc.setup
end
end
end
describe "in non-rdoc mode" do
it "should get all non-dynamic reference if --all" do
@doc.options[:all] = true
static = double('static', :dynamic? => false)
dynamic = double('dynamic', :dynamic? => true)
allow(Puppet::Util::Reference).to receive(:reference).with(:static).and_return(static)
allow(Puppet::Util::Reference).to receive(:reference).with(:dynamic).and_return(dynamic)
allow(Puppet::Util::Reference).to receive(:references).and_return([:static,:dynamic])
@doc.setup_reference
expect(@doc.options[:references]).to eq([:static])
end
it "should default to :type if no references" do
@doc.setup_reference
expect(@doc.options[:references]).to eq([:type])
end
end
describe "in rdoc mode" do
describe "when there are unknown args" do
it "should expand --modulepath if any" do
@doc.unknown_args = [ { :opt => "--modulepath", :arg => "path" } ]
allow(Puppet.settings).to receive(:handlearg)
@doc.setup_rdoc
expect(@doc.unknown_args[0][:arg]).to eq(File.expand_path('path'))
end
it "should give them to Puppet.settings" do
@doc.unknown_args = [ { :opt => :option, :arg => :argument } ]
expect(Puppet.settings).to receive(:handlearg).with(:option,:argument)
@doc.setup_rdoc
end
end
it "should operate in server run_mode" do
expect(@doc.class.run_mode.name).to eq(:server)
@doc.setup_rdoc
end
end
end
describe "when running" do
describe "in rdoc mode" do
include PuppetSpec::Files
let(:envdir) { tmpdir('env') }
let(:modules) { File.join(envdir, "modules") }
let(:modules2) { File.join(envdir, "modules2") }
let(:manifests) { File.join(envdir, "manifests") }
before :each do
@doc.manifest = false
allow(Puppet).to receive(:info)
Puppet[:trace] = false
Puppet[:modulepath] = modules
Puppet[:manifest] = manifests
@doc.options[:all] = false
@doc.options[:outputdir] = 'doc'
@doc.options[:charset] = nil
allow(Puppet.settings).to receive(:define_settings)
allow(Puppet::Util::RDoc).to receive(:rdoc)
allow(@doc.command_line).to receive(:args).and_return([])
end
around(:each) do |example|
FileUtils.mkdir_p(modules)
env = Puppet::Node::Environment.create(Puppet[:environment].to_sym, [modules], "#{manifests}/site.pp")
Puppet.override({:environments => Puppet::Environments::Static.new(env), :current_environment => env}) do
example.run
end
end
it "should set document_all on --all" do
@doc.options[:all] = true
expect(Puppet.settings).to receive(:[]=).with(:document_all, true)
expect { @doc.rdoc }.to exit_with(0)
end
it "should call Puppet::Util::RDoc.rdoc in full mode" do
expect(Puppet::Util::RDoc).to receive(:rdoc).with('doc', [modules, manifests], nil)
expect { @doc.rdoc }.to exit_with(0)
end
it "should call Puppet::Util::RDoc.rdoc with a charset if --charset has been provided" do
@doc.options[:charset] = 'utf-8'
expect(Puppet::Util::RDoc).to receive(:rdoc).with('doc', [modules, manifests], "utf-8")
expect { @doc.rdoc }.to exit_with(0)
end
it "should call Puppet::Util::RDoc.rdoc in full mode with outputdir set to doc if no --outputdir" do
@doc.options[:outputdir] = false
expect(Puppet::Util::RDoc).to receive(:rdoc).with('doc', [modules, manifests], nil)
expect { @doc.rdoc }.to exit_with(0)
end
it "should call Puppet::Util::RDoc.manifestdoc in manifest mode" do
@doc.manifest = true
expect(Puppet::Util::RDoc).to receive(:manifestdoc)
expect { @doc.rdoc }.to exit_with(0)
end
it "should get modulepath and manifest values from the environment" do
FileUtils.mkdir_p(modules)
FileUtils.mkdir_p(modules2)
env = Puppet::Node::Environment.create(Puppet[:environment].to_sym,
[modules, modules2],
"envmanifests/site.pp")
Puppet.override({:environments => Puppet::Environments::Static.new(env), :current_environment => env}) do
allow(Puppet::Util::RDoc).to receive(:rdoc).with('doc', [modules.to_s, modules2.to_s, env.manifest.to_s], nil)
expect { @doc.rdoc }.to exit_with(0)
end
end
end
describe "in the other modes" do
it "should get reference in given format" do
reference = double('reference')
@doc.options[:mode] = :none
@doc.options[:references] = [:ref]
expect(Puppet::Util::Reference).to receive(:reference).with(:ref).and_return(reference)
@doc.options[:format] = :format
allow(@doc).to receive(:exit)
expect(reference).to receive(:send).with(:format, anything).and_return('doc')
@doc.other
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/application/resource_spec.rb | spec/unit/application/resource_spec.rb | require 'spec_helper'
require 'puppet/application/resource'
require 'puppet_spec/character_encoding'
describe Puppet::Application::Resource do
include PuppetSpec::Files
before :each do
@resource_app = Puppet::Application[:resource]
allow(Puppet::Util::Log).to receive(:newdestination)
end
describe "in preinit" do
it "should include provider parameter by default" do
@resource_app.preinit
expect(@resource_app.extra_params).to eq([:provider])
end
end
describe "when handling options" do
[:debug, :verbose, :edit].each do |option|
it "should store argument value when calling handle_#{option}" do
expect(@resource_app.options).to receive(:[]=).with(option, 'arg')
@resource_app.send("handle_#{option}".to_sym, 'arg')
end
end
it "should load a display all types with types option" do
type1 = double('type1', :name => :type1)
type2 = double('type2', :name => :type2)
allow(Puppet::Type).to receive(:loadall)
allow(Puppet::Type).to receive(:eachtype).and_yield(type1).and_yield(type2)
expect(@resource_app).to receive(:puts).with(['type1','type2'])
expect { @resource_app.handle_types(nil) }.to exit_with 0
end
it "should add param to extra_params list" do
@resource_app.extra_params = [ :param1 ]
@resource_app.handle_param("whatever")
expect(@resource_app.extra_params).to eq([ :param1, :whatever ])
end
it "should get a parameter in the printed data if extra_params are passed" do
tty = double("tty", :tty? => true )
path = tmpfile('testfile')
command_line = Puppet::Util::CommandLine.new("puppet", [ 'resource', 'file', path ], tty )
allow(@resource_app).to receive(:command_line).and_return(command_line)
# provider is a parameter that should always be available
@resource_app.extra_params = [ :provider ]
expect {
@resource_app.main
}.to output(/provider\s+=>/).to_stdout
end
end
describe "during setup" do
before :each do
allow(Puppet::Log).to receive(:newdestination)
end
it "should set console as the log destination" do
expect(Puppet::Log).to receive(:newdestination).with(:console)
@resource_app.setup
end
it "should set log level to debug if --debug was passed" do
allow(@resource_app.options).to receive(:[]).with(:debug).and_return(true)
@resource_app.setup
expect(Puppet::Log.level).to eq(:debug)
end
it "should set log level to info if --verbose was passed" do
allow(@resource_app.options).to receive(:[]).with(:debug).and_return(false)
allow(@resource_app.options).to receive(:[]).with(:verbose).and_return(true)
@resource_app.setup
expect(Puppet::Log.level).to eq(:info)
end
end
describe "when running" do
before :each do
@type = double('type', :properties => [])
allow(@resource_app.command_line).to receive(:args).and_return(['mytype'])
allow(Puppet::Type).to receive(:type).and_return(@type)
@res = double("resource")
allow(@res).to receive(:prune_parameters).and_return(@res)
allow(@res).to receive(:to_manifest).and_return("resource")
@report = double("report")
allow(@resource_app).to receive(:puts)
end
it "should raise an error if no type is given" do
allow(@resource_app.command_line).to receive(:args).and_return([])
expect { @resource_app.main }.to raise_error(RuntimeError, "You must specify the type to display")
end
it "should raise an error if the type is not found" do
allow(Puppet::Type).to receive(:type).and_return(nil)
expect { @resource_app.main }.to raise_error(RuntimeError, 'Could not find type mytype')
end
it "should search for resources" do
expect(Puppet::Resource.indirection).to receive(:search).with('mytype/', {}).and_return([])
@resource_app.main
end
it "should describe the given resource" do
allow(@resource_app.command_line).to receive(:args).and_return(['type','name'])
expect(Puppet::Resource.indirection).to receive(:find).with('type/name').and_return(@res)
@resource_app.main
end
before :each do
allow(@res).to receive(:ref).and_return("type/name")
end
it "should add given parameters to the object" do
allow(@resource_app.command_line).to receive(:args).and_return(['type','name','param=temp'])
expect(Puppet::Resource.indirection).to receive(:save).with(@res, 'type/name').and_return([@res, @report])
expect(Puppet::Resource).to receive(:new).with('type', 'name', {:parameters => {'param' => 'temp'}}).and_return(@res)
resource_status = instance_double('Puppet::Resource::Status')
allow(@report).to receive(:resource_statuses).and_return({'type/name' => resource_status})
allow(resource_status).to receive(:failed?).and_return(false)
@resource_app.main
end
end
describe "when printing output" do
Puppet::Type.newtype(:stringify) do
ensurable
newparam(:name, isnamevar: true)
newproperty(:string)
end
Puppet::Type.type(:stringify).provide(:stringify) do
def exists?
true
end
def string=(value)
end
def string
Puppet::Util::Execution::ProcessOutput.new('test', 0)
end
end
it "should not emit puppet class tags when printing yaml when strict mode is off" do
Puppet[:strict] = :warning
@resource_app.options[:to_yaml] = true
allow(@resource_app.command_line).to receive(:args).and_return(['stringify', 'hello', 'ensure=present', 'string=asd'])
expect(@resource_app).to receive(:puts).with(<<~YAML)
---
stringify:
hello:
ensure: present
string: test
YAML
expect { @resource_app.main }.not_to raise_error
end
it "should ensure all values to be printed are in the external encoding" do
resources = [
Puppet::Type.type(:user).new(:name => "\u2603".force_encoding(Encoding::UTF_8)).to_resource,
Puppet::Type.type(:user).new(:name => "Jos\xE9".force_encoding(Encoding::ISO_8859_1)).to_resource
]
expect(Puppet::Resource.indirection).to receive(:search).with('user/', {}).and_return(resources)
allow(@resource_app.command_line).to receive(:args).and_return(['user'])
# All of our output should be in external encoding
expect(@resource_app).to receive(:puts) { |args| expect(args.encoding).to eq(Encoding::ISO_8859_1) }
# This would raise an error if we weren't handling it
PuppetSpec::CharacterEncoding.with_external_encoding(Encoding::ISO_8859_1) do
expect { @resource_app.main }.not_to raise_error
end
end
end
describe "when handling file type" do
before :each do
allow(Facter).to receive(:loadfacts)
@resource_app.preinit
end
it "should raise an exception if no file specified" do
allow(@resource_app.command_line).to receive(:args).and_return(['file'])
expect { @resource_app.main }.to raise_error(RuntimeError, /Listing all file instances is not supported/)
end
it "should output a file resource when given a file path" do
path = File.expand_path('/etc')
res = Puppet::Type.type(:file).new(:path => path).to_resource
expect(Puppet::Resource.indirection).to receive(:find).and_return(res)
allow(@resource_app.command_line).to receive(:args).and_return(['file', path])
expect(@resource_app).to receive(:puts).with(/file \{ '#{Regexp.escape(path)}'/m)
@resource_app.main
end
end
describe 'when handling a custom type' do
it 'the Puppet::Pops::Loaders instance is available' do
Puppet::Type.newtype(:testing) do
newparam(:name) do
isnamevar
end
def self.instances
fail('Loader not found') unless Puppet::Pops::Loaders.find_loader(nil).is_a?(Puppet::Pops::Loader::Loader)
@instances ||= [new(:name => name)]
end
end
allow(@resource_app.command_line).to receive(:args).and_return(['testing', 'hello'])
expect(@resource_app).to receive(:puts).with("testing { 'hello':\n}")
expect { @resource_app.main }.not_to raise_error
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/data_providers/hiera_data_provider_spec.rb | spec/unit/data_providers/hiera_data_provider_spec.rb | require 'spec_helper'
require 'puppet_spec/compiler'
describe "when using a hiera data provider" do
include PuppetSpec::Compiler
# There is a fully configured 'sample' environment in fixtures at this location
let(:environmentpath) { parent_fixture('environments') }
let(:facts) { Puppet::Node::Facts.new("facts", {}) }
around(:each) do |example|
# Initialize settings to get a full compile as close as possible to a real
# environment load
Puppet.settings.initialize_global_settings
# Initialize loaders based on the environmentpath. It does not work to
# just set the setting environmentpath for some reason - this achieves the same:
# - first a loader is created, loading directory environments from the fixture (there is
# one environment, 'sample', which will be loaded since the node references this
# environment by name).
# - secondly, the created env loader is set as 'environments' in the puppet context.
#
loader = Puppet::Environments::Directories.new(environmentpath, [])
Puppet.override(:environments => loader) do
example.run
end
end
def compile_and_get_notifications(environment, code = nil)
extract_notifications(compile(environment, code))
end
def compile(environment, code = nil)
Puppet[:code] = code if code
node = Puppet::Node.new("testnode", :facts => facts, :environment => environment)
compiler = Puppet::Parser::Compiler.new(node)
compiler.topscope['domain'] = 'example.com'
compiler.topscope['my_fact'] = 'server3'
block_given? ? compiler.compile { |catalog| yield(compiler); catalog } : compiler.compile
end
def extract_notifications(catalog)
catalog.resources.map(&:ref).select { |r| r.start_with?('Notify[') }.map { |r| r[7..-2] }
end
it 'uses default configuration for environment and module data' do
resources = compile_and_get_notifications('hiera_defaults')
expect(resources).to include('module data param_a is 100, param default is 200, env data param_c is 300')
end
it 'reads hiera.yaml in environment root and configures multiple json and yaml providers' do
resources = compile_and_get_notifications('hiera_env_config')
expect(resources).to include("env data param_a is 10, env data param_b is 20, env data param_c is 30, env data param_d is 40, env data param_e is 50, env data param_yaml_utf8 is \u16EB\u16D2\u16E6, env data param_json_utf8 is \u16A0\u16C7\u16BB")
end
it 'reads hiera.yaml in module root and configures multiple json and yaml providers' do
resources = compile_and_get_notifications('hiera_module_config')
expect(resources).to include('module data param_a is 100, module data param_b is 200, module data param_c is 300, module data param_d is 400, module data param_e is 500')
end
it 'keeps lookup_options in one module separate from lookup_options in another' do
resources1 = compile('hiera_modules', 'include one').resources.select {|r| r.ref.start_with?('Class[One]')}
resources2 = compile('hiera_modules', 'include two').resources.select {|r| r.ref.start_with?('Class[One]')}
expect(resources1).to eq(resources2)
end
it 'does not perform merge of values declared in environment and module when resolving parameters' do
resources = compile_and_get_notifications('hiera_misc')
expect(resources).to include('env 1, ')
end
it 'performs hash merge of values declared in environment and module' do
resources = compile_and_get_notifications('hiera_misc', '$r = lookup(one::test::param, Hash[String,String], hash) notify{"${r[key1]}, ${r[key2]}":}')
expect(resources).to include('env 1, module 2')
end
it 'performs unique merge of values declared in environment and module' do
resources = compile_and_get_notifications('hiera_misc', '$r = lookup(one::array, Array[String], unique) notify{"${r}":}')
expect(resources.size).to eq(1)
expect(resources[0][1..-2].split(', ')).to contain_exactly('first', 'second', 'third', 'fourth')
end
it 'performs merge found in lookup_options in environment of values declared in environment and module' do
resources = compile_and_get_notifications('hiera_misc', 'include one::lopts_test')
expect(resources.size).to eq(1)
expect(resources[0]).to eq('A, B, C, MA, MB, MC')
end
it 'performs merge found in lookup_options in module of values declared in environment and module' do
resources = compile_and_get_notifications('hiera_misc', 'include one::loptsm_test')
expect(resources.size).to eq(1)
expect(resources[0]).to eq('A, B, C, MA, MB, MC')
end
it "will not find 'lookup_options' as a regular value" do
expect { compile_and_get_notifications('hiera_misc', '$r = lookup("lookup_options")') }.to raise_error(Puppet::DataBinding::LookupError, /did not find a value/)
end
it 'does find unqualified keys in the environment' do
resources = compile_and_get_notifications('hiera_misc', 'notify{lookup(ukey1):}')
expect(resources).to include('Some value')
end
it 'does not find unqualified keys in the module' do
expect do
compile_and_get_notifications('hiera_misc', 'notify{lookup(ukey2):}')
end.to raise_error(Puppet::ParseError, /did not find a value for the name 'ukey2'/)
end
it 'can use interpolation lookup method "alias"' do
resources = compile_and_get_notifications('hiera_misc', 'notify{lookup(km_alias):}')
expect(resources).to include('Value from interpolation with alias')
end
it 'can use interpolation lookup method "lookup"' do
resources = compile_and_get_notifications('hiera_misc', 'notify{lookup(km_lookup):}')
expect(resources).to include('Value from interpolation with lookup')
end
it 'can use interpolation lookup method "hiera"' do
resources = compile_and_get_notifications('hiera_misc', 'notify{lookup(km_hiera):}')
expect(resources).to include('Value from interpolation with hiera')
end
it 'can use interpolation lookup method "literal"' do
resources = compile_and_get_notifications('hiera_misc', 'notify{lookup(km_literal):}')
expect(resources).to include('Value from interpolation with literal')
end
it 'can use interpolation lookup method "scope"' do
resources = compile_and_get_notifications('hiera_misc', '$target_scope = "with scope" notify{lookup(km_scope):}')
expect(resources).to include('Value from interpolation with scope')
end
it 'can use interpolation using default lookup method (scope)' do
resources = compile_and_get_notifications('hiera_misc', '$target_default = "with default" notify{lookup(km_default):}')
expect(resources).to include('Value from interpolation with default')
end
it 'performs lookup using qualified expressions in interpolation' do
resources = compile_and_get_notifications('hiera_misc', "$os = { name => 'Fedora' } notify{lookup(km_qualified):}")
expect(resources).to include('Value from qualified interpolation OS = Fedora')
end
it 'can have multiple interpolate expressions in one value' do
resources = compile_and_get_notifications('hiera_misc', 'notify{lookup(km_multi):}')
expect(resources).to include('cluster/%{::cluster}/%{role}')
end
it 'performs single quoted interpolation' do
resources = compile_and_get_notifications('hiera_misc', 'notify{lookup(km_sqalias):}')
expect(resources).to include('Value from interpolation with alias')
end
it 'uses compiler lifecycle for caching' do
Puppet[:code] = 'notify{lookup(one::my_var):}'
node = Puppet::Node.new('testnode', :facts => facts, :environment => 'hiera_module_config')
compiler = Puppet::Parser::Compiler.new(node)
compiler.topscope['my_fact'] = 'server1'
expect(extract_notifications(compiler.compile)).to include('server1')
compiler = Puppet::Parser::Compiler.new(node)
compiler.topscope['my_fact'] = 'server2'
expect(extract_notifications(compiler.compile)).to include('server2')
compiler = Puppet::Parser::Compiler.new(node)
compiler.topscope['my_fact'] = 'server3'
expect(extract_notifications(compiler.compile)).to include('In name.yaml')
end
it 'traps endless interpolate recursion' do
expect do
compile_and_get_notifications('hiera_misc', '$r1 = "%{r2}" $r2 = "%{r1}" notify{lookup(recursive):}')
end.to raise_error(Puppet::DataBinding::RecursiveLookupError, /detected in \[recursive, scope:r1, scope:r2\]/)
end
it 'does not consider use of same key in the lookup and scope namespaces as recursion' do
resources = compile_and_get_notifications('hiera_misc', 'notify{lookup(domain):}')
expect(resources).to include('-- example.com --')
end
it 'traps bad alias declarations' do
expect do
compile_and_get_notifications('hiera_misc', "$r1 = 'Alias within string %{alias(\"r2\")}' $r2 = '%{r1}' notify{lookup(recursive):}")
end.to raise_error(Puppet::DataBinding::LookupError, /'alias' interpolation is only permitted if the expression is equal to the entire string/)
end
it 'reports syntax errors for JSON files' do
expect do
compile_and_get_notifications('hiera_bad_syntax_json')
end.to raise_error(Puppet::DataBinding::LookupError, /Unable to parse \(#{environmentpath}[^)]+\):/)
end
it 'reports syntax errors for YAML files' do
expect do
compile_and_get_notifications('hiera_bad_syntax_yaml')
end.to raise_error(Puppet::DataBinding::LookupError, /Unable to parse \(#{environmentpath}[^)]+\):/)
end
describe 'when using explain' do
it 'will report config path (original and resolved), data path (original and resolved), and interpolation (before and after)' do
compile('hiera_misc', '$target_scope = "with scope"') do |compiler|
lookup_invocation = Puppet::Pops::Lookup::Invocation.new(compiler.topscope, {}, {}, true)
Puppet::Pops::Lookup.lookup('km_scope', nil, nil, nil, nil, lookup_invocation)
expect(lookup_invocation.explainer.explain).to include(<<-EOS)
Path "#{environmentpath}/hiera_misc/data/common.yaml"
Original path: "common.yaml"
Interpolation on "Value from interpolation %{scope("target_scope")}"
Global Scope
Found key: "target_scope" value: "with scope"
Found key: "km_scope" value: "Value from interpolation with scope"
EOS
end
end
it 'will report that merge options was found in the lookup_options hash' do
compile('hiera_misc', '$target_scope = "with scope"') do |compiler|
lookup_invocation = Puppet::Pops::Lookup::Invocation.new(compiler.topscope, {}, {}, true)
Puppet::Pops::Lookup.lookup('one::loptsm_test::hash', nil, nil, nil, nil, lookup_invocation)
expect(lookup_invocation.explainer.explain).to include("Using merge options from \"lookup_options\" hash")
end
end
it 'will report lookup_options details in combination with details of found value' do
compile('hiera_misc', '$target_scope = "with scope"') do |compiler|
lookup_invocation = Puppet::Pops::Lookup::Invocation.new(compiler.topscope, {}, {}, Puppet::Pops::Lookup::Explainer.new(true))
Puppet::Pops::Lookup.lookup('one::loptsm_test::hash', nil, nil, nil, nil, lookup_invocation)
expect(lookup_invocation.explainer.explain).to eq(<<EOS)
Searching for "lookup_options"
Global Data Provider (hiera configuration version 5)
No such key: "lookup_options"
Environment Data Provider (hiera configuration version 5)
Hierarchy entry "Common"
Path "#{environmentpath}/hiera_misc/data/common.yaml"
Original path: "common.yaml"
Found key: "lookup_options" value: {
"one::lopts_test::hash" => {
"merge" => "deep"
}
}
Module "one" Data Provider (hiera configuration version 5)
Hierarchy entry "Common"
Path "#{environmentpath}/hiera_misc/modules/one/data/common.yaml"
Original path: "common.yaml"
Found key: "lookup_options" value: {
"one::loptsm_test::hash" => {
"merge" => "deep"
}
}
Merge strategy hash
Global and Environment
Found key: "lookup_options" value: {
"one::lopts_test::hash" => {
"merge" => "deep"
}
}
Module one
Found key: "lookup_options" value: {
"one::loptsm_test::hash" => {
"merge" => "deep"
}
}
Merged result: {
"one::loptsm_test::hash" => {
"merge" => "deep"
},
"one::lopts_test::hash" => {
"merge" => "deep"
}
}
Using merge options from "lookup_options" hash
Searching for "one::loptsm_test::hash"
Merge strategy deep
Global Data Provider (hiera configuration version 5)
No such key: "one::loptsm_test::hash"
Environment Data Provider (hiera configuration version 5)
Hierarchy entry "Common"
Path "#{environmentpath}/hiera_misc/data/common.yaml"
Original path: "common.yaml"
Found key: "one::loptsm_test::hash" value: {
"a" => "A",
"b" => "B",
"m" => {
"ma" => "MA",
"mb" => "MB"
}
}
Module "one" Data Provider (hiera configuration version 5)
Hierarchy entry "Common"
Path "#{environmentpath}/hiera_misc/modules/one/data/common.yaml"
Original path: "common.yaml"
Found key: "one::loptsm_test::hash" value: {
"a" => "A",
"c" => "C",
"m" => {
"ma" => "MA",
"mc" => "MC"
}
}
Merged result: {
"a" => "A",
"c" => "C",
"m" => {
"ma" => "MA",
"mc" => "MC",
"mb" => "MB"
},
"b" => "B"
}
EOS
end
end
it 'will report config path (original and resolved), data path (original and resolved), and interpolation (before and after)' do
compile('hiera_misc', '$target_scope = "with scope"') do |compiler|
lookup_invocation = Puppet::Pops::Lookup::Invocation.new(compiler.topscope, {}, {}, Puppet::Pops::Lookup::Explainer.new(true, true))
Puppet::Pops::Lookup.lookup('one::loptsm_test::hash', nil, nil, nil, nil, lookup_invocation)
expect(lookup_invocation.explainer.explain).to eq(<<EOS)
Merge strategy hash
Global Data Provider (hiera configuration version 5)
No such key: "lookup_options"
Environment Data Provider (hiera configuration version 5)
Hierarchy entry "Common"
Path "#{environmentpath}/hiera_misc/data/common.yaml"
Original path: "common.yaml"
Found key: "lookup_options" value: {
"one::lopts_test::hash" => {
"merge" => "deep"
}
}
Module "one" Data Provider (hiera configuration version 5)
Hierarchy entry "Common"
Path "#{environmentpath}/hiera_misc/modules/one/data/common.yaml"
Original path: "common.yaml"
Found key: "lookup_options" value: {
"one::loptsm_test::hash" => {
"merge" => "deep"
}
}
Merged result: {
"one::loptsm_test::hash" => {
"merge" => "deep"
},
"one::lopts_test::hash" => {
"merge" => "deep"
}
}
EOS
end
end
end
def parent_fixture(dir_name)
File.absolute_path(File.join(my_fixture_dir(), "../#{dir_name}"))
end
def resources_in(catalog)
catalog.resources.map(&:ref)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/data_providers/function_data_provider_spec.rb | spec/unit/data_providers/function_data_provider_spec.rb | require 'spec_helper'
require 'puppet_spec/compiler'
describe "when using function data provider" do
include PuppetSpec::Compiler
# There is a fully configured environment in fixtures in this location
let(:environmentpath) { parent_fixture('environments') }
around(:each) do |example|
# Initialize settings to get a full compile as close as possible to a real
# environment load
Puppet.settings.initialize_global_settings
# Initialize loaders based on the environmentpath. It does not work to
# just set the setting environmentpath for some reason - this achieves the same:
# - first a loader is created, loading directory environments from the fixture (there is
# one such environment, 'production', which will be loaded since the node references this
# environment by name).
# - secondly, the created env loader is set as 'environments' in the puppet context.
#
loader = Puppet::Environments::Directories.new(environmentpath, [])
Puppet.override(:environments => loader) do
example.run
end
end
# The environment configured in the fixture has one module called 'abc'. Its class abc, includes
# a class called 'def'. This class has three parameters test1, test2, and test3 and it creates
# three notify with name set to the value of the three parameters.
#
# Since the abc class does not provide any parameter values to its def class, it attempts to
# get them from data lookup. The fixture has an environment that is configured to load data from
# a function called environment::data, this data sets test1, and test2.
# The module 'abc' is configured to get data by calling the function abc::data(), this function
# returns data for all three parameters test1-test3, now with the prefix 'module'.
#
# The result should be that the data set in the environment wins over those set in the
# module.
#
it 'gets data from module and environment functions and combines them with env having higher precedence' do
Puppet[:code] = 'include abc'
node = Puppet::Node.new("testnode", :facts => Puppet::Node::Facts.new("facts", {}), :environment => 'production')
compiler = Puppet::Parser::Compiler.new(node)
catalog = compiler.compile()
resources_created_in_fixture = ["Notify[env_test1]", "Notify[env_test2]", "Notify[module_test3]", "Notify[env_test2-ipl]"]
expect(resources_in(catalog)).to include(*resources_created_in_fixture)
end
it 'gets data from module having a puppet function delivering module data' do
Puppet[:code] = 'include xyz'
node = Puppet::Node.new("testnode", :facts => Puppet::Node::Facts.new("facts", {}), :environment => 'production')
compiler = Puppet::Parser::Compiler.new(node)
catalog = compiler.compile()
resources_created_in_fixture = ["Notify[env_test1]", "Notify[env_test2]", "Notify[module_test3]"]
expect(resources_in(catalog)).to include(*resources_created_in_fixture)
end
it 'gets data from puppet function delivering environment data' do
Puppet[:code] = <<-CODE
function environment::data() {
{ 'cls::test1' => 'env_puppet1',
'cls::test2' => 'env_puppet2'
}
}
class cls ($test1, $test2) {
notify { $test1: }
notify { $test2: }
}
include cls
CODE
node = Puppet::Node.new('testnode', :facts => Puppet::Node::Facts.new('facts', {}), :environment => 'production')
catalog = Puppet::Parser::Compiler.new(node).compile
expect(resources_in(catalog)).to include('Notify[env_puppet1]', 'Notify[env_puppet2]')
end
it 'raises an error if the environment data function does not return a hash' do
Puppet[:code] = 'include abc'
# find the loaders to patch with faulty function
node = Puppet::Node.new("testnode", :facts => Puppet::Node::Facts.new("facts", {}), :environment => 'production')
compiler = Puppet::Parser::Compiler.new(node)
loaders = compiler.loaders()
env_loader = loaders.private_environment_loader()
f = Puppet::Functions.create_function('environment::data') do
def data()
'this is not a hash'
end
end
env_loader.add_entry(:function, 'environment::data', f.new(compiler.topscope, env_loader), nil)
expect do
compiler.compile()
end.to raise_error(/Value returned from deprecated API function 'environment::data' has wrong type/)
end
it 'raises an error if the module data function does not return a hash' do
Puppet[:code] = 'include abc'
# find the loaders to patch with faulty function
node = Puppet::Node.new("testnode", :facts => Puppet::Node::Facts.new("facts", {}), :environment => 'production')
compiler = Puppet::Parser::Compiler.new(node)
loaders = compiler.loaders()
module_loader = loaders.public_loader_for_module('abc')
f = Puppet::Functions.create_function('abc::data') do
def data()
'this is not a hash'
end
end
module_loader.add_entry(:function, 'abc::data', f.new(compiler.topscope, module_loader), nil)
expect do
compiler.compile()
end.to raise_error(/Value returned from deprecated API function 'abc::data' has wrong type/)
end
def parent_fixture(dir_name)
File.absolute_path(File.join(my_fixture_dir(), "../#{dir_name}"))
end
def resources_in(catalog)
catalog.resources.map(&:ref)
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/concurrent/thread_local_singleton_spec.rb | spec/unit/concurrent/thread_local_singleton_spec.rb | require 'spec_helper'
require 'puppet/concurrent/thread_local_singleton'
class PuppetSpec::Singleton
extend Puppet::Concurrent::ThreadLocalSingleton
end
# Use the `equal?` matcher to ensure we get the same object
describe Puppet::Concurrent::ThreadLocalSingleton do
it 'returns the same object for a single thread' do
expect(PuppetSpec::Singleton.singleton).to equal(PuppetSpec::Singleton.singleton)
end
it 'is not inherited for a newly created thread' do
main_thread_local = PuppetSpec::Singleton.singleton
Thread.new do
expect(main_thread_local).to_not equal(PuppetSpec::Singleton.singleton)
end.join
end
it 'does not leak outside a thread' do
thread_local = nil
Thread.new do
thread_local = PuppetSpec::Singleton.singleton
end.join
expect(thread_local).to_not equal(PuppetSpec::Singleton.singleton)
end
it 'is different for each thread' do
locals = []
Thread.new do
locals << PuppetSpec::Singleton.singleton
end.join
Thread.new do
locals << PuppetSpec::Singleton.singleton
end.join
expect(locals.first).to_not equal(locals.last)
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/concurrent/lock_spec.rb | spec/unit/concurrent/lock_spec.rb | require 'spec_helper'
require 'puppet/concurrent/lock'
describe Puppet::Concurrent::Lock do
if Puppet::Util::Platform.jruby?
context 'on jruby' do
it 'synchronizes a block on itself' do
iterations = 100
value = 0
lock = Puppet::Concurrent::Lock.new
threads = iterations.times.collect do
Thread.new do
lock.synchronize do
tmp = (value += 1)
sleep(0.001)
# This update using tmp is designed to lose increments if threads overlap
value = tmp + 1
end
end
end
threads.each(&:join)
# In my testing this always fails by quite a lot when not synchronized (ie on mri)
expect(value).to eq(iterations * 2)
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/scheduler/splay_job_spec.rb | spec/unit/scheduler/splay_job_spec.rb | require 'spec_helper'
require 'puppet/scheduler'
describe Puppet::Scheduler::SplayJob do
let(:run_interval) { 10 }
let(:last_run) { 50 }
let(:splay_limit) { 5 }
let(:start_time) { 23 }
let(:job) { described_class.new(run_interval, splay_limit) }
it "does not apply a splay after the first run" do
job.run(last_run)
expect(job.interval_to_next_from(last_run)).to eq(run_interval)
end
it "calculates the first run splayed from the start time" do
job.start_time = start_time
expect(job.interval_to_next_from(start_time)).to eq(job.splay)
end
it "interval to the next run decreases as time advances" do
time_passed = 3
job.start_time = start_time
expect(job.interval_to_next_from(start_time + time_passed)).to eq(job.splay - time_passed)
end
it "is not immediately ready if splayed" do
job.start_time = start_time
expect(job).to receive(:splay).and_return(6)
expect(job.ready?(start_time)).not_to be
end
it "does not apply a splay if the splaylimit is unchanged" do
old_splay = job.splay
job.splay_limit = splay_limit
expect(job.splay).to eq(old_splay)
end
it "applies a splay if the splaylimit is changed" do
new_splay = 999
allow(job).to receive(:rand).and_return(new_splay)
job.splay_limit = splay_limit + 1
expect(job.splay).to eq(new_splay)
end
it "returns the splay_limit" do
expect(job.splay_limit).to eq(splay_limit)
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/scheduler/scheduler_spec.rb | spec/unit/scheduler/scheduler_spec.rb | require 'spec_helper'
require 'puppet/scheduler'
describe Puppet::Scheduler::Scheduler do
let(:now) { 183550 }
let(:timer) { MockTimer.new(now) }
class MockTimer
attr_reader :wait_for_calls
def initialize(start=1729)
@now = start
@wait_for_calls = []
end
def wait_for(seconds)
@wait_for_calls << seconds
@now += seconds
end
def now
@now
end
end
def one_time_job(interval)
Puppet::Scheduler::Job.new(interval) { |j| j.disable }
end
def disabled_job(interval)
job = Puppet::Scheduler::Job.new(interval) { |j| j.disable }
job.disable
job
end
let(:scheduler) { Puppet::Scheduler::Scheduler.new(timer) }
it "uses the minimum interval" do
later_job = one_time_job(7)
earlier_job = one_time_job(2)
later_job.last_run = now
earlier_job.last_run = now
scheduler.run_loop([later_job, earlier_job])
expect(timer.wait_for_calls).to eq([2, 5])
end
it "ignores disabled jobs when calculating intervals" do
enabled = one_time_job(7)
enabled.last_run = now
disabled = disabled_job(2)
scheduler.run_loop([enabled, disabled])
expect(timer.wait_for_calls).to eq([7])
end
it "asks the timer to wait for the job interval" do
job = one_time_job(5)
job.last_run = now
scheduler.run_loop([job])
expect(timer.wait_for_calls).to eq([5])
end
it "does not run when there are no jobs" do
scheduler.run_loop([])
expect(timer.wait_for_calls).to be_empty
end
it "does not run when there are only disabled jobs" do
disabled_job = Puppet::Scheduler::Job.new(0)
disabled_job.disable
scheduler.run_loop([disabled_job])
expect(timer.wait_for_calls).to be_empty
end
it "stops running when there are no more enabled jobs" do
disabling_job = Puppet::Scheduler::Job.new(0) do |j|
j.disable
end
scheduler.run_loop([disabling_job])
expect(timer.wait_for_calls.size).to eq(1)
end
it "marks the start of the run loop" do
disabled_job = Puppet::Scheduler::Job.new(0)
disabled_job.disable
scheduler.run_loop([disabled_job])
expect(disabled_job.start_time).to eq(now)
end
it "calculates the next interval from the start of a job" do
countdown = 2
slow_job = Puppet::Scheduler::Job.new(10) do |job|
timer.wait_for(3)
countdown -= 1
job.disable if countdown == 0
end
scheduler.run_loop([slow_job])
expect(timer.wait_for_calls).to eq([0, 3, 7, 3])
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/scheduler/job_spec.rb | spec/unit/scheduler/job_spec.rb | require 'spec_helper'
require 'puppet/scheduler'
describe Puppet::Scheduler::Job do
let(:run_interval) { 10 }
let(:job) { described_class.new(run_interval) }
it "has a minimum run interval of 0" do
expect(Puppet::Scheduler::Job.new(-1).run_interval).to eq(0)
end
describe "when not run yet" do
it "is ready" do
expect(job.ready?(2)).to be
end
it "gives the time to next run as 0" do
expect(job.interval_to_next_from(2)).to eq(0)
end
end
describe "when run at least once" do
let(:last_run) { 50 }
before(:each) do
job.run(last_run)
end
it "is ready when the time is greater than the last run plus the interval" do
expect(job.ready?(last_run + run_interval + 1)).to be
end
it "is ready when the time is equal to the last run plus the interval" do
expect(job.ready?(last_run + run_interval)).to be
end
it "is not ready when the time is less than the last run plus the interval" do
expect(job.ready?(last_run + run_interval - 1)).not_to be
end
context "when calculating the next run" do
it "returns the run interval if now == last run" do
expect(job.interval_to_next_from(last_run)).to eq(run_interval)
end
it "when time is between the last and next runs gives the remaining portion of the run_interval" do
time_since_last_run = 2
now = last_run + time_since_last_run
expect(job.interval_to_next_from(now)).to eq(run_interval - time_since_last_run)
end
it "when time is later than last+interval returns 0" do
time_since_last_run = run_interval + 5
now = last_run + time_since_last_run
expect(job.interval_to_next_from(now)).to eq(0)
end
end
end
it "starts enabled" do
expect(job.enabled?).to be
end
it "can be disabled" do
job.disable
expect(job.enabled?).not_to be
end
it "has the job instance as a parameter" do
passed_job = nil
job = Puppet::Scheduler::Job.new(run_interval) do |j|
passed_job = j
end
job.run(5)
expect(passed_job).to eql(job)
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/reports/store_spec.rb | spec/unit/reports/store_spec.rb | require 'spec_helper'
require 'puppet/reports'
require 'time'
require 'pathname'
require 'tempfile'
require 'fileutils'
describe Puppet::Reports.report(:store) do
describe "#process" do
include PuppetSpec::Files
before :each do
Puppet[:reportdir] = File.join(tmpdir('reports'), 'reports')
end
let(:report) do
# It's possible to install Psych 5 with Ruby 2.7, so check whether underlying YAML supports
# unsafe_load_file. This check can be removed in PUP-11718
if YAML.respond_to?(:unsafe_load_file)
report = YAML.unsafe_load_file(File.join(PuppetSpec::FIXTURE_DIR, 'yaml/report2.6.x.yaml'))
else
report = YAML.load_file(File.join(PuppetSpec::FIXTURE_DIR, 'yaml/report2.6.x.yaml'))
end
report.extend(described_class)
report
end
it "should create a report directory for the client if one doesn't exist" do
report.process
expect(File).to be_directory(File.join(Puppet[:reportdir], report.host))
end
it "should write the report to the file in YAML" do
allow(Time).to receive(:now).and_return(Time.utc(2011,01,06,12,00,00))
report.process
expect(File.read(File.join(Puppet[:reportdir], report.host, "201101061200.yaml"))).to eq(report.to_yaml)
end
it "rejects invalid hostnames" do
report.host = ".."
expect(Puppet::FileSystem).not_to receive(:exist?)
expect { report.process }.to raise_error(ArgumentError, /Invalid node/)
end
end
describe "::destroy" do
it "rejects invalid hostnames" do
expect(Puppet::FileSystem).not_to receive(:unlink)
expect { described_class.destroy("..") }.to raise_error(ArgumentError, /Invalid node/)
end
end
describe "::validate_host" do
['..', 'hello/', '/hello', 'he/llo', 'hello/..', '.'].each do |node|
it "rejects #{node.inspect}" do
expect { described_class.validate_host(node) }.to raise_error(ArgumentError, /Invalid node/)
end
end
['.hello', 'hello.', '..hi', 'hi..'].each do |node|
it "accepts #{node.inspect}" do
described_class.validate_host(node)
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/reports/http_spec.rb | spec/unit/reports/http_spec.rb | require 'spec_helper'
require 'puppet/reports'
describe Puppet::Reports.report(:http) do
subject { Puppet::Transaction::Report.new.extend(described_class) }
let(:url) { "https://puppet.example.com/report/upload" }
before :each do
Puppet[:reporturl] = url
end
describe "when setting up the connection" do
it "raises if the connection fails" do
stub_request(:post, url).to_raise(Errno::ECONNREFUSED.new('Connection refused - connect(2)'))
expect {
subject.process
}.to raise_error(Puppet::HTTP::HTTPError, /Request to #{url} failed after .* seconds: .*Connection refused/)
end
it "configures the connection for ssl when using https" do
stub_request(:post, url)
expect_any_instance_of(Net::HTTP).to receive(:start) do |http|
expect(http).to be_use_ssl
expect(http.verify_mode).to eq(OpenSSL::SSL::VERIFY_PEER)
end
subject.process
end
it "does not configure the connection for ssl when using http" do
Puppet[:reporturl] = 'http://puppet.example.com:8080/the/path'
stub_request(:post, Puppet[:reporturl])
expect_any_instance_of(Net::HTTP).to receive(:start) do |http|
expect(http).to_not be_use_ssl
end
subject.process
end
end
describe "when making a request" do
it "uses the path specified by the 'reporturl' setting" do
req = stub_request(:post, url)
subject.process
expect(req).to have_been_requested
end
it "uses the username and password specified by the 'reporturl' setting" do
Puppet[:reporturl] = "https://user:pass@puppet.example.com/report/upload"
req = stub_request(:post, %r{/report/upload}).with(basic_auth: ['user', 'pass'])
subject.process
expect(req).to have_been_requested
end
it "passes metric_id options" do
stub_request(:post, url)
expect(Puppet.runtime[:http]).to receive(:post).with(anything, anything, hash_including(options: hash_including(metric_id: [:puppet, :report, :http]))).and_call_original
subject.process
end
it "passes the report as YAML" do
req = stub_request(:post, url).with(body: subject.to_yaml)
subject.process
expect(req).to have_been_requested
end
it "sets content-type to 'application/x-yaml'" do
req = stub_request(:post, url).with(headers: {'Content-Type' => 'application/x-yaml'})
subject.process
expect(req).to have_been_requested
end
it "doesn't log anything if the request succeeds" do
req = stub_request(:post, url).to_return(status: [200, "OK"])
subject.process
expect(req).to have_been_requested
expect(@logs).to eq([])
end
it "follows redirects" do
location = {headers: {'Location' => url}}
req = stub_request(:post, url)
.to_return(**location, status: [301, "Moved Permanently"]).then
.to_return(**location, status: [302, "Found"]).then
.to_return(**location, status: [307, "Temporary Redirect"]).then
.to_return(status: [200, "OK"])
subject.process
expect(req).to have_been_requested.times(4)
end
it "logs an error if the request fails" do
stub_request(:post, url).to_return(status: [500, "Internal Server Error"])
subject.process
expect(@logs).to include(having_attributes(level: :err, message: "Unable to submit report to #{url} [500] Internal Server Error"))
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/property/ensure_spec.rb | spec/unit/property/ensure_spec.rb | require 'spec_helper'
require 'puppet/property/ensure'
klass = Puppet::Property::Ensure
describe klass do
it "should be a subclass of Property" do
expect(klass.superclass).to eq(Puppet::Property)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/property/list_spec.rb | spec/unit/property/list_spec.rb | require 'spec_helper'
require 'puppet/property/list'
list_class = Puppet::Property::List
describe list_class do
it "should be a subclass of Property" do
expect(list_class.superclass).to eq(Puppet::Property)
end
describe "as an instance" do
before do
# Wow that's a messy interface to the resource.
list_class.initvars
@resource = double('resource', :[]= => nil, :property => nil)
@property = list_class.new(:resource => @resource)
end
it "should have a , as default delimiter" do
expect(@property.delimiter).to eq(",")
end
it "should have a :membership as default membership" do
expect(@property.membership).to eq(:membership)
end
it "should return the same value passed into should_to_s" do
@property.should_to_s("foo") == "foo"
end
it "should return the passed in array values joined with the delimiter from is_to_s" do
expect(@property.is_to_s(["foo","bar"])).to eq("foo,bar")
end
it "should be able to correctly convert ':absent' to a quoted string" do
expect(@property.is_to_s(:absent)).to eq("'absent'")
end
describe "when adding should to current" do
it "should add the arrays when current is an array" do
expect(@property.add_should_with_current(["foo"], ["bar"])).to eq(["foo", "bar"])
end
it "should return should if current is not an array" do
expect(@property.add_should_with_current(["foo"], :absent)).to eq(["foo"])
end
it "should return only the uniq elements" do
expect(@property.add_should_with_current(["foo", "bar"], ["foo", "baz"])).to eq(["foo", "bar", "baz"])
end
end
describe "when calling inclusive?" do
it "should use the membership method to look up on the @resource" do
expect(@property).to receive(:membership).and_return(:membership)
expect(@resource).to receive(:[]).with(:membership)
@property.inclusive?
end
it "should return true when @resource[membership] == inclusive" do
allow(@property).to receive(:membership).and_return(:membership)
allow(@resource).to receive(:[]).with(:membership).and_return(:inclusive)
expect(@property.inclusive?).to eq(true)
end
it "should return false when @resource[membership] != inclusive" do
allow(@property).to receive(:membership).and_return(:membership)
allow(@resource).to receive(:[]).with(:membership).and_return(:minimum)
expect(@property.inclusive?).to eq(false)
end
end
describe "when calling should" do
it "should return nil if @should is nil" do
expect(@property.should).to eq(nil)
end
it "should return the sorted values of @should as a string if inclusive" do
@property.should = ["foo", "bar"]
expect(@property).to receive(:inclusive?).and_return(true)
expect(@property.should).to eq("bar,foo")
end
it "should return the uniq sorted values of @should + retrieve as a string if !inclusive" do
@property.should = ["foo", "bar"]
expect(@property).to receive(:inclusive?).and_return(false)
expect(@property).to receive(:retrieve).and_return(["foo","baz"])
expect(@property.should).to eq("bar,baz,foo")
end
end
describe "when calling retrieve" do
let(:provider) { @provider }
before do
@provider = double("provider")
allow(@property).to receive(:provider).and_return(provider)
end
it "should send 'name' to the provider" do
expect(@provider).to receive(:send).with(:group)
expect(@property).to receive(:name).and_return(:group)
@property.retrieve
end
it "should return an array with the provider returned info" do
allow(@provider).to receive(:send).with(:group).and_return("foo,bar,baz")
allow(@property).to receive(:name).and_return(:group)
@property.retrieve == ["foo", "bar", "baz"]
end
it "should return :absent when the provider returns :absent" do
allow(@provider).to receive(:send).with(:group).and_return(:absent)
allow(@property).to receive(:name).and_return(:group)
@property.retrieve == :absent
end
context "and provider is nil" do
let(:provider) { nil }
it "should return :absent" do
@property.retrieve == :absent
end
end
end
describe "when calling safe_insync?" do
it "should return true unless @should is defined and not nil" do
expect(@property).to be_safe_insync("foo")
end
it "should return true unless the passed in values is not nil" do
@property.should = "foo"
expect(@property).to be_safe_insync(nil)
end
it "should call prepare_is_for_comparison with value passed in and should" do
@property.should = "foo"
expect(@property).to receive(:prepare_is_for_comparison).with("bar")
expect(@property).to receive(:should)
@property.safe_insync?("bar")
end
it "should return true if 'is' value is array of comma delimited should values" do
@property.should = "bar,foo"
expect(@property).to receive(:inclusive?).and_return(true)
expect(@property).to be_safe_insync(["bar","foo"])
end
it "should return true if 'is' value is :absent and should value is empty string" do
@property.should = ""
expect(@property).to receive(:inclusive?).and_return(true)
expect(@property).to be_safe_insync([])
end
it "should return false if prepared value != should value" do
@property.should = "bar,baz,foo"
expect(@property).to receive(:inclusive?).and_return(true)
expect(@property).to_not be_safe_insync(["bar","foo"])
end
end
describe "when calling dearrayify" do
it "should sort and join the array with 'delimiter'" do
array = double("array")
expect(array).to receive(:sort).and_return(array)
expect(array).to receive(:join).with(@property.delimiter)
@property.dearrayify(array)
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/property/boolean_spec.rb | spec/unit/property/boolean_spec.rb | require 'spec_helper'
require 'puppet/property/boolean'
describe Puppet::Property::Boolean do
let (:resource) { double('resource') }
subject { described_class.new(:resource => resource) }
[ true, :true, 'true', :yes, 'yes', 'TrUe', 'yEs' ].each do |arg|
it "should munge #{arg.inspect} as true" do
expect(subject.munge(arg)).to eq(true)
end
end
[ false, :false, 'false', :no, 'no', 'FaLSE', 'nO' ].each do |arg|
it "should munge #{arg.inspect} as false" do
expect(subject.munge(arg)).to eq(false)
end
end
[ nil, :undef, 'undef', '0', 0, '1', 1, 9284 ].each do |arg|
it "should fail to munge #{arg.inspect}" do
expect { subject.munge(arg) }.to raise_error Puppet::Error
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/property/keyvalue_spec.rb | spec/unit/property/keyvalue_spec.rb | require 'spec_helper'
require 'puppet/property/keyvalue'
describe 'Puppet::Property::KeyValue' do
let(:klass) { Puppet::Property::KeyValue }
it "should be a subclass of Property" do
expect(klass.superclass).to eq(Puppet::Property)
end
describe "as an instance" do
before do
# Wow that's a messy interface to the resource.
klass.initvars
@resource = double('resource', :[]= => nil, :property => nil)
@property = klass.new(:resource => @resource)
klass.log_only_changed_or_new_keys = false
end
it "should have a , as default delimiter" do
expect(@property.delimiter).to eq(";")
end
it "should have a = as default separator" do
expect(@property.separator).to eq("=")
end
it "should have a :membership as default membership" do
expect(@property.membership).to eq(:key_value_membership)
end
it "should return the same value passed into should_to_s" do
@property.should_to_s({:foo => "baz", :bar => "boo"}) == "foo=baz;bar=boo"
end
it "should return the passed in hash values joined with the delimiter from is_to_s" do
s = @property.is_to_s({"foo" => "baz" , "bar" => "boo"})
# We can't predict the order the hash is processed in...
expect(["foo=baz;bar=boo", "bar=boo;foo=baz"]).to be_include s
end
describe "when calling hash_to_key_value_s" do
let(:input) do
{
:key1 => "value1",
:key2 => "value2",
:key3 => "value3"
}
end
before(:each) do
@property.instance_variable_set(:@changed_or_new_keys, [:key1, :key2])
end
it "returns only the changed or new keys if log_only_changed_or_new_keys is set" do
klass.log_only_changed_or_new_keys = true
expect(@property.hash_to_key_value_s(input)).to eql("key1=value1;key2=value2")
end
end
describe "when calling inclusive?" do
it "should use the membership method to look up on the @resource" do
expect(@property).to receive(:membership).and_return(:key_value_membership)
expect(@resource).to receive(:[]).with(:key_value_membership)
@property.inclusive?
end
it "should return true when @resource[membership] == inclusive" do
allow(@property).to receive(:membership).and_return(:key_value_membership)
allow(@resource).to receive(:[]).with(:key_value_membership).and_return(:inclusive)
expect(@property.inclusive?).to eq(true)
end
it "should return false when @resource[membership] != inclusive" do
allow(@property).to receive(:membership).and_return(:key_value_membership)
allow(@resource).to receive(:[]).with(:key_value_membership).and_return(:minimum)
expect(@property.inclusive?).to eq(false)
end
end
describe "when calling process_current_hash" do
it "should return {} if hash is :absent" do
expect(@property.process_current_hash(:absent)).to eq({})
end
it "should set every key to nil if inclusive?" do
allow(@property).to receive(:inclusive?).and_return(true)
expect(@property.process_current_hash({:foo => "bar", :do => "re"})).to eq({ :foo => nil, :do => nil })
end
it "should return the hash if !inclusive?" do
allow(@property).to receive(:inclusive?).and_return(false)
expect(@property.process_current_hash({:foo => "bar", :do => "re"})).to eq({:foo => "bar", :do => "re"})
end
end
describe "when calling should" do
it "should return nil if @should is nil" do
expect(@property.should).to eq(nil)
end
it "should call process_current_hash" do
@property.should = ["foo=baz", "bar=boo"]
allow(@property).to receive(:retrieve).and_return({:do => "re", :mi => "fa" })
expect(@property).to receive(:process_current_hash).and_return({})
@property.should
end
it "should return the hashed values of @should and the nilled values of retrieve if inclusive" do
@property.should = ["foo=baz", "bar=boo"]
expect(@property).to receive(:retrieve).and_return({:do => "re", :mi => "fa" })
expect(@property).to receive(:inclusive?).and_return(true)
expect(@property.should).to eq({ :foo => "baz", :bar => "boo", :do => nil, :mi => nil })
end
it "should return the hashed @should + the unique values of retrieve if !inclusive" do
@property.should = ["foo=baz", "bar=boo"]
expect(@property).to receive(:retrieve).and_return({:foo => "diff", :do => "re", :mi => "fa"})
expect(@property).to receive(:inclusive?).and_return(false)
expect(@property.should).to eq({ :foo => "baz", :bar => "boo", :do => "re", :mi => "fa" })
end
it "should mark the keys that will change or be added as a result of our Puppet run" do
@property.should = {
:key1 => "new_value1",
:key2 => "value2",
:key3 => "new_value3",
:key4 => "value4"
}
allow(@property).to receive(:retrieve).and_return(
{
:key1 => "value1",
:key2 => "value2",
:key3 => "value3"
}
)
allow(@property).to receive(:inclusive?).and_return(false)
@property.should
expect(@property.instance_variable_get(:@changed_or_new_keys)).to eql([:key1, :key3, :key4])
end
end
describe "when calling retrieve" do
before do
@provider = double("provider")
allow(@property).to receive(:provider).and_return(@provider)
end
it "should send 'name' to the provider" do
expect(@provider).to receive(:send).with(:keys)
expect(@property).to receive(:name).and_return(:keys)
@property.retrieve
end
it "should return a hash with the provider returned info" do
allow(@provider).to receive(:send).with(:keys).and_return({"do" => "re", "mi" => "fa" })
allow(@property).to receive(:name).and_return(:keys)
@property.retrieve == {"do" => "re", "mi" => "fa" }
end
it "should return :absent when the provider returns :absent" do
allow(@provider).to receive(:send).with(:keys).and_return(:absent)
allow(@property).to receive(:name).and_return(:keys)
@property.retrieve == :absent
end
end
describe "when calling hashify_should" do
it "should return the underlying hash if the user passed in a hash" do
@property.should = { "foo" => "bar" }
expect(@property.hashify_should).to eql({ :foo => "bar" })
end
it "should hashify the array of key/value pairs if that is what our user passed in" do
@property.should = [ "foo=baz", "bar=boo" ]
expect(@property.hashify_should).to eq({ :foo => "baz", :bar => "boo" })
end
end
describe "when calling safe_insync?" do
before do
@provider = double("provider")
allow(@property).to receive(:provider).and_return(@provider)
allow(@property).to receive(:name).and_return(:prop_name)
end
it "should return true unless @should is defined and not nil" do
@property.safe_insync?("foo") == true
end
it "should return true if the passed in values is nil" do
@property.safe_insync?(nil) == true
end
it "should return true if hashified should value == (retrieved) value passed in" do
allow(@provider).to receive(:prop_name).and_return({ :foo => "baz", :bar => "boo" })
@property.should = ["foo=baz", "bar=boo"]
expect(@property).to receive(:inclusive?).and_return(true)
expect(@property.safe_insync?({ :foo => "baz", :bar => "boo" })).to eq(true)
end
it "should return false if prepared value != should value" do
allow(@provider).to receive(:prop_name).and_return({ "foo" => "bee", "bar" => "boo" })
@property.should = ["foo=baz", "bar=boo"]
expect(@property).to receive(:inclusive?).and_return(true)
expect(@property.safe_insync?({ "foo" => "bee", "bar" => "boo" })).to eq(false)
end
end
describe 'when validating a passed-in property value' do
it 'should raise a Puppet::Error if the property value is anything but a Hash or a String' do
expect { @property.validate(5) }.to raise_error do |error|
expect(error).to be_a(Puppet::Error)
expect(error.message).to match("specified as a hash or an array")
end
end
it 'should accept a Hash property value' do
@property.validate({ 'foo' => 'bar' })
end
it "should raise a Puppet::Error if the property value isn't a key/value pair" do
expect { @property.validate('foo') }.to raise_error do |error|
expect(error).to be_a(Puppet::Error)
expect(error.message).to match("separated by '='")
end
end
it 'should accept a valid key/value pair property value' do
@property.validate('foo=bar')
end
end
describe 'when munging a passed-in property value' do
it 'should return the value as-is if it is a string' do
expect(@property.munge('foo=bar')).to eql('foo=bar')
end
it 'should stringify + symbolize the keys and stringify the values if it is a hash' do
input = {
1 => 2,
true => false,
' foo ' => 'bar'
}
expected_output = {
:'1' => '2',
:true => 'false',
:foo => 'bar'
}
expect(@property.munge(input)).to eql(expected_output)
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/property/ordered_list_spec.rb | spec/unit/property/ordered_list_spec.rb | require 'spec_helper'
require 'puppet/property/ordered_list'
describe Puppet::Property::OrderedList do
it "should be a subclass of List" do
expect(described_class.superclass).to eq(Puppet::Property::List)
end
describe "as an instance" do
before do
# Wow that's a messy interface to the resource.
described_class.initvars
@resource = double('resource', :[]= => nil, :property => nil)
@property = described_class.new(:resource => @resource)
end
describe "when adding should to current" do
it "should add the arrays when current is an array" do
expect(@property.add_should_with_current(["should"], ["current"])).to eq(["should", "current"])
end
it "should return 'should' if current is not an array" do
expect(@property.add_should_with_current(["should"], :absent)).to eq(["should"])
end
it "should return only the uniq elements leading with the order of 'should'" do
expect(@property.add_should_with_current(["this", "is", "should"], ["is", "this", "current"])).to eq(["this", "is", "should", "current"])
end
end
describe "when calling should" do
it "should return nil if @should is nil" do
expect(@property.should).to eq(nil)
end
it "should return the values of @should (without sorting) as a string if inclusive" do
@property.should = ["foo", "bar"]
expect(@property).to receive(:inclusive?).and_return(true)
expect(@property.should).to eq("foo,bar")
end
it "should return the uniq values of @should + retrieve as a string if !inclusive with the @ values leading" do
@property.should = ["foo", "bar"]
expect(@property).to receive(:inclusive?).and_return(false)
expect(@property).to receive(:retrieve).and_return(["foo","baz"])
expect(@property.should).to eq("foo,bar,baz")
end
end
describe "when calling dearrayify" do
it "should join the array with the delimiter" do
array = double("array")
expect(array).to receive(:join).with(@property.delimiter)
@property.dearrayify(array)
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/file_system/uniquefile_spec.rb | spec/unit/file_system/uniquefile_spec.rb | require 'spec_helper'
describe Puppet::FileSystem::Uniquefile do
include PuppetSpec::Files
it "makes the name of the file available" do
Puppet::FileSystem::Uniquefile.open_tmp('foo') do |file|
expect(file.path).to match(/foo/)
end
end
it "ensures the file has permissions 0600", unless: Puppet::Util::Platform.windows? do
Puppet::FileSystem::Uniquefile.open_tmp('foo') do |file|
expect(Puppet::FileSystem.stat(file.path).mode & 07777).to eq(0600)
end
end
it "provides a writeable file" do
Puppet::FileSystem::Uniquefile.open_tmp('foo') do |file|
file.write("stuff")
file.flush
expect(Puppet::FileSystem.read(file.path)).to eq("stuff")
end
end
it "returns the value of the block" do
the_value = Puppet::FileSystem::Uniquefile.open_tmp('foo') do |file|
"my value"
end
expect(the_value).to eq("my value")
end
it "unlinks the temporary file" do
filename = Puppet::FileSystem::Uniquefile.open_tmp('foo') do |file|
file.path
end
expect(Puppet::FileSystem.exist?(filename)).to be_falsey
end
it "unlinks the temporary file even if the block raises an error" do
filename = nil
begin
Puppet::FileSystem::Uniquefile.open_tmp('foo') do |file|
filename = file.path
raise "error!"
end
rescue
end
expect(Puppet::FileSystem.exist?(filename)).to be_falsey
end
it "propagates lock creation failures" do
# use an arbitrary exception so as not accidentally collide
# with the ENOENT that occurs when trying to call rmdir
allow(Puppet::FileSystem::Uniquefile).to receive(:mkdir).and_raise('arbitrary failure')
expect(Puppet::FileSystem::Uniquefile).not_to receive(:rmdir)
expect {
Puppet::FileSystem::Uniquefile.open_tmp('foo') { |tmp| }
}.to raise_error('arbitrary failure')
end
it "only removes lock files that exist" do
# prevent the .lock directory from being created
allow(Puppet::FileSystem::Uniquefile).to receive(:mkdir)
# and expect cleanup to be skipped
expect(Puppet::FileSystem::Uniquefile).not_to receive(:rmdir)
Puppet::FileSystem::Uniquefile.open_tmp('foo') { |tmp| }
end
it "reports when a parent directory does not exist" do
dir = tmpdir('uniquefile')
lock = File.join(dir, 'path', 'to', 'lock')
expect {
Puppet::FileSystem::Uniquefile.new('foo', lock) { |tmp| }
}.to raise_error(Errno::ENOENT, %r{No such file or directory - A directory component in .* does not exist or is a dangling symbolic link})
end
it "should use UTF8 characters in TMP,TEMP,TMPDIR environment variable", :if => Puppet::Util::Platform.windows? do
rune_utf8 = "\u16A0\u16C7\u16BB\u16EB\u16D2\u16E6\u16A6\u16EB\u16A0\u16B1\u16A9\u16A0\u16A2\u16B1\u16EB\u16A0\u16C1\u16B1\u16AA\u16EB\u16B7\u16D6\u16BB\u16B9\u16E6\u16DA\u16B3\u16A2\u16D7"
temp_rune_utf8 = File.join(Dir.tmpdir, rune_utf8)
Puppet::FileSystem.mkpath(temp_rune_utf8)
# Set the temporary environment variables to the UTF8 temp path
Puppet::Util::Windows::Process.set_environment_variable('TMPDIR', temp_rune_utf8)
Puppet::Util::Windows::Process.set_environment_variable('TMP', temp_rune_utf8)
Puppet::Util::Windows::Process.set_environment_variable('TEMP', temp_rune_utf8)
# Create a unique file
filename = Puppet::FileSystem::Uniquefile.open_tmp('foo') do |file|
File.dirname(file.path)
end
expect(filename).to eq(temp_rune_utf8)
end
it "preserves tilde characters" do
Puppet::FileSystem::Uniquefile.open_tmp('~foo') do |file|
expect(File.basename(file.path)).to start_with('~foo')
end
end
context "Ruby 1.9.3 Tempfile tests" do
# the remaining tests in this file are ported directly from the ruby 1.9.3 source,
# since most of this file was ported from there
# see: https://github.com/ruby/ruby/blob/v1_9_3_547/test/test_tempfile.rb
def tempfile(*args, &block)
t = Puppet::FileSystem::Uniquefile.new(*args, &block)
@tempfile = (t unless block)
end
after(:each) do
if @tempfile
@tempfile.close!
end
end
it "creates tempfiles" do
t = tempfile("foo")
path = t.path
t.write("hello world")
t.close
expect(File.read(path)).to eq("hello world")
end
it "saves in tmpdir by default" do
t = tempfile("foo")
expect(Dir.tmpdir).to eq(File.dirname(t.path))
end
it "saves in given directory" do
subdir = File.join(Dir.tmpdir, "tempfile-test-#{rand}")
Dir.mkdir(subdir)
begin
tempfile = Tempfile.new("foo", subdir)
tempfile.close
begin
expect(subdir).to eq(File.dirname(tempfile.path))
ensure
tempfile.unlink
end
ensure
Dir.rmdir(subdir)
end
end
it "supports basename" do
t = tempfile("foo")
expect(File.basename(t.path)).to match(/^foo/)
end
it "supports basename with suffix" do
t = tempfile(["foo", ".txt"])
expect(File.basename(t.path)).to match(/^foo/)
expect(File.basename(t.path)).to match(/\.txt$/)
end
it "supports unlink" do
t = tempfile("foo")
path = t.path
t.close
expect(File.exist?(path)).to eq(true)
t.unlink
expect(File.exist?(path)).to eq(false)
expect(t.path).to eq(nil)
end
it "supports closing" do
t = tempfile("foo")
expect(t.closed?).to eq(false)
t.close
expect(t.closed?).to eq(true)
end
it "supports closing and unlinking via boolean argument" do
t = tempfile("foo")
path = t.path
t.close(true)
expect(t.closed?).to eq(true)
expect(t.path).to eq(nil)
expect(File.exist?(path)).to eq(false)
end
context "on unix platforms", :unless => Puppet::Util::Platform.windows? do
it "close doesn't unlink if already unlinked" do
t = tempfile("foo")
path = t.path
t.unlink
File.open(path, "w").close
begin
t.close(true)
expect(File.exist?(path)).to eq(true)
ensure
File.unlink(path) rescue nil
end
end
end
it "supports close!" do
t = tempfile("foo")
path = t.path
t.close!
expect(t.closed?).to eq(true)
expect(t.path).to eq(nil)
expect(File.exist?(path)).to eq(false)
end
context "on unix platforms", :unless => Puppet::Util::Platform.windows? do
it "close! doesn't unlink if already unlinked" do
t = tempfile("foo")
path = t.path
t.unlink
File.open(path, "w").close
begin
t.close!
expect(File.exist?(path)).to eq(true)
ensure
File.unlink(path) rescue nil
end
end
end
it "close does not make path nil" do
t = tempfile("foo")
t.close
expect(t.path.nil?).to eq(false)
end
it "close flushes buffer" do
t = tempfile("foo")
t.write("hello")
t.close
expect(File.size(t.path)).to eq(5)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/file_system/path_pattern_spec.rb | spec/unit/file_system/path_pattern_spec.rb | require 'spec_helper'
require 'puppet_spec/files'
require 'puppet/file_system'
require 'puppet/util'
describe Puppet::FileSystem::PathPattern do
include PuppetSpec::Files
InvalidPattern = Puppet::FileSystem::PathPattern::InvalidPattern
describe 'relative' do
it "can not be created with a traversal up the directory tree" do
expect do
Puppet::FileSystem::PathPattern.relative("my/../other")
end.to raise_error(InvalidPattern, "PathPatterns cannot be created with directory traversals.")
end
it "can be created with a '..' prefixing a filename" do
expect(Puppet::FileSystem::PathPattern.relative("my/..other").to_s).to eq("my/..other")
end
it "can be created with a '..' suffixing a filename" do
expect(Puppet::FileSystem::PathPattern.relative("my/other..").to_s).to eq("my/other..")
end
it "can be created with a '..' embedded in a filename" do
expect(Puppet::FileSystem::PathPattern.relative("my/ot..her").to_s).to eq("my/ot..her")
end
it "can not be created with a \\0 byte embedded" do
expect do
Puppet::FileSystem::PathPattern.relative("my/\0/other")
end.to raise_error(InvalidPattern, "PathPatterns cannot be created with a zero byte.")
end
it "can not be created with a windows drive" do
expect do
Puppet::FileSystem::PathPattern.relative("c:\\relative\\path")
end.to raise_error(InvalidPattern, "A relative PathPattern cannot be prefixed with a drive.")
end
it "can not be created with a windows drive (with space)" do
expect do
Puppet::FileSystem::PathPattern.relative(" c:\\relative\\path")
end.to raise_error(InvalidPattern, "A relative PathPattern cannot be prefixed with a drive.")
end
it "can not create an absolute relative path" do
expect do
Puppet::FileSystem::PathPattern.relative("/no/absolutes")
end.to raise_error(InvalidPattern, "A relative PathPattern cannot be an absolute path.")
end
it "can not create an absolute relative path (with space)" do
expect do
Puppet::FileSystem::PathPattern.relative("\t/no/absolutes")
end.to raise_error(InvalidPattern, "A relative PathPattern cannot be an absolute path.")
end
it "can not create a relative path that is a windows path relative to the current drive" do
expect do
Puppet::FileSystem::PathPattern.relative("\\no\relatives")
end.to raise_error(InvalidPattern, "A PathPattern cannot be a Windows current drive relative path.")
end
it "creates a relative PathPattern from a valid relative path" do
expect(Puppet::FileSystem::PathPattern.relative("a/relative/path").to_s).to eq("a/relative/path")
end
it "is not absolute" do
expect(Puppet::FileSystem::PathPattern.relative("a/relative/path")).to_not be_absolute
end
end
describe 'absolute' do
it "can not create a relative absolute path" do
expect do
Puppet::FileSystem::PathPattern.absolute("no/relatives")
end.to raise_error(InvalidPattern, "An absolute PathPattern cannot be a relative path.")
end
it "can not create an absolute path that is a windows path relative to the current drive" do
expect do
Puppet::FileSystem::PathPattern.absolute("\\no\\relatives")
end.to raise_error(InvalidPattern, "A PathPattern cannot be a Windows current drive relative path.")
end
it "creates an absolute PathPattern from a valid absolute path" do
expect(Puppet::FileSystem::PathPattern.absolute("/an/absolute/path").to_s).to eq("/an/absolute/path")
end
it "creates an absolute PathPattern from a valid Windows absolute path" do
expect(Puppet::FileSystem::PathPattern.absolute("c:/absolute/windows/path").to_s).to eq("c:/absolute/windows/path")
end
it "can be created with a '..' embedded in a filename on windows", :if => Puppet::Util::Platform.windows? do
expect(Puppet::FileSystem::PathPattern.absolute(%q{c:\..my\ot..her\one..}).to_s).to eq(%q{c:\..my\ot..her\one..})
end
it "is absolute" do
expect(Puppet::FileSystem::PathPattern.absolute("c:/absolute/windows/path")).to be_absolute
end
end
it "prefixes the relative path pattern with another path" do
pattern = Puppet::FileSystem::PathPattern.relative("docs/*_thoughts.txt")
prefix = Puppet::FileSystem::PathPattern.absolute("/prefix")
absolute_pattern = pattern.prefix_with(prefix)
expect(absolute_pattern).to be_absolute
expect(absolute_pattern.to_s).to eq(File.join("/prefix", "docs/*_thoughts.txt"))
end
it "refuses to prefix with a relative pattern" do
pattern = Puppet::FileSystem::PathPattern.relative("docs/*_thoughts.txt")
prefix = Puppet::FileSystem::PathPattern.relative("prefix")
expect do
pattern.prefix_with(prefix)
end.to raise_error(InvalidPattern, "An absolute PathPattern cannot be a relative path.")
end
it "applies the pattern to the filesystem as a glob" do
dir = tmpdir('globtest')
create_file_in(dir, "found_one")
create_file_in(dir, "found_two")
create_file_in(dir, "third_not_found")
pattern = Puppet::FileSystem::PathPattern.relative("found_*").prefix_with(
Puppet::FileSystem::PathPattern.absolute(dir))
expect(pattern.glob).to match_array([File.join(dir, "found_one"),
File.join(dir, "found_two")])
end
it 'globs wildcard patterns properly' do
dir = tmpdir('globtest')
create_file_in(dir, 'foo.pp')
create_file_in(dir, 'foo.pp.pp')
pattern = Puppet::FileSystem::PathPattern.absolute(File.join(dir, '**/*.pp'))
expect(pattern.glob).to match_array([File.join(dir, 'foo.pp'),
File.join(dir, 'foo.pp.pp')])
end
def create_file_in(dir, name)
File.open(File.join(dir, name), "w") { |f| f.puts "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/configurer/downloader_spec.rb | spec/unit/configurer/downloader_spec.rb | require 'spec_helper'
require 'puppet/configurer/downloader'
describe Puppet::Configurer::Downloader do
require 'puppet_spec/files'
include PuppetSpec::Files
let(:path) { Puppet[:plugindest] }
let(:source) { 'puppet://puppet/plugins' }
it "should require a name" do
expect { Puppet::Configurer::Downloader.new }.to raise_error(ArgumentError)
end
it "should require a path and a source at initialization" do
expect { Puppet::Configurer::Downloader.new("name") }.to raise_error(ArgumentError)
end
it "should set the name, path and source appropriately" do
dler = Puppet::Configurer::Downloader.new("facts", "path", "source")
expect(dler.name).to eq("facts")
expect(dler.path).to eq("path")
expect(dler.source).to eq("source")
end
def downloader(options = {})
options[:name] ||= "facts"
options[:path] ||= path
options[:source_permissions] ||= :ignore
Puppet::Configurer::Downloader.new(options[:name], options[:path], source, options[:ignore], options[:environment], options[:source_permissions])
end
def generate_file_resource(options = {})
dler = downloader(options)
dler.file
end
describe "when creating the file that does the downloading" do
it "should create a file instance with the right path and source" do
file = generate_file_resource(:path => path, :source => source)
expect(file[:path]).to eq(path)
expect(file[:source]).to eq([source])
end
it "should tag the file with the downloader name" do
name = "mydownloader"
file = generate_file_resource(:name => name)
expect(file[:tag]).to eq([name])
end
it "should always recurse" do
file = generate_file_resource
expect(file[:recurse]).to be_truthy
end
it "should follow links by default" do
file = generate_file_resource
expect(file[:links]).to eq(:follow)
end
it "should always purge" do
file = generate_file_resource
expect(file[:purge]).to be_truthy
end
it "should never be in noop" do
file = generate_file_resource
expect(file[:noop]).to be_falsey
end
it "should set source_permissions to ignore by default" do
file = generate_file_resource
expect(file[:source_permissions]).to eq(:ignore)
end
it "should ignore the max file limit" do
file = generate_file_resource
expect(file[:max_files]).to eq(-1)
end
describe "on POSIX", :if => Puppet.features.posix? do
it "should allow source_permissions to be overridden" do
file = generate_file_resource(:source_permissions => :use)
expect(file[:source_permissions]).to eq(:use)
end
it "should always set the owner to the current UID" do
expect(Process).to receive(:uid).and_return(51)
file = generate_file_resource(:path => '/path')
expect(file[:owner]).to eq(51)
end
it "should always set the group to the current GID" do
expect(Process).to receive(:gid).and_return(61)
file = generate_file_resource(:path => '/path')
expect(file[:group]).to eq(61)
end
end
describe "on Windows", :if => Puppet::Util::Platform.windows? do
it "should omit the owner" do
file = generate_file_resource(:path => 'C:/path')
expect(file[:owner]).to be_nil
end
it "should omit the group" do
file = generate_file_resource(:path => 'C:/path')
expect(file[:group]).to be_nil
end
end
it "should always force the download" do
file = generate_file_resource
expect(file[:force]).to be_truthy
end
it "should never back up when downloading" do
file = generate_file_resource
expect(file[:backup]).to be_falsey
end
it "should support providing an 'ignore' parameter" do
file = generate_file_resource(:ignore => '.svn')
expect(file[:ignore]).to eq(['.svn'])
end
it "should split the 'ignore' parameter on whitespace" do
file = generate_file_resource(:ignore => '.svn CVS')
expect(file[:ignore]).to eq(['.svn', 'CVS'])
end
end
describe "when creating the catalog to do the downloading" do
before do
@path = make_absolute("/download/path")
@dler = Puppet::Configurer::Downloader.new("foo", @path, make_absolute("source"))
end
it "should create a catalog and add the file to it" do
catalog = @dler.catalog
expect(catalog.resources.size).to eq(1)
expect(catalog.resources.first.class).to eq(Puppet::Type::File)
expect(catalog.resources.first.name).to eq(@path)
end
it "should specify that it is not managing a host catalog" do
expect(@dler.catalog.host_config).to eq(false)
end
it "should not issue a deprecation warning for source_permissions" do
expect(Puppet).not_to receive(:puppet_deprecation_warning)
catalog = @dler.catalog
expect(catalog.resources.size).to eq(1) # Must consume catalog to fix warnings
end
end
describe "when downloading" do
before do
@dl_name = tmpfile("downloadpath")
source_name = tmpfile("source")
File.open(source_name, 'w') {|f| f.write('hola mundo') }
env = Puppet::Node::Environment.remote('foo')
@dler = Puppet::Configurer::Downloader.new("foo", @dl_name, source_name, Puppet[:pluginsignore], env)
end
it "should not skip downloaded resources when filtering on tags" do
Puppet[:tags] = 'maytag'
@dler.evaluate
expect(Puppet::FileSystem.exist?(@dl_name)).to be_truthy
end
it "should log that it is downloading" do
expect(Puppet).to receive(:info)
@dler.evaluate
end
it "should return all changed file paths" do
Puppet[:ignore_plugin_errors] = true
trans = double('transaction')
catalog = double('catalog')
expect(@dler).to receive(:catalog).and_return(catalog)
expect(catalog).to receive(:apply).and_yield(trans)
resource = double('resource')
expect(resource).to receive(:[]).with(:path).and_return("/changed/file")
expect(trans).to receive(:changed?).and_return([resource])
expect(@dler.evaluate).to eq(%w{/changed/file})
end
it "should yield the resources if a block is given" do
Puppet[:ignore_plugin_errors] = true
trans = double('transaction')
catalog = double('catalog')
expect(@dler).to receive(:catalog).and_return(catalog)
expect(catalog).to receive(:apply).and_yield(trans)
resource = double('resource')
expect(resource).to receive(:[]).with(:path).and_return("/changed/file")
expect(trans).to receive(:changed?).and_return([resource])
yielded = nil
@dler.evaluate { |r| yielded = r }
expect(yielded).to eq(resource)
end
it "should catch and log exceptions" do
Puppet[:ignore_plugin_errors] = true
expect(Puppet).to receive(:log_exception)
# The downloader creates a new catalog for each apply, and really the only object
# that it is possible to stub for the purpose of generating a puppet error
allow_any_instance_of(Puppet::Resource::Catalog).to receive(:apply).and_raise(Puppet::Error, "testing")
expect { @dler.evaluate }.not_to raise_error
end
it "raises an exception if catalog application fails" do
expect(@dler.file).to receive(:retrieve).and_raise(Puppet::Error, "testing")
expect {
@dler.evaluate
}.to raise_error(Puppet::Error, /testing/)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/configurer/plugin_handler_spec.rb | spec/unit/configurer/plugin_handler_spec.rb | require 'spec_helper'
require 'puppet/configurer'
require 'puppet/configurer/plugin_handler'
describe Puppet::Configurer::PluginHandler do
let(:pluginhandler) { Puppet::Configurer::PluginHandler.new() }
let(:environment) { Puppet::Node::Environment.create(:myenv, []) }
before :each do
# PluginHandler#load_plugin has an extra-strong rescue clause
# this mock is to make sure that we don't silently ignore errors
expect(Puppet).not_to receive(:err)
end
context "server agent version is 5.3.4" do
around do |example|
Puppet.override(server_agent_version: "5.3.4") do
example.run
end
end
context "when i18n is enabled" do
before :each do
Puppet[:disable_i18n] = false
end
it "downloads plugins, facts, and locales" do
times_called = 0
allow_any_instance_of(Puppet::Configurer::Downloader).to receive(:evaluate) { times_called += 1 }.and_return([])
pluginhandler.download_plugins(environment)
expect(times_called).to eq(3)
end
it "returns downloaded plugin, fact, and locale filenames" do
times_called = 0
allow_any_instance_of(Puppet::Configurer::Downloader).to receive(:evaluate) do
times_called += 1
if times_called == 1
%w[/a]
elsif times_called == 2
%w[/b]
else
%w[/c]
end
end
expect(pluginhandler.download_plugins(environment)).to match_array(%w[/a /b /c])
expect(times_called).to eq(3)
end
end
context "when i18n is disabled" do
before :each do
Puppet[:disable_i18n] = true
end
it "downloads plugins, facts, but no locales" do
times_called = 0
allow_any_instance_of(Puppet::Configurer::Downloader).to receive(:evaluate) { times_called += 1 }.and_return([])
pluginhandler.download_plugins(environment)
expect(times_called).to eq(2)
end
it "returns downloaded plugin, fact, and locale filenames" do
times_called = 0
allow_any_instance_of(Puppet::Configurer::Downloader).to receive(:evaluate) do
times_called += 1
if times_called == 1
%w[/a]
elsif times_called == 2
%w[/b]
else
%w[/c]
end
end
expect(pluginhandler.download_plugins(environment)).to match_array(%w[/a /b])
expect(times_called).to eq(2)
end
end
end
context "server agent version is 5.3.3" do
around do |example|
Puppet.override(server_agent_version: "5.3.3") do
example.run
end
end
it "returns downloaded plugin, fact, but not locale filenames" do
times_called = 0
allow_any_instance_of(Puppet::Configurer::Downloader).to receive(:evaluate) do
times_called += 1
if times_called == 1
%w[/a]
else
%w[/b]
end
end
expect(pluginhandler.download_plugins(environment)).to match_array(%w[/a /b])
expect(times_called).to eq(2)
end
end
context "blank server agent version" do
around do |example|
Puppet.override(server_agent_version: "") do
example.run
end
end
it "returns downloaded plugin, fact, but not locale filenames" do
times_called = 0
allow_any_instance_of(Puppet::Configurer::Downloader).to receive(:evaluate) do
times_called += 1
if times_called == 1
%w[/a]
else
%w[/b]
end
end
expect(pluginhandler.download_plugins(environment)).to match_array(%w[/a /b])
expect(times_called).to eq(2)
end
end
context "nil server agent version" do
it "returns downloaded plugin, fact, but not locale filenames" do
times_called = 0
allow_any_instance_of(Puppet::Configurer::Downloader).to receive(:evaluate) do
times_called += 1
if times_called == 1
%w[/a]
else
%w[/b]
end
end
expect(pluginhandler.download_plugins(environment)).to match_array(%w[/a /b])
expect(times_called).to eq(2)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/configurer/fact_handler_spec.rb | spec/unit/configurer/fact_handler_spec.rb | require 'spec_helper'
require 'puppet/configurer'
require 'puppet/configurer/fact_handler'
require 'matchers/json'
class FactHandlerTester
include Puppet::Configurer::FactHandler
attr_accessor :environment
def initialize(environment)
self.environment = environment
end
def reload_facter
# don't want to do this in tests
end
end
describe Puppet::Configurer::FactHandler do
include JSONMatchers
let(:facthandler) { FactHandlerTester.new('production') }
describe "when finding facts" do
it "should use the node name value to retrieve the facts" do
foo_facts = Puppet::Node::Facts.new('foo')
bar_facts = Puppet::Node::Facts.new('bar')
Puppet::Node::Facts.indirection.save(foo_facts)
Puppet::Node::Facts.indirection.save(bar_facts)
Puppet[:certname] = 'foo'
Puppet[:node_name_value] = 'bar'
expect(facthandler.find_facts).to eq(bar_facts)
end
it "should set the facts name based on the node_name_fact" do
facts = Puppet::Node::Facts.new(Puppet[:node_name_value], 'my_name_fact' => 'other_node_name')
Puppet::Node::Facts.indirection.save(facts)
Puppet[:node_name_fact] = 'my_name_fact'
expect(facthandler.find_facts.name).to eq('other_node_name')
end
it "should set the node_name_value based on the node_name_fact" do
facts = Puppet::Node::Facts.new(Puppet[:node_name_value], 'my_name_fact' => 'other_node_name')
Puppet::Node::Facts.indirection.save(facts)
Puppet[:node_name_fact] = 'my_name_fact'
facthandler.find_facts
expect(Puppet[:node_name_value]).to eq('other_node_name')
end
it "should fail if finding facts fails" do
expect(Puppet::Node::Facts.indirection).to receive(:find).and_raise(RuntimeError)
expect { facthandler.find_facts }.to raise_error(Puppet::Error, /Could not retrieve local facts/)
end
it "should only load fact plugins once" do
expect(Puppet::Node::Facts.indirection).to receive(:find).once
facthandler.find_facts
end
end
context "when serializing" do
facts_with_special_characters = [
{ :hash => { 'afact' => 'a+b' }, :encoded => '%22values%22%3A%7B%22afact%22%3A%22' + 'a%2Bb' + '%22%7D' },
{ :hash => { 'afact' => 'a b' }, :encoded => '%22values%22%3A%7B%22afact%22%3A%22' + 'a%20b' + '%22%7D' },
{ :hash => { 'afact' => 'a&b' }, :encoded => '%22values%22%3A%7B%22afact%22%3A%22' + 'a%26b' + '%22%7D' },
{ :hash => { 'afact' => 'a*b' }, :encoded => '%22values%22%3A%7B%22afact%22%3A%22' + 'a%2Ab' + '%22%7D' },
{ :hash => { 'afact' => 'a=b' }, :encoded => '%22values%22%3A%7B%22afact%22%3A%22' + 'a%3Db' + '%22%7D' },
# 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
{ :hash => { 'afact' => "A\u06FF\u16A0\u{2070E}" }, :encoded => '%22values%22%3A%7B%22afact%22%3A%22' + 'A%DB%BF%E1%9A%A0%F0%A0%9C%8E' + '%22%7D' },
]
context "as pson", if: Puppet.features.pson? do
before :each do
Puppet[:preferred_serialization_format] = 'pson'
end
it "should serialize and CGI escape the fact values for uploading" do
facts = Puppet::Node::Facts.new(Puppet[:node_name_value], 'my_name_fact' => 'other_node_name')
Puppet::Node::Facts.indirection.save(facts)
text = Puppet::Util.uri_query_encode(facthandler.find_facts.render(:pson))
expect(text).to include('%22values%22%3A%7B%22my_name_fact%22%3A%22other_node_name%22%7D')
expect(facthandler.facts_for_uploading).to eq({:facts_format => :pson, :facts => text})
end
facts_with_special_characters.each do |test_fact|
it "should properly accept the fact #{test_fact[:hash]}" do
facts = Puppet::Node::Facts.new(Puppet[:node_name_value], test_fact[:hash])
Puppet::Node::Facts.indirection.save(facts)
text = Puppet::Util.uri_query_encode(facthandler.find_facts.render(:pson))
to_upload = facthandler.facts_for_uploading
expect(to_upload).to eq({:facts_format => :pson, :facts => text})
expect(text).to include(test_fact[:encoded])
# this is not sufficient to test whether these values are sent via HTTP GET or HTTP POST in actual catalog request
expect(JSON.parse(Puppet::Util.uri_unescape(to_upload[:facts]))['values']).to eq(test_fact[:hash])
end
end
end
context "as json" do
it "should serialize and CGI escape the fact values for uploading" do
facts = Puppet::Node::Facts.new(Puppet[:node_name_value], 'my_name_fact' => 'other_node_name')
Puppet::Node::Facts.indirection.save(facts)
text = Puppet::Util.uri_query_encode(facthandler.find_facts.render(:json))
expect(text).to include('%22values%22%3A%7B%22my_name_fact%22%3A%22other_node_name%22%7D')
expect(facthandler.facts_for_uploading).to eq({:facts_format => 'application/json', :facts => text})
end
facts_with_special_characters.each do |test_fact|
it "should properly accept the fact #{test_fact[:hash]}" do
facts = Puppet::Node::Facts.new(Puppet[:node_name_value], test_fact[:hash])
Puppet::Node::Facts.indirection.save(facts)
text = Puppet::Util.uri_query_encode(facthandler.find_facts.render(:json))
to_upload = facthandler.facts_for_uploading
expect(to_upload).to eq({:facts_format => 'application/json', :facts => text})
expect(text).to include(test_fact[:encoded])
expect(JSON.parse(Puppet::Util.uri_unescape(to_upload[:facts]))['values']).to eq(test_fact[:hash])
end
end
end
it "should generate valid facts data against the facts schema" do
facts = Puppet::Node::Facts.new(Puppet[:node_name_value], 'my_name_fact' => 'other_node_name')
Puppet::Node::Facts.indirection.save(facts)
# prefer Puppet::Util.uri_unescape but validate CGI also works
encoded_facts = facthandler.facts_for_uploading[:facts]
expect(Puppet::Util.uri_unescape(encoded_facts)).to validate_against('api/schemas/facts.json')
expect(CGI.unescape(encoded_facts)).to validate_against('api/schemas/facts.json')
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/provider/parsedfile_spec.rb | spec/unit/provider/parsedfile_spec.rb | require 'spec_helper'
require 'puppet_spec/files'
require 'puppet'
require 'puppet/provider/parsedfile'
Puppet::Type.newtype(:parsedfile_type) do
newparam(:name)
newproperty(:target)
end
# Most of the tests for this are still in test/ral/provider/parsedfile.rb.
describe Puppet::Provider::ParsedFile do
# The ParsedFile provider class is meant to be used as an abstract base class
# but also stores a lot of state within the singleton class. To avoid
# sharing data between classes we construct an anonymous class that inherits
# the ParsedFile provider instead of directly working with the ParsedFile
# provider itself.
let(:parsed_type) do
Puppet::Type.type(:parsedfile_type)
end
let!(:provider) { parsed_type.provide(:parsedfile_provider, :parent => described_class) }
describe "when looking up records loaded from disk" do
it "should return nil if no records have been loaded" do
expect(provider.record?("foo")).to be_nil
end
end
describe "when generating a list of instances" do
it "should return an instance for each record parsed from all of the registered targets" do
expect(provider).to receive(:targets).and_return(%w{/one /two})
allow(provider).to receive(:skip_record?).and_return(false)
one = [:uno1, :uno2]
two = [:dos1, :dos2]
expect(provider).to receive(:prefetch_target).with("/one").and_return(one)
expect(provider).to receive(:prefetch_target).with("/two").and_return(two)
results = []
(one + two).each do |inst|
results << inst.to_s + "_instance"
expect(provider).to receive(:new).with(inst).and_return(results[-1])
end
expect(provider.instances).to eq(results)
end
it "should ignore target when retrieve fails" do
expect(provider).to receive(:targets).and_return(%w{/one /two /three})
allow(provider).to receive(:skip_record?).and_return(false)
expect(provider).to receive(:retrieve).with("/one").and_return([
{:name => 'target1_record1'},
{:name => 'target1_record2'}
])
expect(provider).to receive(:retrieve).with("/two").and_raise(Puppet::Util::FileType::FileReadError, "some error")
expect(provider).to receive(:retrieve).with("/three").and_return([
{:name => 'target3_record1'},
{:name => 'target3_record2'}
])
expect(Puppet).to receive(:err).with('Could not prefetch parsedfile_type provider \'parsedfile_provider\' target \'/two\': some error. Treating as empty')
expect(provider).to receive(:new).with({:name => 'target1_record1', :on_disk => true, :target => '/one', :ensure => :present}).and_return('r1')
expect(provider).to receive(:new).with({:name => 'target1_record2', :on_disk => true, :target => '/one', :ensure => :present}).and_return('r2')
expect(provider).to receive(:new).with({:name => 'target3_record1', :on_disk => true, :target => '/three', :ensure => :present}).and_return('r3')
expect(provider).to receive(:new).with({:name => 'target3_record2', :on_disk => true, :target => '/three', :ensure => :present}).and_return('r4')
expect(provider.instances).to eq(%w{r1 r2 r3 r4})
end
it "should skip specified records" do
expect(provider).to receive(:targets).and_return(%w{/one})
expect(provider).to receive(:skip_record?).with(:uno).and_return(false)
expect(provider).to receive(:skip_record?).with(:dos).and_return(true)
one = [:uno, :dos]
expect(provider).to receive(:prefetch_target).and_return(one)
expect(provider).to receive(:new).with(:uno).and_return("eh")
expect(provider).not_to receive(:new).with(:dos)
provider.instances
end
it "should raise if parsing returns nil" do
expect(provider).to receive(:targets).and_return(%w{/one})
expect_any_instance_of(Puppet::Util::FileType::FileTypeFlat).to receive(:read).and_return('a=b')
expect(provider).to receive(:parse).and_return(nil)
expect {
provider.instances
}.to raise_error(Puppet::DevError, %r{Prefetching /one for provider parsedfile_provider returned nil})
end
end
describe "when matching resources to existing records" do
let(:first_resource) { double(:one, :name => :one) }
let(:second_resource) { double(:two, :name => :two) }
let(:resources) {{:one => first_resource, :two => second_resource}}
it "returns a resource if the record name matches the resource name" do
record = {:name => :one}
expect(provider.resource_for_record(record, resources)).to be first_resource
end
it "doesn't return a resource if the record name doesn't match any resource names" do
record = {:name => :three}
expect(provider.resource_for_record(record, resources)).to be_nil
end
end
describe "when flushing a file's records to disk" do
before do
# This way we start with some @records, like we would in real life.
allow(provider).to receive(:retrieve).and_return([])
provider.default_target = "/foo/bar"
provider.initvars
provider.prefetch
@filetype = Puppet::Util::FileType.filetype(:flat).new("/my/file")
allow(Puppet::Util::FileType.filetype(:flat)).to receive(:new).with("/my/file").and_return(@filetype)
allow(@filetype).to receive(:write)
end
it "should back up the file being written if the filetype can be backed up" do
expect(@filetype).to receive(:backup)
provider.flush_target("/my/file")
end
it "should not try to back up the file if the filetype cannot be backed up" do
@filetype = Puppet::Util::FileType.filetype(:ram).new("/my/file")
expect(Puppet::Util::FileType.filetype(:flat)).to receive(:new).and_return(@filetype)
allow(@filetype).to receive(:write)
provider.flush_target("/my/file")
end
it "should not back up the file more than once between calls to 'prefetch'" do
expect(@filetype).to receive(:backup).once
provider.flush_target("/my/file")
provider.flush_target("/my/file")
end
it "should back the file up again once the file has been reread" do
expect(@filetype).to receive(:backup).twice
provider.flush_target("/my/file")
provider.prefetch
provider.flush_target("/my/file")
end
end
describe "when flushing multiple files" do
describe "and an error is encountered" do
it "the other file does not fail" do
allow(provider).to receive(:backup_target)
bad_file = 'broken'
good_file = 'writable'
bad_writer = double('bad')
expect(bad_writer).to receive(:write).and_raise(Exception, "Failed to write to bad file")
good_writer = double('good')
expect(good_writer).to receive(:write).and_return(nil)
allow(provider).to receive(:target_object).with(bad_file).and_return(bad_writer)
allow(provider).to receive(:target_object).with(good_file).and_return(good_writer)
bad_resource = parsed_type.new(:name => 'one', :target => bad_file)
good_resource = parsed_type.new(:name => 'two', :target => good_file)
expect {
bad_resource.flush
}.to raise_error(Exception, "Failed to write to bad file")
good_resource.flush
end
end
end
end
describe "A very basic provider based on ParsedFile" do
include PuppetSpec::Files
let(:input_text) { File.read(my_fixture('simple.txt')) }
let(:target) { tmpfile('parsedfile_spec') }
let(:provider) do
example_provider_class = Class.new(Puppet::Provider::ParsedFile)
example_provider_class.default_target = target
# Setup some record rules
example_provider_class.instance_eval do
text_line :text, :match => %r{.}
end
example_provider_class.initvars
example_provider_class.prefetch
# evade a race between multiple invocations of the header method
allow(example_provider_class).to receive(:header).
and_return("# HEADER As added by puppet.\n")
example_provider_class
end
context "writing file contents back to disk" do
it "should not change anything except from adding a header" do
input_records = provider.parse(input_text)
expect(provider.to_file(input_records)).
to match provider.header + input_text
end
end
context "rewriting a file containing a native header" do
let(:regex) { %r/^# HEADER.*third party\.\n/ }
let(:input_records) { provider.parse(input_text) }
before :each do
allow(provider).to receive(:native_header_regex).and_return(regex)
end
it "should move the native header to the top" do
expect(provider.to_file(input_records)).not_to match(/\A#{provider.header}/)
end
context "and dropping native headers found in input" do
before :each do
allow(provider).to receive(:drop_native_header).and_return(true)
end
it "should not include the native header in the output" do
expect(provider.to_file(input_records)).not_to match regex
end
end
end
context 'parsing a record type' do
let(:input_text) { File.read(my_fixture('aliases.txt')) }
let(:target) { tmpfile('parsedfile_spec') }
let(:provider) do
example_provider_class = Class.new(Puppet::Provider::ParsedFile)
example_provider_class.default_target = target
# Setup some record rules
example_provider_class.instance_eval do
record_line :aliases, :fields => %w{manager alias}, :separator => ':'
end
example_provider_class.initvars
example_provider_class.prefetch
example_provider_class
end
let(:expected_result) do
[
{:manager=>"manager", :alias=>" root", :record_type=>:aliases},
{:manager=>"dumper", :alias=>" postmaster", :record_type=>:aliases}
]
end
subject { provider.parse(input_text) }
it { is_expected.to match_array(expected_result) }
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/provider/nameservice_spec.rb | spec/unit/provider/nameservice_spec.rb | require 'spec_helper'
require 'puppet/provider/nameservice'
require 'puppet/etc'
require 'puppet_spec/character_encoding'
Puppet::Type.newtype(:nameservice_dummytype) do
newparam(:name)
ensurable
newproperty(:foo)
newproperty(:bar)
end
Puppet::Type.type(:nameservice_dummytype).provide(:nameservice_dummyprovider, parent: Puppet::Provider::NameService) do
def posixmethod(param)
param
end
def modifycmd(param, value)
[]
end
end
describe Puppet::Provider::NameService do
before :each do
provider.class.initvars
provider.class.resource_type = faketype
end
# These are values getpwent might give you
let :users do
[
Etc::Passwd.new('root', 'x', 0, 0),
Etc::Passwd.new('foo', 'x', 1000, 2000),
nil
]
end
# These are values getgrent might give you
let :groups do
[
Etc::Group.new('root', 'x', 0, %w{root}),
Etc::Group.new('bin', 'x', 1, %w{root bin daemon}),
nil
]
end
# A fake struct besides Etc::Group and Etc::Passwd
let :fakestruct do
Struct.new(:foo, :bar)
end
# A fake value get<foo>ent might return
let :fakeetcobject do
fakestruct.new('fooval', 'barval')
end
# The provider sometimes relies on @resource for valid properties so let's
# create a fake type with properties that match our fake struct.
let :faketype do
Puppet::Type.type(:nameservice_dummytype)
end
let :provider do
Puppet::Type.type(:nameservice_dummytype).provider(:nameservice_dummyprovider)
.new(:name => 'bob', :foo => 'fooval', :bar => 'barval')
end
let :resource do
resource = faketype.new(:name => 'bob', :ensure => :present)
resource.provider = provider
resource
end
# These values simulate what Ruby Etc would return from a host with the "same"
# user represented in different encodings on disk.
let(:utf_8_jose) { "Jos\u00E9"}
let(:utf_8_labeled_as_latin_1_jose) { utf_8_jose.dup.force_encoding(Encoding::ISO_8859_1) }
let(:valid_latin1_jose) { utf_8_jose.encode(Encoding::ISO_8859_1)}
let(:invalid_utf_8_jose) { valid_latin1_jose.dup.force_encoding(Encoding::UTF_8) }
let(:escaped_utf_8_jose) { "Jos\uFFFD".force_encoding(Encoding::UTF_8) }
let(:utf_8_mixed_users) {
[
Etc::Passwd.new('root', 'x', 0, 0),
Etc::Passwd.new('foo', 'x', 1000, 2000),
Etc::Passwd.new(utf_8_jose, utf_8_jose, 1001, 2000), # UTF-8 character
# In a UTF-8 environment, ruby will return strings labeled as UTF-8 even if they're not valid in UTF-8
Etc::Passwd.new(invalid_utf_8_jose, invalid_utf_8_jose, 1002, 2000),
nil
]
}
let(:latin_1_mixed_users) {
[
# In a LATIN-1 environment, ruby will return *all* strings labeled as LATIN-1
Etc::Passwd.new('root'.force_encoding(Encoding::ISO_8859_1), 'x', 0, 0),
Etc::Passwd.new('foo'.force_encoding(Encoding::ISO_8859_1), 'x', 1000, 2000),
Etc::Passwd.new(utf_8_labeled_as_latin_1_jose, utf_8_labeled_as_latin_1_jose, 1002, 2000),
Etc::Passwd.new(valid_latin1_jose, valid_latin1_jose, 1001, 2000), # UTF-8 character
nil
]
}
describe "#options" do
it "should add options for a valid property" do
provider.class.options :foo, :key1 => 'val1', :key2 => 'val2'
provider.class.options :bar, :key3 => 'val3'
expect(provider.class.option(:foo, :key1)).to eq('val1')
expect(provider.class.option(:foo, :key2)).to eq('val2')
expect(provider.class.option(:bar, :key3)).to eq('val3')
end
it "should raise an error for an invalid property" do
expect { provider.class.options :baz, :key1 => 'val1' }.to raise_error(
Puppet::Error, 'baz is not a valid attribute for nameservice_dummytype')
end
end
describe "#option" do
it "should return the correct value" do
provider.class.options :foo, :key1 => 'val1', :key2 => 'val2'
expect(provider.class.option(:foo, :key2)).to eq('val2')
end
it "should symbolize the name first" do
provider.class.options :foo, :key1 => 'val1', :key2 => 'val2'
expect(provider.class.option('foo', :key2)).to eq('val2')
end
it "should return nil if no option has been specified earlier" do
expect(provider.class.option(:foo, :key2)).to be_nil
end
it "should return nil if no option for that property has been specified earlier" do
provider.class.options :bar, :key2 => 'val2'
expect(provider.class.option(:foo, :key2)).to be_nil
end
it "should return nil if no matching key can be found for that property" do
provider.class.options :foo, :key3 => 'val2'
expect(provider.class.option(:foo, :key2)).to be_nil
end
end
describe "#section" do
it "should raise an error if resource_type has not been set" do
expect(provider.class).to receive(:resource_type).and_return(nil)
expect { provider.class.section }.to raise_error Puppet::Error, 'Cannot determine Etc section without a resource type'
end
# the return values are hard coded so I am using types that actually make
# use of the nameservice provider
it "should return pw for users" do
provider.class.resource_type = Puppet::Type.type(:user)
expect(provider.class.section).to eq('pw')
end
it "should return gr for groups" do
provider.class.resource_type = Puppet::Type.type(:group)
expect(provider.class.section).to eq('gr')
end
end
describe "instances" do
it "should return a list of objects in UTF-8 with any invalid characters replaced with '?'" do
# These two tests simulate an environment where there are two users with
# the same name on disk, but each name is stored on disk in a different
# encoding
allow(Etc).to receive(:getpwent).and_return(*utf_8_mixed_users)
result = PuppetSpec::CharacterEncoding.with_external_encoding(Encoding::UTF_8) do
provider.class.instances
end
expect(result.map(&:name)).to eq(
[
'root'.force_encoding(Encoding::UTF_8), # started as UTF-8 on disk, returned unaltered as UTF-8
'foo'.force_encoding(Encoding::UTF_8), # started as UTF-8 on disk, returned unaltered as UTF-8
utf_8_jose, # started as UTF-8 on disk, returned unaltered as UTF-8
escaped_utf_8_jose # started as LATIN-1 on disk, but Etc returned as UTF-8 and we escaped invalid chars
]
)
end
it "should have object names in their original encoding/bytes if they would not be valid UTF-8" do
allow(Etc).to receive(:getpwent).and_return(*latin_1_mixed_users)
result = PuppetSpec::CharacterEncoding.with_external_encoding(Encoding::ISO_8859_1) do
provider.class.instances
end
expect(result.map(&:name)).to eq(
[
'root'.force_encoding(Encoding::UTF_8), # started as LATIN-1 on disk, we overrode to UTF-8
'foo'.force_encoding(Encoding::UTF_8), # started as LATIN-1 on disk, we overrode to UTF-8
utf_8_jose, # started as UTF-8 on disk, returned by Etc as LATIN-1, and we overrode to UTF-8
valid_latin1_jose # started as LATIN-1 on disk, returned by Etc as valid LATIN-1, and we leave as LATIN-1
]
)
end
it "should pass the Puppet::Etc :canonical_name Struct member to the constructor" do
users = [ Etc::Passwd.new(invalid_utf_8_jose, invalid_utf_8_jose, 1002, 2000), nil ]
allow(Etc).to receive(:getpwent).and_return(*users)
expect(provider.class).to receive(:new).with({:name => escaped_utf_8_jose, :canonical_name => invalid_utf_8_jose, :ensure => :present})
provider.class.instances
end
end
describe "validate" do
it "should pass if no check is registered at all" do
expect { provider.class.validate(:foo, 300) }.to_not raise_error
expect { provider.class.validate('foo', 300) }.to_not raise_error
end
it "should pass if no check for that property is registered" do
provider.class.verify(:bar, 'Must be 100') { |val| val == 100 }
expect { provider.class.validate(:foo, 300) }.to_not raise_error
expect { provider.class.validate('foo', 300) }.to_not raise_error
end
it "should pass if the value is valid" do
provider.class.verify(:foo, 'Must be 100') { |val| val == 100 }
expect { provider.class.validate(:foo, 100) }.to_not raise_error
expect { provider.class.validate('foo', 100) }.to_not raise_error
end
it "should raise an error if the value is invalid" do
provider.class.verify(:foo, 'Must be 100') { |val| val == 100 }
expect { provider.class.validate(:foo, 200) }.to raise_error(ArgumentError, 'Invalid value 200: Must be 100')
expect { provider.class.validate('foo', 200) }.to raise_error(ArgumentError, 'Invalid value 200: Must be 100')
end
end
describe "getinfo" do
before :each do
# with section=foo we'll call Etc.getfoonam instead of getpwnam or getgrnam
allow(provider.class).to receive(:section).and_return('foo')
resource # initialize the resource so our provider has a @resource instance variable
end
it "should return a hash if we can retrieve something" do
expect(Puppet::Etc).to receive(:send).with(:getfoonam, 'bob').and_return(fakeetcobject)
expect(provider).to receive(:info2hash).with(fakeetcobject).and_return(:foo => 'fooval', :bar => 'barval')
expect(provider.getinfo(true)).to eq({:foo => 'fooval', :bar => 'barval'})
end
it "should return nil if we cannot retrieve anything" do
expect(Puppet::Etc).to receive(:send).with(:getfoonam, 'bob').and_raise(ArgumentError, "can't find bob")
expect(provider).not_to receive(:info2hash)
expect(provider.getinfo(true)).to be_nil
end
# Nameservice instances track the original resource name on disk, before
# overriding to UTF-8, in @canonical_name for querying that state on disk
# again if needed
it "should use the instance's @canonical_name to query the system" do
provider_instance = provider.class.new(:name => 'foo', :canonical_name => 'original_foo', :ensure => :present)
expect(Puppet::Etc).to receive(:send).with(:getfoonam, 'original_foo')
provider_instance.getinfo(true)
end
it "should use the instance's name instead of canonical_name if not supplied during instantiation" do
provider_instance = provider.class.new(:name => 'foo', :ensure => :present)
expect(Puppet::Etc).to receive(:send).with(:getfoonam, 'foo')
provider_instance.getinfo(true)
end
end
describe "info2hash" do
it "should return a hash with all properties" do
expect(provider.info2hash(fakeetcobject)).to eq({ :foo => 'fooval', :bar => 'barval' })
end
end
describe "munge" do
it "should return the input value if no munge method has be defined" do
expect(provider.munge(:foo, 100)).to eq(100)
end
it "should return the munged value otherwise" do
provider.class.options(:foo, :munge => proc { |x| x*2 })
expect(provider.munge(:foo, 100)).to eq(200)
end
end
describe "unmunge" do
it "should return the input value if no unmunge method has been defined" do
expect(provider.unmunge(:foo, 200)).to eq(200)
end
it "should return the unmunged value otherwise" do
provider.class.options(:foo, :unmunge => proc { |x| x/2 })
expect(provider.unmunge(:foo, 200)).to eq(100)
end
end
describe "exists?" do
it "should return true if we can retrieve anything" do
expect(provider).to receive(:getinfo).with(true).and_return(:foo => 'fooval', :bar => 'barval')
expect(provider).to be_exists
end
it "should return false if we cannot retrieve anything" do
expect(provider).to receive(:getinfo).with(true).and_return(nil)
expect(provider).not_to be_exists
end
end
describe "get" do
it "should return the correct getinfo value" do
expect(provider).to receive(:getinfo).with(false).and_return(:foo => 'fooval', :bar => 'barval')
expect(provider.get(:bar)).to eq('barval')
end
it "should unmunge the value first" do
provider.class.options(:bar, :munge => proc { |x| x*2}, :unmunge => proc {|x| x/2})
expect(provider).to receive(:getinfo).with(false).and_return(:foo => 200, :bar => 500)
expect(provider.get(:bar)).to eq(250)
end
it "should return nil if getinfo cannot retrieve the value" do
expect(provider).to receive(:getinfo).with(false).and_return(:foo => 'fooval', :bar => 'barval')
expect(provider.get(:no_such_key)).to be_nil
end
end
describe "set" do
before :each do
resource # initialize resource so our provider has a @resource object
provider.class.verify(:foo, 'Must be 100') { |val| val == 100 }
end
it "should raise an error on invalid values" do
expect { provider.set(:foo, 200) }.to raise_error(ArgumentError, 'Invalid value 200: Must be 100')
end
it "should execute the modify command on valid values" do
expect(provider).to receive(:modifycmd).with(:foo, 100).and_return(['/bin/modify', '-f', '100' ])
expect(provider).to receive(:execute).with(['/bin/modify', '-f', '100'], hash_including(custom_environment: {}))
provider.set(:foo, 100)
end
it "should munge the value first" do
provider.class.options(:foo, :munge => proc { |x| x*2}, :unmunge => proc {|x| x/2})
expect(provider).to receive(:modifycmd).with(:foo, 200).and_return(['/bin/modify', '-f', '200' ])
expect(provider).to receive(:execute).with(['/bin/modify', '-f', '200'], hash_including(custom_environment: {}))
provider.set(:foo, 100)
end
it "should fail if the modify command fails" do
expect(provider).to receive(:modifycmd).with(:foo, 100).and_return(['/bin/modify', '-f', '100' ])
expect(provider).to receive(:execute).with(['/bin/modify', '-f', '100'], kind_of(Hash)).and_raise(Puppet::ExecutionFailure, "Execution of '/bin/modify' returned 1: some_failure")
expect { provider.set(:foo, 100) }.to raise_error Puppet::Error, /Could not set foo/
end
end
describe "comments_insync?" do
# comments_insync? overrides Puppet::Property#insync? and will act on an
# array containing a should value (the expected value of Puppet::Property
# @should)
context "given strings with compatible encodings" do
it "should return false if the is-value and should-value are not equal" do
is_value = "foo"
should_value = ["bar"]
expect(provider.comments_insync?(is_value, should_value)).to be_falsey
end
it "should return true if the is-value and should-value are equal" do
is_value = "foo"
should_value = ["foo"]
expect(provider.comments_insync?(is_value, should_value)).to be_truthy
end
end
context "given strings with incompatible encodings" do
let(:snowman_iso) { "\u2603".force_encoding(Encoding::ISO_8859_1) }
let(:snowman_utf8) { "\u2603".force_encoding(Encoding::UTF_8) }
let(:snowman_binary) { "\u2603".force_encoding(Encoding::ASCII_8BIT) }
let(:arabic_heh_utf8) { "\u06FF".force_encoding(Encoding::UTF_8) }
it "should be able to compare unequal strings and return false" do
expect(Encoding.compatible?(snowman_iso, arabic_heh_utf8)).to be_falsey
expect(provider.comments_insync?(snowman_iso, [arabic_heh_utf8])).to be_falsey
end
it "should be able to compare equal strings and return true" do
expect(Encoding.compatible?(snowman_binary, snowman_utf8)).to be_falsey
expect(provider.comments_insync?(snowman_binary, [snowman_utf8])).to be_truthy
end
it "should not manipulate the actual encoding of either string" do
expect(Encoding.compatible?(snowman_binary, snowman_utf8)).to be_falsey
provider.comments_insync?(snowman_binary, [snowman_utf8])
expect(snowman_binary.encoding).to eq(Encoding::ASCII_8BIT)
expect(snowman_utf8.encoding).to eq(Encoding::UTF_8)
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/provider/aix_object_spec.rb | spec/unit/provider/aix_object_spec.rb | require 'spec_helper'
require 'puppet/provider/aix_object'
describe 'Puppet::Provider::AixObject' do
let(:resource) do
Puppet::Type.type(:user).new(
:name => 'test_aix_user',
:ensure => :present
)
end
let(:klass) { Puppet::Provider::AixObject }
let(:provider) do
Puppet::Provider::AixObject.new(resource)
end
# Clear out the class-level + instance-level mappings
def clear_attributes
klass.instance_variable_set(:@mappings, nil)
end
before(:each) do
clear_attributes
end
describe '.mapping' do
let(:puppet_property) { :uid }
let(:aix_attribute) { :id }
let(:info) do
{
:puppet_property => puppet_property,
:aix_attribute => aix_attribute
}
end
shared_examples 'a mapping' do |from, to|
context "<#{from}> => <#{to}>" do
let(:from_suffix) { from.to_s.split("_")[-1] }
let(:to_suffix) { to.to_s.split("_")[-1] }
let(:conversion_fn) do
"convert_#{from_suffix}_value".to_sym
end
it 'creates the mapping for a pure conversion function and defines it' do
conversion_fn_lambda = "#{from_suffix}_to_#{to_suffix}".to_sym
info[conversion_fn_lambda] = lambda { |x| x.to_s }
provider.class.mapping(info)
mappings = provider.class.mappings[to]
expect(mappings).to include(info[from])
mapping = mappings[info[from]]
expect(mapping.public_methods).to include(conversion_fn)
expect(mapping.send(conversion_fn, 3)).to eql('3')
end
it 'creates the mapping for an impure conversion function without defining it' do
conversion_fn_lambda = "#{from_suffix}_to_#{to_suffix}".to_sym
info[conversion_fn_lambda] = lambda { |provider, x| x.to_s }
provider.class.mapping(info)
mappings = provider.class.mappings[to]
expect(mappings).to include(info[from])
mapping = mappings[info[from]]
expect(mapping.public_methods).not_to include(conversion_fn)
end
it 'uses the identity function as the conversion function if none is provided' do
provider.class.mapping(info)
mappings = provider.class.mappings[to]
expect(mappings).to include(info[from])
mapping = mappings[info[from]]
expect(mapping.public_methods).to include(conversion_fn)
expect(mapping.send(conversion_fn, 3)).to eql(3)
end
end
end
include_examples 'a mapping',
:puppet_property,
:aix_attribute
include_examples 'a mapping',
:aix_attribute,
:puppet_property
it 'sets the AIX attribute to the Puppet property if it is not provided' do
info[:aix_attribute] = nil
provider.class.mapping(info)
mappings = provider.class.mappings[:puppet_property]
expect(mappings).to include(info[:puppet_property])
end
end
describe '.numeric_mapping' do
let(:info) do
info_hash = {
:puppet_property => :uid,
:aix_attribute => :id
}
provider.class.numeric_mapping(info_hash)
info_hash
end
let(:aix_attribute) do
provider.class.mappings[:aix_attribute][info[:puppet_property]]
end
let(:puppet_property) do
provider.class.mappings[:puppet_property][info[:aix_attribute]]
end
it 'raises an ArgumentError for a non-numeric Puppet property value' do
value = 'foo'
expect do
aix_attribute.convert_property_value(value)
end.to raise_error do |error|
expect(error).to be_a(ArgumentError)
expect(error.message).to match(value)
expect(error.message).to match(info[:puppet_property].to_s)
end
end
it 'converts the numeric Puppet property to a numeric AIX attribute' do
expect(aix_attribute.convert_property_value(10)).to eql('10')
end
it 'converts the numeric AIX attribute to a numeric Puppet property' do
expect(puppet_property.convert_attribute_value('10')).to eql(10)
end
end
describe '.mk_resource_methods' do
before(:each) do
# Add some Puppet properties
provider.class.mapping(
puppet_property: :foo,
aix_attribute: :foo
)
provider.class.mapping(
puppet_property: :bar,
aix_attribute: :bar
)
provider.class.mk_resource_methods
end
it 'defines the property getters' do
provider = Puppet::Provider::AixObject.new(resource)
provider.instance_variable_set(:@object_info, { :foo => 'foo', :baz => 'baz' })
(provider.class.mappings[:aix_attribute].keys + [:attributes]).each do |property|
expect(provider).to receive(:get).with(property).and_return('value')
expect(provider.send(property)).to eql('value')
end
end
it 'defines the property setters' do
provider = Puppet::Provider::AixObject.new(resource)
value = '15'
provider.class.mappings[:aix_attribute].keys.each do |property|
expect(provider).to receive(:set).with(property, value)
provider.send("#{property}=".to_sym, value)
end
end
end
describe '.parse_colon_separated_list' do
it 'parses a single empty item' do
input = ''
output = ['']
expect(provider.class.parse_colon_separated_list(input)).to eql(output)
end
it 'parses a single nonempty item' do
input = 'item'
output = ['item']
expect(provider.class.parse_colon_separated_list(input)).to eql(output)
end
it "parses an escaped ':'" do
input = '#!:'
output = [':']
expect(provider.class.parse_colon_separated_list(input)).to eql(output)
end
it "parses a single item with an escaped ':'" do
input = 'fd8c#!:215d#!:178#!:'
output = ['fd8c:215d:178:']
expect(provider.class.parse_colon_separated_list(input)).to eql(output)
end
it "parses multiple items that do not have an escaped ':'" do
input = "foo:bar baz:buu:1234"
output = ["foo", "bar baz", "buu", "1234"]
expect(provider.class.parse_colon_separated_list(input)).to eql(output)
end
it "parses multiple items some of which have escaped ':'" do
input = "1234#!:567:foo bar#!:baz:buu#!bob:sally:fd8c#!:215d#!:178"
output = ["1234:567", "foo bar:baz", "buu#!bob", "sally", 'fd8c:215d:178']
expect(provider.class.parse_colon_separated_list(input)).to eql(output)
end
it "parses a list with several empty items" do
input = "foo:::bar:baz:boo:"
output = ["foo", "", "", "bar", "baz", "boo", ""]
expect(provider.class.parse_colon_separated_list(input)).to eql(output)
end
it "parses a list with an escaped ':' and empty item at the end" do
input = "foo:bar#!::"
output = ["foo", "bar:", ""]
expect(provider.class.parse_colon_separated_list(input)).to eql(output)
end
it 'parses a real world example' do
input = File.read(my_fixture('aix_colon_list_real_world_input.out')).chomp
output = Object.instance_eval(File.read(my_fixture('aix_colon_list_real_world_output.out')))
expect(provider.class.parse_colon_separated_list(input)).to eql(output)
end
end
describe '.parse_aix_objects' do
# parse_colon_separated_list is well tested, so we don't need to be
# as strict on the formatting of the output here. Main point of these
# tests is to capture the 'wholemeal' parsing that's going on, i.e.
# that we can parse a bunch of objects together.
let(:output) do
<<-AIX_OBJECTS
#name:id:pgrp:groups
root:0:system:system,bin,sys,security,cron,audit,lp
#name:id:pgrp:groups:home:gecos
user:10000:staff:staff:/home/user3:Some User
AIX_OBJECTS
end
let(:expected_aix_attributes) do
[
{
:name => 'root',
:attributes => {
:id => '0',
:pgrp => 'system',
:groups => 'system,bin,sys,security,cron,audit,lp',
}
},
{
:name => 'user',
:attributes => {
:id => '10000',
:pgrp => 'staff',
:groups => 'staff',
:home => '/home/user3',
:gecos => 'Some User'
}
}
]
end
it 'parses the AIX attributes from the command output' do
expect(provider.class.parse_aix_objects(output)).to eql(expected_aix_attributes)
end
end
describe 'list_all' do
let(:output) do
<<-OUTPUT
#name:id
system:0
#name:id
staff:1
#name:id
bin:2
OUTPUT
end
it 'lists all of the objects' do
lscmd = 'lsgroups'
allow(provider.class).to receive(:command).with(:list).and_return(lscmd)
allow(provider.class).to receive(:execute).with([lscmd, '-c', '-a', 'id', 'ALL']).and_return(output)
expected_objects = [
{ :name => 'system', :id => '0' },
{ :name => 'staff', :id => '1' },
{ :name => 'bin', :id => '2' }
]
expect(provider.class.list_all).to eql(expected_objects)
end
end
describe '.instances' do
let(:objects) do
[
{ :name => 'group1', :id => '1' },
{ :name => 'group2', :id => '2' }
]
end
it 'returns all of the available instances' do
allow(provider.class).to receive(:list_all).and_return(objects)
expect(provider.class.instances.map(&:name)).to eql(['group1', 'group2'])
end
end
describe '#mappings' do
# Returns a pair [ instance_level_mapped_object, class_level_mapped_object ]
def mapped_objects(type, input)
[
provider.mappings[type][input],
provider.class.mappings[type][input]
]
end
before(:each) do
# Create a pure mapping
provider.class.numeric_mapping(
puppet_property: :pure_puppet_property,
aix_attribute: :pure_aix_attribute
)
# Create an impure mapping
impure_conversion_fn = lambda do |provider, value|
"Provider instance's name is #{provider.name}"
end
provider.class.mapping(
puppet_property: :impure_puppet_property,
aix_attribute: :impure_aix_attribute,
property_to_attribute: impure_conversion_fn,
attribute_to_property: impure_conversion_fn
)
end
it 'memoizes the result' do
provider.instance_variable_set(:@mappings, 'memoized')
expect(provider.mappings).to eql('memoized')
end
it 'creates the instance-level mappings with the same structure as the class-level one' do
expect(provider.mappings.keys).to eql(provider.class.mappings.keys)
provider.mappings.keys.each do |type|
expect(provider.mappings[type].keys).to eql(provider.class.mappings[type].keys)
end
end
shared_examples 'uses the right mapped object for a given mapping' do |from_type, to_type|
context "<#{from_type}> => <#{to_type}>" do
it 'shares the class-level mapped object for pure mappings' do
input = "pure_#{from_type}".to_sym
instance_level_mapped_object, class_level_mapped_object = mapped_objects(to_type, input)
expect(instance_level_mapped_object.object_id).to eql(class_level_mapped_object.object_id)
end
it 'dups the class-level mapped object for impure mappings' do
input = "impure_#{from_type}".to_sym
instance_level_mapped_object, class_level_mapped_object = mapped_objects(to_type, input)
expect(instance_level_mapped_object.object_id).to_not eql(
class_level_mapped_object.object_id
)
end
it 'defines the conversion function for impure mappings' do
from_type_suffix = from_type.to_s.split("_")[-1]
conversion_fn = "convert_#{from_type_suffix}_value".to_sym
input = "impure_#{from_type}".to_sym
mapped_object, _ = mapped_objects(to_type, input)
expect(mapped_object.public_methods).to include(conversion_fn)
expect(mapped_object.send(conversion_fn, 3)).to match(provider.name)
end
end
end
include_examples 'uses the right mapped object for a given mapping',
:puppet_property,
:aix_attribute
include_examples 'uses the right mapped object for a given mapping',
:aix_attribute,
:puppet_property
end
describe '#attributes_to_args' do
let(:attributes) do
{
:attribute1 => 'value1',
:attribute2 => 'value2'
}
end
it 'converts the attributes hash to CLI arguments' do
expect(provider.attributes_to_args(attributes)).to eql(
["attribute1=value1", "attribute2=value2"]
)
end
end
describe '#ia_module_args' do
it 'returns no arguments if ia_load_module parameter or forcelocal parameter are not specified' do
allow(provider.resource).to receive(:[]).with(:ia_load_module).and_return(nil)
allow(provider.resource).to receive(:[]).with(:forcelocal).and_return(nil)
expect(provider.ia_module_args).to eql([])
end
it 'returns the ia_load_module as a CLI argument when ia_load_module is specified' do
allow(provider.resource).to receive(:[]).with(:ia_load_module).and_return('module')
allow(provider.resource).to receive(:[]).with(:forcelocal).and_return(nil)
expect(provider.ia_module_args).to eql(['-R', 'module'])
end
it 'returns "files" as a CLI argument when forcelocal is specified' do
allow(provider.resource).to receive(:[]).with(:ia_load_module).and_return(nil)
allow(provider.resource).to receive(:[]).with(:forcelocal).and_return(true)
expect(provider.ia_module_args).to eql(['-R', 'files'])
end
it 'raises argument error when both ia_load_module and forcelocal parameters are set' do
allow(provider.resource).to receive(:[]).with(:ia_load_module).and_return('files')
allow(provider.resource).to receive(:[]).with(:forcelocal).and_return(true)
expect { provider.ia_module_args }.to raise_error(ArgumentError, "Cannot have both 'forcelocal' and 'ia_load_module' at the same time!")
end
end
describe '#lscmd' do
it 'returns the lscmd' do
allow(provider.class).to receive(:command).with(:list).and_return('list')
allow(provider).to receive(:ia_module_args).and_return(['ia_module_args'])
expect(provider.lscmd).to eql(
['list', '-c', 'ia_module_args', provider.resource.name]
)
end
end
describe '#addcmd' do
let(:attributes) do
{
:attribute1 => 'value1',
:attribute2 => 'value2'
}
end
it 'returns the addcmd passing in the attributes as CLI arguments' do
allow(provider.class).to receive(:command).with(:add).and_return('add')
allow(provider).to receive(:ia_module_args).and_return(['ia_module_args'])
expect(provider.addcmd(attributes)).to eql(
['add', 'ia_module_args', 'attribute1=value1', 'attribute2=value2', provider.resource.name]
)
end
end
describe '#deletecmd' do
it 'returns the lscmd' do
allow(provider.class).to receive(:command).with(:delete).and_return('delete')
allow(provider).to receive(:ia_module_args).and_return(['ia_module_args'])
expect(provider.deletecmd).to eql(
['delete', 'ia_module_args', provider.resource.name]
)
end
end
describe '#modifycmd' do
let(:attributes) do
{
:attribute1 => 'value1',
:attribute2 => 'value2'
}
end
it 'returns the addcmd passing in the attributes as CLI arguments' do
allow(provider.class).to receive(:command).with(:modify).and_return('modify')
allow(provider).to receive(:ia_module_args).and_return(['ia_module_args'])
expect(provider.modifycmd(attributes)).to eql(
['modify', 'ia_module_args', 'attribute1=value1', 'attribute2=value2', provider.resource.name]
)
end
end
describe '#modify_object' do
let(:new_attributes) do
{
:nofiles => 10000,
:fsize => 30000
}
end
it 'modifies the AIX object with the new attributes' do
allow(provider).to receive(:modifycmd).with(new_attributes).and_return('modify_cmd')
expect(provider).to receive(:execute).with('modify_cmd')
expect(provider).to receive(:object_info).with(true)
provider.modify_object(new_attributes)
end
end
describe '#get' do
# Input
let(:property) { :uid }
let!(:object_info) do
hash = {}
provider.instance_variable_set(:@object_info, hash)
hash
end
it 'returns :absent if the AIX object does not exist' do
allow(provider).to receive(:exists?).and_return(false)
object_info[property] = 15
expect(provider.get(property)).to eql(:absent)
end
it 'returns :absent if the property is not present on the system' do
allow(provider).to receive(:exists?).and_return(true)
expect(provider.get(property)).to eql(:absent)
end
it "returns the property's value" do
allow(provider).to receive(:exists?).and_return(true)
object_info[property] = 15
expect(provider.get(property)).to eql(15)
end
end
describe '#set' do
# Input
let(:property) { :uid }
let(:value) { 10 }
# AIX attribute params
let(:aix_attribute) { :id }
let(:property_to_attribute) do
lambda { |x| x.to_s }
end
before(:each) do
# Add an attribute
provider.class.mapping(
puppet_property: property,
aix_attribute: aix_attribute,
property_to_attribute: property_to_attribute
)
end
it "raises a Puppet::Error if it fails to set the property's value" do
allow(provider).to receive(:modify_object)
.with({ :id => value.to_s })
.and_raise(Puppet::ExecutionFailure, 'failed to modify the AIX object!')
expect { provider.set(property, value) }.to raise_error do |error|
expect(error).to be_a(Puppet::Error)
end
end
it "sets the given property's value to the passed-in value" do
expect(provider).to receive(:modify_object).with({ :id => value.to_s })
provider.set(property, value)
end
end
describe '#validate_new_attributes' do
let(:new_attributes) do
{
:nofiles => 10000,
:fsize => 100000
}
end
it 'raises a Puppet::Error if a specified attributes corresponds to a Puppet property, reporting all of the attribute-property conflicts' do
provider.class.mapping(puppet_property: :uid, aix_attribute: :id)
provider.class.mapping(puppet_property: :groups, aix_attribute: :groups)
new_attributes[:id] = '25'
new_attributes[:groups] = 'groups'
expect { provider.validate_new_attributes(new_attributes) }.to raise_error do |error|
expect(error).to be_a(Puppet::Error)
expect(error.message).to match("'uid', 'groups'")
expect(error.message).to match("'id', 'groups'")
end
end
end
describe '#attributes=' do
let(:new_attributes) do
{
:nofiles => 10000,
:fsize => 100000
}
end
it 'raises a Puppet::Error if one of the specified attributes corresponds to a Puppet property' do
provider.class.mapping(puppet_property: :uid, aix_attribute: :id)
new_attributes[:id] = '25'
expect { provider.attributes = new_attributes }.to raise_error do |error|
expect(error).to be_a(Puppet::Error)
expect(error.message).to match('uid')
expect(error.message).to match('id')
end
end
it 'raises a Puppet::Error if it fails to set the new AIX attributes' do
allow(provider).to receive(:modify_object)
.with(new_attributes)
.and_raise(Puppet::ExecutionFailure, 'failed to modify the AIX object!')
expect { provider.attributes = new_attributes }.to raise_error do |error|
expect(error).to be_a(Puppet::Error)
expect(error.message).to match('failed to modify the AIX object!')
end
end
it 'sets the new AIX attributes' do
expect(provider).to receive(:modify_object).with(new_attributes)
provider.attributes = new_attributes
end
end
describe '#object_info' do
before(:each) do
# Add some Puppet properties
provider.class.mapping(
puppet_property: :uid,
aix_attribute: :id,
attribute_to_property: lambda { |x| x.to_i },
)
provider.class.mapping(
puppet_property: :groups,
aix_attribute: :groups
)
# Mock out our lscmd
allow(provider).to receive(:lscmd).and_return("lsuser #{resource[:name]}")
end
it 'memoizes the result' do
provider.instance_variable_set(:@object_info, {})
expect(provider.object_info).to eql({})
end
it 'returns nil if the AIX object does not exist' do
allow(provider).to receive(:execute).with(provider.lscmd).and_raise(
Puppet::ExecutionFailure, 'lscmd failed!'
)
expect(provider.object_info).to be_nil
end
it 'collects the Puppet properties' do
output = 'mock_output'
allow(provider).to receive(:execute).with(provider.lscmd).and_return(output)
# Mock the AIX attributes on the system
mock_attributes = {
:id => '1',
:groups => 'foo,bar,baz',
:attribute1 => 'value1',
:attribute2 => 'value2'
}
allow(provider.class).to receive(:parse_aix_objects)
.with(output)
.and_return([{ :name => resource.name, :attributes => mock_attributes }])
expected_property_values = {
:uid => 1,
:groups => 'foo,bar,baz',
:attributes => {
:attribute1 => 'value1',
:attribute2 => 'value2'
}
}
provider.object_info
expect(provider.instance_variable_get(:@object_info)).to eql(expected_property_values)
end
end
describe '#exists?' do
it 'should return true if the AIX object exists' do
allow(provider).to receive(:object_info).and_return({})
expect(provider.exists?).to be(true)
end
it 'should return false if the AIX object does not exist' do
allow(provider).to receive(:object_info).and_return(nil)
expect(provider.exists?).to be(false)
end
end
describe "#create" do
let(:property_attributes) do
{}
end
def stub_attributes_property(attributes)
allow(provider.resource).to receive(:should).with(:attributes).and_return(attributes)
end
def set_property(puppet_property, aix_attribute, property_to_attribute, should_value = nil)
property_to_attribute ||= lambda { |x| x }
provider.class.mapping(
puppet_property: puppet_property,
aix_attribute: aix_attribute,
property_to_attribute: property_to_attribute
)
allow(provider.resource).to receive(:should).with(puppet_property).and_return(should_value)
if should_value
property_attributes[aix_attribute] = property_to_attribute.call(should_value)
end
end
before(:each) do
clear_attributes
# Clear out the :attributes property. We will be setting this later.
stub_attributes_property(nil)
# Add some properties
set_property(:uid, :id, lambda { |x| x.to_s }, 10)
set_property(:groups, :groups, nil, 'group1,group2,group3')
set_property(:shell, :shell, nil)
end
it 'raises a Puppet::Error if one of the specified attributes corresponds to a Puppet property' do
stub_attributes_property({ :id => 15 })
provider.class.mapping(puppet_property: :uid, aix_attribute: :id)
expect { provider.create }.to raise_error do |error|
expect(error).to be_a(Puppet::Error)
expect(error.message).to match('uid')
expect(error.message).to match('id')
end
end
it "raises a Puppet::Error if it fails to create the AIX object" do
allow(provider).to receive(:addcmd)
allow(provider).to receive(:execute).and_raise(
Puppet::ExecutionFailure, "addcmd failed!"
)
expect { provider.create }.to raise_error do |error|
expect(error).to be_a(Puppet::Error)
expect(error.message).to match("not create")
end
end
it "creates the AIX object with the given AIX attributes + Puppet properties" do
attributes = { :fsize => 1000 }
stub_attributes_property(attributes)
expect(provider).to receive(:addcmd)
.with(attributes.merge(property_attributes))
.and_return('addcmd')
expect(provider).to receive(:execute).with('addcmd')
provider.create
end
end
describe "#delete" do
before(:each) do
allow(provider).to receive(:deletecmd).and_return('deletecmd')
end
it "raises a Puppet::Error if it fails to delete the AIX object" do
allow(provider).to receive(:execute).with(provider.deletecmd).and_raise(
Puppet::ExecutionFailure, "deletecmd failed!"
)
expect { provider.delete }.to raise_error do |error|
expect(error).to be_a(Puppet::Error)
expect(error.message).to match("not delete")
end
end
it "deletes the AIX object" do
expect(provider).to receive(:execute).with(provider.deletecmd)
expect(provider).to receive(:object_info).with(true)
provider.delete
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/provider/ldap_spec.rb | spec/unit/provider/ldap_spec.rb | require 'spec_helper'
require 'puppet/provider/ldap'
describe Puppet::Provider::Ldap do
before do
@class = Class.new(Puppet::Provider::Ldap)
end
it "should be able to define its manager" do
manager = double('manager')
expect(Puppet::Util::Ldap::Manager).to receive(:new).and_return(manager)
allow(@class).to receive(:mk_resource_methods)
expect(manager).to receive(:manages).with(:one)
expect(@class.manages(:one)).to equal(manager)
expect(@class.manager).to equal(manager)
end
it "should be able to prefetch instances from ldap" do
expect(@class).to respond_to(:prefetch)
end
it "should create its resource getter/setter methods when the manager is defined" do
manager = double('manager')
expect(Puppet::Util::Ldap::Manager).to receive(:new).and_return(manager)
expect(@class).to receive(:mk_resource_methods)
allow(manager).to receive(:manages)
expect(@class.manages(:one)).to equal(manager)
end
it "should have an instances method" do
expect(@class).to respond_to(:instances)
end
describe "when providing a list of instances" do
it "should convert all results returned from the manager's :search method into provider instances" do
manager = double('manager')
allow(@class).to receive(:manager).and_return(manager)
expect(manager).to receive(:search).and_return(%w{one two three})
expect(@class).to receive(:new).with("one").and_return(1)
expect(@class).to receive(:new).with("two").and_return(2)
expect(@class).to receive(:new).with("three").and_return(3)
expect(@class.instances).to eq([1,2,3])
end
end
it "should have a prefetch method" do
expect(@class).to respond_to(:prefetch)
end
describe "when prefetching" do
before do
@manager = double('manager')
allow(@class).to receive(:manager).and_return(@manager)
@resource = double('resource')
@resources = {"one" => @resource}
end
it "should find an entry for each passed resource" do
expect(@manager).to receive(:find).with("one").and_return(nil)
allow(@class).to receive(:new)
allow(@resource).to receive(:provider=)
@class.prefetch(@resources)
end
describe "resources that do not exist" do
it "should create a provider with :ensure => :absent" do
expect(@manager).to receive(:find).with("one").and_return(nil)
expect(@class).to receive(:new).with({:ensure => :absent}).and_return("myprovider")
expect(@resource).to receive(:provider=).with("myprovider")
@class.prefetch(@resources)
end
end
describe "resources that exist" do
it "should create a provider with the results of the find" do
expect(@manager).to receive(:find).with("one").and_return("one" => "two")
expect(@class).to receive(:new).with({"one" => "two", :ensure => :present}).and_return("myprovider")
expect(@resource).to receive(:provider=).with("myprovider")
@class.prefetch(@resources)
end
it "should set :ensure to :present in the returned values" do
expect(@manager).to receive(:find).with("one").and_return("one" => "two")
expect(@class).to receive(:new).with({"one" => "two", :ensure => :present}).and_return("myprovider")
expect(@resource).to receive(:provider=).with("myprovider")
@class.prefetch(@resources)
end
end
end
describe "when being initialized" do
it "should fail if no manager has been defined" do
expect { @class.new }.to raise_error(Puppet::DevError)
end
it "should fail if the manager is invalid" do
manager = double("manager", :valid? => false)
allow(@class).to receive(:manager).and_return(manager)
expect { @class.new }.to raise_error(Puppet::DevError)
end
describe "with a hash" do
before do
@manager = double("manager", :valid? => true)
allow(@class).to receive(:manager).and_return(@manager)
@resource_class = double('resource_class')
allow(@class).to receive(:resource_type).and_return(@resource_class)
@property_class = double('property_class', :array_matching => :all, :superclass => Puppet::Property)
allow(@resource_class).to receive(:attrclass).with(:one).and_return(@property_class)
allow(@resource_class).to receive(:valid_parameter?).and_return(true)
end
it "should store a copy of the hash as its ldap_properties" do
instance = @class.new(:one => :two)
expect(instance.ldap_properties).to eq({:one => :two})
end
it "should only store the first value of each value array for those attributes that do not match all values" do
expect(@property_class).to receive(:array_matching).and_return(:first)
instance = @class.new(:one => %w{two three})
expect(instance.properties).to eq({:one => "two"})
end
it "should store the whole value array for those attributes that match all values" do
expect(@property_class).to receive(:array_matching).and_return(:all)
instance = @class.new(:one => %w{two three})
expect(instance.properties).to eq({:one => %w{two three}})
end
it "should only use the first value for attributes that are not properties" do
# Yay. hackish, but easier than mocking everything.
expect(@resource_class).to receive(:attrclass).with(:a).and_return(Puppet::Type.type(:user).attrclass(:name))
allow(@property_class).to receive(:array_matching).and_return(:all)
instance = @class.new(:one => %w{two three}, :a => %w{b c})
expect(instance.properties).to eq({:one => %w{two three}, :a => "b"})
end
it "should discard any properties not valid in the resource class" do
expect(@resource_class).to receive(:valid_parameter?).with(:a).and_return(false)
allow(@property_class).to receive(:array_matching).and_return(:all)
instance = @class.new(:one => %w{two three}, :a => %w{b})
expect(instance.properties).to eq({:one => %w{two three}})
end
end
end
describe "when an instance" do
before do
@manager = double("manager", :valid? => true)
allow(@class).to receive(:manager).and_return(@manager)
@instance = @class.new
@property_class = double('property_class', :array_matching => :all, :superclass => Puppet::Property)
@resource_class = double('resource_class', :attrclass => @property_class, :valid_parameter? => true, :validproperties => [:one, :two])
allow(@class).to receive(:resource_type).and_return(@resource_class)
end
it "should have a method for creating the ldap entry" do
expect(@instance).to respond_to(:create)
end
it "should have a method for removing the ldap entry" do
expect(@instance).to respond_to(:delete)
end
it "should have a method for returning the class's manager" do
expect(@instance.manager).to equal(@manager)
end
it "should indicate when the ldap entry already exists" do
@instance = @class.new(:ensure => :present)
expect(@instance.exists?).to be_truthy
end
it "should indicate when the ldap entry does not exist" do
@instance = @class.new(:ensure => :absent)
expect(@instance.exists?).to be_falsey
end
describe "is being flushed" do
it "should call the manager's :update method with its name, current attributes, and desired attributes" do
allow(@instance).to receive(:name).and_return("myname")
allow(@instance).to receive(:ldap_properties).and_return(:one => :two)
allow(@instance).to receive(:properties).and_return(:three => :four)
expect(@manager).to receive(:update).with(@instance.name, {:one => :two}, {:three => :four})
@instance.flush
end
end
describe "is being created" do
before do
@rclass = double('resource_class')
allow(@rclass).to receive(:validproperties).and_return([:one, :two])
@resource = double('resource')
allow(@resource).to receive(:class).and_return(@rclass)
allow(@resource).to receive(:should).and_return(nil)
allow(@instance).to receive(:resource).and_return(@resource)
end
it "should set its :ensure value to :present" do
@instance.create
expect(@instance.properties[:ensure]).to eq(:present)
end
it "should set all of the other attributes from the resource" do
expect(@resource).to receive(:should).with(:one).and_return("oneval")
expect(@resource).to receive(:should).with(:two).and_return("twoval")
@instance.create
expect(@instance.properties[:one]).to eq("oneval")
expect(@instance.properties[:two]).to eq("twoval")
end
end
describe "is being deleted" do
it "should set its :ensure value to :absent" do
@instance.delete
expect(@instance.properties[:ensure]).to eq(:absent)
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/provider/command_spec.rb | spec/unit/provider/command_spec.rb | require 'spec_helper'
require 'puppet/provider/command'
describe Puppet::Provider::Command do
let(:name) { "the name" }
let(:the_options) { { :option => 1 } }
let(:no_options) { {} }
let(:executable) { "foo" }
let(:executable_absolute_path) { "/foo/bar" }
let(:executor) { double('executor') }
let(:resolver) { double('resolver') }
let(:path_resolves_to_itself) do
resolves = Object.new
class << resolves
def which(path)
path
end
end
resolves
end
it "executes a simple command" do
expect(executor).to receive(:execute).with([executable], no_options)
command = Puppet::Provider::Command.new(name, executable, path_resolves_to_itself, executor)
command.execute()
end
it "executes a command with extra options" do
expect(executor).to receive(:execute).with([executable], the_options)
command = Puppet::Provider::Command.new(name, executable, path_resolves_to_itself, executor, the_options)
command.execute()
end
it "executes a command with arguments" do
expect(executor).to receive(:execute).with([executable, "arg1", "arg2"], no_options)
command = Puppet::Provider::Command.new(name, executable, path_resolves_to_itself, executor)
command.execute("arg1", "arg2")
end
it "resolves to an absolute path for better execution" do
expect(resolver).to receive(:which).with(executable).and_return(executable_absolute_path)
expect(executor).to receive(:execute).with([executable_absolute_path], no_options)
command = Puppet::Provider::Command.new(name, executable, resolver, executor)
command.execute()
end
it "errors when the executable resolves to nothing" do
expect(resolver).to receive(:which).with(executable).and_return(nil)
expect(executor).not_to receive(:execute)
command = Puppet::Provider::Command.new(name, executable, resolver, executor)
expect { command.execute() }.to raise_error(Puppet::Error, "Command #{name} is missing")
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/provider/package_targetable_spec.rb | spec/unit/provider/package_targetable_spec.rb | require 'spec_helper'
require 'puppet'
require 'puppet/provider/package_targetable'
require 'puppet/provider/package/gem'
describe Puppet::Provider::Package::Targetable do
let(:provider) { Puppet::Type.type(:package).provider(:gem) }
let(:command) { '/opt/bin/gem' }
describe "when prefetching" do
context "with a package without a command attribute" do
let(:resource) { Puppet::Type.type(:package).new(:name => 'noo', :provider => 'gem', :ensure => :present) }
let(:catalog) { Puppet::Resource::Catalog.new }
let(:instance) { provider.new(resource) }
let(:packages) { { 'noo' => resource } }
it "should pass a command to the instances method of the provider" do
catalog.add_resource(resource)
expect(provider).to receive(:instances).with(nil).and_return([instance])
expect(provider.prefetch(packages)).to eq([nil]) # prefetch arbitrarily returns the array of commands for a provider in the catalog
end
end
context "with a package with a command attribute" do
let(:resource) { Puppet::Type.type(:package).new(:name => 'noo', :provider => 'gem', :ensure => :present) }
let(:resource_targeted) { Puppet::Type.type(:package).new(:name => 'yes', :provider => 'gem', :command => command, :ensure => :present) }
let(:catalog) { Puppet::Resource::Catalog.new }
let(:instance) { provider.new(resource) }
let(:instance_targeted) { provider.new(resource_targeted) }
let(:packages) { { 'noo' => resource, 'yes' => resource_targeted } }
it "should pass the command to the instances method of the provider" do
catalog.add_resource(resource)
catalog.add_resource(resource_targeted)
expect(provider).to receive(:instances).with(nil).and_return([instance])
expect(provider).to receive(:instances).with(command).and_return([instance_targeted]).once
expect(provider.prefetch(packages)).to eq([nil, command]) # prefetch arbitrarily returns the array of commands for a provider in the catalog
end
end
end
describe "when validating a command" do
context "with no command" do
it "report not functional" do
expect { provider.validate_command(nil) }.to raise_error(Puppet::Error, "Provider gem package command is not functional on this host")
end
end
context "with a missing command" do
it "report does not exist" do
expect { provider.validate_command(command) }.to raise_error(Puppet::Error, "Provider gem package command '#{command}' does not exist on this host")
end
end
context "with an existing command" do
it "validates" do
allow(File).to receive(:file?).with(command).and_return(true)
expect { provider.validate_command(command) }.not_to raise_error
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/provider/exec_spec.rb | spec/unit/provider/exec_spec.rb | require 'spec_helper'
require 'puppet/provider/exec'
require 'puppet_spec/compiler'
require 'puppet_spec/files'
describe Puppet::Provider::Exec do
include PuppetSpec::Compiler
include PuppetSpec::Files
describe "#extractexe" do
it "should return the first element of an array" do
expect(subject.extractexe(['one', 'two'])).to eq('one')
end
{
# double-quoted commands
%q{"/has whitespace"} => "/has whitespace",
%q{"/no/whitespace"} => "/no/whitespace",
# singe-quoted commands
%q{'/has whitespace'} => "/has whitespace",
%q{'/no/whitespace'} => "/no/whitespace",
# combinations
%q{"'/has whitespace'"} => "'/has whitespace'",
%q{'"/has whitespace"'} => '"/has whitespace"',
%q{"/has 'special' characters"} => "/has 'special' characters",
%q{'/has "special" characters'} => '/has "special" characters',
# whitespace split commands
%q{/has whitespace} => "/has",
%q{/no/whitespace} => "/no/whitespace",
}.each do |base_command, exe|
['', ' and args', ' "and args"', " 'and args'"].each do |args|
command = base_command + args
it "should extract #{exe.inspect} from #{command.inspect}" do
expect(subject.extractexe(command)).to eq(exe)
end
end
end
end
context "when handling sensitive data" do
before :each do
Puppet[:log_level] = 'debug'
end
let(:supersecret) { 'supersecret' }
let(:path) do
if Puppet::Util::Platform.windows?
# The `apply_compiled_manifest` helper doesn't add the `path` fact, so
# we can't reference that in our manifest. Windows PATHs can contain
# double quotes and trailing backslashes, which confuse HEREDOC
# interpolation below. So sanitize it:
ENV['PATH'].split(File::PATH_SEPARATOR)
.map { |dir| dir.gsub(/"/, '\"').gsub(/\\$/, '') }
.map { |dir| Pathname.new(dir).cleanpath.to_s }
.join(File::PATH_SEPARATOR)
else
ENV['PATH']
end
end
def ruby_exit_0
"ruby -e 'exit 0'"
end
def echo_from_ruby_exit_0(message)
# Escape double quotes due to HEREDOC interpolation below
"ruby -e 'puts \"#{message}\"; exit 0'".gsub(/"/, '\"')
end
def echo_from_ruby_exit_1(message)
# Escape double quotes due to HEREDOC interpolation below
"ruby -e 'puts \"#{message}\"; exit 1'".gsub(/"/, '\"')
end
context "when validating the command" do
it "redacts the arguments if the command is relative" do
expect {
apply_compiled_manifest(<<-MANIFEST)
exec { 'echo':
command => Sensitive.new('echo #{supersecret}')
}
MANIFEST
}.to raise_error do |err|
expect(err).to be_a(Puppet::Error)
expect(err.message).to match(/'echo' is not qualified and no path was specified. Please qualify the command or specify a path./)
expect(err.message).to_not match(/#{supersecret}/)
end
end
it "redacts the arguments if the command is a directory" do
dir = tmpdir('exec')
apply_compiled_manifest(<<-MANIFEST)
exec { 'echo':
command => Sensitive.new('#{dir} #{supersecret}'),
}
MANIFEST
expect(@logs).to include(an_object_having_attributes(level: :err, message: /'#{dir}' is a directory, not a file/))
expect(@logs).to_not include(an_object_having_attributes(message: /#{supersecret}/))
end
it "redacts the arguments if the command isn't executable" do
file = tmpfile('exec')
Puppet::FileSystem.touch(file)
Puppet::FileSystem.chmod(0644, file)
apply_compiled_manifest(<<-MANIFEST)
exec { 'echo':
command => Sensitive.new('#{file} #{supersecret}'),
}
MANIFEST
# Execute permission works differently on Windows, but execute will fail since the
# file doesn't have a valid extension and isn't a valid executable. The raised error
# will be Errno::EIO, which is not useful. The Windows execute code needs to raise
# Puppet::Util::Windows::Error so the Win32 error message is preserved.
pending("PUP-3561 Needs to raise a meaningful Puppet::Error") if Puppet::Util::Platform.windows?
expect(@logs).to include(an_object_having_attributes(level: :err, message: /'#{file}' is not executable/))
expect(@logs).to_not include(an_object_having_attributes(message: /#{supersecret}/))
end
it "redacts the arguments if the relative command cannot be resolved using the path parameter" do
file = File.basename(tmpfile('exec'))
dir = tmpdir('exec')
apply_compiled_manifest(<<-MANIFEST)
exec { 'echo':
command => Sensitive.new('#{file} #{supersecret}'),
path => "#{dir}",
}
MANIFEST
expect(@logs).to include(an_object_having_attributes(level: :err, message: /Could not find command '#{file}'/))
expect(@logs).to_not include(an_object_having_attributes(message: /#{supersecret}/))
end
end
it "redacts the command on success", unless: Puppet::Util::Platform.jruby? do
command = echo_from_ruby_exit_0(supersecret)
apply_compiled_manifest(<<-MANIFEST)
exec { 'true':
command => Sensitive.new("#{command}"),
path => "#{path}",
}
MANIFEST
expect(@logs).to include(an_object_having_attributes(level: :debug, message: "Executing '[redacted]'", source: /Exec\[true\]/))
expect(@logs).to include(an_object_having_attributes(level: :debug, message: "Executing: '[redacted]'", source: "Puppet"))
expect(@logs).to include(an_object_having_attributes(level: :notice, message: "executed successfully"))
expect(@logs).to_not include(an_object_having_attributes(message: /#{supersecret}/))
end
it "redacts the command on failure", unless: Puppet::Util::Platform.jruby? do
command = echo_from_ruby_exit_1(supersecret)
apply_compiled_manifest(<<-MANIFEST)
exec { 'false':
command => Sensitive.new("#{command}"),
path => "#{path}",
}
MANIFEST
expect(@logs).to include(an_object_having_attributes(level: :debug, message: "Executing '[redacted]'", source: /Exec\[false\]/))
expect(@logs).to include(an_object_having_attributes(level: :debug, message: "Executing: '[redacted]'", source: "Puppet"))
expect(@logs).to include(an_object_having_attributes(level: :err, message: "[command redacted] returned 1 instead of one of [0]"))
expect(@logs).to_not include(an_object_having_attributes(message: /#{supersecret}/))
end
context "when handling checks", unless: Puppet::Util::Platform.jruby? do
let(:onlyifsecret) { "onlyifsecret" }
let(:unlesssecret) { "unlesssecret" }
it "redacts command and onlyif outputs" do
onlyif = echo_from_ruby_exit_0(onlyifsecret)
apply_compiled_manifest(<<-MANIFEST)
exec { 'true':
command => Sensitive.new("#{ruby_exit_0}"),
onlyif => Sensitive.new("#{onlyif}"),
path => "#{path}",
}
MANIFEST
expect(@logs).to include(an_object_having_attributes(level: :debug, message: "Executing check '[redacted]'"))
expect(@logs).to include(an_object_having_attributes(level: :debug, message: "Executing '[redacted]'", source: /Exec\[true\]/))
expect(@logs).to include(an_object_having_attributes(level: :debug, message: "Executing: '[redacted]'", source: "Puppet"))
expect(@logs).to include(an_object_having_attributes(level: :debug, message: "[output redacted]"))
expect(@logs).to include(an_object_having_attributes(level: :notice, message: "executed successfully"))
expect(@logs).to_not include(an_object_having_attributes(message: /#{onlyifsecret}/))
end
it "redacts the command that would have been executed but didn't due to onlyif" do
command = echo_from_ruby_exit_0(supersecret)
onlyif = echo_from_ruby_exit_1(onlyifsecret)
apply_compiled_manifest(<<-MANIFEST)
exec { 'true':
command => Sensitive.new("#{command}"),
onlyif => Sensitive.new("#{onlyif}"),
path => "#{path}",
}
MANIFEST
expect(@logs).to include(an_object_having_attributes(level: :debug, message: "Executing check '[redacted]'"))
expect(@logs).to include(an_object_having_attributes(level: :debug, message: "Executing: '[redacted]'", source: "Puppet"))
expect(@logs).to include(an_object_having_attributes(level: :debug, message: "[output redacted]"))
expect(@logs).to include(an_object_having_attributes(level: :debug, message: "'[command redacted]' won't be executed because of failed check 'onlyif'"))
expect(@logs).to_not include(an_object_having_attributes(message: /#{supersecret}/))
expect(@logs).to_not include(an_object_having_attributes(message: /#{onlyifsecret}/))
end
it "redacts command and unless outputs" do
unlesscmd = echo_from_ruby_exit_1(unlesssecret)
apply_compiled_manifest(<<-MANIFEST)
exec { 'true':
command => Sensitive.new("#{ruby_exit_0}"),
unless => Sensitive.new("#{unlesscmd}"),
path => "#{path}",
}
MANIFEST
expect(@logs).to include(an_object_having_attributes(level: :debug, message: "Executing check '[redacted]'"))
expect(@logs).to include(an_object_having_attributes(level: :debug, message: "Executing '[redacted]'", source: /Exec\[true\]/))
expect(@logs).to include(an_object_having_attributes(level: :debug, message: "Executing: '[redacted]'", source: "Puppet"))
expect(@logs).to include(an_object_having_attributes(level: :debug, message: "[output redacted]"))
expect(@logs).to include(an_object_having_attributes(level: :notice, message: "executed successfully"))
expect(@logs).to_not include(an_object_having_attributes(message: /#{unlesssecret}/))
end
it "redacts the command that would have been executed but didn't due to unless" do
command = echo_from_ruby_exit_0(supersecret)
unlesscmd = echo_from_ruby_exit_0(unlesssecret)
apply_compiled_manifest(<<-MANIFEST)
exec { 'true':
command => Sensitive.new("#{command}"),
unless => Sensitive.new("#{unlesscmd}"),
path => "#{path}",
}
MANIFEST
expect(@logs).to include(an_object_having_attributes(level: :debug, message: "Executing check '[redacted]'"))
expect(@logs).to include(an_object_having_attributes(level: :debug, message: "Executing: '[redacted]'", source: "Puppet"))
expect(@logs).to include(an_object_having_attributes(level: :debug, message: "[output redacted]"))
expect(@logs).to include(an_object_having_attributes(level: :debug, message: "'[command redacted]' won't be executed because of failed check 'unless'"))
expect(@logs).to_not include(an_object_having_attributes(message: /#{supersecret}/))
expect(@logs).to_not include(an_object_having_attributes(message: /#{unlesssecret}/))
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/provider/service/daemontools_spec.rb | spec/unit/provider/service/daemontools_spec.rb | require 'spec_helper'
describe 'Puppet::Type::Service::Provider::Daemontools',
unless: Puppet::Util::Platform.windows? || Puppet::Util::Platform.jruby? do
let(:provider_class) { Puppet::Type.type(:service).provider(:daemontools) }
before(:each) do
# Create a mock resource
@resource = double('resource')
@provider = provider_class.new
@servicedir = "/etc/service"
@provider.servicedir=@servicedir
@daemondir = "/var/lib/service"
@provider.class.defpath=@daemondir
# A catch all; no parameters set
allow(@resource).to receive(:[]).and_return(nil)
# But set name, source and path (because we won't run
# the thing that will fetch the resource path from the provider)
allow(@resource).to receive(:[]).with(:name).and_return("myservice")
allow(@resource).to receive(:[]).with(:ensure).and_return(:enabled)
allow(@resource).to receive(:[]).with(:path).and_return(@daemondir)
allow(@resource).to receive(:ref).and_return("Service[myservice]")
@provider.resource = @resource
allow(@provider).to receive(:command).with(:svc).and_return("svc")
allow(@provider).to receive(:command).with(:svstat).and_return("svstat")
allow(@provider).to receive(:svc)
allow(@provider).to receive(:svstat)
end
it "should have a restart method" do
expect(@provider).to respond_to(:restart)
end
it "should have a start method" do
expect(@provider).to respond_to(:start)
end
it "should have a stop method" do
expect(@provider).to respond_to(:stop)
end
it "should have an enabled? method" do
expect(@provider).to respond_to(:enabled?)
end
it "should have an enable method" do
expect(@provider).to respond_to(:enable)
end
it "should have a disable method" do
expect(@provider).to respond_to(:disable)
end
context "when starting" do
it "should use 'svc' to start the service" do
allow(@provider).to receive(:enabled?).and_return(:true)
expect(@provider).to receive(:svc).with("-u", "/etc/service/myservice")
@provider.start
end
it "should enable the service if it is not enabled" do
allow(@provider).to receive(:svc)
expect(@provider).to receive(:enabled?).and_return(:false)
expect(@provider).to receive(:enable)
@provider.start
end
end
context "when stopping" do
it "should use 'svc' to stop the service" do
allow(@provider).to receive(:disable)
expect(@provider).to receive(:svc).with("-d", "/etc/service/myservice")
@provider.stop
end
end
context "when restarting" do
it "should use 'svc' to restart the service" do
expect(@provider).to receive(:svc).with("-t", "/etc/service/myservice")
@provider.restart
end
end
context "when enabling" do
it "should create a symlink between daemon dir and service dir", :if => Puppet.features.manages_symlinks? do
daemon_path = File.join(@daemondir, "myservice")
service_path = File.join(@servicedir, "myservice")
expect(Puppet::FileSystem).to receive(:symlink?).with(service_path).and_return(false)
expect(Puppet::FileSystem).to receive(:symlink).with(daemon_path, service_path).and_return(0)
@provider.enable
end
end
context "when disabling" do
it "should remove the symlink between daemon dir and service dir" do
allow(FileTest).to receive(:directory?).and_return(false)
path = File.join(@servicedir,"myservice")
expect(Puppet::FileSystem).to receive(:symlink?).with(path).and_return(true)
expect(Puppet::FileSystem).to receive(:unlink).with(path)
allow(@provider).to receive(:execute).and_return("")
@provider.disable
end
it "should stop the service" do
allow(FileTest).to receive(:directory?).and_return(false)
expect(Puppet::FileSystem).to receive(:symlink?).and_return(true)
allow(Puppet::FileSystem).to receive(:unlink)
expect(@provider).to receive(:stop)
@provider.disable
end
end
context "when checking if the service is enabled?" do
it "should return true if it is running" do
allow(@provider).to receive(:status).and_return(:running)
expect(@provider.enabled?).to eq(:true)
end
[true, false].each do |t|
it "should return #{t} if the symlink exists" do
allow(@provider).to receive(:status).and_return(:stopped)
path = File.join(@servicedir,"myservice")
expect(Puppet::FileSystem).to receive(:symlink?).with(path).and_return(t)
expect(@provider.enabled?).to eq("#{t}".to_sym)
end
end
end
context "when checking status" do
it "should call the external command 'svstat /etc/service/myservice'" do
expect(@provider).to receive(:svstat).with(File.join(@servicedir,"myservice"))
@provider.status
end
end
context "when checking status" do
it "and svstat fails, properly raise a Puppet::Error" do
expect(@provider).to receive(:svstat).with(File.join(@servicedir,"myservice")).and_raise(Puppet::ExecutionFailure, "failure")
expect { @provider.status }.to raise_error(Puppet::Error, 'Could not get status for service Service[myservice]: failure')
end
it "and svstat returns up, then return :running" do
expect(@provider).to receive(:svstat).with(File.join(@servicedir,"myservice")).and_return("/etc/service/myservice: up (pid 454) 954326 seconds")
expect(@provider.status).to eq(:running)
end
it "and svstat returns not running, then return :stopped" do
expect(@provider).to receive(:svstat).with(File.join(@servicedir,"myservice")).and_return("/etc/service/myservice: supervise not running")
expect(@provider.status).to eq(:stopped)
end
end
context '.instances' do
before do
allow(provider_class).to receive(:defpath).and_return(path)
end
context 'when defpath is nil' do
let(:path) { nil }
it 'returns info message' do
expect(Puppet).to receive(:info).with(/daemontools is unsuitable because service directory is nil/)
provider_class.instances
end
end
context 'when defpath does not exist' do
let(:path) { '/inexistent_path' }
it 'returns notice about missing path' do
expect(Puppet).to receive(:notice).with(/Service path #{path} does not exist/)
provider_class.instances
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/provider/service/rcng_spec.rb | spec/unit/provider/service/rcng_spec.rb | require 'spec_helper'
describe 'Puppet::Type::Service::Provider::Rcng',
unless: Puppet::Util::Platform.windows? || Puppet::Util::Platform.jruby? do
let(:provider_class) { Puppet::Type.type(:service).provider(:rcng) }
before :each do
allow(Puppet::Type.type(:service)).to receive(:defaultprovider).and_return(provider_class)
allow(Facter).to receive(:value).with('os.name').and_return(:netbsd)
allow(Facter).to receive(:value).with('os.family').and_return('NetBSD')
allow(provider_class).to receive(:defpath).and_return('/etc/rc.d')
@provider = provider_class.new
allow(@provider).to receive(:initscript)
end
context "#enable" do
it "should have an enable method" do
expect(@provider).to respond_to(:enable)
end
it "should set the proper contents to enable" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd'))
allow(Dir).to receive(:mkdir).with('/etc/rc.conf.d')
fh = double('fh')
expect(Puppet::Util).to receive(:replace_file).with('/etc/rc.conf.d/sshd', 0644).and_yield(fh)
expect(fh).to receive(:puts).with("sshd=${sshd:=YES}\n")
provider.enable
end
it "should set the proper contents to enable when disabled" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd'))
allow(Dir).to receive(:mkdir).with('/etc/rc.conf.d')
allow(File).to receive(:read).with('/etc/rc.conf.d/sshd').and_return("sshd_enable=\"NO\"\n")
fh = double('fh')
expect(Puppet::Util).to receive(:replace_file).with('/etc/rc.conf.d/sshd', 0644).and_yield(fh)
expect(fh).to receive(:puts).with("sshd=${sshd:=YES}\n")
provider.enable
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/provider/service/debian_spec.rb | spec/unit/provider/service/debian_spec.rb | require 'spec_helper'
describe 'Puppet::Type::Service::Provider::Debian',
unless: Puppet::Util::Platform.jruby? || Puppet::Util::Platform.windows? do
let(:provider_class) { Puppet::Type.type(:service).provider(:debian) }
before(:each) do
# Create a mock resource
@resource = double('resource')
@provider = provider_class.new
# A catch all; no parameters set
allow(@resource).to receive(:[]).and_return(nil)
# But set name, source and path
allow(@resource).to receive(:[]).with(:name).and_return("myservice")
allow(@resource).to receive(:[]).with(:ensure).and_return(:enabled)
allow(@resource).to receive(:ref).and_return("Service[myservice]")
@provider.resource = @resource
allow(@provider).to receive(:command).with(:update_rc).and_return("update_rc")
allow(@provider).to receive(:command).with(:invoke_rc).and_return("invoke_rc")
allow(@provider).to receive(:command).with(:service).and_return("service")
allow(@provider).to receive(:update_rc)
allow(@provider).to receive(:invoke_rc)
end
['1','2'].each do |version|
it "should be the default provider on CumulusLinux #{version}" do
expect(Facter).to receive(:value).with('os.name').at_least(:once).and_return('CumulusLinux')
expect(Facter).to receive(:value).with('os.release.major').and_return(version)
expect(provider_class.default?).to be_truthy
end
end
it "should be the default provider on Devuan" do
expect(Facter).to receive(:value).with('os.name').at_least(:once).and_return('Devuan')
expect(provider_class.default?).to be_truthy
end
it "should be the default provider on Debian" do
expect(Facter).to receive(:value).with('os.name').at_least(:once).and_return('Debian')
expect(Facter).to receive(:value).with('os.release.major').and_return('7')
expect(provider_class.default?).to be_truthy
end
it "should have an enabled? method" do
expect(@provider).to respond_to(:enabled?)
end
it "should have an enable method" do
expect(@provider).to respond_to(:enable)
end
it "should have a disable method" do
expect(@provider).to respond_to(:disable)
end
context "when enabling" do
it "should call update-rc.d twice" do
expect(@provider).to receive(:update_rc).twice
@provider.enable
end
end
context "when disabling" do
it "should be able to disable services with newer sysv-rc versions" do
allow(@provider).to receive(:`).with("dpkg --compare-versions $(dpkg-query -W --showformat '${Version}' sysv-rc) ge 2.88 ; echo $?").and_return("0")
expect(@provider).to receive(:update_rc).with(@resource[:name], "disable")
@provider.disable
end
it "should be able to enable services with older sysv-rc versions" do
allow(@provider).to receive(:`).with("dpkg --compare-versions $(dpkg-query -W --showformat '${Version}' sysv-rc) ge 2.88 ; echo $?").and_return("1")
expect(@provider).to receive(:update_rc).with("-f", @resource[:name], "remove")
expect(@provider).to receive(:update_rc).with(@resource[:name], "stop", "00", "1", "2", "3", "4", "5", "6", ".")
@provider.disable
end
end
context "when checking whether it is enabled" do
it "should execute the query command" do
expect(@provider).to receive(:execute).with(["/usr/sbin/invoke-rc.d", "--quiet", "--query", @resource[:name], "start"], {:failonfail => false})
.and_return(Puppet::Util::Execution::ProcessOutput.new('', 0))
@provider.enabled?
end
it "should return true when invoke-rc.d exits with 104 status" do
expect(@provider).to receive(:execute).and_return(Puppet::Util::Execution::ProcessOutput.new('', 104))
expect(@provider.enabled?).to eq(:true)
end
it "should return true when invoke-rc.d exits with 106 status" do
expect(@provider).to receive(:execute).and_return(Puppet::Util::Execution::ProcessOutput.new('', 106))
expect(@provider.enabled?).to eq(:true)
end
it "should consider nonexistent services to be disabled" do
@provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'doesnotexist'))
expect(@provider).to receive(:execute).with(["/usr/sbin/invoke-rc.d", "--quiet", "--query", "doesnotexist", "start"], {:failonfail => false})
.and_return(Puppet::Util::Execution::ProcessOutput.new("", 1))
expect(@provider.enabled?).to be(:false)
end
shared_examples "manually queries service status" do |status|
it "links count is 4" do
allow(@provider).to receive(:execute).and_return(Puppet::Util::Execution::ProcessOutput.new('', status))
allow(@provider).to receive(:get_start_link_count).and_return(4)
expect(@provider.enabled?).to eq(:true)
end
it "links count is less than 4" do
allow(@provider).to receive(:execute).and_return(Puppet::Util::Execution::ProcessOutput.new('', status))
allow(@provider).to receive(:get_start_link_count).and_return(3)
expect(@provider.enabled?).to eq(:false)
end
end
context "when invoke-rc.d exits with 101 status" do
it_should_behave_like "manually queries service status", 101
end
context "when invoke-rc.d exits with 105 status" do
it_should_behave_like "manually queries service status", 105
end
context "when invoke-rc.d exits with 101 status" do
it_should_behave_like "manually queries service status", 101
end
context "when invoke-rc.d exits with 105 status" do
it_should_behave_like "manually queries service status", 105
end
# pick a range of non-[104.106] numbers, strings and booleans to test with.
[-100, -1, 0, 1, 100, "foo", "", :true, :false].each do |exitstatus|
it "should return false when invoke-rc.d exits with #{exitstatus} status" do
allow(@provider).to receive(:execute).and_return(Puppet::Util::Execution::ProcessOutput.new('', exitstatus))
expect(@provider.enabled?).to eq(:false)
end
end
end
context "when checking service status" do
it "should use the service command" do
allow(Facter).to receive(:value).with('os.name').and_return('Debian')
allow(Facter).to receive(:value).with('os.release.major').and_return('8')
allow(@resource).to receive(:[]).with(:hasstatus).and_return(:true)
expect(@provider.statuscmd).to eq(["service", @resource[:name], "status"])
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/provider/service/upstart_spec.rb | spec/unit/provider/service/upstart_spec.rb | require 'spec_helper'
describe 'Puppet::Type::Service::Provider::Upstart',
unless: Puppet::Util::Platform.windows? || Puppet::Util::Platform.jruby? do
let(:manual) { "\nmanual" }
let(:start_on_default_runlevels) { "\nstart on runlevel [2,3,4,5]" }
let!(:provider_class) { Puppet::Type.type(:service).provider(:upstart) }
let(:process_output) { Puppet::Util::Execution::ProcessOutput.new('', 0) }
def given_contents_of(file, content)
File.open(file, 'w') do |f|
f.write(content)
end
end
def then_contents_of(file)
File.open(file).read
end
def lists_processes_as(output)
allow(Puppet::Util::Execution).to receive(:execpipe).with("/sbin/initctl list").and_yield(output)
allow(provider_class).to receive(:which).with("/sbin/initctl").and_return("/sbin/initctl")
end
it "should be the default provider on Ubuntu" do
expect(Facter).to receive(:value).with('os.name').and_return("Ubuntu")
expect(Facter).to receive(:value).with('os.release.major').and_return("12.04")
expect(provider_class.default?).to be_truthy
end
context "upstart daemon existence confine" do
let(:initctl_version) { ['/sbin/initctl', 'version', '--quiet'] }
before(:each) do
allow(Puppet::Util).to receive(:which).with('/sbin/initctl').and_return('/sbin/initctl')
end
it "should return true when the daemon is running" do
expect(Puppet::Util::Execution).to receive(:execute).with(initctl_version, instance_of(Hash))
expect(provider_class).to be_has_initctl
end
it "should return false when the daemon is not running" do
expect(Puppet::Util::Execution).to receive(:execute)
.with(initctl_version, instance_of(Hash))
.and_raise(Puppet::ExecutionFailure, "initctl failed!")
expect(provider_class).to_not be_has_initctl
end
end
describe "excluding services" do
it "ignores tty and serial on Redhat systems" do
allow(Facter).to receive(:value).with('os.family').and_return('RedHat')
expect(provider_class.excludes).to include 'serial'
expect(provider_class.excludes).to include 'tty'
end
end
describe "#instances" do
it "should be able to find all instances" do
lists_processes_as("rc stop/waiting\nssh start/running, process 712")
expect(provider_class.instances.map {|provider| provider.name}).to match_array(["rc","ssh"])
end
it "should attach the interface name for network interfaces" do
lists_processes_as("network-interface (eth0)")
expect(provider_class.instances.first.name).to eq("network-interface INTERFACE=eth0")
end
it "should attach the job name for network interface security" do
processes = "network-interface-security (network-interface/eth0)"
allow(provider_class).to receive(:execpipe).and_yield(processes)
expect(provider_class.instances.first.name).to eq("network-interface-security JOB=network-interface/eth0")
end
it "should not find excluded services" do
processes = "wait-for-state stop/waiting"
processes += "\nportmap-wait start/running"
processes += "\nidmapd-mounting stop/waiting"
processes += "\nstartpar-bridge start/running"
processes += "\ncryptdisks-udev stop/waiting"
processes += "\nstatd-mounting stop/waiting"
processes += "\ngssd-mounting stop/waiting"
allow(provider_class).to receive(:execpipe).and_yield(processes)
expect(provider_class.instances).to be_empty
end
end
describe "#search" do
it "searches through paths to find a matching conf file" do
allow(File).to receive(:directory?).and_return(true)
allow(Puppet::FileSystem).to receive(:exist?).and_return(false)
expect(Puppet::FileSystem).to receive(:exist?).with("/etc/init/foo-bar.conf").and_return(true)
resource = Puppet::Type.type(:service).new(:name => "foo-bar", :provider => :upstart)
provider = provider_class.new(resource)
expect(provider.initscript).to eq("/etc/init/foo-bar.conf")
end
it "searches for just the name of a compound named service" do
allow(File).to receive(:directory?).and_return(true)
allow(Puppet::FileSystem).to receive(:exist?).and_return(false)
expect(Puppet::FileSystem).to receive(:exist?).with("/etc/init/network-interface.conf").and_return(true)
resource = Puppet::Type.type(:service).new(:name => "network-interface INTERFACE=lo", :provider => :upstart)
provider = provider_class.new(resource)
expect(provider.initscript).to eq("/etc/init/network-interface.conf")
end
end
describe "#status" do
it "should use the default status command if none is specified" do
resource = Puppet::Type.type(:service).new(:name => "foo", :provider => :upstart)
provider = provider_class.new(resource)
allow(provider).to receive(:is_upstart?).and_return(true)
expect(provider).to receive(:status_exec)
.with(["foo"])
.and_return(Puppet::Util::Execution::ProcessOutput.new("foo start/running, process 1000", 0))
expect(provider.status).to eq(:running)
end
describe "when a special status command is specifed" do
it "should use the provided status command" do
resource = Puppet::Type.type(:service).new(:name => 'foo', :provider => :upstart, :status => '/bin/foo')
provider = provider_class.new(resource)
allow(provider).to receive(:is_upstart?).and_return(true)
expect(provider).not_to receive(:status_exec).with(['foo'])
expect(provider).to receive(:execute)
.with(['/bin/foo'], {:failonfail => false, :override_locale => false, :squelch => false, :combine => true})
.and_return(process_output)
provider.status
end
it "should return :stopped when the provided status command return non-zero" do
resource = Puppet::Type.type(:service).new(:name => 'foo', :provider => :upstart, :status => '/bin/foo')
provider = provider_class.new(resource)
allow(provider).to receive(:is_upstart?).and_return(true)
expect(provider).not_to receive(:status_exec).with(['foo'])
expect(provider).to receive(:execute)
.with(['/bin/foo'], {:failonfail => false, :override_locale => false, :squelch => false, :combine => true})
.and_return(Puppet::Util::Execution::ProcessOutput.new('', 1))
expect(provider.status).to eq(:stopped)
end
it "should return :running when the provided status command return zero" do
resource = Puppet::Type.type(:service).new(:name => 'foo', :provider => :upstart, :status => '/bin/foo')
provider = provider_class.new(resource)
allow(provider).to receive(:is_upstart?).and_return(true)
expect(provider).not_to receive(:status_exec).with(['foo'])
expect(provider).to receive(:execute)
.with(['/bin/foo'], {:failonfail => false, :override_locale => false, :squelch => false, :combine => true})
.and_return(process_output)
expect(provider.status).to eq(:running)
end
end
describe "when :hasstatus is set to false" do
it "should return :stopped if the pid can not be found" do
resource = Puppet::Type.type(:service).new(:name => 'foo', :hasstatus => false, :provider => :upstart)
provider = provider_class.new(resource)
allow(provider).to receive(:is_upstart?).and_return(true)
expect(provider).not_to receive(:status_exec).with(['foo'])
expect(provider).to receive(:getpid).and_return(nil)
expect(provider.status).to eq(:stopped)
end
it "should return :running if the pid can be found" do
resource = Puppet::Type.type(:service).new(:name => 'foo', :hasstatus => false, :provider => :upstart)
provider = provider_class.new(resource)
allow(provider).to receive(:is_upstart?).and_return(true)
expect(provider).not_to receive(:status_exec).with(['foo'])
expect(provider).to receive(:getpid).and_return(2706)
expect(provider.status).to eq(:running)
end
end
describe "when a special status command is specifed" do
it "should use the provided status command" do
resource = Puppet::Type.type(:service).new(:name => 'foo', :provider => :upstart, :status => '/bin/foo')
provider = provider_class.new(resource)
allow(provider).to receive(:is_upstart?).and_return(true)
expect(provider).not_to receive(:status_exec).with(['foo'])
expect(provider).to receive(:execute)
.with(['/bin/foo'], {:failonfail => false, :override_locale => false, :squelch => false, :combine => true})
.and_return(process_output)
provider.status
end
it "should return :stopped when the provided status command return non-zero" do
resource = Puppet::Type.type(:service).new(:name => 'foo', :provider => :upstart, :status => '/bin/foo')
provider = provider_class.new(resource)
allow(provider).to receive(:is_upstart?).and_return(true)
expect(provider).not_to receive(:status_exec).with(['foo'])
expect(provider).to receive(:execute)
.with(['/bin/foo'], {:failonfail => false, :override_locale => false, :squelch => false, :combine => true})
.and_return(Puppet::Util::Execution::ProcessOutput.new('', 1))
expect(provider.status).to eq(:stopped)
end
it "should return :running when the provided status command return zero" do
resource = Puppet::Type.type(:service).new(:name => 'foo', :provider => :upstart, :status => '/bin/foo')
provider = provider_class.new(resource)
allow(provider).to receive(:is_upstart?).and_return(true)
expect(provider).not_to receive(:status_exec).with(['foo'])
expect(provider).to receive(:execute)
.with(['/bin/foo'], {:failonfail => false, :override_locale => false, :squelch => false, :combine => true})
.and_return(process_output)
expect(provider.status).to eq(:running)
end
end
describe "when :hasstatus is set to false" do
it "should return :stopped if the pid can not be found" do
resource = Puppet::Type.type(:service).new(:name => 'foo', :hasstatus => false, :provider => :upstart)
provider = provider_class.new(resource)
allow(provider).to receive(:is_upstart?).and_return(true)
expect(provider).not_to receive(:status_exec).with(['foo'])
expect(provider).to receive(:getpid).and_return(nil)
expect(provider.status).to eq(:stopped)
end
it "should return :running if the pid can be found" do
resource = Puppet::Type.type(:service).new(:name => 'foo', :hasstatus => false, :provider => :upstart)
provider = provider_class.new(resource)
allow(provider).to receive(:is_upstart?).and_return(true)
expect(provider).not_to receive(:status_exec).with(['foo'])
expect(provider).to receive(:getpid).and_return(2706)
expect(provider.status).to eq(:running)
end
end
it "should properly handle services with 'start' in their name" do
resource = Puppet::Type.type(:service).new(:name => "foostartbar", :provider => :upstart)
provider = provider_class.new(resource)
allow(provider).to receive(:is_upstart?).and_return(true)
expect(provider).to receive(:status_exec)
.with(["foostartbar"]).and_return("foostartbar stop/waiting")
.and_return(process_output)
expect(provider.status).to eq(:stopped)
end
end
describe "inheritance" do
let :resource do
Puppet::Type.type(:service).new(:name => "foo", :provider => :upstart)
end
let :provider do
provider_class.new(resource)
end
describe "when upstart job" do
before(:each) do
allow(provider).to receive(:is_upstart?).and_return(true)
end
["start", "stop"].each do |action|
it "should return the #{action}cmd of its parent provider" do
expect(provider.send("#{action}cmd".to_sym)).to eq([provider.command(action.to_sym), resource.name])
end
end
it "should return nil for the statuscmd" do
expect(provider.statuscmd).to be_nil
end
end
end
describe "should be enableable" do
let :resource do
Puppet::Type.type(:service).new(:name => "foo", :provider => :upstart)
end
let :provider do
provider_class.new(resource)
end
let :init_script do
PuppetSpec::Files.tmpfile("foo.conf")
end
let :over_script do
PuppetSpec::Files.tmpfile("foo.override")
end
let :disabled_content do
"\t # \t start on\nother file stuff"
end
let :multiline_disabled do
"# \t start on other file stuff (\n" +
"# more stuff ( # )))))inline comment\n" +
"# finishing up )\n" +
"# and done )\n" +
"this line shouldn't be touched\n"
end
let :multiline_disabled_bad do
"# \t start on other file stuff (\n" +
"# more stuff ( # )))))inline comment\n" +
"# finishing up )\n" +
"# and done )\n" +
"# this is a comment i want to be a comment\n" +
"this line shouldn't be touched\n"
end
let :multiline_enabled_bad do
" \t start on other file stuff (\n" +
" more stuff ( # )))))inline comment\n" +
" finishing up )\n" +
" and done )\n" +
"# this is a comment i want to be a comment\n" +
"this line shouldn't be touched\n"
end
let :multiline_enabled do
" \t start on other file stuff (\n" +
" more stuff ( # )))))inline comment\n" +
" finishing up )\n" +
" and done )\n" +
"this line shouldn't be touched\n"
end
let :multiline_enabled_standalone do
" \t start on other file stuff (\n" +
" more stuff ( # )))))inline comment\n" +
" finishing up )\n" +
" and done )\n"
end
let :enabled_content do
"\t \t start on\nother file stuff"
end
let :content do
"just some text"
end
describe "Upstart version < 0.6.7" do
before(:each) do
allow(provider).to receive(:is_upstart?).and_return(true)
allow(provider).to receive(:upstart_version).and_return("0.6.5")
allow(provider).to receive(:search).and_return(init_script)
end
[:enabled?,:enable,:disable].each do |enableable|
it "should respond to #{enableable}" do
expect(provider).to respond_to(enableable)
end
end
describe "when enabling" do
it "should open and uncomment the '#start on' line" do
given_contents_of(init_script, disabled_content)
provider.enable
expect(then_contents_of(init_script)).to eq(enabled_content)
end
it "should add a 'start on' line if none exists" do
given_contents_of(init_script, "this is a file")
provider.enable
expect(then_contents_of(init_script)).to eq("this is a file" + start_on_default_runlevels)
end
it "should handle multiline 'start on' stanzas" do
given_contents_of(init_script, multiline_disabled)
provider.enable
expect(then_contents_of(init_script)).to eq(multiline_enabled)
end
it "should leave not 'start on' comments alone" do
given_contents_of(init_script, multiline_disabled_bad)
provider.enable
expect(then_contents_of(init_script)).to eq(multiline_enabled_bad)
end
end
describe "when disabling" do
it "should open and comment the 'start on' line" do
given_contents_of(init_script, enabled_content)
provider.disable
expect(then_contents_of(init_script)).to eq("#" + enabled_content)
end
it "should handle multiline 'start on' stanzas" do
given_contents_of(init_script, multiline_enabled)
provider.disable
expect(then_contents_of(init_script)).to eq(multiline_disabled)
end
end
describe "when checking whether it is enabled" do
it "should consider 'start on ...' to be enabled" do
given_contents_of(init_script, enabled_content)
expect(provider.enabled?).to eq(:true)
end
it "should consider '#start on ...' to be disabled" do
given_contents_of(init_script, disabled_content)
expect(provider.enabled?).to eq(:false)
end
it "should consider no start on line to be disabled" do
given_contents_of(init_script, content)
expect(provider.enabled?).to eq(:false)
end
end
end
describe "Upstart version < 0.9.0" do
before(:each) do
allow(provider).to receive(:is_upstart?).and_return(true)
allow(provider).to receive(:upstart_version).and_return("0.7.0")
allow(provider).to receive(:search).and_return(init_script)
end
[:enabled?,:enable,:disable].each do |enableable|
it "should respond to #{enableable}" do
expect(provider).to respond_to(enableable)
end
end
describe "when enabling" do
it "should open and uncomment the '#start on' line" do
given_contents_of(init_script, disabled_content)
provider.enable
expect(then_contents_of(init_script)).to eq(enabled_content)
end
it "should add a 'start on' line if none exists" do
given_contents_of(init_script, "this is a file")
provider.enable
expect(then_contents_of(init_script)).to eq("this is a file" + start_on_default_runlevels)
end
it "should handle multiline 'start on' stanzas" do
given_contents_of(init_script, multiline_disabled)
provider.enable
expect(then_contents_of(init_script)).to eq(multiline_enabled)
end
it "should remove manual stanzas" do
given_contents_of(init_script, multiline_enabled + manual)
provider.enable
expect(then_contents_of(init_script)).to eq(multiline_enabled)
end
it "should leave not 'start on' comments alone" do
given_contents_of(init_script, multiline_disabled_bad)
provider.enable
expect(then_contents_of(init_script)).to eq(multiline_enabled_bad)
end
end
describe "when disabling" do
it "should add a manual stanza" do
given_contents_of(init_script, enabled_content)
provider.disable
expect(then_contents_of(init_script)).to eq(enabled_content + manual)
end
it "should remove manual stanzas before adding new ones" do
given_contents_of(init_script, multiline_enabled + manual + "\n" + multiline_enabled)
provider.disable
expect(then_contents_of(init_script)).to eq(multiline_enabled + "\n" + multiline_enabled + manual)
end
it "should handle multiline 'start on' stanzas" do
given_contents_of(init_script, multiline_enabled)
provider.disable
expect(then_contents_of(init_script)).to eq(multiline_enabled + manual)
end
end
describe "when checking whether it is enabled" do
describe "with no manual stanza" do
it "should consider 'start on ...' to be enabled" do
given_contents_of(init_script, enabled_content)
expect(provider.enabled?).to eq(:true)
end
it "should consider '#start on ...' to be disabled" do
given_contents_of(init_script, disabled_content)
expect(provider.enabled?).to eq(:false)
end
it "should consider no start on line to be disabled" do
given_contents_of(init_script, content)
expect(provider.enabled?).to eq(:false)
end
end
describe "with manual stanza" do
it "should consider 'start on ...' to be disabled if there is a trailing manual stanza" do
given_contents_of(init_script, enabled_content + manual + "\nother stuff")
expect(provider.enabled?).to eq(:false)
end
it "should consider two start on lines with a manual in the middle to be enabled" do
given_contents_of(init_script, enabled_content + manual + "\n" + enabled_content)
expect(provider.enabled?).to eq(:true)
end
end
end
end
describe "Upstart version > 0.9.0" do
before(:each) do
allow(provider).to receive(:is_upstart?).and_return(true)
allow(provider).to receive(:upstart_version).and_return("0.9.5")
allow(provider).to receive(:search).and_return(init_script)
allow(provider).to receive(:overscript).and_return(over_script)
end
[:enabled?,:enable,:disable].each do |enableable|
it "should respond to #{enableable}" do
expect(provider).to respond_to(enableable)
end
end
describe "when enabling" do
it "should add a 'start on' line if none exists" do
given_contents_of(init_script, "this is a file")
provider.enable
expect(then_contents_of(init_script)).to eq("this is a file")
expect(then_contents_of(over_script)).to eq(start_on_default_runlevels)
end
it "should handle multiline 'start on' stanzas" do
given_contents_of(init_script, multiline_disabled)
provider.enable
expect(then_contents_of(init_script)).to eq(multiline_disabled)
expect(then_contents_of(over_script)).to eq(start_on_default_runlevels)
end
it "should remove any manual stanzas from the override file" do
given_contents_of(over_script, manual)
given_contents_of(init_script, enabled_content)
provider.enable
expect(then_contents_of(init_script)).to eq(enabled_content)
expect(then_contents_of(over_script)).to eq("")
end
it "should copy existing start on from conf file if conf file is disabled" do
given_contents_of(init_script, multiline_enabled_standalone + manual)
provider.enable
expect(then_contents_of(init_script)).to eq(multiline_enabled_standalone + manual)
expect(then_contents_of(over_script)).to eq(multiline_enabled_standalone)
end
it "should leave not 'start on' comments alone" do
given_contents_of(init_script, multiline_disabled_bad)
given_contents_of(over_script, "")
provider.enable
expect(then_contents_of(init_script)).to eq(multiline_disabled_bad)
expect(then_contents_of(over_script)).to eq(start_on_default_runlevels)
end
end
describe "when disabling" do
it "should add a manual stanza to the override file" do
given_contents_of(init_script, enabled_content)
provider.disable
expect(then_contents_of(init_script)).to eq(enabled_content)
expect(then_contents_of(over_script)).to eq(manual)
end
it "should handle multiline 'start on' stanzas" do
given_contents_of(init_script, multiline_enabled)
provider.disable
expect(then_contents_of(init_script)).to eq(multiline_enabled)
expect(then_contents_of(over_script)).to eq(manual)
end
end
describe "when checking whether it is enabled" do
describe "with no override file" do
it "should consider 'start on ...' to be enabled" do
given_contents_of(init_script, enabled_content)
expect(provider.enabled?).to eq(:true)
end
it "should consider '#start on ...' to be disabled" do
given_contents_of(init_script, disabled_content)
expect(provider.enabled?).to eq(:false)
end
it "should consider no start on line to be disabled" do
given_contents_of(init_script, content)
expect(provider.enabled?).to eq(:false)
end
end
describe "with override file" do
it "should consider 'start on ...' to be disabled if there is manual in override file" do
given_contents_of(init_script, enabled_content)
given_contents_of(over_script, manual + "\nother stuff")
expect(provider.enabled?).to eq(:false)
end
it "should consider '#start on ...' to be enabled if there is a start on in the override file" do
given_contents_of(init_script, disabled_content)
given_contents_of(over_script, "start on stuff")
expect(provider.enabled?).to eq(:true)
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/provider/service/openbsd_spec.rb | spec/unit/provider/service/openbsd_spec.rb | require 'spec_helper'
describe 'Puppet::Type::Service::Provider::Openbsd',
unless: Puppet::Util::Platform.windows? || Puppet::Util::Platform.jruby? do
let(:provider_class) { Puppet::Type.type(:service).provider(:openbsd) }
before :each do
allow(Puppet::Type.type(:service)).to receive(:defaultprovider).and_return(provider_class)
allow(Facter).to receive(:value).with('os.name').and_return(:openbsd)
allow(Facter).to receive(:value).with('os.family').and_return('OpenBSD')
allow(FileTest).to receive(:file?).with('/usr/sbin/rcctl').and_return(true)
allow(FileTest).to receive(:executable?).with('/usr/sbin/rcctl').and_return(true)
end
context "#instances" do
it "should have an instances method" do
expect(provider_class).to respond_to :instances
end
it "should list all available services" do
allow(provider_class).to receive(:execpipe).with(['/usr/sbin/rcctl', :getall]).and_yield(File.read(my_fixture('rcctl_getall')))
expect(provider_class.instances.map(&:name)).to eq([
'accounting', 'pf', 'postgresql', 'tftpd', 'wsmoused', 'xdm',
])
end
end
context "#start" do
it "should use the supplied start command if specified" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :start => '/bin/foo'))
expect(provider).to receive(:execute).with(['/bin/foo'], {:failonfail => true, :override_locale => false, :squelch => false, :combine => true})
provider.start
end
it "should start the service otherwise" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd'))
expect(provider).to receive(:execute).with(['/usr/sbin/rcctl', '-f', :start, 'sshd'], hash_including(failonfail: true))
provider.start
end
end
context "#stop" do
it "should use the supplied stop command if specified" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :stop => '/bin/foo'))
expect(provider).to receive(:execute).with(['/bin/foo'], {:failonfail => true, :override_locale => false, :squelch => false, :combine => true})
provider.stop
end
it "should stop the service otherwise" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd'))
expect(provider).to receive(:execute).with(['/usr/sbin/rcctl', :stop, 'sshd'], hash_including(failonfail: true))
provider.stop
end
end
context "#status" do
it "should use the status command from the resource" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :status => '/bin/foo'))
expect(provider).not_to receive(:execute).with(['/usr/sbin/rcctl', :get, 'sshd', :status], {:failonfail => true, :override_locale => false, :squelch => false, :combine => true})
expect(provider).to receive(:execute)
.with(['/bin/foo'], {:failonfail => false, :override_locale => false, :squelch => false, :combine => true})
.and_return(Puppet::Util::Execution::ProcessOutput.new('', 0))
provider.status
end
it "should return :stopped when status command returns with a non-zero exitcode" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :status => '/bin/foo'))
expect(provider).not_to receive(:execute).with(['/usr/sbin/rcctl', :get, 'sshd', :status], {:failonfail => true, :override_locale => false, :squelch => false, :combine => true})
expect(provider).to receive(:execute)
.with(['/bin/foo'], {:failonfail => false, :override_locale => false, :squelch => false, :combine => true})
.and_return(Puppet::Util::Execution::ProcessOutput.new('', 3))
expect(provider.status).to eq(:stopped)
end
it "should return :running when status command returns with a zero exitcode" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :status => '/bin/foo'))
expect(provider).not_to receive(:execute).with(['/usr/sbin/rcctl', :get, 'sshd', :status], {:failonfail => true, :override_locale => false, :squelch => false, :combine => true})
expect(provider).to receive(:execute)
.with(['/bin/foo'], {:failonfail => false, :override_locale => false, :squelch => false, :combine => true})
.and_return(Puppet::Util::Execution::ProcessOutput.new('', 0))
expect(provider.status).to eq(:running)
end
end
context "#restart" do
it "should use the supplied restart command if specified" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :restart => '/bin/foo'))
expect(provider).not_to receive(:execute).with(['/usr/sbin/rcctl', '-f', :restart, 'sshd'], {:failonfail => true, :override_locale => false, :squelch => false, :combine => true})
expect(provider).to receive(:execute)
.with(['/bin/foo'], {:failonfail => true, :override_locale => false, :squelch => false, :combine => true})
.and_return(Puppet::Util::Execution::ProcessOutput.new('', 0))
provider.restart
end
it "should restart the service with rcctl restart if hasrestart is true" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :hasrestart => true))
expect(provider).to receive(:execute).with(['/usr/sbin/rcctl', '-f', :restart, 'sshd'], hash_including(failonfail: true))
provider.restart
end
it "should restart the service with rcctl stop/start if hasrestart is false" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :hasrestart => false))
expect(provider).not_to receive(:execute).with(['/usr/sbin/rcctl', '-f', :restart, 'sshd'], any_args)
expect(provider).to receive(:execute).with(['/usr/sbin/rcctl', :stop, 'sshd'], hash_including(failonfail: true))
expect(provider).to receive(:execute).with(['/usr/sbin/rcctl', '-f', :start, 'sshd'], hash_including(failonfail: true))
provider.restart
end
end
context "#enabled?" do
it "should return :true if the service is enabled" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd'))
expect(provider).to receive(:execute).with(['/usr/sbin/rcctl', 'get', 'sshd', 'status'], {:failonfail => false, :combine => false, :squelch => false}).and_return(double(:exitstatus => 0))
expect(provider.enabled?).to eq(:true)
end
it "should return :false if the service is disabled" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd'))
expect(provider).to receive(:execute).with(['/usr/sbin/rcctl', 'get', 'sshd', 'status'], {:failonfail => false, :combine => false, :squelch => false}).and_return(Puppet::Util::Execution::ProcessOutput.new('NO', 1))
expect(provider.enabled?).to eq(:false)
end
end
context "#enable" do
it "should run rcctl enable to enable the service" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd'))
expect(provider).to receive(:rcctl).with(:enable, 'sshd')
provider.enable
end
it "should run rcctl enable with flags if provided" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :flags => '-6'))
expect(provider).to receive(:rcctl).with(:enable, 'sshd')
expect(provider).to receive(:rcctl).with(:set, 'sshd', :flags, '-6')
provider.enable
end
end
context "#disable" do
it "should run rcctl disable to disable the service" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd'))
expect(provider).to receive(:rcctl).with(:disable, 'sshd')
provider.disable
end
end
context "#running?" do
it "should run rcctl check to check the service" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd'))
expect(provider).to receive(:execute).with(['/usr/sbin/rcctl', 'check', 'sshd'], {:failonfail => false, :combine => false, :squelch => false}).and_return('sshd(ok)')
expect(provider.running?).to be_truthy
end
it "should return true if the service is running" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd'))
expect(provider).to receive(:execute).with(['/usr/sbin/rcctl', 'check', 'sshd'], {:failonfail => false, :combine => false, :squelch => false}).and_return('sshd(ok)')
expect(provider.running?).to be_truthy
end
it "should return nil if the service is not running" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd'))
expect(provider).to receive(:execute).with(['/usr/sbin/rcctl', 'check', 'sshd'], {:failonfail => false, :combine => false, :squelch => false}).and_return('sshd(failed)')
expect(provider.running?).to be_nil
end
end
context "#flags" do
it "should return flags when set" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :flags => '-6'))
expect(provider).to receive(:execute).with(['/usr/sbin/rcctl', 'get', 'sshd', 'flags'], {:failonfail => false, :combine => false, :squelch => false}).and_return('-6')
provider.flags
end
it "should return empty flags" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd'))
expect(provider).to receive(:execute).with(['/usr/sbin/rcctl', 'get', 'sshd', 'flags'], {:failonfail => false, :combine => false, :squelch => false}).and_return('')
provider.flags
end
it "should return flags for special services" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'pf'))
expect(provider).to receive(:execute).with(['/usr/sbin/rcctl', 'get', 'pf', 'flags'], {:failonfail => false, :combine => false, :squelch => false}).and_return('YES')
provider.flags
end
end
context "#flags=" do
it "should run rcctl to set flags", unless: Puppet::Util::Platform.windows? || RUBY_PLATFORM == 'java' do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd'))
expect(provider).to receive(:execute).with(['/usr/sbin/rcctl', 'get', 'sshd', 'flags'], any_args).and_return('')
expect(provider).to receive(:rcctl).with(:set, 'sshd', :flags, '-4')
expect(provider).to receive(:execute).with(['/usr/sbin/rcctl', 'check', 'sshd'], any_args).and_return('')
provider.flags = '-4'
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/provider/service/freebsd_spec.rb | spec/unit/provider/service/freebsd_spec.rb | require 'spec_helper'
describe 'Puppet::Type::Service::Provider::Freebsd',
unless: Puppet::Util::Platform.windows? || Puppet::Util::Platform.jruby? do
let(:provider_class) { Puppet::Type.type(:service).provider(:freebsd) }
before :each do
@provider = provider_class.new
allow(@provider).to receive(:initscript)
allow(Facter).to receive(:value).with('os.family').and_return('FreeBSD')
end
it "should correctly parse rcvar for FreeBSD < 7" do
allow(@provider).to receive(:execute).and_return(<<OUTPUT)
# ntpd
$ntpd_enable=YES
OUTPUT
expect(@provider.rcvar).to eq(['# ntpd', 'ntpd_enable=YES'])
end
it "should correctly parse rcvar for FreeBSD 7 to 8" do
allow(@provider).to receive(:execute).and_return(<<OUTPUT)
# ntpd
ntpd_enable=YES
OUTPUT
expect(@provider.rcvar).to eq(['# ntpd', 'ntpd_enable=YES'])
end
it "should correctly parse rcvar for FreeBSD >= 8.1" do
allow(@provider).to receive(:execute).and_return(<<OUTPUT)
# ntpd
#
ntpd_enable="YES"
# (default: "")
OUTPUT
expect(@provider.rcvar).to eq(['# ntpd', 'ntpd_enable="YES"', '# (default: "")'])
end
it "should correctly parse rcvar for DragonFly BSD" do
allow(@provider).to receive(:execute).and_return(<<OUTPUT)
# ntpd
$ntpd=YES
OUTPUT
expect(@provider.rcvar).to eq(['# ntpd', 'ntpd=YES'])
end
it 'should parse service names with a description' do
allow(@provider).to receive(:execute).and_return(<<OUTPUT)
# local_unbound : local caching forwarding resolver
local_unbound_enable="YES"
OUTPUT
expect(@provider.service_name).to eq('local_unbound')
end
it 'should parse service names without a description' do
allow(@provider).to receive(:execute).and_return(<<OUTPUT)
# local_unbound
local_unbound="YES"
OUTPUT
expect(@provider.service_name).to eq('local_unbound')
end
it "should find the right rcvar_value for FreeBSD < 7" do
allow(@provider).to receive(:rcvar).and_return(['# ntpd', 'ntpd_enable=YES'])
expect(@provider.rcvar_value).to eq("YES")
end
it "should find the right rcvar_value for FreeBSD >= 7" do
allow(@provider).to receive(:rcvar).and_return(['# ntpd', 'ntpd_enable="YES"', '# (default: "")'])
expect(@provider.rcvar_value).to eq("YES")
end
it "should find the right rcvar_name" do
allow(@provider).to receive(:rcvar).and_return(['# ntpd', 'ntpd_enable="YES"'])
expect(@provider.rcvar_name).to eq("ntpd")
end
it "should enable only the selected service" do
allow(Puppet::FileSystem).to receive(:exist?).with('/etc/rc.conf').and_return(true)
allow(File).to receive(:read).with('/etc/rc.conf').and_return("openntpd_enable=\"NO\"\nntpd_enable=\"NO\"\n")
fh = double('fh')
allow(Puppet::FileSystem).to receive(:replace_file).with('/etc/rc.conf').and_yield(fh)
expect(fh).to receive(:<<).with("openntpd_enable=\"NO\"\nntpd_enable=\"YES\"\n")
allow(Puppet::FileSystem).to receive(:exist?).with('/etc/rc.conf.local').and_return(false)
allow(Puppet::FileSystem).to receive(:exist?).with('/etc/rc.conf.d/ntpd').and_return(false)
@provider.rc_replace('ntpd', 'ntpd', 'YES')
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/provider/service/redhat_spec.rb | spec/unit/provider/service/redhat_spec.rb | require 'spec_helper'
describe 'Puppet::Type::Service::Provider::Redhat',
unless: Puppet::Util::Platform.windows? || Puppet::Util::Platform.jruby? do
let(:provider_class) { Puppet::Type.type(:service).provider(:redhat) }
before :each do
@class = Puppet::Type.type(:service).provider(:redhat)
@resource = double('resource')
allow(@resource).to receive(:[]).and_return(nil)
allow(@resource).to receive(:[]).with(:name).and_return("myservice")
@provider = provider_class.new
allow(@resource).to receive(:provider).and_return(@provider)
@provider.resource = @resource
allow(@provider).to receive(:get).with(:hasstatus).and_return(false)
allow(FileTest).to receive(:file?).with('/sbin/service').and_return(true)
allow(FileTest).to receive(:executable?).with('/sbin/service').and_return(true)
allow(Facter).to receive(:value).with('os.name').and_return('CentOS')
allow(Facter).to receive(:value).with('os.family').and_return('RedHat')
end
[4, 5, 6].each do |ver|
it "should be the default provider on rhel#{ver}" do
allow(Facter).to receive(:value).with('os.name').and_return(:redhat)
allow(Facter).to receive(:value).with('os.release.major').and_return(ver)
expect(provider_class.default?).to be_truthy
end
end
it "should be the default provider on sles11" do
allow(Facter).to receive(:value).with('os.family').and_return(:suse)
allow(Facter).to receive(:value).with('os.name').and_return(:suse)
allow(Facter).to receive(:value).with('os.release.major').and_return("11")
expect(provider_class.default?).to be_truthy
end
# test self.instances
context "when getting all service instances" do
before :each do
@services = ['one', 'two', 'three', 'four', 'kudzu', 'functions', 'halt', 'killall', 'single', 'linuxconf', 'boot', 'reboot']
@not_services = ['functions', 'halt', 'killall', 'single', 'linuxconf', 'reboot', 'boot']
allow(Dir).to receive(:entries).and_return(@services)
allow(Puppet::FileSystem).to receive(:directory?).and_call_original
allow(Puppet::FileSystem).to receive(:directory?).with('/etc/init.d').and_return(true)
allow(Puppet::FileSystem).to receive(:executable?).and_return(true)
end
it "should return instances for all services" do
(@services-@not_services).each do |inst|
expect(@class).to receive(:new).with(hash_including(name: inst, path: '/etc/init.d')).and_return("#{inst}_instance")
end
results = (@services-@not_services).collect {|x| "#{x}_instance"}
expect(@class.instances).to eq(results)
end
it "should call service status when initialized from provider" do
allow(@resource).to receive(:[]).with(:status).and_return(nil)
allow(@provider).to receive(:get).with(:hasstatus).and_return(true)
expect(@provider).to receive(:execute)
.with(['/sbin/service', 'myservice', 'status'], any_args)
.and_return(Puppet::Util::Execution::ProcessOutput.new('', 0))
@provider.send(:status)
end
end
it "should use '--add' and 'on' when calling enable" do
expect(provider_class).to receive(:chkconfig).with("--add", @resource[:name])
expect(provider_class).to receive(:chkconfig).with(@resource[:name], :on)
@provider.enable
end
it "(#15797) should explicitly turn off the service in all run levels" do
expect(provider_class).to receive(:chkconfig).with("--level", "0123456", @resource[:name], :off)
@provider.disable
end
it "should have an enabled? method" do
expect(@provider).to respond_to(:enabled?)
end
context "when checking enabled? on Suse" do
before :each do
expect(Facter).to receive(:value).with('os.family').and_return('Suse')
end
it "should check for on" do
allow(provider_class).to receive(:chkconfig).with(@resource[:name]).and_return("#{@resource[:name]} on")
expect(@provider.enabled?).to eq(:true)
end
it "should check for B" do
allow(provider_class).to receive(:chkconfig).with(@resource[:name]).and_return("#{@resource[:name]} B")
expect(@provider.enabled?).to eq(:true)
end
it "should check for off" do
allow(provider_class).to receive(:chkconfig).with(@resource[:name]).and_return("#{@resource[:name]} off")
expect(@provider.enabled?).to eq(:false)
end
it "should check for unknown service" do
allow(provider_class).to receive(:chkconfig).with(@resource[:name]).and_return("#{@resource[:name]}: unknown service")
expect(@provider.enabled?).to eq(:false)
end
end
it "should have an enable method" do
expect(@provider).to respond_to(:enable)
end
it "should have a disable method" do
expect(@provider).to respond_to(:disable)
end
[:start, :stop, :status, :restart].each do |method|
it "should have a #{method} method" do
expect(@provider).to respond_to(method)
end
describe "when running #{method}" do
it "should use any provided explicit command" do
allow(@resource).to receive(:[]).with(method).and_return("/user/specified/command")
expect(@provider).to receive(:execute)
.with(["/user/specified/command"], any_args)
.and_return(Puppet::Util::Execution::ProcessOutput.new('', 0))
@provider.send(method)
end
it "should execute the service script with #{method} when no explicit command is provided" do
allow(@resource).to receive(:[]).with("has#{method}".intern).and_return(:true)
expect(@provider).to receive(:execute)
.with(['/sbin/service', 'myservice', method.to_s], any_args)
.and_return(Puppet::Util::Execution::ProcessOutput.new('', 0))
@provider.send(method)
end
end
end
context "when checking status" do
context "when hasstatus is :true" do
before :each do
allow(@resource).to receive(:[]).with(:hasstatus).and_return(:true)
end
it "should execute the service script with fail_on_failure false" do
expect(@provider).to receive(:execute)
.with(['/sbin/service', 'myservice', 'status'], any_args)
.and_return(Puppet::Util::Execution::ProcessOutput.new('', 0))
@provider.status
end
it "should consider the process running if the command returns 0" do
expect(@provider).to receive(:execute)
.with(['/sbin/service', 'myservice', 'status'], hash_including(failonfail: false))
.and_return(Puppet::Util::Execution::ProcessOutput.new('', 0))
expect(@provider.status).to eq(:running)
end
[-10,-1,1,10].each { |ec|
it "should consider the process stopped if the command returns something non-0" do
expect(@provider).to receive(:execute)
.with(['/sbin/service', 'myservice', 'status'], hash_including(failonfail: false))
.and_return(Puppet::Util::Execution::ProcessOutput.new('', ec))
expect(@provider.status).to eq(:stopped)
end
}
end
context "when hasstatus is not :true" do
it "should consider the service :running if it has a pid" do
expect(@provider).to receive(:getpid).and_return("1234")
expect(@provider.status).to eq(:running)
end
it "should consider the service :stopped if it doesn't have a pid" do
expect(@provider).to receive(:getpid).and_return(nil)
expect(@provider.status).to eq(:stopped)
end
end
end
context "when restarting and hasrestart is not :true" do
it "should stop and restart the process with the server script" do
expect(@provider).to receive(:execute).with(['/sbin/service', 'myservice', 'stop'], hash_including(failonfail: true))
expect(@provider).to receive(:execute).with(['/sbin/service', 'myservice', 'start'], hash_including(failonfail: true))
@provider.restart
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/provider/service/systemd_spec.rb | spec/unit/provider/service/systemd_spec.rb | require 'spec_helper'
describe 'Puppet::Type::Service::Provider::Systemd',
unless: Puppet::Util::Platform.windows? || Puppet::Util::Platform.jruby? do
let(:provider_class) { Puppet::Type.type(:service).provider(:systemd) }
before :each do
allow(Puppet::Type.type(:service)).to receive(:defaultprovider).and_return(provider_class)
allow(provider_class).to receive(:which).with('systemctl').and_return('/bin/systemctl')
end
let :provider do
provider_class.new(:name => 'sshd.service')
end
let :process_output do
Puppet::Util::Execution::ProcessOutput.new('', 0)
end
osfamilies = %w[archlinux coreos gentoo]
osfamilies.each do |osfamily|
it "should be the default provider on #{osfamily}" do
allow(Facter).to receive(:value).with('os.family').and_return(osfamily)
allow(Facter).to receive(:value).with('os.name').and_return(osfamily)
allow(Facter).to receive(:value).with('os.release.major').and_return("1234")
expect(provider_class).to be_default
end
end
[7, 8, 9].each do |ver|
it "should be the default provider on rhel#{ver}" do
allow(Facter).to receive(:value).with('os.family').and_return(:redhat)
allow(Facter).to receive(:value).with('os.name').and_return(:redhat)
allow(Facter).to receive(:value).with('os.release.major').and_return(ver.to_s)
expect(provider_class).to be_default
end
end
[4, 5, 6].each do |ver|
it "should not be the default provider on rhel#{ver}" do
allow(Facter).to receive(:value).with('os.family').and_return(:redhat)
allow(Facter).to receive(:value).with('os.name').and_return(:redhat)
allow(Facter).to receive(:value).with('os.release.major').and_return("#{ver}")
expect(provider_class).not_to be_default
end
end
(17..23).to_a.each do |ver|
it "should be the default provider on fedora#{ver}" do
allow(Facter).to receive(:value).with('os.family').and_return(:redhat)
allow(Facter).to receive(:value).with('os.name').and_return(:fedora)
allow(Facter).to receive(:value).with('os.release.major').and_return("#{ver}")
expect(provider_class).to be_default
end
end
[2, 2023].each do |ver|
it "should be the default provider on Amazon Linux #{ver}" do
allow(Facter).to receive(:value).with('os.family').and_return(:redhat)
allow(Facter).to receive(:value).with('os.name').and_return(:amazon)
allow(Facter).to receive(:value).with('os.release.major').and_return("#{ver}")
expect(provider_class).to be_default
end
end
it "should not be the default provider on Amazon Linux 2017.09" do
allow(Facter).to receive(:value).with('os.family').and_return(:redhat)
allow(Facter).to receive(:value).with('os.name').and_return(:amazon)
allow(Facter).to receive(:value).with('os.release.major').and_return("2017")
expect(provider_class).not_to be_default
end
it "should be the default provider on cumulus3" do
allow(Facter).to receive(:value).with('os.family').and_return(:debian)
allow(Facter).to receive(:value).with('os.name').and_return('CumulusLinux')
allow(Facter).to receive(:value).with('os.release.major').and_return("3")
expect(provider_class).to be_default
end
it "should be the default provider on sles12" do
allow(Facter).to receive(:value).with('os.family').and_return(:suse)
allow(Facter).to receive(:value).with('os.name').and_return(:suse)
allow(Facter).to receive(:value).with('os.release.major').and_return("12")
expect(provider_class).to be_default
end
it "should be the default provider on opensuse13" do
allow(Facter).to receive(:value).with('os.family').and_return(:suse)
allow(Facter).to receive(:value).with('os.name').and_return(:suse)
allow(Facter).to receive(:value).with('os.release.major').and_return("13")
expect(provider_class).to be_default
end
# tumbleweed is a rolling release with date-based major version numbers
it "should be the default provider on tumbleweed" do
allow(Facter).to receive(:value).with('os.family').and_return(:suse)
allow(Facter).to receive(:value).with('os.name').and_return(:suse)
allow(Facter).to receive(:value).with('os.release.major').and_return("20150829")
expect(provider_class).to be_default
end
# leap is the next generation suse release
it "should be the default provider on leap" do
allow(Facter).to receive(:value).with('os.family').and_return(:suse)
allow(Facter).to receive(:value).with('os.name').and_return(:leap)
allow(Facter).to receive(:value).with('os.release.major').and_return("42")
expect(provider_class).to be_default
end
it "should not be the default provider on debian7" do
allow(Facter).to receive(:value).with('os.family').and_return(:debian)
allow(Facter).to receive(:value).with('os.name').and_return(:debian)
allow(Facter).to receive(:value).with('os.release.major').and_return("7")
expect(provider_class).not_to be_default
end
it "should be the default provider on debian8" do
allow(Facter).to receive(:value).with('os.family').and_return(:debian)
allow(Facter).to receive(:value).with('os.name').and_return(:debian)
allow(Facter).to receive(:value).with('os.release.major').and_return("8")
expect(provider_class).to be_default
end
it "should be the default provider on debian11" do
allow(Facter).to receive(:value).with('os.family').and_return(:debian)
allow(Facter).to receive(:value).with('os.name').and_return(:debian)
allow(Facter).to receive(:value).with('os.release.major').and_return("11")
expect(provider_class).to be_default
end
it "should be the default provider on debian bookworm/sid" do
allow(Facter).to receive(:value).with('os.family').and_return(:debian)
allow(Facter).to receive(:value).with('os.name').and_return(:debian)
allow(Facter).to receive(:value).with('os.release.major').and_return("bookworm/sid")
expect(provider_class).to be_default
end
it "should not be the default provider on ubuntu14.04" do
allow(Facter).to receive(:value).with('os.family').and_return(:debian)
allow(Facter).to receive(:value).with('os.name').and_return(:ubuntu)
allow(Facter).to receive(:value).with('os.release.major').and_return("14.04")
expect(provider_class).not_to be_default
end
%w[15.04 15.10 16.04 16.10 17.04 17.10 18.04].each do |ver|
it "should be the default provider on ubuntu#{ver}" do
allow(Facter).to receive(:value).with('os.family').and_return(:debian)
allow(Facter).to receive(:value).with('os.name').and_return(:ubuntu)
allow(Facter).to receive(:value).with('os.release.major').and_return("#{ver}")
expect(provider_class).to be_default
end
end
('10'..'17').to_a.each do |ver|
it "should not be the default provider on LinuxMint#{ver}" do
allow(Facter).to receive(:value).with('os.family').and_return(:debian)
allow(Facter).to receive(:value).with('os.name').and_return(:LinuxMint)
allow(Facter).to receive(:value).with('os.release.major').and_return("#{ver}")
expect(provider_class).not_to be_default
end
end
['18', '19'].each do |ver|
it "should be the default provider on LinuxMint#{ver}" do
allow(Facter).to receive(:value).with('os.family').and_return(:debian)
allow(Facter).to receive(:value).with('os.name').and_return(:LinuxMint)
allow(Facter).to receive(:value).with('os.release.major').and_return("#{ver}")
expect(provider_class).to be_default
end
end
it "should be the default provider on raspbian12" do
allow(Facter).to receive(:value).with('os.family').and_return(:debian)
allow(Facter).to receive(:value).with('os.name').and_return(:raspbian)
allow(Facter).to receive(:value).with('os.release.major').and_return("12")
expect(provider_class).to be_default
end
%i[enabled? daemon_reload? enable disable start stop status restart].each do |method|
it "should have a #{method} method" do
expect(provider).to respond_to(method)
end
end
describe ".instances" do
it "should have an instances method" do
expect(provider_class).to respond_to :instances
end
it "should return only services" do
expect(provider_class).to receive(:systemctl).with('list-unit-files', '--type', 'service', '--full', '--all', '--no-pager').and_return(File.read(my_fixture('list_unit_files_services')))
expect(provider_class.instances.map(&:name)).to match_array(%w{
arp-ethers.service
auditd.service
autovt@.service
avahi-daemon.service
blk-availability.service
apparmor.service
umountnfs.service
urandom.service
brandbot.service
})
end
it "correctly parses services when list-unit-files has an additional column" do
expect(provider_class).to receive(:systemctl).with('list-unit-files', '--type', 'service', '--full', '--all', '--no-pager').and_return(File.read(my_fixture('list_unit_files_services_vendor_preset')))
expect(provider_class.instances.map(&:name)).to match_array(%w{
arp-ethers.service
auditd.service
dbus.service
umountnfs.service
urandom.service
})
end
it "should print a debug message when a service with the state `bad` is found" do
expect(provider_class).to receive(:systemctl).with('list-unit-files', '--type', 'service', '--full', '--all', '--no-pager').and_return(File.read(my_fixture('list_unit_files_services')))
expect(Puppet).to receive(:debug).with("apparmor.service marked as bad by `systemctl`. It is recommended to be further checked.")
provider_class.instances
end
end
describe "#start" do
it "should use the supplied start command if specified" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd.service', :start => '/bin/foo'))
expect(provider).to receive(:daemon_reload?).and_return('no')
expect(provider).to receive(:execute).with(['/bin/foo'], {:failonfail => true, :override_locale => false, :squelch => false, :combine => true})
provider.start
end
it "should start the service with systemctl start otherwise" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd.service'))
expect(provider).to receive(:systemctl).with(:unmask, '--', 'sshd.service')
expect(provider).to receive(:daemon_reload?).and_return('no')
expect(provider).to receive(:execute).with(['/bin/systemctl','start', '--', 'sshd.service'], {:failonfail => true, :override_locale => false, :squelch => false, :combine => true})
provider.start
end
it "should show journald logs on failure" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd.service'))
expect(provider).to receive(:systemctl).with(:unmask, '--', 'sshd.service')
expect(provider).to receive(:daemon_reload?).and_return('no')
expect(provider).to receive(:execute).with(['/bin/systemctl','start', '--', 'sshd.service'],{:failonfail => true, :override_locale => false, :squelch => false, :combine => true})
.and_raise(Puppet::ExecutionFailure, "Failed to start sshd.service: Unit sshd.service failed to load: Invalid argument. See system logs and 'systemctl status sshd.service' for details.")
journalctl_logs = <<-EOS
-- Logs begin at Tue 2016-06-14 11:59:21 UTC, end at Tue 2016-06-14 21:45:02 UTC. --
Jun 14 21:41:34 foo.example.com systemd[1]: Stopping sshd Service...
Jun 14 21:41:35 foo.example.com systemd[1]: Starting sshd Service...
Jun 14 21:43:23 foo.example.com systemd[1]: sshd.service lacks both ExecStart= and ExecStop= setting. Refusing.
EOS
expect(provider).to receive(:execute).with("journalctl -n 50 --since '5 minutes ago' -u sshd.service --no-pager").and_return(journalctl_logs)
expect { provider.start }.to raise_error(Puppet::Error, /Systemd start for sshd.service failed![\n]+journalctl log for sshd.service:[\n]+-- Logs begin at Tue 2016-06-14 11:59:21 UTC, end at Tue 2016-06-14 21:45:02 UTC. --/m)
end
end
describe "#stop" do
it "should use the supplied stop command if specified" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd.service', :stop => '/bin/foo'))
expect(provider).to receive(:execute).with(['/bin/foo'], {:failonfail => true, :override_locale => false, :squelch => false, :combine => true})
provider.stop
end
it "should stop the service with systemctl stop otherwise" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd.service'))
expect(provider).to receive(:execute).with(['/bin/systemctl','stop', '--', 'sshd.service'], {:failonfail => true, :override_locale => false, :squelch => false, :combine => true})
provider.stop
end
it "should show journald logs on failure" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd.service'))
expect(provider).to receive(:execute).with(['/bin/systemctl','stop', '--', 'sshd.service'],{:failonfail => true, :override_locale => false, :squelch => false, :combine => true})
.and_raise(Puppet::ExecutionFailure, "Failed to stop sshd.service: Unit sshd.service failed to load: Invalid argument. See system logs and 'systemctl status sshd.service' for details.")
journalctl_logs = <<-EOS
-- Logs begin at Tue 2016-06-14 11:59:21 UTC, end at Tue 2016-06-14 21:45:02 UTC. --
Jun 14 21:41:34 foo.example.com systemd[1]: Stopping sshd Service...
Jun 14 21:41:35 foo.example.com systemd[1]: Starting sshd Service...
Jun 14 21:43:23 foo.example.com systemd[1]: sshd.service lacks both ExecStart= and ExecStop= setting. Refusing.
EOS
expect(provider).to receive(:execute).with("journalctl -n 50 --since '5 minutes ago' -u sshd.service --no-pager").and_return(journalctl_logs)
expect { provider.stop }.to raise_error(Puppet::Error, /Systemd stop for sshd.service failed![\n]+journalctl log for sshd.service:[\n]-- Logs begin at Tue 2016-06-14 11:59:21 UTC, end at Tue 2016-06-14 21:45:02 UTC. --/m)
end
end
describe "#daemon_reload?" do
it "should skip the systemctl daemon_reload if not required by the service" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd.service'))
expect(provider).to receive(:execute).with(['/bin/systemctl', 'show', '--property=NeedDaemonReload', '--', 'sshd.service'], {:failonfail => false}).and_return("no")
provider.daemon_reload?
end
it "should run a systemctl daemon_reload if the service has been modified" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd.service'))
expect(provider).to receive(:execute).with(['/bin/systemctl', 'show', '--property=NeedDaemonReload', '--', 'sshd.service'], {:failonfail => false}).and_return("yes")
expect(provider).to receive(:execute).with(['/bin/systemctl', 'daemon-reload'], {:failonfail => false})
provider.daemon_reload?
end
end
describe "#enabled?" do
it "should return :true if the service is enabled" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd.service'))
expect(provider).to receive(:execute).with(['/bin/systemctl','is-enabled', '--', 'sshd.service'], {:failonfail => false}).
and_return(Puppet::Util::Execution::ProcessOutput.new("enabled\n", 0))
expect(provider.enabled?).to eq(:true)
end
it "should return :true if the service is static" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd.service'))
expect(provider).to receive(:execute).with(['/bin/systemctl','is-enabled','--', 'sshd.service'], {:failonfail => false}).
and_return(Puppet::Util::Execution::ProcessOutput.new("static\n", 0))
expect(provider.enabled?).to eq(:true)
end
it "should return :false if the service is disabled" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd.service'))
expect(provider).to receive(:execute).with(['/bin/systemctl','is-enabled', '--', 'sshd.service'], {:failonfail => false}).
and_return(Puppet::Util::Execution::ProcessOutput.new("disabled\n", 1))
expect(provider.enabled?).to eq(:false)
end
it "should return :false if the service is indirect" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd.service'))
expect(provider).to receive(:execute).with(['/bin/systemctl','is-enabled', '--', 'sshd.service'], {:failonfail => false}).
and_return(Puppet::Util::Execution::ProcessOutput.new("indirect\n", 0))
expect(provider.enabled?).to eq(:false)
end
it "should return :false if the service is masked and the resource is attempting to be disabled" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd.service', :enable => false))
expect(provider).to receive(:execute).with(['/bin/systemctl','is-enabled', '--', 'sshd.service'], {:failonfail => false}).
and_return(Puppet::Util::Execution::ProcessOutput.new("masked\n", 1))
expect(provider.enabled?).to eq(:false)
end
it "should return :mask if the service is masked and the resource is attempting to be masked" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd.service', :enable => 'mask'))
expect(provider).to receive(:execute).with(['/bin/systemctl','is-enabled', '--', 'sshd.service'], {:failonfail => false}).
and_return(Puppet::Util::Execution::ProcessOutput.new("masked\n", 1))
expect(provider.enabled?).to eq(:mask)
end
it "should consider nonexistent services to be disabled" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'doesnotexist'))
allow(Facter).to receive(:value).with('os.family').and_return('debian')
expect(provider).to receive(:execute).with(['/bin/systemctl','is-enabled', '--', 'doesnotexist'], {:failonfail => false})
.and_return(Puppet::Util::Execution::ProcessOutput.new("", 1))
expect(provider).to receive(:execute).with(["/usr/sbin/invoke-rc.d", "--quiet", "--query", "doesnotexist", "start"], {:failonfail => false})
.and_return(Puppet::Util::Execution::ProcessOutput.new("", 1))
expect(provider.enabled?).to be(:false)
end
end
describe "#enable" do
it "should run systemctl enable to enable a service" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd.service'))
expect(provider).to receive(:systemctl).with(:unmask, '--', 'sshd.service')
expect(provider).to receive(:systemctl).with(:enable, '--', 'sshd.service')
provider.enable
end
end
describe "#disable" do
it "should run systemctl disable to disable a service" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd.service'))
expect(provider).to receive(:systemctl).with(:disable, '--', 'sshd.service')
provider.disable
end
end
describe "#mask" do
it "should run systemctl to disable and mask a service" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd.service'))
expect(provider).to receive(:execute).
with(['/bin/systemctl','cat', '--', 'sshd.service'], {:failonfail => false}).
and_return(Puppet::Util::Execution::ProcessOutput.new("# /lib/systemd/system/sshd.service\n...", 0))
# :disable is the only call in the provider that uses a symbol instead of
# a string.
# This should be made consistent in the future and all tests updated.
expect(provider).to receive(:systemctl).with(:disable, '--', 'sshd.service')
expect(provider).to receive(:systemctl).with(:mask, '--', 'sshd.service')
provider.mask
end
it "masks a service that doesn't exist" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'doesnotexist.service'))
expect(provider).to receive(:execute).
with(['/bin/systemctl','cat', '--', 'doesnotexist.service'], {:failonfail => false}).
and_return(Puppet::Util::Execution::ProcessOutput.new("No files found for doesnotexist.service.\n", 1))
expect(provider).to receive(:systemctl).with(:mask, '--', 'doesnotexist.service')
provider.mask
end
end
# Note: systemd provider does not care about hasstatus or a custom status
# command. I just assume that it does not make sense for systemd.
describe "#status" do
it "should return running if the command returns 0" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd.service'))
expect(provider).to receive(:execute)
.with(['/bin/systemctl','is-active', '--', 'sshd.service'], {:failonfail => false, :override_locale => false, :squelch => false, :combine => true})
.and_return(Puppet::Util::Execution::ProcessOutput.new("active\n", 0))
expect(provider.status).to eq(:running)
end
[-10,-1,3,10].each { |ec|
it "should return stopped if the command returns something non-0" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd.service'))
expect(provider).to receive(:execute)
.with(['/bin/systemctl','is-active', '--', 'sshd.service'], {:failonfail => false, :override_locale => false, :squelch => false, :combine => true})
.and_return(Puppet::Util::Execution::ProcessOutput.new("inactive\n", ec))
expect(provider.status).to eq(:stopped)
end
}
it "should use the supplied status command if specified" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd.service', :status => '/bin/foo'))
expect(provider).to receive(:execute)
.with(['/bin/foo'], {:failonfail => false, :override_locale => false, :squelch => false, :combine => true})
.and_return(process_output)
provider.status
end
end
# Note: systemd provider does not care about hasrestart. I just assume it
# does not make sense for systemd
describe "#restart" do
it "should use the supplied restart command if specified" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :restart => '/bin/foo'))
expect(provider).to receive(:daemon_reload?).and_return('no')
expect(provider).to receive(:execute).with(['/bin/systemctl','restart', '--', 'sshd.service'], {:failonfail => true, :override_locale => false, :squelch => false, :combine => true}).never
expect(provider).to receive(:execute).with(['/bin/foo'], {:failonfail => true, :override_locale => false, :squelch => false, :combine => true})
provider.restart
end
it "should restart the service with systemctl restart" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd.service'))
expect(provider).to receive(:daemon_reload?).and_return('no')
expect(provider).to receive(:execute).with(['/bin/systemctl','restart','--','sshd.service'], {:failonfail => true, :override_locale => false, :squelch => false, :combine => true})
provider.restart
end
it "should show journald logs on failure" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd.service'))
expect(provider).to receive(:daemon_reload?).and_return('no')
expect(provider).to receive(:execute).with(['/bin/systemctl','restart','--','sshd.service'],{:failonfail => true, :override_locale => false, :squelch => false, :combine => true})
.and_raise(Puppet::ExecutionFailure, "Failed to restart sshd.service: Unit sshd.service failed to load: Invalid argument. See system logs and 'systemctl status sshd.service' for details.")
journalctl_logs = <<-EOS
-- Logs begin at Tue 2016-06-14 11:59:21 UTC, end at Tue 2016-06-14 21:45:02 UTC. --
Jun 14 21:41:34 foo.example.com systemd[1]: Stopping sshd Service...
Jun 14 21:41:35 foo.example.com systemd[1]: Starting sshd Service...
Jun 14 21:43:23 foo.example.com systemd[1]: sshd.service lacks both ExecStart= and ExecStop= setting. Refusing.
EOS
expect(provider).to receive(:execute).with("journalctl -n 50 --since '5 minutes ago' -u sshd.service --no-pager").and_return(journalctl_logs)
expect { provider.restart }.to raise_error(Puppet::Error, /Systemd restart for sshd.service failed![\n]+journalctl log for sshd.service:[\n]+-- Logs begin at Tue 2016-06-14 11:59:21 UTC, end at Tue 2016-06-14 21:45:02 UTC. --/m)
end
end
describe "#debian_enabled?" do
[104, 106].each do |status|
it "should return true when invoke-rc.d returns #{status}" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd.service'))
allow(provider).to receive(:execute).and_return(Puppet::Util::Execution::ProcessOutput.new('', status))
expect(provider.debian_enabled?).to eq(:true)
end
end
[101, 105].each do |status|
it "should return true when status is #{status} and there are at least 4 start links" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd.service'))
allow(provider).to receive(:execute).and_return(Puppet::Util::Execution::ProcessOutput.new('', status))
expect(provider).to receive(:get_start_link_count).and_return(4)
expect(provider.debian_enabled?).to eq(:true)
end
it "should return false when status is #{status} and there are less than 4 start links" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd.service'))
allow(provider).to receive(:execute).and_return(Puppet::Util::Execution::ProcessOutput.new('', status))
expect(provider).to receive(:get_start_link_count).and_return(1)
expect(provider.debian_enabled?).to eq(:false)
end
end
end
describe "#insync_enabled?" do
let(:provider) do
provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd.service', :enable => false))
end
before do
allow(provider).to receive(:cached_enabled?).and_return({ output: service_state, exitcode: 0 })
end
context 'when service state is static' do
let(:service_state) { 'static' }
context 'when enable is not mask' do
it 'is always enabled_insync even if current value is the same as expected' do
expect(provider).to be_enabled_insync(:false)
end
it 'is always enabled_insync even if current value is not the same as expected' do
expect(provider).to be_enabled_insync(:true)
end
it 'logs a debug messsage' do
expect(Puppet).to receive(:debug).with("Unable to enable or disable static service sshd.service")
provider.enabled_insync?(:true)
end
end
context 'when enable is mask' do
let(:provider) do
provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd.service',
:enable => 'mask'))
end
it 'is enabled_insync if current value is the same as expected' do
expect(provider).to be_enabled_insync(:mask)
end
it 'is not enabled_insync if current value is not the same as expected' do
expect(provider).not_to be_enabled_insync(:true)
end
it 'logs no debug messsage' do
expect(Puppet).not_to receive(:debug)
provider.enabled_insync?(:true)
end
end
end
context 'when service state is indirect' do
let(:service_state) { 'indirect' }
it 'is always enabled_insync even if current value is the same as expected' do
expect(provider).to be_enabled_insync(:false)
end
it 'is always enabled_insync even if current value is not the same as expected' do
expect(provider).to be_enabled_insync(:true)
end
it 'logs a debug messsage' do
expect(Puppet).to receive(:debug).with("Service sshd.service is in 'indirect' state and cannot be enabled/disabled")
provider.enabled_insync?(:true)
end
end
context 'when service state is enabled' do
let(:service_state) { 'enabled' }
it 'is enabled_insync if current value is the same as expected' do
expect(provider).to be_enabled_insync(:false)
end
it 'is not enabled_insync if current value is not the same as expected' do
expect(provider).not_to be_enabled_insync(:true)
end
it 'logs no debug messsage' do
expect(Puppet).not_to receive(:debug)
provider.enabled_insync?(:true)
end
end
end
describe "#get_start_link_count" do
it "should strip the '.service' from the search if present in the resource name" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd.service'))
expect(Dir).to receive(:glob).with("/etc/rc*.d/S??sshd").and_return(['files'])
provider.get_start_link_count
end
it "should use the full service name if it does not include '.service'" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd'))
expect(Dir).to receive(:glob).with("/etc/rc*.d/S??sshd").and_return(['files'])
provider.get_start_link_count
end
end
it "(#16451) has command systemctl without being fully qualified" do
expect(provider_class.instance_variable_get(:@commands)).to include(:systemctl => 'systemctl')
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/provider/service/bsd_spec.rb | spec/unit/provider/service/bsd_spec.rb | require 'spec_helper'
describe 'Puppet::Type::Service::Provider::Bsd',
unless: Puppet::Util::Platform.windows? || Puppet::Util::Platform.jruby? do
let(:provider_class) { Puppet::Type.type(:service).provider(:bsd) }
before :each do
allow(Puppet::Type.type(:service)).to receive(:defaultprovider).and_return(provider_class)
allow(Facter).to receive(:value).with('os.name').and_return(:netbsd)
allow(Facter).to receive(:value).with('os.family').and_return('NetBSD')
allow(provider_class).to receive(:defpath).and_return('/etc/rc.conf.d')
@provider = provider_class.new
allow(@provider).to receive(:initscript)
end
context "#instances" do
it "should have an instances method" do
expect(provider_class).to respond_to :instances
end
it "should use defpath" do
expect(provider_class.instances).to be_all { |provider| provider.get(:path) == provider_class.defpath }
end
end
context "#disable" do
it "should have a disable method" do
expect(@provider).to respond_to(:disable)
end
it "should remove a service file to disable" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd'))
allow(Puppet::FileSystem).to receive(:exist?).with('/etc/rc.conf.d/sshd').and_return(true)
expect(Puppet::FileSystem).to receive(:exist?).with('/etc/rc.conf.d/sshd').and_return(true)
allow(File).to receive(:delete).with('/etc/rc.conf.d/sshd')
provider.disable
end
it "should not remove a service file if it doesn't exist" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd'))
allow(File).to receive(:exist?).with('/etc/rc.conf.d/sshd').and_return(false)
expect(Puppet::FileSystem).to receive(:exist?).with('/etc/rc.conf.d/sshd').and_return(false)
provider.disable
end
end
context "#enable" do
it "should have an enable method" do
expect(@provider).to respond_to(:enable)
end
it "should set the proper contents to enable" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd'))
allow(Dir).to receive(:mkdir).with('/etc/rc.conf.d')
fh = double('fh')
allow(File).to receive(:open).with('/etc/rc.conf.d/sshd', File::WRONLY | File::APPEND | File::CREAT, 0644).and_yield(fh)
expect(fh).to receive(:<<).with("sshd_enable=\"YES\"\n")
provider.enable
end
it "should set the proper contents to enable when disabled" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd'))
allow(Dir).to receive(:mkdir).with('/etc/rc.conf.d')
allow(File).to receive(:read).with('/etc/rc.conf.d/sshd').and_return("sshd_enable=\"NO\"\n")
fh = double('fh')
allow(File).to receive(:open).with('/etc/rc.conf.d/sshd', File::WRONLY | File::APPEND | File::CREAT, 0644).and_yield(fh)
expect(fh).to receive(:<<).with("sshd_enable=\"YES\"\n")
provider.enable
end
end
context "#enabled?" do
it "should have an enabled? method" do
expect(@provider).to respond_to(:enabled?)
end
it "should return false if the service file does not exist" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd'))
allow(Puppet::FileSystem).to receive(:exist?).with('/etc/rc.conf.d/sshd').and_return(false)
expect(provider.enabled?).to eq(:false)
end
it "should return true if the service file exists" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd'))
allow(Puppet::FileSystem).to receive(:exist?).with('/etc/rc.conf.d/sshd').and_return(true)
expect(provider.enabled?).to eq(:true)
end
end
context "#startcmd" do
it "should have a startcmd method" do
expect(@provider).to respond_to(:startcmd)
end
it "should use the supplied start command if specified" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :start => '/bin/foo'))
expect(provider).to receive(:execute).with(['/bin/foo'], {:failonfail => true, :override_locale => false, :squelch => false, :combine => true})
provider.start
end
it "should start the serviced directly otherwise" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd'))
expect(provider).to receive(:execute).with(['/etc/rc.d/sshd', :onestart], {:failonfail => true, :override_locale => false, :squelch => false, :combine => true})
expect(provider).to receive(:search).with('sshd').and_return('/etc/rc.d/sshd')
provider.start
end
end
context "#stopcmd" do
it "should have a stopcmd method" do
expect(@provider).to respond_to(:stopcmd)
end
it "should use the supplied stop command if specified" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :stop => '/bin/foo'))
expect(provider).to receive(:execute).with(['/bin/foo'], {:failonfail => true, :override_locale => false, :squelch => false, :combine => true})
provider.stop
end
it "should stop the serviced directly otherwise" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd'))
expect(provider).to receive(:execute).with(['/etc/rc.d/sshd', :onestop], {:failonfail => true, :override_locale => false, :squelch => false, :combine => true})
expect(provider).to receive(:search).with('sshd').and_return('/etc/rc.d/sshd')
provider.stop
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/provider/service/openwrt_spec.rb | spec/unit/provider/service/openwrt_spec.rb | require 'spec_helper'
describe 'Puppet::Type::Service::Provider::Openwrt',
unless: Puppet::Util::Platform.windows? || Puppet::Util::Platform.jruby? do
let(:provider_class) { Puppet::Type.type(:service).provider(:openwrt) }
let(:resource) do
Puppet::Type.type(:service).new(
:name => 'myservice',
:path => '/etc/init.d',
:hasrestart => true,
)
end
let(:provider) do
provider = provider_class.new
provider.resource = resource
provider
end
before :each do
resource.provider = provider
# All OpenWrt tests operate on the init script directly. It must exist.
allow(Puppet::FileSystem).to receive(:directory?).and_call_original
allow(Puppet::FileSystem).to receive(:directory?).with('/etc/init.d').and_return(true)
allow(Puppet::FileSystem).to receive(:exist?).with('/etc/init.d/myservice').and_return(true)
allow(Puppet::FileSystem).to receive(:file?).and_call_original
allow(Puppet::FileSystem).to receive(:file?).with('/etc/init.d/myservice').and_return(true)
allow(Puppet::FileSystem).to receive(:executable?).with('/etc/init.d/myservice').and_return(true)
end
it "should be the default provider on 'openwrt'" do
expect(Facter).to receive(:value).with('os.name').and_return('openwrt')
expect(provider_class.default?).to be_truthy
end
# test self.instances
describe "when getting all service instances" do
let(:services) { ['dnsmasq', 'dropbear', 'firewall', 'led', 'puppet', 'uhttpd' ] }
before :each do
allow(Dir).to receive(:entries).and_call_original
allow(Dir).to receive(:entries).with('/etc/init.d').and_return(services)
allow(Puppet::FileSystem).to receive(:executable?).and_return(true)
end
it "should return instances for all services" do
services.each do |inst|
expect(provider_class).to receive(:new).with(hash_including(:name => inst, :path => '/etc/init.d')).and_return("#{inst}_instance")
end
results = services.collect { |x| "#{x}_instance"}
expect(provider_class.instances).to eq(results)
end
end
it "should have an enabled? method" do
expect(provider).to respond_to(:enabled?)
end
it "should have an enable method" do
expect(provider).to respond_to(:enable)
end
it "should have a disable method" do
expect(provider).to respond_to(:disable)
end
[:start, :stop, :restart].each do |method|
it "should have a #{method} method" do
expect(provider).to respond_to(method)
end
describe "when running #{method}" do
it "should use any provided explicit command" do
resource[method] = '/user/specified/command'
expect(provider).to receive(:execute).with(['/user/specified/command'], any_args)
provider.send(method)
end
it "should execute the init script with #{method} when no explicit command is provided" do
expect(provider).to receive(:execute).with(['/etc/init.d/myservice', method], any_args)
provider.send(method)
end
end
end
describe "when checking status" do
it "should consider the service :running if it has a pid" do
expect(provider).to receive(:getpid).and_return("1234")
expect(provider.status).to eq(:running)
end
it "should consider the service :stopped if it doesn't have a pid" do
expect(provider).to receive(:getpid).and_return(nil)
expect(provider.status).to eq(:stopped)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/provider/service/src_spec.rb | spec/unit/provider/service/src_spec.rb | require 'spec_helper'
describe 'Puppet::Type::Service::Provider::Src',
unless: Puppet::Util::Platform.windows? || Puppet::Util::Platform.jruby? do
let(:provider_class) { Puppet::Type.type(:service).provider(:src) }
before :each do
@resource = double('resource')
allow(@resource).to receive(:[]).and_return(nil)
allow(@resource).to receive(:[]).with(:name).and_return("myservice")
@provider = provider_class.new
@provider.resource = @resource
allow(@provider).to receive(:command).with(:stopsrc).and_return("/usr/bin/stopsrc")
allow(@provider).to receive(:command).with(:startsrc).and_return("/usr/bin/startsrc")
allow(@provider).to receive(:command).with(:lssrc).and_return("/usr/bin/lssrc")
allow(@provider).to receive(:command).with(:refresh).and_return("/usr/bin/refresh")
allow(@provider).to receive(:command).with(:lsitab).and_return("/usr/sbin/lsitab")
allow(@provider).to receive(:command).with(:mkitab).and_return("/usr/sbin/mkitab")
allow(@provider).to receive(:command).with(:rmitab).and_return("/usr/sbin/rmitab")
allow(@provider).to receive(:command).with(:chitab).and_return("/usr/sbin/chitab")
allow(@provider).to receive(:stopsrc)
allow(@provider).to receive(:startsrc)
allow(@provider).to receive(:lssrc)
allow(@provider).to receive(:refresh)
allow(@provider).to receive(:lsitab)
allow(@provider).to receive(:mkitab)
allow(@provider).to receive(:rmitab)
allow(@provider).to receive(:chitab)
end
context ".instances" do
it "should have a .instances method" do
expect(provider_class).to respond_to :instances
end
it "should get a list of running services" do
sample_output = <<_EOF_
#subsysname:synonym:cmdargs:path:uid:auditid:standin:standout:standerr:action:multi:contact:svrkey:svrmtype:priority:signorm:sigforce:display:waittime:grpname:
myservice.1:::/usr/sbin/inetd:0:0:/dev/console:/dev/console:/dev/console:-O:-Q:-K:0:0:20:0:0:-d:20:tcpip:
myservice.2:::/usr/sbin/inetd:0:0:/dev/console:/dev/console:/dev/console:-O:-Q:-K:0:0:20:0:0:-d:20:tcpip:
myservice.3:::/usr/sbin/inetd:0:0:/dev/console:/dev/console:/dev/console:-O:-Q:-K:0:0:20:0:0:-d:20:tcpip:
myservice.4:::/usr/sbin/inetd:0:0:/dev/console:/dev/console:/dev/console:-O:-Q:-K:0:0:20:0:0:-d:20:tcpip:
_EOF_
allow(provider_class).to receive(:lssrc).and_return(sample_output)
expect(provider_class.instances.map(&:name)).to eq([
'myservice.1',
'myservice.2',
'myservice.3',
'myservice.4'
])
end
end
context "when starting a service" do
it "should execute the startsrc command" do
expect(@provider).to receive(:execute).with(['/usr/bin/startsrc', '-s', "myservice"], {:override_locale => false, :squelch => false, :combine => true, :failonfail => true})
expect(@provider).to receive(:status).and_return(:running)
@provider.start
end
it "should error if timeout occurs while stopping the service" do
expect(@provider).to receive(:execute).with(['/usr/bin/startsrc', '-s', "myservice"], {:override_locale => false, :squelch => false, :combine => true, :failonfail => true})
expect(Timeout).to receive(:timeout).with(60).and_raise(Timeout::Error)
expect { @provider.start }.to raise_error Puppet::Error, ('Timed out waiting for myservice to transition states')
end
end
context "when stopping a service" do
it "should execute the stopsrc command" do
expect(@provider).to receive(:execute).with(['/usr/bin/stopsrc', '-s', "myservice"], {:override_locale => false, :squelch => false, :combine => true, :failonfail => true})
expect(@provider).to receive(:status).and_return(:stopped)
@provider.stop
end
it "should error if timeout occurs while stopping the service" do
expect(@provider).to receive(:execute).with(['/usr/bin/stopsrc', '-s', "myservice"], {:override_locale => false, :squelch => false, :combine => true, :failonfail => true})
expect(Timeout).to receive(:timeout).with(60).and_raise(Timeout::Error)
expect { @provider.stop }.to raise_error Puppet::Error, ('Timed out waiting for myservice to transition states')
end
end
context "should have a set of methods" do
[:enabled?, :enable, :disable, :start, :stop, :status, :restart].each do |method|
it "should have a #{method} method" do
expect(@provider).to respond_to(method)
end
end
end
context "when enabling" do
it "should execute the mkitab command" do
expect(@provider).to receive(:mkitab).with("myservice:2:once:/usr/bin/startsrc -s myservice").once
@provider.enable
end
end
context "when disabling" do
it "should execute the rmitab command" do
expect(@provider).to receive(:rmitab).with("myservice")
@provider.disable
end
end
context "when checking if it is enabled" do
it "should execute the lsitab command" do
expect(@provider).to receive(:execute)
.with(['/usr/sbin/lsitab', 'myservice'], {:combine => true, :failonfail => false})
.and_return(Puppet::Util::Execution::ProcessOutput.new('', 0))
@provider.enabled?
end
it "should return false when lsitab returns non-zero" do
expect(@provider).to receive(:execute).and_return(Puppet::Util::Execution::ProcessOutput.new('', 1))
expect(@provider.enabled?).to eq(:false)
end
it "should return true when lsitab returns zero" do
allow(@provider).to receive(:execute).and_return(Puppet::Util::Execution::ProcessOutput.new('', 0))
expect(@provider.enabled?).to eq(:true)
end
end
context "when checking a subsystem's status" do
it "should execute status and return running if the subsystem is active" do
sample_output = <<_EOF_
Subsystem Group PID Status
myservice tcpip 1234 active
_EOF_
expect(@provider).to receive(:execute).with(['/usr/bin/lssrc', '-s', "myservice"]).and_return(sample_output)
expect(@provider.status).to eq(:running)
end
it "should execute status and return stopped if the subsystem is inoperative" do
sample_output = <<_EOF_
Subsystem Group PID Status
myservice tcpip inoperative
_EOF_
expect(@provider).to receive(:execute).with(['/usr/bin/lssrc', '-s', "myservice"]).and_return(sample_output)
expect(@provider.status).to eq(:stopped)
end
it "should execute status and return nil if the status is not known" do
sample_output = <<_EOF_
Subsystem Group PID Status
myservice tcpip randomdata
_EOF_
expect(@provider).to receive(:execute).with(['/usr/bin/lssrc', '-s', "myservice"]).and_return(sample_output)
expect(@provider.status).to eq(nil)
end
it "should consider a non-existing service to be have a status of :stopped" do
expect(@provider).to receive(:execute).with(['/usr/bin/lssrc', '-s', 'myservice']).and_raise(Puppet::ExecutionFailure, "fail")
expect(@provider.status).to eq(:stopped)
end
end
context "when restarting a service" do
it "should execute restart which runs refresh" do
sample_output = <<_EOF_
#subsysname:synonym:cmdargs:path:uid:auditid:standin:standout:standerr:action:multi:contact:svrkey:svrmtype:priority:signorm:sigforce:display:waittime:grpname:
myservice:::/usr/sbin/inetd:0:0:/dev/console:/dev/console:/dev/console:-O:-Q:-K:0:0:20:0:0:-d:20:tcpip:
_EOF_
expect(@provider).to receive(:execute).with(['/usr/bin/lssrc', '-Ss', "myservice"]).and_return(sample_output)
expect(@provider).to receive(:execute).with(['/usr/bin/refresh', '-s', "myservice"])
@provider.restart
end
it "should execute restart which runs stop then start" do
sample_output = <<_EOF_
#subsysname:synonym:cmdargs:path:uid:auditid:standin:standout:standerr:action:multi:contact:svrkey:svrmtype:priority:signorm:sigforce:display:waittime:grpname:
myservice::--no-daemonize:/usr/sbin/puppetd:0:0:/dev/null:/var/log/puppet.log:/var/log/puppet.log:-O:-Q:-S:0:0:20:15:9:-d:20::"
_EOF_
expect(@provider).to receive(:execute).with(['/usr/bin/lssrc', '-Ss', "myservice"]).and_return(sample_output)
expect(@provider).to receive(:stop)
expect(@provider).to receive(:start)
@provider.restart
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/provider/service/windows_spec.rb | spec/unit/provider/service/windows_spec.rb | require 'spec_helper'
describe 'Puppet::Type::Service::Provider::Windows',
:if => Puppet::Util::Platform.windows? && !Puppet::Util::Platform.jruby? do
let(:provider_class) { Puppet::Type.type(:service).provider(:windows) }
let(:name) { 'nonexistentservice' }
let(:resource) { Puppet::Type.type(:service).new(:name => name, :provider => :windows) }
let(:provider) { resource.provider }
let(:config) { Struct::ServiceConfigInfo.new }
let(:status) { Struct::ServiceStatus.new }
let(:service_util) { Puppet::Util::Windows::Service }
let(:service_handle) { double() }
before :each do
# make sure we never actually execute anything (there are two execute methods)
allow(provider.class).to receive(:execute)
allow(provider).to receive(:execute)
allow(service_util).to receive(:exists?).with(resource[:name]).and_return(true)
end
describe ".instances" do
it "should enumerate all services" do
list_of_services = {'snmptrap' => {}, 'svchost' => {}, 'sshd' => {}}
expect(service_util).to receive(:services).and_return(list_of_services)
expect(provider_class.instances.map(&:name)).to match_array(['snmptrap', 'svchost', 'sshd'])
end
end
describe "#start" do
before(:each) do
allow(provider).to receive(:status).and_return(:stopped)
end
it "should resume a paused service" do
allow(provider).to receive(:status).and_return(:paused)
expect(service_util).to receive(:resume)
provider.start
end
it "should start the service" do
expect(service_util).to receive(:service_start_type).with(name).and_return(:SERVICE_AUTO_START)
expect(service_util).to receive(:start)
provider.start
end
context "when the service is disabled" do
before :each do
expect(service_util).to receive(:service_start_type).with(name).and_return(:SERVICE_DISABLED)
end
it "should refuse to start if not managing enable" do
expect { provider.start }.to raise_error(Puppet::Error, /Will not start disabled service/)
end
it "should enable if managing enable and enable is true" do
resource[:enable] = :true
expect(service_util).to receive(:start)
expect(service_util).to receive(:set_startup_configuration).with(name, options: {startup_type: :SERVICE_AUTO_START})
provider.start
end
it "should manual start if managing enable and enable is false" do
resource[:enable] = :false
expect(service_util).to receive(:start)
expect(service_util).to receive(:set_startup_configuration).with(name, options: {startup_type: :SERVICE_DEMAND_START})
provider.start
end
end
end
describe "#stop" do
it "should stop a running service" do
expect(service_util).to receive(:stop)
provider.stop
end
end
describe "#status" do
it "should report a nonexistent service as stopped" do
allow(service_util).to receive(:exists?).with(resource[:name]).and_return(false)
expect(provider.status).to eql(:stopped)
end
it "should report service as stopped when status cannot be retrieved" do
allow(service_util).to receive(:exists?).with(resource[:name]).and_return(true)
allow(service_util).to receive(:service_state).with(name).and_raise(Puppet::Error.new('Service query failed: The specified path is invalid.'))
expect(Puppet).to receive(:warning).with("Status for service #{resource[:name]} could not be retrieved: Service query failed: The specified path is invalid.")
expect(provider.status).to eql(:stopped)
end
[
:SERVICE_PAUSED,
:SERVICE_PAUSE_PENDING
].each do |state|
it "should report a #{state} service as paused" do
expect(service_util).to receive(:service_state).with(name).and_return(state)
expect(provider.status).to eq(:paused)
end
end
[
:SERVICE_STOPPED,
:SERVICE_STOP_PENDING
].each do |state|
it "should report a #{state} service as stopped" do
expect(service_util).to receive(:service_state).with(name).and_return(state)
expect(provider.status).to eq(:stopped)
end
end
[
:SERVICE_RUNNING,
:SERVICE_CONTINUE_PENDING,
:SERVICE_START_PENDING,
].each do |state|
it "should report a #{state} service as running" do
expect(service_util).to receive(:service_state).with(name).and_return(state)
expect(provider.status).to eq(:running)
end
end
context 'when querying lmhosts', if: Puppet::Util::Platform.windows? do
# This service should be ubiquitous across all supported Windows platforms
let(:service) { Puppet::Type.type(:service).new(:name => 'lmhosts') }
before :each do
allow(service_util).to receive(:exists?).with(service.name).and_call_original
end
it "reports if the service is enabled" do
expect([:true, :false, :manual]).to include(service.provider.enabled?)
end
it "reports on the service status" do
expect(
[
:running,
:'continue pending',
:'pause pending',
:paused,
:running,
:'start pending',
:'stop pending',
:stopped
]
).to include(service.provider.status)
end
end
end
describe "#restart" do
it "should use the supplied restart command if specified" do
resource[:restart] = 'c:/bin/foo'
expect(provider).to receive(:execute).with(['c:/bin/foo'], :failonfail => true, :override_locale => false, :squelch => false, :combine => true)
provider.restart
end
it "should restart the service" do
expect(provider).to receive(:stop).ordered
expect(provider).to receive(:start).ordered
provider.restart
end
end
describe "#enabled?" do
it "should report a nonexistent service as false" do
allow(service_util).to receive(:exists?).with(resource[:name]).and_return(false)
expect(provider.enabled?).to eql(:false)
end
it "should report a service with a startup type of manual as manual" do
expect(service_util).to receive(:service_start_type).with(name).and_return(:SERVICE_DEMAND_START)
expect(provider.enabled?).to eq(:manual)
end
it "should report a service with a startup type of delayed as delayed" do
expect(service_util).to receive(:service_start_type).with(name).and_return(:SERVICE_DELAYED_AUTO_START)
expect(provider.enabled?).to eq(:delayed)
end
it "should report a service with a startup type of disabled as false" do
expect(service_util).to receive(:service_start_type).with(name).and_return(:SERVICE_DISABLED)
expect(provider.enabled?).to eq(:false)
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_AUTO_START,
:SERVICE_BOOT_START,
:SERVICE_SYSTEM_START
].each do |start_type|
it "should report a service with a startup type of '#{start_type}' as true" do
expect(service_util).to receive(:service_start_type).with(name).and_return(start_type)
expect(provider.enabled?).to eq(:true)
end
end
end
end
describe "#enable" do
it "should set service start type to Service_Auto_Start when enabled" do
expect(service_util).to receive(:set_startup_configuration).with(name, options: {startup_type: :SERVICE_AUTO_START})
provider.enable
end
it "raises an error if set_startup_configuration fails" do
expect(service_util).to receive(:set_startup_configuration).with(name, options: {startup_type: :SERVICE_AUTO_START}).and_raise(Puppet::Error.new('foobar'))
expect {
provider.enable
}.to raise_error(Puppet::Error, /Cannot enable #{name}/)
end
end
describe "#disable" do
it "should set service start type to Service_Disabled when disabled" do
expect(service_util).to receive(:set_startup_configuration).with(name, options: {startup_type: :SERVICE_DISABLED})
provider.disable
end
it "raises an error if set_startup_configuration fails" do
expect(service_util).to receive(:set_startup_configuration).with(name, options: {startup_type: :SERVICE_DISABLED}).and_raise(Puppet::Error.new('foobar'))
expect {
provider.disable
}.to raise_error(Puppet::Error, /Cannot disable #{name}/)
end
end
describe "#manual_start" do
it "should set service start type to Service_Demand_Start (manual) when manual" do
expect(service_util).to receive(:set_startup_configuration).with(name, options: {startup_type: :SERVICE_DEMAND_START})
provider.manual_start
end
it "raises an error if set_startup_configuration fails" do
expect(service_util).to receive(:set_startup_configuration).with(name, options: {startup_type: :SERVICE_DEMAND_START}).and_raise(Puppet::Error.new('foobar'))
expect {
provider.manual_start
}.to raise_error(Puppet::Error, /Cannot enable #{name}/)
end
end
describe "#delayed_start" do
it "should set service start type to Service_Config_Delayed_Auto_Start (delayed) when delayed" do
expect(service_util).to receive(:set_startup_configuration).with(name, options: {startup_type: :SERVICE_AUTO_START, delayed: true})
provider.delayed_start
end
it "raises an error if set_startup_configuration fails" do
expect(service_util).to receive(:set_startup_configuration).with(name, options: {startup_type: :SERVICE_AUTO_START, delayed: true}).and_raise(Puppet::Error.new('foobar'))
expect {
provider.delayed_start
}.to raise_error(Puppet::Error, /Cannot enable #{name}/)
end
end
describe "when managing logon credentials" do
before do
allow(Puppet::Util::Windows::ADSI).to receive(:computer_name).and_return(computer_name)
allow(Puppet::Util::Windows::SID).to receive(:name_to_principal).and_return(principal)
allow(Puppet::Util::Windows::Service).to receive(:set_startup_configuration).and_return(nil)
end
let(:computer_name) { 'myPC' }
describe "#logonaccount=" do
before do
allow(Puppet::Util::Windows::User).to receive(:password_is?).and_return(true)
resource[:logonaccount] = user_input
provider.logonaccount_insync?(user_input)
end
let(:user_input) { principal.account }
let(:principal) do
Puppet::Util::Windows::SID::Principal.new("myUser", nil, nil, computer_name, :SidTypeUser)
end
context "when given user is 'myUser'" do
it "should fail when the `Log On As A Service` right is missing from given user" do
allow(Puppet::Util::Windows::User).to receive(:get_rights).with(principal.domain_account).and_return("")
expect { provider.logonaccount=(user_input) }.to raise_error(Puppet::Error, /".\\#{principal.account}" is missing the 'Log On As A Service' right./)
end
it "should fail when the `Log On As A Service` right is set to denied for given user" do
allow(Puppet::Util::Windows::User).to receive(:get_rights).with(principal.domain_account).and_return("SeDenyServiceLogonRight")
expect { provider.logonaccount=(user_input) }.to raise_error(Puppet::Error, /".\\#{principal.account}" has the 'Log On As A Service' right set to denied./)
end
it "should not fail when given user has the `Log On As A Service` right" do
allow(Puppet::Util::Windows::User).to receive(:get_rights).with(principal.domain_account).and_return("SeServiceLogonRight")
expect { provider.logonaccount=(user_input) }.not_to raise_error
end
['myUser', 'myPC\\myUser', ".\\myUser", "MYPC\\mYuseR"].each do |user_input_variant|
let(:user_input) { user_input_variant }
it "should succesfully munge #{user_input_variant} to '.\\myUser'" do
allow(Puppet::Util::Windows::User).to receive(:get_rights).with(principal.domain_account).and_return("SeServiceLogonRight")
expect { provider.logonaccount=(user_input) }.not_to raise_error
expect(resource[:logonaccount]).to eq(".\\myUser")
end
end
end
context "when given user is a system account" do
before do
allow(Puppet::Util::Windows::User).to receive(:default_system_account?).and_return(true)
end
let(:user_input) { principal.account }
let(:principal) do
Puppet::Util::Windows::SID::Principal.new("LOCAL SERVICE", nil, nil, "NT AUTHORITY", :SidTypeUser)
end
it "should not fail when given user is a default system account even if the `Log On As A Service` right is missing" do
expect(Puppet::Util::Windows::User).not_to receive(:get_rights)
expect { provider.logonaccount=(user_input) }.not_to raise_error
end
['LocalSystem', '.\LocalSystem', 'myPC\LocalSystem', 'lOcALsysTem'].each do |user_input_variant|
let(:user_input) { user_input_variant }
it "should succesfully munge #{user_input_variant} to 'LocalSystem'" do
expect { provider.logonaccount=(user_input) }.not_to raise_error
expect(resource[:logonaccount]).to eq('LocalSystem')
end
end
end
context "when domain is different from computer name" do
before do
allow(Puppet::Util::Windows::User).to receive(:get_rights).and_return("SeServiceLogonRight")
end
context "when given user is from AD" do
let(:user_input) { 'myRemoteUser' }
let(:principal) do
Puppet::Util::Windows::SID::Principal.new("myRemoteUser", nil, nil, "AD", :SidTypeUser)
end
it "should not raise any error" do
expect { provider.logonaccount=(user_input) }.not_to raise_error
end
it "should succesfully be munged" do
expect { provider.logonaccount=(user_input) }.not_to raise_error
expect(resource[:logonaccount]).to eq('AD\myRemoteUser')
end
end
context "when given user is LocalService" do
let(:user_input) { 'LocalService' }
let(:principal) do
Puppet::Util::Windows::SID::Principal.new("LOCAL SERVICE", nil, nil, "NT AUTHORITY", :SidTypeWellKnownGroup)
end
it "should succesfully munge well known user" do
expect { provider.logonaccount=(user_input) }.not_to raise_error
expect(resource[:logonaccount]).to eq('NT AUTHORITY\LOCAL SERVICE')
end
end
context "when given user is in SID form" do
let(:user_input) { 'S-1-5-20' }
let(:principal) do
Puppet::Util::Windows::SID::Principal.new("NETWORK SERVICE", nil, nil, "NT AUTHORITY", :SidTypeUser)
end
it "should succesfully munge" do
expect { provider.logonaccount=(user_input) }.not_to raise_error
expect(resource[:logonaccount]).to eq('NT AUTHORITY\NETWORK SERVICE')
end
end
context "when given user is actually a group" do
let(:principal) do
Puppet::Util::Windows::SID::Principal.new("Administrators", nil, nil, "BUILTIN", :SidTypeAlias)
end
let(:user_input) { 'Administrators' }
it "should fail when sid type is not user or well known user" do
expect { provider.logonaccount=(user_input) }.to raise_error(Puppet::Error, /"BUILTIN\\#{user_input}" is not a valid account/)
end
end
end
end
describe "#logonpassword=" do
before do
allow(Puppet::Util::Windows::User).to receive(:get_rights).and_return('SeServiceLogonRight')
resource[:logonaccount] = account
resource[:logonpassword] = user_input
provider.logonaccount_insync?(account)
end
let(:account) { 'LocalSystem' }
describe "when given logonaccount is a predefined_local_account" do
let(:user_input) { 'pass' }
let(:principal) { nil }
it "should pass validation when given account is 'LocalSystem'" do
allow(Puppet::Util::Windows::User).to receive(:localsystem?).with('LocalSystem').and_return(true)
allow(Puppet::Util::Windows::User).to receive(:default_system_account?).with('LocalSystem').and_return(true)
expect(Puppet::Util::Windows::User).not_to receive(:password_is?)
expect { provider.logonpassword=(user_input) }.not_to raise_error
end
['LOCAL SERVICE', 'NETWORK SERVICE', 'SYSTEM'].each do |predefined_local_account|
describe "when given account is #{predefined_local_account}" do
let(:account) { 'predefined_local_account' }
let(:principal) do
Puppet::Util::Windows::SID::Principal.new(account, nil, nil, "NT AUTHORITY", :SidTypeUser)
end
it "should pass validation" do
allow(Puppet::Util::Windows::User).to receive(:localsystem?).with(principal.account).and_return(false)
allow(Puppet::Util::Windows::User).to receive(:localsystem?).with(principal.domain_account).and_return(false)
expect(Puppet::Util::Windows::User).to receive(:default_system_account?).with(principal.domain_account).and_return(true).twice
expect(Puppet::Util::Windows::User).not_to receive(:password_is?)
expect { provider.logonpassword=(user_input) }.not_to raise_error
end
end
end
end
describe "when given logonaccount is not a predefined local account" do
before do
allow(Puppet::Util::Windows::User).to receive(:localsystem?).with(".\\#{principal.account}").and_return(false)
allow(Puppet::Util::Windows::User).to receive(:default_system_account?).with(".\\#{principal.account}").and_return(false)
end
let(:account) { 'myUser' }
let(:principal) do
Puppet::Util::Windows::SID::Principal.new(account, nil, nil, computer_name, :SidTypeUser)
end
describe "when password is proven correct" do
let(:user_input) { 'myPass' }
it "should pass validation" do
allow(Puppet::Util::Windows::User).to receive(:password_is?).with('myUser', 'myPass', '.').and_return(true)
expect { provider.logonpassword=(user_input) }.not_to raise_error
end
end
describe "when password is not proven correct" do
let(:user_input) { 'myWrongPass' }
it "should not pass validation" do
allow(Puppet::Util::Windows::User).to receive(:password_is?).with('myUser', 'myWrongPass', '.').and_return(false)
expect { provider.logonpassword=(user_input) }.to raise_error(Puppet::Error, /The given password is invalid for user '.\\myUser'/)
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/provider/service/smf_spec.rb | spec/unit/provider/service/smf_spec.rb | require 'spec_helper'
describe 'Puppet::Type::Service::Provider::Smf',
unless: Puppet::Util::Platform.windows? || Puppet::Util::Platform.jruby? do
let(:provider_class) { Puppet::Type.type(:service).provider(:smf) }
def set_resource_params(params = {})
params.each do |param, value|
if value.nil?
@provider.resource.delete(param) if @provider.resource[param]
else
@provider.resource[param] = value
end
end
end
before(:each) do
# Create a mock resource
@resource = Puppet::Type.type(:service).new(
:name => "/system/myservice", :ensure => :running, :enable => :true)
@provider = provider_class.new(@resource)
allow(FileTest).to receive(:file?).with('/usr/sbin/svcadm').and_return(true)
allow(FileTest).to receive(:executable?).with('/usr/sbin/svcadm').and_return(true)
allow(FileTest).to receive(:file?).with('/usr/bin/svcs').and_return(true)
allow(FileTest).to receive(:executable?).with('/usr/bin/svcs').and_return(true)
allow(Facter).to receive(:value).with('os.name').and_return('Solaris')
allow(Facter).to receive(:value).with('os.family').and_return('Solaris')
allow(Facter).to receive(:value).with('os.release.full').and_return('11.2')
end
context ".instances" do
it "should have an instances method" do
expect(provider_class).to respond_to :instances
end
it "should get a list of services (excluding legacy)" do
expect(provider_class).to receive(:svcs).with('-H', '-o', 'state,fmri').and_return(File.read(my_fixture('svcs_instances.out')))
instances = provider_class.instances.map { |p| {:name => p.get(:name), :ensure => p.get(:ensure)} }
# we dont manage legacy
expect(instances.size).to eq(3)
expect(instances[0]).to eq({:name => 'svc:/system/svc/restarter:default', :ensure => :running })
expect(instances[1]).to eq({:name => 'svc:/network/cswrsyncd:default', :ensure => :maintenance })
expect(instances[2]).to eq({:name => 'svc:/network/dns/client:default', :ensure => :degraded })
end
end
describe '#service_exists?' do
it 'returns true if the service exists' do
expect(@provider).to receive(:service_fmri)
expect(@provider.service_exists?).to be(true)
end
it 'returns false if the service does not exist' do
expect(@provider).to receive(:service_fmri).and_raise(
Puppet::ExecutionFailure, 'svcs failed!'
)
expect(@provider.service_exists?).to be(false)
end
end
describe '#setup_service' do
it 'noops if the service resource does not have the manifest parameter passed-in' do
expect(@provider).not_to receive(:svccfg)
set_resource_params({ :manifest => nil })
@provider.setup_service
end
context 'when the service resource has a manifest parameter passed-in' do
let(:manifest) { 'foo' }
before(:each) { set_resource_params({ :manifest => manifest }) }
it 'noops if the service resource already exists' do
expect(@provider).not_to receive(:svccfg)
expect(@provider).to receive(:service_exists?).and_return(true)
@provider.setup_service
end
it "imports the service resource's manifest" do
expect(@provider).to receive(:service_exists?).and_return(false)
expect(@provider).to receive(:svccfg).with(:import, manifest)
@provider.setup_service
end
it 'raises a Puppet::Error if SMF fails to import the manifest' do
expect(@provider).to receive(:service_exists?).and_return(false)
failure_reason = 'svccfg failed!'
expect(@provider).to receive(:svccfg).with(:import, manifest).and_raise(Puppet::ExecutionFailure, failure_reason)
expect { @provider.setup_service }.to raise_error do |error|
expect(error).to be_a(Puppet::Error)
expect(error.message).to match(failure_reason)
end
end
end
end
describe '#service_fmri' do
it 'returns the memoized the fmri if it exists' do
@provider.instance_variable_set(:@fmri, 'resource_fmri')
expect(@provider.service_fmri).to eql('resource_fmri')
end
it 'raises a Puppet::Error if the service resource matches multiple FMRIs' do
expect(@provider).to receive(:svcs).with('-l', @provider.resource[:name]).and_return(File.read(my_fixture('svcs_multiple_fmris.out')))
expect { @provider.service_fmri }.to raise_error do |error|
expect(error).to be_a(Puppet::Error)
expect(error.message).to match(@provider.resource[:name])
expect(error.message).to match('multiple')
matched_fmris = ["svc:/application/tstapp:one", "svc:/application/tstapp:two"]
expect(error.message).to match(matched_fmris.join(', '))
end
end
it 'raises a Puppet:ExecutionFailure if svcs fails' do
expect(@provider).to receive(:svcs).with('-l', @provider.resource[:name]).and_raise(
Puppet::ExecutionFailure, 'svcs failed!'
)
expect { @provider.service_fmri }.to raise_error do |error|
expect(error).to be_a(Puppet::ExecutionFailure)
expect(error.message).to match('svcs failed!')
end
end
it "returns the service resource's fmri and memoizes it" do
expect(@provider).to receive(:svcs).with('-l', @provider.resource[:name]).and_return(File.read(my_fixture('svcs_fmri.out')))
expected_fmri = 'svc:/application/tstapp:default'
expect(@provider.service_fmri).to eql(expected_fmri)
expect(@provider.instance_variable_get(:@fmri)).to eql(expected_fmri)
end
end
describe '#enabled?' do
let(:fmri) { 'resource_fmri' }
before(:each) do
allow(@provider).to receive(:service_fmri).and_return(fmri)
end
it 'returns :true if the service is enabled' do
expect(@provider).to receive(:svccfg).with('-s', fmri, 'listprop', 'general/enabled').and_return(
'general/enabled boolean true'
)
expect(@provider.enabled?).to be(:true)
end
it 'return :false if the service is not enabled' do
expect(@provider).to receive(:svccfg).with('-s', fmri, 'listprop', 'general/enabled').and_return(
'general/enabled boolean false'
)
expect(@provider.enabled?).to be(:false)
end
it 'returns :false if the service does not exist' do
expect(@provider).to receive(:service_exists?).and_return(false)
expect(@provider.enabled?).to be(:false)
end
end
describe '#restartcmd' do
let(:fmri) { 'resource_fmri' }
before(:each) do
allow(@provider).to receive(:service_fmri).and_return(fmri)
end
it 'returns the right command for restarting the service for Solaris versions newer than 11.2' do
expect(Facter).to receive(:value).with('os.release.full').and_return('11.3')
expect(@provider.restartcmd).to eql([@provider.command(:adm), :restart, '-s', fmri])
end
it 'returns the right command for restarting the service on Solaris 11.2' do
expect(Facter).to receive(:value).with('os.release.full').and_return('11.2')
expect(@provider.restartcmd).to eql([@provider.command(:adm), :restart, '-s', fmri])
end
it 'returns the right command for restarting the service for Solaris versions older than Solaris 11.2' do
expect(Facter).to receive(:value).with('os.release.full').and_return('10.3')
expect(@provider.restartcmd).to eql([@provider.command(:adm), :restart, fmri])
end
end
describe '#service_states' do
let(:fmri) { 'resource_fmri' }
before(:each) do
allow(@provider).to receive(:service_fmri).and_return(fmri)
end
it 'returns the current and next states of the service' do
expect(@provider).to receive(:svcs).with('-H', '-o', 'state,nstate', fmri).and_return(
'online disabled'
)
expect(@provider.service_states).to eql({ :current => 'online', :next => 'disabled' })
end
it "returns nil for the next state if svcs marks it as '-'" do
expect(@provider).to receive(:svcs).with('-H', '-o', 'state,nstate', fmri).and_return(
'online -'
)
expect(@provider.service_states).to eql({ :current => 'online', :next => nil })
end
end
describe '#wait' do
# TODO: Document this method!
def transition_service(from, to, tries)
intermediate_returns = [{ :current => from, :next => to }] * (tries - 1)
final_return = { :current => to, :next => nil }
allow(@provider).to receive(:service_states).and_return(*intermediate_returns.push(final_return))
end
before(:each) do
allow(Timeout).to receive(:timeout).and_yield
allow(Kernel).to receive(:sleep)
end
it 'waits for the service to enter the desired state' do
transition_service('online', 'disabled', 1)
@provider.wait('offline', 'disabled', 'uninitialized')
end
it 'times out and raises a Puppet::Error after sixty seconds' do
expect(Timeout).to receive(:timeout).with(60).and_raise(Timeout::Error, 'method timed out!')
expect { @provider.wait('online') }.to raise_error do |error|
expect(error).to be_a(Puppet::Error)
expect(error.message).to match(@provider.resource[:name])
end
end
it 'sleeps a bit before querying the service state' do
transition_service('disabled', 'online', 10)
expect(Kernel).to receive(:sleep).with(1).exactly(9).times
@provider.wait('online')
end
end
describe '#restart' do
let(:fmri) { 'resource_fmri' }
before(:each) do
allow(@provider).to receive(:service_fmri).and_return(fmri)
allow(@provider).to receive(:execute)
allow(@provider).to receive(:wait)
end
it 'should restart the service' do
expect(@provider).to receive(:execute)
@provider.restart
end
it 'should wait for the service to restart' do
expect(@provider).to receive(:wait).with('online')
@provider.restart
end
end
describe '#status' do
let(:states) do
{
:current => 'online',
:next => nil
}
end
before(:each) do
allow(@provider).to receive(:service_states).and_return(states)
allow(Facter).to receive(:value).with('os.release.full').and_return('10.3')
end
it "should run the status command if it's passed in" do
set_resource_params({ :status => 'status_cmd' })
expect(@provider).to receive(:execute)
.with(["status_cmd"], hash_including(failonfail: false))
.and_return(Puppet::Util::Execution::ProcessOutput.new('', 0))
expect(@provider).not_to receive(:service_states)
expect(@provider.status).to eql(:running)
end
shared_examples 'returns the right status' do |svcs_state, expected_state|
it "returns '#{expected_state}' if the svcs state is '#{svcs_state}'" do
states[:current] = svcs_state
expect(@provider.status).to eql(expected_state)
end
end
include_examples 'returns the right status', 'online', :running
include_examples 'returns the right status', 'offline', :stopped
include_examples 'returns the right status', 'disabled', :stopped
include_examples 'returns the right status', 'uninitialized', :stopped
include_examples 'returns the right status', 'maintenance', :maintenance
include_examples 'returns the right status', 'degraded', :degraded
it "raises a Puppet::Error if the svcs state is 'legacy_run'" do
states[:current] = 'legacy_run'
expect { @provider.status }.to raise_error do |error|
expect(error).to be_a(Puppet::Error)
expect(error.message).to match('legacy')
end
end
it "raises a Puppet::Error if the svcs state is unmanageable" do
states[:current] = 'unmanageable state'
expect { @provider.status }.to raise_error do |error|
expect(error).to be_a(Puppet::Error)
expect(error.message).to match(states[:current])
end
end
it "returns 'stopped' if the service does not exist" do
expect(@provider).to receive(:service_states).and_raise(Puppet::ExecutionFailure, 'service does not exist!')
expect(@provider.status).to eql(:stopped)
end
it "uses the current state for comparison if the next state is not provided" do
states[:next] = 'disabled'
expect(@provider.status).to eql(:stopped)
end
it "should return stopped for an incomplete service on Solaris 11" do
allow(Facter).to receive(:value).with('os.release.full').and_return('11.3')
allow(@provider).to receive(:complete_service?).and_return(false)
allow(@provider).to receive(:svcs).with('-l', @provider.resource[:name]).and_return(File.read(my_fixture('svcs_fmri.out')))
expect(@provider.status).to eq(:stopped)
end
end
describe '#maybe_clear_service_then_svcadm' do
let(:fmri) { 'resource_fmri' }
before(:each) do
allow(@provider).to receive(:service_fmri).and_return(fmri)
end
it 'applies the svcadm subcommand with the given flags' do
expect(@provider).to receive(:adm).with('enable', '-rst', fmri)
@provider.maybe_clear_service_then_svcadm(:stopped, 'enable', '-rst')
end
[:maintenance, :degraded].each do |status|
it "clears the service before applying the svcadm subcommand if the service status is #{status}" do
expect(@provider).to receive(:adm).with('clear', fmri)
expect(@provider).to receive(:adm).with('enable', '-rst', fmri)
@provider.maybe_clear_service_then_svcadm(status, 'enable', '-rst')
end
end
end
describe '#flush' do
def mark_property_for_syncing(property, value)
properties_to_sync = @provider.instance_variable_get(:@properties_to_sync)
properties_to_sync[property] = value
end
it 'should noop if enable and ensure do not need to be syncd' do
expect(@provider).not_to receive(:setup_service)
@provider.flush
end
context 'enable or ensure need to be syncd' do
let(:stopped_states) do
['offline', 'disabled', 'uninitialized']
end
let(:fmri) { 'resource_fmri' }
let(:mock_status) { :maintenance }
before(:each) do
allow(@provider).to receive(:setup_service)
allow(@provider).to receive(:service_fmri).and_return(fmri)
# We will update this mock on a per-test basis.
allow(@provider).to receive(:status).and_return(mock_status)
allow(@provider).to receive(:wait)
end
context 'only ensure needs to be syncd' do
it 'stops the service if ensure == stopped' do
mark_property_for_syncing(:ensure, :stopped)
expect(@provider).to receive(:maybe_clear_service_then_svcadm).with(mock_status, 'disable', '-st')
expect(@provider).to receive(:wait).with(*stopped_states)
@provider.flush
end
it 'starts the service if ensure == running' do
mark_property_for_syncing(:ensure, :running)
expect(@provider).to receive(:maybe_clear_service_then_svcadm).with(mock_status, 'enable', '-rst')
expect(@provider).to receive(:wait).with('online')
@provider.flush
end
end
context 'enable needs to be syncd' do
before(:each) do
# We will stub this value out later, this default is useful
# for the final state tests.
mark_property_for_syncing(:enable, true)
end
it 'enables the service' do
mark_property_for_syncing(:enable, true)
expect(@provider).to receive(:maybe_clear_service_then_svcadm).with(mock_status, 'enable', '-rs')
expect(@provider).to receive(:adm).with('mark', '-I', 'maintenance', fmri)
@provider.flush
end
it 'disables the service' do
mark_property_for_syncing(:enable, false)
expect(@provider).to receive(:maybe_clear_service_then_svcadm).with(mock_status, 'disable', '-s')
expect(@provider).to receive(:adm).with('mark', '-I', 'maintenance', fmri)
@provider.flush
end
context 'when the final service state is running' do
before(:each) do
allow(@provider).to receive(:status).and_return(:running)
end
it 'starts the service if enable was false' do
mark_property_for_syncing(:enable, false)
expect(@provider).to receive(:adm).with('disable', '-s', fmri)
expect(@provider).to receive(:adm).with('enable', '-rst', fmri)
expect(@provider).to receive(:wait).with('online')
@provider.flush
end
it 'waits for the service to start if enable was true' do
mark_property_for_syncing(:enable, true)
expect(@provider).to receive(:adm).with('enable', '-rs', fmri)
expect(@provider).to receive(:wait).with('online')
@provider.flush
end
end
context 'when the final service state is stopped' do
before(:each) do
allow(@provider).to receive(:status).and_return(:stopped)
end
it 'stops the service if enable was true' do
mark_property_for_syncing(:enable, true)
expect(@provider).to receive(:adm).with('enable', '-rs', fmri)
expect(@provider).to receive(:adm).with('disable', '-st', fmri)
expect(@provider).to receive(:wait).with(*stopped_states)
@provider.flush
end
it 'waits for the service to stop if enable was false' do
mark_property_for_syncing(:enable, false)
expect(@provider).to_not receive(:adm).with('disable', '-st', fmri)
expect(@provider).to receive(:wait).with(*stopped_states)
@provider.flush
end
end
it 'marks the service as being under maintenance if the final state is maintenance' do
expect(@provider).to receive(:status).and_return(:maintenance)
expect(@provider).to receive(:adm).with('clear', fmri)
expect(@provider).to receive(:adm).with('enable', '-rs', fmri)
expect(@provider).to receive(:adm).with('mark', '-I', 'maintenance', fmri)
expect(@provider).to receive(:wait).with('maintenance')
@provider.flush
end
it 'uses the ensure value as the final state if ensure also needs to be syncd' do
mark_property_for_syncing(:ensure, :running)
expect(@provider).to receive(:status).and_return(:stopped)
expect(@provider).to receive(:adm).with('enable', '-rs', fmri)
expect(@provider).to receive(:wait).with('online')
@provider.flush
end
it 'marks the final state of a degraded service as running' do
expect(@provider).to receive(:status).and_return(:degraded)
expect(@provider).to receive(:adm).with('clear', fmri)
expect(@provider).to receive(:adm).with('enable', '-rs', fmri)
expect(@provider).to receive(:wait).with('online')
@provider.flush
end
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/provider/service/launchd_spec.rb | spec/unit/provider/service/launchd_spec.rb | require 'spec_helper'
describe 'Puppet::Type::Service::Provider::Launchd',
unless: Puppet::Util::Platform.windows? || Puppet::Util::Platform.jruby? do
let(:provider_class) { Puppet::Type.type(:service).provider(:launchd) }
let (:plistlib) { Puppet::Util::Plist }
let (:joblabel) { "com.foo.food" }
let (:provider) { subject.class }
let (:resource) { Puppet::Type.type(:service).new(:name => joblabel, :provider => :launchd) }
let (:launchd_overrides_6_9) { '/var/db/launchd.db/com.apple.launchd/overrides.plist' }
let (:launchd_overrides_10_) { '/var/db/com.apple.xpc.launchd/disabled.plist' }
subject { resource.provider }
after :each do
provider.instance_variable_set(:@job_list, nil)
end
describe "the type interface" do
%w{ start stop enabled? enable disable status}.each do |method|
it { is_expected.to respond_to method.to_sym }
end
end
describe 'the status of the services' do
it "should call the external command 'launchctl list' once" do
expect(provider).to receive(:launchctl).with(:list).and_return(joblabel)
expect(provider).to receive(:jobsearch).and_return({joblabel => "/Library/LaunchDaemons/#{joblabel}"})
provider.prefetch({})
end
it "should return stopped if not listed in launchctl list output" do
expect(provider).to receive(:launchctl).with(:list).and_return('com.bar.is_running')
expect(provider).to receive(:jobsearch).and_return({'com.bar.is_not_running' => "/Library/LaunchDaemons/com.bar.is_not_running"})
expect(provider.prefetch({}).last.status).to eq(:stopped)
end
it "should return running if listed in launchctl list output" do
expect(provider).to receive(:launchctl).with(:list).and_return('com.bar.is_running')
expect(provider).to receive(:jobsearch).and_return({'com.bar.is_running' => "/Library/LaunchDaemons/com.bar.is_running"})
expect(provider.prefetch({}).last.status).to eq(:running)
end
describe "when hasstatus is set to false" do
before :each do
resource[:hasstatus] = :false
end
it "should use the user-provided status command if present and return running if true" do
resource[:status] = '/bin/true'
expect(subject).to receive(:execute)
.with(["/bin/true"], hash_including(failonfail: false))
.and_return(Puppet::Util::Execution::ProcessOutput.new('', 0))
expect(subject.status).to eq(:running)
end
it "should use the user-provided status command if present and return stopped if false" do
resource[:status] = '/bin/false'
expect(subject).to receive(:execute)
.with(["/bin/false"], hash_including(failonfail: false))
.and_return(Puppet::Util::Execution::ProcessOutput.new('', 1))
expect(subject.status).to eq(:stopped)
end
it "should fall back to getpid if no status command is provided" do
expect(subject).to receive(:getpid).and_return(123)
expect(subject.status).to eq(:running)
end
end
end
[[10, '10.6'], [13, '10.9']].each do |kernel, version|
describe "when checking whether the service is enabled on OS X #{version}" do
it "should return true if the job plist says disabled is true and the global overrides says disabled is false" do
expect(provider).to receive(:get_os_version).and_return(kernel).at_least(:once)
expect(subject).to receive(:plist_from_label).and_return([joblabel, {"Disabled" => true}])
expect(plistlib).to receive(:read_plist_file).with(launchd_overrides_6_9).and_return({joblabel => {"Disabled" => false}})
expect(FileTest).to receive(:file?).with(launchd_overrides_6_9).and_return(true)
expect(subject.enabled?).to eq(:true)
end
it "should return false if the job plist says disabled is false and the global overrides says disabled is true" do
expect(provider).to receive(:get_os_version).and_return(kernel).at_least(:once)
expect(subject).to receive(:plist_from_label).and_return([joblabel, {"Disabled" => false}])
expect(plistlib).to receive(:read_plist_file).with(launchd_overrides_6_9).and_return({joblabel => {"Disabled" => true}})
expect(FileTest).to receive(:file?).with(launchd_overrides_6_9).and_return(true)
expect(subject.enabled?).to eq(:false)
end
it "should return true if the job plist and the global overrides have no disabled keys" do
expect(provider).to receive(:get_os_version).and_return(kernel).at_least(:once)
expect(subject).to receive(:plist_from_label).and_return([joblabel, {}])
expect(plistlib).to receive(:read_plist_file).with(launchd_overrides_6_9).and_return({})
expect(FileTest).to receive(:file?).with(launchd_overrides_6_9).and_return(true)
expect(subject.enabled?).to eq(:true)
end
end
end
describe "when checking whether the service is enabled on OS X 10.10" do
it "should return true if the job plist says disabled is true and the global overrides says disabled is false" do
expect(provider).to receive(:get_os_version).and_return(14).at_least(:once)
expect(subject).to receive(:plist_from_label).and_return([joblabel, {"Disabled" => true}])
expect(plistlib).to receive(:read_plist_file).with(launchd_overrides_10_).and_return({joblabel => false})
expect(FileTest).to receive(:file?).with(launchd_overrides_10_).and_return(true)
expect(subject.enabled?).to eq(:true)
end
it "should return false if the job plist says disabled is false and the global overrides says disabled is true" do
expect(provider).to receive(:get_os_version).and_return(14).at_least(:once)
expect(subject).to receive(:plist_from_label).and_return([joblabel, {"Disabled" => false}])
expect(plistlib).to receive(:read_plist_file).with(launchd_overrides_10_).and_return({joblabel => true})
expect(FileTest).to receive(:file?).with(launchd_overrides_10_).and_return(true)
expect(subject.enabled?).to eq(:false)
end
it "should return true if the job plist and the global overrides have no disabled keys" do
expect(provider).to receive(:get_os_version).and_return(14).at_least(:once)
expect(subject).to receive(:plist_from_label).and_return([joblabel, {}])
expect(plistlib).to receive(:read_plist_file).with(launchd_overrides_10_).and_return({})
expect(FileTest).to receive(:file?).with(launchd_overrides_10_).and_return(true)
expect(subject.enabled?).to eq(:true)
end
end
describe "when starting the service" do
let(:services) { "12345 0 #{joblabel}" }
it "should call any explicit 'start' command" do
resource[:start] = "/bin/false"
expect(subject).to receive(:execute).with(["/bin/false"], hash_including(failonfail: true))
subject.start
end
it "should look for the relevant plist once" do
allow(provider).to receive(:launchctl).with(:list).and_return(services)
expect(subject).to receive(:plist_from_label).and_return([joblabel, {}]).once
expect(subject).to receive(:enabled?).and_return(:true)
expect(subject).to receive(:execute).with([:launchctl, :load, "-w", joblabel])
subject.start
end
it "should execute 'launchctl load' once without writing to the plist if the job is enabled" do
allow(provider).to receive(:launchctl).with(:list).and_return(services)
expect(subject).to receive(:plist_from_label).and_return([joblabel, {}])
expect(subject).to receive(:enabled?).and_return(:true)
expect(subject).to receive(:execute).with([:launchctl, :load, "-w", joblabel]).once
subject.start
end
it "should execute 'launchctl load' with writing to the plist once if the job is disabled" do
expect(subject).to receive(:plist_from_label).and_return([joblabel, {}])
expect(subject).to receive(:enabled?).and_return(:false)
expect(subject).to receive(:execute).with([:launchctl, :load, "-w", joblabel]).once
subject.start
end
it "should disable the job once if the job is disabled and should be disabled at boot" do
resource[:enable] = false
expect(subject).to receive(:plist_from_label).and_return([joblabel, {"Disabled" => true}])
expect(subject).to receive(:enabled?).and_return(:false)
expect(subject).to receive(:execute).with([:launchctl, :load, "-w", joblabel])
expect(subject).to receive(:disable).once
subject.start
end
it "(#2773) should execute 'launchctl load -w' if the job is enabled but stopped" do
expect(subject).to receive(:plist_from_label).and_return([joblabel, {}])
expect(subject).to receive(:enabled?).and_return(:true)
expect(subject).to receive(:status).and_return(:stopped)
expect(subject).to receive(:execute).with([:launchctl, :load, '-w', joblabel])
subject.start
end
it "(#16271) Should stop and start the service when a restart is called" do
expect(subject).to receive(:stop)
expect(subject).to receive(:start)
subject.restart
end
end
describe "when stopping the service" do
it "should call any explicit 'stop' command" do
resource[:stop] = "/bin/false"
expect(subject).to receive(:execute).with(["/bin/false"], hash_including(failonfail: true))
subject.stop
end
it "should look for the relevant plist once" do
expect(subject).to receive(:plist_from_label).and_return([joblabel, {}]).once
expect(subject).to receive(:enabled?).and_return(:true)
expect(subject).to receive(:execute).with([:launchctl, :unload, '-w', joblabel])
subject.stop
end
it "should execute 'launchctl unload' once without writing to the plist if the job is disabled" do
expect(subject).to receive(:plist_from_label).and_return([joblabel, {}])
expect(subject).to receive(:enabled?).and_return(:false)
expect(subject).to receive(:execute).with([:launchctl, :unload, joblabel]).once
subject.stop
end
it "should execute 'launchctl unload' with writing to the plist once if the job is enabled" do
expect(subject).to receive(:plist_from_label).and_return([joblabel, {}])
expect(subject).to receive(:enabled?).and_return(:true)
expect(subject).to receive(:execute).with([:launchctl, :unload, '-w', joblabel]).once
subject.stop
end
it "should enable the job once if the job is enabled and should be enabled at boot" do
resource[:enable] = true
expect(subject).to receive(:plist_from_label).and_return([joblabel, {"Disabled" => false}])
expect(subject).to receive(:enabled?).and_return(:true)
expect(subject).to receive(:execute).with([:launchctl, :unload, "-w", joblabel])
expect(subject).to receive(:enable).once
subject.stop
end
end
describe "when enabling the service" do
it "should look for the relevant plist once" do ### Do we need this test? Differentiating it?
resource[:enable] = true
expect(subject).to receive(:plist_from_label).and_return([joblabel, {}]).once
expect(subject).to receive(:enabled?).and_return(:false)
expect(subject).to receive(:execute).with([:launchctl, :unload, joblabel])
subject.stop
end
it "should check if the job is enabled once" do
resource[:enable] = true
expect(subject).to receive(:plist_from_label).and_return([joblabel, {}]).once
expect(subject).to receive(:enabled?).once
expect(subject).to receive(:execute).with([:launchctl, :unload, joblabel])
subject.stop
end
end
describe "when disabling the service" do
it "should look for the relevant plist once" do
resource[:enable] = false
expect(subject).to receive(:plist_from_label).and_return([joblabel, {}]).once
expect(subject).to receive(:enabled?).and_return(:true)
expect(subject).to receive(:execute).with([:launchctl, :unload, '-w', joblabel])
subject.stop
end
end
describe "when a service is unavailable" do
let(:map) { {"some.random.job" => "/path/to/job.plist"} }
before :each do
allow(provider).to receive(:make_label_to_path_map).and_return(map)
end
it "should fail when searching for the unavailable service" do
expect { provider.jobsearch("NOSUCH") }.to raise_error(Puppet::Error)
end
it "should return false when enabling the service" do
expect(subject.enabled?).to eq(:false)
end
it "should fail when starting the service" do
expect { subject.start }.to raise_error(Puppet::Error)
end
it "should fail when starting the service" do
expect { subject.stop }.to raise_error(Puppet::Error)
end
end
[[10, "10.6"], [13, "10.9"]].each do |kernel, version|
describe "when enabling the service on OS X #{version}" do
it "should write to the global launchd overrides file once" do
resource[:enable] = true
expect(provider).to receive(:get_os_version).and_return(kernel).at_least(:once)
expect(plistlib).to receive(:read_plist_file).with(launchd_overrides_6_9).and_return({})
expect(plistlib).to receive(:write_plist_file).with(hash_including(resource[:name] => {'Disabled' => false}), launchd_overrides_6_9).once
subject.enable
end
end
describe "when disabling the service on OS X #{version}" do
it "should write to the global launchd overrides file once" do
resource[:enable] = false
expect(provider).to receive(:get_os_version).and_return(kernel).at_least(:once)
expect(plistlib).to receive(:read_plist_file).with(launchd_overrides_6_9).and_return({})
expect(plistlib).to receive(:write_plist_file).with(hash_including(resource[:name] => {'Disabled' => true}), launchd_overrides_6_9).once
subject.disable
end
end
end
describe "when enabling the service on OS X 10.10" do
it "should write to the global launchd overrides file once" do
resource[:enable] = true
expect(provider).to receive(:get_os_version).and_return(14).at_least(:once)
expect(plistlib).to receive(:read_plist_file).with(launchd_overrides_10_).and_return({})
expect(plistlib).to receive(:write_plist_file).with(hash_including(resource[:name] => false), launchd_overrides_10_).once
subject.enable
end
end
describe "when disabling the service on OS X 10.10" do
it "should write to the global launchd overrides file once" do
resource[:enable] = false
expect(provider).to receive(:get_os_version).and_return(14).at_least(:once)
expect(plistlib).to receive(:read_plist_file).with(launchd_overrides_10_).and_return({})
expect(plistlib).to receive(:write_plist_file).with(hash_including(resource[:name] => true), launchd_overrides_10_).once
subject.disable
end
end
describe "make_label_to_path_map" do
before do
# clear out this class variable between runs
if provider.instance_variable_defined? :@label_to_path_map
provider.send(:remove_instance_variable, :@label_to_path_map)
end
end
describe "when encountering malformed plists" do
let(:plist_without_label) do
{
'LimitLoadToSessionType' => 'Aqua'
}
end
let(:plist_without_label_not_hash) { 'just a string' }
let(:busted_plist_path) { '/Library/LaunchAgents/org.busted.plist' }
let(:binary_plist_path) { '/Library/LaunchAgents/org.binary.plist' }
it "[17624] should warn that the plist in question is being skipped" do
expect(provider).to receive(:launchd_paths).and_return(['/Library/LaunchAgents'])
expect(provider).to receive(:return_globbed_list_of_file_paths).with('/Library/LaunchAgents').and_return([busted_plist_path])
expect(plistlib).to receive(:read_plist_file).with(busted_plist_path).and_return(plist_without_label)
expect(Puppet).to receive(:debug).with("Reading launchd plist #{busted_plist_path}")
expect(Puppet).to receive(:debug).with("The #{busted_plist_path} plist does not contain a 'label' key; Puppet is skipping it")
provider.make_label_to_path_map
end
it "it should warn that the malformed plist in question is being skipped" do
expect(provider).to receive(:launchd_paths).and_return(['/Library/LaunchAgents'])
expect(provider).to receive(:return_globbed_list_of_file_paths).with('/Library/LaunchAgents').and_return([busted_plist_path])
expect(plistlib).to receive(:read_plist_file).with(busted_plist_path).and_return(plist_without_label_not_hash)
expect(Puppet).to receive(:debug).with("Reading launchd plist #{busted_plist_path}")
expect(Puppet).to receive(:debug).with("The #{busted_plist_path} plist does not contain a 'label' key; Puppet is skipping it")
provider.make_label_to_path_map
end
end
it "should return the cached value when available" do
provider.instance_variable_set(:@label_to_path_map, {'xx'=>'yy'})
expect(provider.make_label_to_path_map).to eq({'xx'=>'yy'})
end
describe "when successful" do
let(:launchd_dir) { '/Library/LaunchAgents' }
let(:plist) { launchd_dir + '/foo.bar.service.plist' }
let(:label) { 'foo.bar.service' }
before do
provider.instance_variable_set(:@label_to_path_map, nil)
expect(provider).to receive(:launchd_paths).and_return([launchd_dir])
expect(provider).to receive(:return_globbed_list_of_file_paths).with(launchd_dir).and_return([plist])
expect(plistlib).to receive(:read_plist_file).with(plist).and_return({'Label'=>'foo.bar.service'})
end
it "should read the plists and return their contents" do
expect(provider.make_label_to_path_map).to eq({label=>plist})
end
it "should re-read the plists and return their contents when refreshed" do
provider.instance_variable_set(:@label_to_path_map, {'xx'=>'yy'})
expect(provider.make_label_to_path_map(true)).to eq({label=>plist})
end
end
end
describe "jobsearch" do
let(:map) { {"org.mozilla.puppet" => "/path/to/puppet.plist",
"org.mozilla.python" => "/path/to/python.plist"} }
it "returns the entire map with no args" do
expect(provider).to receive(:make_label_to_path_map).and_return(map)
expect(provider.jobsearch).to eq(map)
end
it "returns a singleton hash when given a label" do
expect(provider).to receive(:make_label_to_path_map).and_return(map)
expect(provider.jobsearch("org.mozilla.puppet")).to eq({ "org.mozilla.puppet" => "/path/to/puppet.plist" })
end
it "refreshes the label_to_path_map when label is not found" do
expect(provider).to receive(:make_label_to_path_map).and_return(map)
expect(provider.jobsearch("org.mozilla.puppet")).to eq({ "org.mozilla.puppet" => "/path/to/puppet.plist" })
end
it "raises Puppet::Error when the label is still not found" do
allow(provider).to receive(:make_label_to_path_map).and_return(map)
expect { provider.jobsearch("NOSUCH") }.to raise_error(Puppet::Error)
end
end
describe "read_overrides" do
before do
allow(Kernel).to receive(:sleep)
end
it "should read overrides" do
expect(provider).to receive(:read_plist).once.and_return({})
expect(provider.read_overrides).to eq({})
end
it "should retry if read_plist fails" do
allow(provider).to receive(:read_plist).and_return({}, nil)
expect(provider.read_overrides).to eq({})
end
it "raises Puppet::Error after 20 attempts" do
expect(provider).to receive(:read_plist).exactly(20).times().and_return(nil)
expect { provider.read_overrides }.to raise_error(Puppet::Error)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/provider/service/base_spec.rb | spec/unit/provider/service/base_spec.rb | require 'spec_helper'
require 'rbconfig'
require 'fileutils'
describe "base service provider" do
include PuppetSpec::Files
let :type do Puppet::Type.type(:service) end
let :provider do type.provider(:base) end
let(:executor) { Puppet::Util::Execution }
let(:start_command) { 'start' }
let(:status_command) { 'status' }
let(:stop_command) { 'stop' }
subject { provider }
context "basic operations" do
subject do
type.new(
:name => "test",
:provider => :base,
:start => start_command,
:status => status_command,
:stop => stop_command
).provider
end
def execute_command(command, options)
case command.shift
when start_command
expect(options[:failonfail]).to eq(true)
raise(Puppet::ExecutionFailure, 'failed to start') if @running
@running = true
Puppet::Util::Execution::ProcessOutput.new('started', 0)
when status_command
expect(options[:failonfail]).to eq(false)
if @running
Puppet::Util::Execution::ProcessOutput.new('running', 0)
else
Puppet::Util::Execution::ProcessOutput.new('not running', 1)
end
when stop_command
expect(options[:failonfail]).to eq(true)
raise(Puppet::ExecutionFailure, 'failed to stop') unless @running
@running = false
Puppet::Util::Execution::ProcessOutput.new('stopped', 0)
else
raise "unexpected command execution: #{command}"
end
end
before :each do
@running = false
expect(executor).to receive(:execute).at_least(:once) { |command, options| execute_command(command, options) }
end
it "should invoke the start command if not running" do
subject.start
end
it "should be stopped before being started" do
expect(subject.status).to eq(:stopped)
end
it "should be running after being started" do
subject.start
expect(subject.status).to eq(:running)
end
it "should invoke the stop command when asked" do
subject.start
expect(subject.status).to eq(:running)
subject.stop
expect(subject.status).to eq(:stopped)
end
it "should raise an error if started twice" do
subject.start
expect {subject.start }.to raise_error(Puppet::Error, 'Could not start Service[test]: failed to start')
end
it "should raise an error if stopped twice" do
subject.start
subject.stop
expect {subject.stop }.to raise_error(Puppet::Error, 'Could not stop Service[test]: failed to stop')
end
end
context "when hasstatus is false" do
subject do
type.new(
:name => "status test",
:provider => :base,
:hasstatus => false,
:pattern => "majestik m\u00f8\u00f8se",
).provider
end
it "retrieves a PID from the process table" do
allow(Facter).to receive(:value).and_call_original
allow(Facter).to receive(:value).with('os.name').and_return("CentOS")
ps_output = File.binread(my_fixture("ps_ef.mixed_encoding")).force_encoding(Encoding::UTF_8)
expect(executor).to receive(:execute).with("ps -ef").and_return(ps_output)
expect(subject.status).to eq(:running)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/provider/service/runit_spec.rb | spec/unit/provider/service/runit_spec.rb | require 'spec_helper'
describe 'Puppet::Type::Service::Provider::Runit',
unless: Puppet::Util::Platform.windows? || Puppet::Util::Platform.jruby? do
let(:provider_class) { Puppet::Type.type(:service).provider(:runit) }
before(:each) do
# Create a mock resource
@resource = double('resource')
@provider = provider_class.new
@servicedir = "/etc/service"
@provider.servicedir=@servicedir
@daemondir = "/etc/sv"
@provider.class.defpath=@daemondir
# A catch all; no parameters set
allow(@resource).to receive(:[]).and_return(nil)
# But set name, source and path (because we won't run
# the thing that will fetch the resource path from the provider)
allow(@resource).to receive(:[]).with(:name).and_return("myservice")
allow(@resource).to receive(:[]).with(:ensure).and_return(:enabled)
allow(@resource).to receive(:[]).with(:path).and_return(@daemondir)
allow(@resource).to receive(:ref).and_return("Service[myservice]")
allow(@provider).to receive(:sv)
allow(@provider).to receive(:resource).and_return(@resource)
end
it "should have a restart method" do
expect(@provider).to respond_to(:restart)
end
it "should have a restartcmd method" do
expect(@provider).to respond_to(:restartcmd)
end
it "should have a start method" do
expect(@provider).to respond_to(:start)
end
it "should have a stop method" do
expect(@provider).to respond_to(:stop)
end
it "should have an enabled? method" do
expect(@provider).to respond_to(:enabled?)
end
it "should have an enable method" do
expect(@provider).to respond_to(:enable)
end
it "should have a disable method" do
expect(@provider).to respond_to(:disable)
end
context "when starting" do
it "should enable the service if it is not enabled" do
allow(@provider).to receive(:sv)
expect(@provider).to receive(:enabled?).and_return(:false)
expect(@provider).to receive(:enable)
allow(@provider).to receive(:sleep)
@provider.start
end
it "should execute external command 'sv start /etc/service/myservice'" do
allow(@provider).to receive(:enabled?).and_return(:true)
expect(@provider).to receive(:sv).with("start", "/etc/service/myservice")
@provider.start
end
end
context "when stopping" do
it "should execute external command 'sv stop /etc/service/myservice'" do
expect(@provider).to receive(:sv).with("stop", "/etc/service/myservice")
@provider.stop
end
end
context "when restarting" do
it "should call 'sv restart /etc/service/myservice'" do
expect(@provider).to receive(:sv).with("restart","/etc/service/myservice")
@provider.restart
end
end
context "when enabling" do
it "should create a symlink between daemon dir and service dir", :if => Puppet.features.manages_symlinks? do
daemon_path = File.join(@daemondir,"myservice")
service_path = File.join(@servicedir,"myservice")
expect(Puppet::FileSystem).to receive(:symlink?).with(service_path).and_return(false)
expect(Puppet::FileSystem).to receive(:symlink).with(daemon_path, File.join(@servicedir,"myservice")).and_return(0)
@provider.enable
end
end
context "when disabling" do
it "should remove the '/etc/service/myservice' symlink" do
path = File.join(@servicedir,"myservice")
allow(FileTest).to receive(:directory?).and_return(false)
expect(Puppet::FileSystem).to receive(:symlink?).with(path).and_return(true)
expect(Puppet::FileSystem).to receive(:unlink).with(path).and_return(0)
@provider.disable
end
end
context "when checking status" do
it "should call the external command 'sv status /etc/sv/myservice'" do
expect(@provider).to receive(:sv).with('status',File.join(@daemondir,"myservice"))
@provider.status
end
end
context "when checking status" do
it "and sv status fails, properly raise a Puppet::Error" do
expect(@provider).to receive(:sv).with('status',File.join(@daemondir,"myservice")).and_raise(Puppet::ExecutionFailure, "fail: /etc/sv/myservice: file not found")
expect { @provider.status }.to raise_error(Puppet::Error, 'Could not get status for service Service[myservice]: fail: /etc/sv/myservice: file not found')
end
it "and sv status returns up, then return :running" do
expect(@provider).to receive(:sv).with('status',File.join(@daemondir,"myservice")).and_return("run: /etc/sv/myservice: (pid 9029) 6s")
expect(@provider.status).to eq(:running)
end
it "and sv status returns not running, then return :stopped" do
expect(@provider).to receive(:sv).with('status',File.join(@daemondir,"myservice")).and_return("fail: /etc/sv/myservice: runsv not running")
expect(@provider.status).to eq(:stopped)
end
it "and sv status returns a warning, then return :stopped" do
expect(@provider).to receive(:sv).with('status',File.join(@daemondir,"myservice")).and_return("warning: /etc/sv/myservice: unable to open supervise/ok: file does not exist")
expect(@provider.status).to eq(:stopped)
end
end
context '.instances' do
before do
allow(provider_class).to receive(:defpath).and_return(path)
end
context 'when defpath is nil' do
let(:path) { nil }
it 'returns info message' do
expect(Puppet).to receive(:info).with(/runit is unsuitable because service directory is nil/)
provider_class.instances
end
end
context 'when defpath does not exist' do
let(:path) { '/inexistent_path' }
it 'returns notice about missing path' do
expect(Puppet).to receive(:notice).with(/Service path #{path} does not exist/)
provider_class.instances
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/provider/service/gentoo_spec.rb | spec/unit/provider/service/gentoo_spec.rb | require 'spec_helper'
describe 'Puppet::Type::Service::Provider::Gentoo',
unless: Puppet::Util::Platform.windows? || Puppet::Util::Platform.jruby? do
let(:provider_class) { Puppet::Type.type(:service).provider(:gentoo) }
before :each do
allow(Puppet::Type.type(:service)).to receive(:defaultprovider).and_return(provider_class)
allow(Puppet::FileSystem).to receive(:file?).with('/sbin/rc-update').and_return(true)
allow(Puppet::FileSystem).to receive(:executable?).with('/sbin/rc-update').and_return(true)
allow(Facter).to receive(:value).with('os.name').and_return('Gentoo')
allow(Facter).to receive(:value).with('os.family').and_return('Gentoo')
# The initprovider (parent of the gentoo provider) does a stat call
# before it even tries to execute an initscript. We use sshd in all the
# tests so make sure it is considered present.
sshd_path = '/etc/init.d/sshd'
allow(Puppet::FileSystem).to receive(:stat).with(sshd_path).and_return(double('stat'))
end
let :initscripts do
[
'alsasound',
'bootmisc',
'functions.sh',
'hwclock',
'reboot.sh',
'rsyncd',
'shutdown.sh',
'sshd',
'vixie-cron',
'wpa_supplicant',
'xdm-setup'
]
end
let :helperscripts do
[
'functions.sh',
'reboot.sh',
'shutdown.sh'
]
end
let :process_output do
Puppet::Util::Execution::ProcessOutput.new('', 0)
end
describe ".instances" do
it "should have an instances method" do
expect(provider_class).to respond_to(:instances)
end
it "should get a list of services from /etc/init.d but exclude helper scripts" do
allow(Puppet::FileSystem).to receive(:directory?).and_call_original
allow(Puppet::FileSystem).to receive(:directory?).with('/etc/init.d').and_return(true)
expect(Dir).to receive(:entries).with('/etc/init.d').and_return(initscripts)
(initscripts - helperscripts).each do |script|
expect(Puppet::FileSystem).to receive(:executable?).with("/etc/init.d/#{script}").and_return(true)
end
helperscripts.each do |script|
expect(Puppet::FileSystem).not_to receive(:executable?).with("/etc/init.d/#{script}")
end
allow(Puppet::FileSystem).to receive(:symlink?).and_return(false)
expect(provider_class.instances.map(&:name)).to eq([
'alsasound',
'bootmisc',
'hwclock',
'rsyncd',
'sshd',
'vixie-cron',
'wpa_supplicant',
'xdm-setup'
])
end
end
describe "#start" do
it "should use the supplied start command if specified" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :start => '/bin/foo'))
expect(provider).to receive(:execute).with(['/bin/foo'], {:failonfail => true, :override_locale => false, :squelch => false, :combine => true})
provider.start
end
it "should start the service with <initscript> start otherwise" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd'))
expect(provider).to receive(:execute).with(['/etc/init.d/sshd',:start], {:failonfail => true, :override_locale => false, :squelch => false, :combine => true})
expect(provider).to receive(:search).with('sshd').and_return('/etc/init.d/sshd')
provider.start
end
end
describe "#stop" do
it "should use the supplied stop command if specified" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :stop => '/bin/foo'))
expect(provider).to receive(:execute).with(['/bin/foo'], {:failonfail => true, :override_locale => false, :squelch => false, :combine => true})
provider.stop
end
it "should stop the service with <initscript> stop otherwise" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd'))
expect(provider).to receive(:execute).with(['/etc/init.d/sshd',:stop], {:failonfail => true, :override_locale => false, :squelch => false, :combine => true})
expect(provider).to receive(:search).with('sshd').and_return('/etc/init.d/sshd')
provider.stop
end
end
describe "#enabled?" do
before :each do
allow_any_instance_of(provider_class).to receive(:update).with(:show).and_return(File.read(my_fixture('rc_update_show')))
end
it "should run rc-update show to get a list of enabled services" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd'))
expect(provider).to receive(:update).with(:show).and_return("\n")
provider.enabled?
end
['hostname', 'net.lo', 'procfs'].each do |service|
it "should consider service #{service} in runlevel boot as enabled" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => service))
expect(provider.enabled?).to eq(:true)
end
end
['alsasound', 'xdm', 'netmount'].each do |service|
it "should consider service #{service} in runlevel default as enabled" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => service))
expect(provider.enabled?).to eq(:true)
end
end
['rsyncd', 'lighttpd', 'mysql'].each do |service|
it "should consider unused service #{service} as disabled" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => service))
expect(provider.enabled?).to eq(:false)
end
end
end
describe "#enable" do
it "should run rc-update add to enable a service" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd'))
expect(provider).to receive(:update).with(:add, 'sshd', :default)
provider.enable
end
end
describe "#disable" do
it "should run rc-update del to disable a service" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd'))
expect(provider).to receive(:update).with(:del, 'sshd', :default)
provider.disable
end
end
describe "#status" do
describe "when a special status command is specified" do
it "should use the status command from the resource" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :status => '/bin/foo'))
expect(provider).not_to receive(:execute).with(['/etc/init.d/sshd',:status], {:failonfail => false, :override_locale => false, :squelch => false, :combine => true})
expect(provider).to receive(:execute)
.with(['/bin/foo'], {:failonfail => false, :override_locale => false, :squelch => false, :combine => true})
.and_return(process_output)
provider.status
end
it "should return :stopped when the status command returns with a non-zero exitcode" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :status => '/bin/foo'))
expect(provider).not_to receive(:execute).with(['/etc/init.d/sshd',:status], {:failonfail => false, :override_locale => false, :squelch => false, :combine => true})
expect(provider).to receive(:execute)
.with(['/bin/foo'], {:failonfail => false, :override_locale => false, :squelch => false, :combine => true})
.and_return(Puppet::Util::Execution::ProcessOutput.new('', 3))
expect(provider.status).to eq(:stopped)
end
it "should return :running when the status command returns with a zero exitcode" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :status => '/bin/foo'))
expect(provider).not_to receive(:execute).with(['/etc/init.d/sshd',:status], {:failonfail => false, :override_locale => false, :squelch => false, :combine => true})
expect(provider).to receive(:execute)
.with(['/bin/foo'], {:failonfail => false, :override_locale => false, :squelch => false, :combine => true})
.and_return(process_output)
expect(provider.status).to eq(:running)
end
end
describe "when hasstatus is false" do
it "should return running if a pid can be found" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :hasstatus => false))
expect(provider).not_to receive(:execute).with(['/etc/init.d/sshd',:status], {:failonfail => false, :override_locale => false, :squelch => false, :combine => true})
expect(provider).to receive(:getpid).and_return(1000)
expect(provider.status).to eq(:running)
end
it "should return stopped if no pid can be found" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :hasstatus => false))
expect(provider).not_to receive(:execute).with(['/etc/init.d/sshd',:status], {:failonfail => false, :override_locale => false, :squelch => false, :combine => true})
expect(provider).to receive(:getpid).and_return(nil)
expect(provider.status).to eq(:stopped)
end
end
describe "when hasstatus is true" do
it "should return running if <initscript> status exits with a zero exitcode" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :hasstatus => true))
expect(provider).to receive(:search).with('sshd').and_return('/etc/init.d/sshd')
expect(provider).to receive(:execute)
.with(['/etc/init.d/sshd',:status], {:failonfail => false, :override_locale => false, :squelch => false, :combine => true})
.and_return(process_output)
expect(provider.status).to eq(:running)
end
it "should return stopped if <initscript> status exits with a non-zero exitcode" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :hasstatus => true))
expect(provider).to receive(:search).with('sshd').and_return('/etc/init.d/sshd')
expect(provider).to receive(:execute)
.with(['/etc/init.d/sshd',:status], {:failonfail => false, :override_locale => false, :squelch => false, :combine => true})
.and_return(Puppet::Util::Execution::ProcessOutput.new('', 3))
expect(provider.status).to eq(:stopped)
end
end
end
describe "#restart" do
it "should use the supplied restart command if specified" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :restart => '/bin/foo'))
expect(provider).not_to receive(:execute).with(['/etc/init.d/sshd',:restart], {:failonfail => true, :override_locale => false, :squelch => false, :combine => true})
expect(provider).to receive(:execute).with(['/bin/foo'], {:failonfail => true, :override_locale => false, :squelch => false, :combine => true})
provider.restart
end
it "should restart the service with <initscript> restart if hasrestart is true" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :hasrestart => true))
expect(provider).to receive(:search).with('sshd').and_return('/etc/init.d/sshd')
expect(provider).to receive(:execute).with(['/etc/init.d/sshd',:restart], {:failonfail => true, :override_locale => false, :squelch => false, :combine => true})
provider.restart
end
it "should restart the service with <initscript> stop/start if hasrestart is false" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :hasrestart => false))
expect(provider).to receive(:search).with('sshd').and_return('/etc/init.d/sshd')
expect(provider).not_to receive(:execute).with(['/etc/init.d/sshd',:restart], {:failonfail => true, :override_locale => false, :squelch => false, :combine => true})
expect(provider).to receive(:execute).with(['/etc/init.d/sshd',:stop], {:failonfail => true, :override_locale => false, :squelch => false, :combine => true})
expect(provider).to receive(:execute).with(['/etc/init.d/sshd',:start], {:failonfail => true, :override_locale => false, :squelch => false, :combine => true})
provider.restart
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/provider/service/init_spec.rb | spec/unit/provider/service/init_spec.rb | require 'spec_helper'
describe 'Puppet::Type::Service::Provider::Init',
unless: Puppet::Util::Platform.windows? || Puppet::Util::Platform.jruby? do
let(:provider_class) { Puppet::Type.type(:service).provider(:init) }
before do
Puppet::Type.type(:service).defaultprovider = provider_class
end
after do
Puppet::Type.type(:service).defaultprovider = nil
end
let :provider do
resource.provider
end
let :resource do
Puppet::Type.type(:service).new(
:name => 'myservice',
:ensure => :running,
:path => paths
)
end
let :paths do
["/service/path","/alt/service/path"]
end
let :excludes do
# Taken from redhat, gentoo, and debian
%w{functions.sh reboot.sh shutdown.sh functions halt killall single linuxconf reboot boot wait-for-state rcS module-init-tools}
end
let :process_output do
Puppet::Util::Execution::ProcessOutput.new('', 0)
end
describe "when running on FreeBSD" do
before :each do
allow(Facter).to receive(:value).with('os.name').and_return('FreeBSD')
allow(Facter).to receive(:value).with('os.family').and_return('FreeBSD')
end
it "should set its default path to include /etc/rc.d and /usr/local/etc/rc.d" do
expect(provider_class.defpath).to eq(["/etc/rc.d", "/usr/local/etc/rc.d"])
end
end
describe "when running on HP-UX" do
before :each do
allow(Facter).to receive(:value).with('os.name').and_return('HP-UX')
end
it "should set its default path to include /sbin/init.d" do
expect(provider_class.defpath).to eq("/sbin/init.d")
end
end
describe "when running on Archlinux" do
before :each do
allow(Facter).to receive(:value).with('os.name').and_return('Archlinux')
end
it "should set its default path to include /etc/rc.d" do
expect(provider_class.defpath).to eq("/etc/rc.d")
end
end
describe "when not running on FreeBSD, HP-UX or Archlinux" do
before :each do
allow(Facter).to receive(:value).with('os.name').and_return('RedHat')
end
it "should set its default path to include /etc/init.d" do
expect(provider_class.defpath).to eq("/etc/init.d")
end
end
describe "when getting all service instances" do
before :each do
allow(provider_class).to receive(:defpath).and_return('tmp')
@services = ['one', 'two', 'three', 'four', 'umountfs']
allow(Dir).to receive(:entries).and_call_original
allow(Dir).to receive(:entries).with('tmp').and_return(@services)
allow(Puppet::FileSystem).to receive(:directory?).and_call_original
allow(Puppet::FileSystem).to receive(:directory?).with('tmp').and_return(true)
allow(Puppet::FileSystem).to receive(:executable?).and_return(true)
end
it "should return instances for all services" do
expect(provider_class.instances.map(&:name)).to eq(@services)
end
it "should omit directories from the service list" do
expect(Puppet::FileSystem).to receive(:directory?).with('tmp/four').and_return(true)
expect(provider_class.instances.map(&:name)).to eq(@services - ['four'])
end
it "should omit an array of services from exclude list" do
exclude = ['two', 'four']
expect(provider_class.get_services(provider_class.defpath, exclude).map(&:name)).to eq(@services - exclude)
end
it "should omit a single service from the exclude list" do
exclude = 'two'
expect(provider_class.get_services(provider_class.defpath, exclude).map(&:name)).to eq(@services - [exclude])
end
it "should omit Yocto services on cisco-wrlinux" do
allow(Facter).to receive(:value).with('os.family').and_return('cisco-wrlinux')
exclude = 'umountfs'
expect(provider_class.get_services(provider_class.defpath).map(&:name)).to eq(@services - [exclude])
end
it "should not omit Yocto services on non cisco-wrlinux platforms" do
expect(provider_class.get_services(provider_class.defpath).map(&:name)).to eq(@services)
end
it "should use defpath" do
expect(provider_class.instances).to be_all { |provider| provider.get(:path) == provider_class.defpath }
end
it "should set hasstatus to true for providers" do
expect(provider_class.instances).to be_all { |provider| provider.get(:hasstatus) == true }
end
it "should discard upstart jobs", :if => Puppet.features.manages_symlinks? do
not_init_service, *valid_services = @services
path = "tmp/#{not_init_service}"
allow(Puppet::FileSystem).to receive(:symlink?).at_least(:once).and_return(false)
allow(Puppet::FileSystem).to receive(:symlink?).with(Puppet::FileSystem.pathname(path)).and_return(true)
allow(Puppet::FileSystem).to receive(:readlink).with(Puppet::FileSystem.pathname(path)).and_return("/lib/init/upstart-job")
expect(provider_class.instances.map(&:name)).to eq(valid_services)
end
it "should discard non-initscript scripts" do
valid_services = @services
all_services = valid_services + excludes
expect(Dir).to receive(:entries).with('tmp').and_return(all_services)
expect(provider_class.instances.map(&:name)).to match_array(valid_services)
end
end
describe "when checking valid paths" do
it "should discard paths that do not exist" do
expect(Puppet::FileSystem).to receive(:directory?).with(paths[0]).and_return(false)
expect(Puppet::FileSystem).to receive(:exist?).with(paths[0]).and_return(false)
expect(Puppet::FileSystem).to receive(:directory?).with(paths[1]).and_return(true)
expect(provider.paths).to eq([paths[1]])
end
it "should discard paths that are not directories" do
paths.each do |path|
expect(Puppet::FileSystem).to receive(:exist?).with(path).and_return(true)
expect(Puppet::FileSystem).to receive(:directory?).with(path).and_return(false)
end
expect(provider.paths).to be_empty
end
end
describe "when searching for the init script" do
before :each do
paths.each {|path| expect(Puppet::FileSystem).to receive(:directory?).with(path).and_return(true) }
end
it "should be able to find the init script in the service path" do
expect(Puppet::FileSystem).to receive(:exist?).with("#{paths[0]}/myservice").and_return(true)
expect(Puppet::FileSystem).not_to receive(:exist?).with("#{paths[1]}/myservice") # first one wins
expect(provider.initscript).to eq("/service/path/myservice")
end
it "should be able to find the init script in an alternate service path" do
expect(Puppet::FileSystem).to receive(:exist?).with("#{paths[0]}/myservice").and_return(false)
expect(Puppet::FileSystem).to receive(:exist?).with("#{paths[1]}/myservice").and_return(true)
expect(provider.initscript).to eq("/alt/service/path/myservice")
end
it "should be able to find the init script if it ends with .sh" do
expect(Puppet::FileSystem).to receive(:exist?).with("#{paths[0]}/myservice").and_return(false)
expect(Puppet::FileSystem).to receive(:exist?).with("#{paths[1]}/myservice").and_return(false)
expect(Puppet::FileSystem).to receive(:exist?).with("#{paths[0]}/myservice.sh").and_return(true)
expect(provider.initscript).to eq("/service/path/myservice.sh")
end
it "should fail if the service isn't there" do
paths.each do |path|
expect(Puppet::FileSystem).to receive(:exist?).with("#{path}/myservice").and_return(false)
expect(Puppet::FileSystem).to receive(:exist?).with("#{path}/myservice.sh").and_return(false)
end
expect { provider.initscript }.to raise_error(Puppet::Error, "Could not find init script for 'myservice'")
end
end
describe "if the init script is present" do
before :each do
allow(Puppet::FileSystem).to receive(:directory?).and_call_original
allow(Puppet::FileSystem).to receive(:directory?).with("/service/path").and_return(true)
allow(Puppet::FileSystem).to receive(:directory?).with("/alt/service/path").and_return(true)
allow(Puppet::FileSystem).to receive(:exist?).with("/service/path/myservice").and_return(true)
end
[:start, :stop, :status, :restart].each do |method|
it "should have a #{method} method" do
expect(provider).to respond_to(method)
end
describe "when running #{method}" do
before :each do
allow(provider).to receive(:execute).and_return(process_output)
end
it "should use any provided explicit command" do
resource[method] = "/user/specified/command"
expect(provider).to receive(:execute).with(["/user/specified/command"], any_args).and_return(process_output)
provider.send(method)
end
it "should pass #{method} to the init script when no explicit command is provided" do
resource[:hasrestart] = :true
resource[:hasstatus] = :true
expect(provider).to receive(:execute).with(["/service/path/myservice", method], any_args).and_return(process_output)
provider.send(method)
end
end
end
describe "when checking status" do
describe "when hasstatus is :true" do
before :each do
resource[:hasstatus] = :true
end
it "should execute the command" do
expect(provider).to receive(:execute)
.with(['/service/path/myservice', :status], hash_including(failonfail: false))
.and_return(process_output)
provider.status
end
it "should consider the process running if the command returns 0" do
expect(provider).to receive(:execute)
.with(['/service/path/myservice', :status], hash_including(failonfail: false))
.and_return(process_output)
expect(provider.status).to eq(:running)
end
[-10,-1,1,10].each { |ec|
it "should consider the process stopped if the command returns something non-0" do
expect(provider).to receive(:execute)
.with(['/service/path/myservice', :status], hash_including(failonfail: false))
.and_return(Puppet::Util::Execution::ProcessOutput.new('', ec))
expect(provider.status).to eq(:stopped)
end
}
end
describe "when hasstatus is not :true" do
before :each do
resource[:hasstatus] = :false
end
it "should consider the service :running if it has a pid" do
expect(provider).to receive(:getpid).and_return("1234")
expect(provider.status).to eq(:running)
end
it "should consider the service :stopped if it doesn't have a pid" do
expect(provider).to receive(:getpid).and_return(nil)
expect(provider.status).to eq(:stopped)
end
end
end
describe "when restarting and hasrestart is not :true" do
before :each do
resource[:hasrestart] = :false
end
it "should stop and restart the process" do
expect(provider).to receive(:execute)
.with(['/service/path/myservice', :stop], hash_including(failonfail: true))
.and_return(process_output)
expect(provider).to receive(:execute)
.with(['/service/path/myservice', :start], hash_including(failonfail: true))
.and_return(process_output)
provider.restart
end
end
describe "when starting a service on Solaris" do
it "should use ctrun" do
allow(Facter).to receive(:value).with('os.family').and_return('Solaris')
expect(provider).to receive(:execute)
.with('/usr/bin/ctrun -l child /service/path/myservice start', {:failonfail => true, :override_locale => false, :squelch => false, :combine => true})
.and_return(process_output)
provider.start
end
end
describe "when starting a service on RedHat" do
it "should not use ctrun" do
allow(Facter).to receive(:value).with('os.family').and_return('RedHat')
expect(provider).to receive(:execute)
.with(['/service/path/myservice', :start], {:failonfail => true, :override_locale => false, :squelch => false, :combine => true})
.and_return(process_output)
provider.start
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/provider/service/openrc_spec.rb | spec/unit/provider/service/openrc_spec.rb | require 'spec_helper'
describe 'Puppet::Type::Service::Provider::Openrc',
unless: Puppet::Util::Platform.windows? || Puppet::Util::Platform.jruby? do
let(:provider_class) { Puppet::Type.type(:service).provider(:openrc) }
before :each do
allow(Puppet::Type.type(:service)).to receive(:defaultprovider).and_return(provider_class)
['/sbin/rc-service', '/bin/rc-status', '/sbin/rc-update'].each do |command|
# Puppet::Util is both mixed in to providers and is also invoked directly
# by Puppet::Provider::CommandDefiner, so we have to stub both out.
allow(provider_class).to receive(:which).with(command).and_return(command)
allow(Puppet::Util).to receive(:which).with(command).and_return(command)
end
end
describe ".instances" do
it "should have an instances method" do
expect(provider_class).to respond_to :instances
end
it "should get a list of services from rc-service --list" do
expect(provider_class).to receive(:rcservice).with('-C','--list').and_return(File.read(my_fixture('rcservice_list')))
expect(provider_class.instances.map(&:name)).to eq([
'alsasound',
'consolefont',
'lvm-monitoring',
'pydoc-2.7',
'pydoc-3.2',
'wpa_supplicant',
'xdm',
'xdm-setup'
])
end
end
describe "#start" do
it "should use the supplied start command if specified" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :start => '/bin/foo'))
expect(provider).to receive(:execute).with(['/bin/foo'], {:failonfail => true, :override_locale => false, :squelch => false, :combine => true})
provider.start
end
it "should start the service with rc-service start otherwise" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd'))
expect(provider).to receive(:execute).with(['/sbin/rc-service','sshd',:start], {:failonfail => true, :override_locale => false, :squelch => false, :combine => true})
provider.start
end
end
describe "#stop" do
it "should use the supplied stop command if specified" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :stop => '/bin/foo'))
expect(provider).to receive(:execute).with(['/bin/foo'], {:failonfail => true, :override_locale => false, :squelch => false, :combine => true})
provider.stop
end
it "should stop the service with rc-service stop otherwise" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd'))
expect(provider).to receive(:execute).with(['/sbin/rc-service','sshd',:stop], {:failonfail => true, :override_locale => false, :squelch => false, :combine => true})
provider.stop
end
end
describe 'when invoking `rc-status`' do
subject { provider_class.new(Puppet::Type.type(:service).new(:name => 'urandom')) }
it "clears the RC_SVCNAME environment variable" do
Puppet::Util.withenv(:RC_SVCNAME => 'puppet') do
expect(Puppet::Util::Execution).to receive(:execute).with(
include('/bin/rc-status'),
hash_including(custom_environment: hash_including(RC_SVCNAME: nil))
).and_return(Puppet::Util::Execution::ProcessOutput.new('', 0))
subject.enabled?
end
end
end
describe "#enabled?" do
before :each do
allow_any_instance_of(provider_class).to receive(:rcstatus).with('-C','-a').and_return(File.read(my_fixture('rcstatus')))
end
it "should run rc-status to get a list of enabled services" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd'))
expect(provider).to receive(:rcstatus).with('-C','-a').and_return("\n")
provider.enabled?
end
['hwclock', 'modules', 'urandom'].each do |service|
it "should consider service #{service} in runlevel boot as enabled" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => service))
expect(provider.enabled?).to eq(:true)
end
end
['netmount', 'xdm', 'local', 'foo_with_very_very_long_servicename_no_still_not_the_end_wait_for_it_almost_there_almost_there_now_finally_the_end'].each do |service|
it "should consider service #{service} in runlevel default as enabled" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => service))
expect(provider.enabled?).to eq(:true)
end
end
['net.eth0', 'pcscd'].each do |service|
it "should consider service #{service} in dynamic runlevel: hotplugged as disabled" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => service))
expect(provider.enabled?).to eq(:false)
end
end
['sysfs', 'udev-mount'].each do |service|
it "should consider service #{service} in dynamic runlevel: needed as disabled" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => service))
expect(provider.enabled?).to eq(:false)
end
end
['sshd'].each do |service|
it "should consider service #{service} in dynamic runlevel: manual as disabled" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => service))
expect(provider.enabled?).to eq(:false)
end
end
end
describe "#enable" do
it "should run rc-update add to enable a service" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd'))
expect(provider).to receive(:rcupdate).with('-C', :add, 'sshd')
provider.enable
end
end
describe "#disable" do
it "should run rc-update del to disable a service" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd'))
expect(provider).to receive(:rcupdate).with('-C', :del, 'sshd')
provider.disable
end
end
describe "#status" do
describe "when a special status command if specified" do
it "should use the status command from the resource" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :status => '/bin/foo'))
expect(provider).not_to receive(:execute).with(['/sbin/rc-service','sshd',:status], :failonfail => false, :override_locale => false, :squelch => false, :combine => true)
expect(provider).to receive(:execute)
.with(['/bin/foo'], {:failonfail => false, :override_locale => false, :squelch => false, :combine => true})
.and_return(Puppet::Util::Execution::ProcessOutput.new('', 0))
provider.status
end
it "should return :stopped when status command returns with a non-zero exitcode" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :status => '/bin/foo'))
expect(provider).not_to receive(:execute).with(['/sbin/rc-service','sshd',:status], {:failonfail => false, :override_locale => false, :squelch => false, :combine => true})
expect(provider).to receive(:execute)
.with(['/bin/foo'], {:failonfail => false, :override_locale => false, :squelch => false, :combine => true})
.and_return(Puppet::Util::Execution::ProcessOutput.new('', 3))
expect(provider.status).to eq(:stopped)
end
it "should return :running when status command returns with a zero exitcode" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :status => '/bin/foo'))
expect(provider).not_to receive(:execute).with(['/sbin/rc-service','sshd',:status], {:failonfail => false, :override_locale => false, :squelch => false, :combine => true})
expect(provider).to receive(:execute)
.with(['/bin/foo'], {:failonfail => false, :override_locale => false, :squelch => false, :combine => true})
.and_return(Puppet::Util::Execution::ProcessOutput.new('', 0))
expect(provider.status).to eq(:running)
end
end
describe "when hasstatus is false" do
it "should return running if a pid can be found" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :hasstatus => false))
expect(provider).not_to receive(:execute).with(['/sbin/rc-service','sshd',:status], {:failonfail => false, :override_locale => false, :squelch => false, :combine => true})
expect(provider).to receive(:getpid).and_return(1000)
expect(provider.status).to eq(:running)
end
it "should return stopped if no pid can be found" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :hasstatus => false))
expect(provider).not_to receive(:execute).with(['/sbin/rc-service','sshd',:status], {:failonfail => false, :override_locale => false, :squelch => false, :combine => true})
expect(provider).to receive(:getpid).and_return(nil)
expect(provider.status).to eq(:stopped)
end
end
describe "when hasstatus is true" do
it "should return running if rc-service status exits with a zero exitcode" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :hasstatus => true))
expect(provider).to receive(:execute)
.with(['/sbin/rc-service','sshd',:status], {:failonfail => false, :override_locale => false, :squelch => false, :combine => true})
.and_return(Puppet::Util::Execution::ProcessOutput.new('', 0))
expect(provider.status).to eq(:running)
end
it "should return stopped if rc-service status exits with a non-zero exitcode" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :hasstatus => true))
expect(provider).to receive(:execute)
.with(['/sbin/rc-service','sshd',:status], {:failonfail => false, :override_locale => false, :squelch => false, :combine => true})
.and_return(Puppet::Util::Execution::ProcessOutput.new('', 3))
expect(provider.status).to eq(:stopped)
end
end
end
describe "#restart" do
it "should use the supplied restart command if specified" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :restart => '/bin/foo'))
expect(provider).not_to receive(:execute).with(['/sbin/rc-service','sshd',:restart], {:failonfail => true, :override_locale => false, :squelch => false, :combine => true})
expect(provider).to receive(:execute).with(['/bin/foo'], {:failonfail => true, :override_locale => false, :squelch => false, :combine => true})
provider.restart
end
it "should restart the service with rc-service restart if hasrestart is true" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :hasrestart => true))
expect(provider).to receive(:execute).with(['/sbin/rc-service','sshd',:restart], {:failonfail => true, :override_locale => false, :squelch => false, :combine => true})
provider.restart
end
it "should restart the service with rc-service stop/start if hasrestart is false" do
provider = provider_class.new(Puppet::Type.type(:service).new(:name => 'sshd', :hasrestart => false))
expect(provider).not_to receive(:execute).with(['/sbin/rc-service','sshd',:restart], {:failonfail => true, :override_locale => false, :squelch => false, :combine => true})
expect(provider).to receive(:execute).with(['/sbin/rc-service','sshd',:stop], {:failonfail => true, :override_locale => false, :squelch => false, :combine => true})
expect(provider).to receive(:execute).with(['/sbin/rc-service','sshd',:start], {:failonfail => true, :override_locale => false, :squelch => false, :combine => true})
provider.restart
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/provider/file/posix_spec.rb | spec/unit/provider/file/posix_spec.rb | require 'spec_helper'
describe Puppet::Type.type(:file).provider(:posix), :if => Puppet.features.posix? do
include PuppetSpec::Files
let(:path) { tmpfile('posix_file_spec') }
let(:resource) { Puppet::Type.type(:file).new :path => path, :mode => '0777', :provider => described_class.name }
let(:provider) { resource.provider }
describe "#mode" do
it "should return a string with the higher-order bits stripped away" do
FileUtils.touch(path)
File.chmod(0644, path)
expect(provider.mode).to eq('0644')
end
it "should return absent if the file doesn't exist" do
expect(provider.mode).to eq(:absent)
end
end
describe "#mode=" do
it "should chmod the file to the specified value" do
FileUtils.touch(path)
File.chmod(0644, path)
provider.mode = '0755'
expect(provider.mode).to eq('0755')
end
it "should pass along any errors encountered" do
expect do
provider.mode = '0644'
end.to raise_error(Puppet::Error, /failed to set mode/)
end
end
describe "#uid2name" do
it "should return the name of the user identified by the id" do
allow(Etc).to receive(:getpwuid).with(501).and_return(Etc::Passwd.new('jilluser', nil, 501))
expect(provider.uid2name(501)).to eq('jilluser')
end
it "should return the argument if it's already a name" do
expect(provider.uid2name('jilluser')).to eq('jilluser')
end
it "should return nil if the argument is above the maximum uid" do
expect(provider.uid2name(Puppet[:maximum_uid] + 1)).to eq(nil)
end
it "should return nil if the user doesn't exist" do
expect(Etc).to receive(:getpwuid).and_raise(ArgumentError, "can't find user for 999")
expect(provider.uid2name(999)).to eq(nil)
end
end
describe "#name2uid" do
it "should return the id of the user if it exists" do
passwd = Etc::Passwd.new('bobbo', nil, 502)
allow(Etc).to receive(:getpwnam).with('bobbo').and_return(passwd)
allow(Etc).to receive(:getpwuid).with(502).and_return(passwd)
expect(provider.name2uid('bobbo')).to eq(502)
end
it "should return the argument if it's already an id" do
expect(provider.name2uid('503')).to eq(503)
end
it "should return false if the user doesn't exist" do
allow(Etc).to receive(:getpwnam).with('chuck').and_raise(ArgumentError, "can't find user for chuck")
expect(provider.name2uid('chuck')).to eq(false)
end
end
describe "#owner" do
it "should return the uid of the file owner" do
FileUtils.touch(path)
owner = Puppet::FileSystem.stat(path).uid
expect(provider.owner).to eq(owner)
end
it "should return absent if the file can't be statted" do
expect(provider.owner).to eq(:absent)
end
it "should warn and return :silly if the value is beyond the maximum uid" do
stat = double('stat', :uid => Puppet[:maximum_uid] + 1)
allow(resource).to receive(:stat).and_return(stat)
expect(provider.owner).to eq(:silly)
expect(@logs).to be_any {|log| log.level == :warning and log.message =~ /Apparently using negative UID/}
end
end
describe "#owner=" do
it "should set the owner but not the group of the file" do
expect(File).to receive(:lchown).with(15, nil, resource[:path])
provider.owner = 15
end
it "should chown a link if managing links" do
resource[:links] = :manage
expect(File).to receive(:lchown).with(20, nil, resource[:path])
provider.owner = 20
end
it "should chown a link target if following links" do
resource[:links] = :follow
expect(File).to receive(:chown).with(20, nil, resource[:path])
provider.owner = 20
end
it "should pass along any error encountered setting the owner" do
expect(File).to receive(:lchown).and_raise(ArgumentError)
expect { provider.owner = 25 }.to raise_error(Puppet::Error, /Failed to set owner to '25'/)
end
end
describe "#gid2name" do
it "should return the name of the group identified by the id" do
allow(Etc).to receive(:getgrgid).with(501).and_return(Etc::Passwd.new('unicorns', nil, nil, 501))
expect(provider.gid2name(501)).to eq('unicorns')
end
it "should return the argument if it's already a name" do
expect(provider.gid2name('leprechauns')).to eq('leprechauns')
end
it "should return nil if the argument is above the maximum gid" do
expect(provider.gid2name(Puppet[:maximum_uid] + 1)).to eq(nil)
end
it "should return nil if the group doesn't exist" do
expect(Etc).to receive(:getgrgid).and_raise(ArgumentError, "can't find group for 999")
expect(provider.gid2name(999)).to eq(nil)
end
end
describe "#name2gid" do
it "should return the id of the group if it exists" do
passwd = Etc::Passwd.new('penguins', nil, nil, 502)
allow(Etc).to receive(:getgrnam).with('penguins').and_return(passwd)
allow(Etc).to receive(:getgrgid).with(502).and_return(passwd)
expect(provider.name2gid('penguins')).to eq(502)
end
it "should return the argument if it's already an id" do
expect(provider.name2gid('503')).to eq(503)
end
it "should return false if the group doesn't exist" do
allow(Etc).to receive(:getgrnam).with('wombats').and_raise(ArgumentError, "can't find group for wombats")
expect(provider.name2gid('wombats')).to eq(false)
end
end
describe "#group" do
it "should return the gid of the file group" do
FileUtils.touch(path)
group = Puppet::FileSystem.stat(path).gid
expect(provider.group).to eq(group)
end
it "should return absent if the file can't be statted" do
expect(provider.group).to eq(:absent)
end
it "should warn and return :silly if the value is beyond the maximum gid" do
stat = double('stat', :gid => Puppet[:maximum_uid] + 1)
allow(resource).to receive(:stat).and_return(stat)
expect(provider.group).to eq(:silly)
expect(@logs).to be_any {|log| log.level == :warning and log.message =~ /Apparently using negative GID/}
end
end
describe "#group=" do
it "should set the group but not the owner of the file" do
expect(File).to receive(:lchown).with(nil, 15, resource[:path])
provider.group = 15
end
it "should change the group for a link if managing links" do
resource[:links] = :manage
expect(File).to receive(:lchown).with(nil, 20, resource[:path])
provider.group = 20
end
it "should change the group for a link target if following links" do
resource[:links] = :follow
expect(File).to receive(:chown).with(nil, 20, resource[:path])
provider.group = 20
end
it "should pass along any error encountered setting the group" do
expect(File).to receive(:lchown).and_raise(ArgumentError)
expect { provider.group = 25 }.to raise_error(Puppet::Error, /Failed to set group to '25'/)
end
end
describe "when validating" do
it "should not perform any validation" do
resource.validate
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/provider/file/windows_spec.rb | spec/unit/provider/file/windows_spec.rb | require 'spec_helper'
if Puppet::Util::Platform.windows?
require 'puppet/util/windows'
class WindowsSecurity
extend Puppet::Util::Windows::Security
end
end
describe Puppet::Type.type(:file).provider(:windows), :if => Puppet::Util::Platform.windows? do
include PuppetSpec::Files
let(:path) { tmpfile('windows_file_spec') }
let(:resource) { Puppet::Type.type(:file).new :path => path, :mode => '0777', :provider => described_class.name }
let(:provider) { resource.provider }
let(:sid) { 'S-1-1-50' }
let(:account) { 'quinn' }
describe "#mode" do
it "should return a string representing the mode in 4-digit octal notation" do
FileUtils.touch(path)
WindowsSecurity.set_mode(0644, path)
expect(provider.mode).to eq('0644')
end
it "should return absent if the file doesn't exist" do
expect(provider.mode).to eq(:absent)
end
end
describe "#mode=" do
it "should chmod the file to the specified value" do
FileUtils.touch(path)
WindowsSecurity.set_mode(0644, path)
provider.mode = '0755'
expect(provider.mode).to eq('0755')
end
it "should pass along any errors encountered" do
expect do
provider.mode = '0644'
end.to raise_error(Puppet::Error, /failed to set mode/)
end
end
describe "#id2name" do
it "should return the name of the user identified by the sid" do
expect(Puppet::Util::Windows::SID).to receive(:valid_sid?).with(sid).and_return(true)
expect(Puppet::Util::Windows::SID).to receive(:sid_to_name).with(sid).and_return(account)
expect(provider.id2name(sid)).to eq(account)
end
it "should return the argument if it's already a name" do
expect(Puppet::Util::Windows::SID).to receive(:valid_sid?).with(account).and_return(false)
expect(Puppet::Util::Windows::SID).not_to receive(:sid_to_name)
expect(provider.id2name(account)).to eq(account)
end
it "should return nil if the user doesn't exist" do
expect(Puppet::Util::Windows::SID).to receive(:valid_sid?).with(sid).and_return(true)
expect(Puppet::Util::Windows::SID).to receive(:sid_to_name).with(sid).and_return(nil)
expect(provider.id2name(sid)).to eq(nil)
end
end
describe "#name2id" do
it "should delegate to name_to_sid" do
expect(Puppet::Util::Windows::SID).to receive(:name_to_sid).with(account).and_return(sid)
expect(provider.name2id(account)).to eq(sid)
end
end
describe "#owner" do
it "should return the sid of the owner if the file does exist" do
FileUtils.touch(resource[:path])
allow(provider).to receive(:get_owner).with(resource[:path]).and_return(sid)
expect(provider.owner).to eq(sid)
end
it "should return absent if the file doesn't exist" do
expect(provider.owner).to eq(:absent)
end
end
describe "#owner=" do
it "should set the owner to the specified value" do
expect(provider).to receive(:set_owner).with(sid, resource[:path])
provider.owner = sid
end
it "should propagate any errors encountered when setting the owner" do
allow(provider).to receive(:set_owner).and_raise(ArgumentError)
expect {
provider.owner = sid
}.to raise_error(Puppet::Error, /Failed to set owner/)
end
end
describe "#group" do
it "should return the sid of the group if the file does exist" do
FileUtils.touch(resource[:path])
allow(provider).to receive(:get_group).with(resource[:path]).and_return(sid)
expect(provider.group).to eq(sid)
end
it "should return absent if the file doesn't exist" do
expect(provider.group).to eq(:absent)
end
end
describe "#group=" do
it "should set the group to the specified value" do
expect(provider).to receive(:set_group).with(sid, resource[:path])
provider.group = sid
end
it "should propagate any errors encountered when setting the group" do
allow(provider).to receive(:set_group).and_raise(ArgumentError)
expect {
provider.group = sid
}.to raise_error(Puppet::Error, /Failed to set group/)
end
end
describe "when validating" do
{:owner => 'foo', :group => 'foo', :mode => '0777'}.each do |k,v|
it "should fail if the filesystem doesn't support ACLs and we're managing #{k}" do
allow_any_instance_of(described_class).to receive(:supports_acl?).and_return(false)
expect {
Puppet::Type.type(:file).new :path => path, k => v
}.to raise_error(Puppet::Error, /Can only manage owner, group, and mode on filesystems that support Windows ACLs, such as NTFS/)
end
end
it "should not fail if the filesystem doesn't support ACLs and we're not managing permissions" do
allow_any_instance_of(described_class).to receive(:supports_acl?).and_return(false)
Puppet::Type.type(:file).new :path => path
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/provider/user/pw_spec.rb | spec/unit/provider/user/pw_spec.rb | require 'spec_helper'
require 'open3'
RSpec::Matchers.define_negated_matcher :excluding, :include
describe Puppet::Type.type(:user).provider(:pw) do
let :resource do
Puppet::Type.type(:user).new(:name => "testuser", :provider => :pw)
end
context "when creating users" do
let :provider do
prov = resource.provider
expect(prov).to receive(:exists?).and_return(nil)
prov
end
it "should run pw with no additional flags when no properties are given" do
expect(provider.addcmd).to eq([described_class.command(:pw), "useradd", "testuser"])
expect(provider).to receive(:execute).with([described_class.command(:pw), "useradd", "testuser"], kind_of(Hash))
provider.create
end
it "should use -o when allowdupe is enabled" do
resource[:allowdupe] = true
expect(provider).to receive(:execute).with(include("-o"), kind_of(Hash))
provider.create
end
it "should use -c with the correct argument when the comment property is set" do
resource[:comment] = "Testuser Name"
expect(provider).to receive(:execute).with(include("-c").and(include("Testuser Name")), kind_of(Hash))
provider.create
end
it "should use -e with the correct argument when the expiry property is set" do
resource[:expiry] = "2010-02-19"
expect(provider).to receive(:execute).with(include("-e").and(include("19-02-2010")), kind_of(Hash))
provider.create
end
it "should use -e 00-00-0000 if the expiry property has to be removed" do
resource[:expiry] = :absent
expect(provider).to receive(:execute).with(include("-e").and(include("00-00-0000")), kind_of(Hash))
provider.create
end
it "should use -g with the correct argument when the gid property is set" do
resource[:gid] = 12345
expect(provider).to receive(:execute).with(include("-g").and(include(12345)), kind_of(Hash))
provider.create
end
it "should use -G with the correct argument when the groups property is set" do
resource[:groups] = "group1"
allow(Puppet::Util::POSIX).to receive(:groups_of).with('testuser').and_return([])
expect(provider).to receive(:execute).with(include("-G").and(include("group1")), kind_of(Hash))
provider.create
end
it "should use -G with all the given groups when the groups property is set to an array" do
resource[:groups] = ["group1", "group2"]
allow(Puppet::Util::POSIX).to receive(:groups_of).with('testuser').and_return([])
expect(provider).to receive(:execute).with(include("-G").and(include("group1,group2")), kind_of(Hash))
provider.create
end
it "should use -d with the correct argument when the home property is set" do
resource[:home] = "/home/testuser"
expect(provider).to receive(:execute).with(include("-d").and(include("/home/testuser")), kind_of(Hash))
provider.create
end
it "should use -m when the managehome property is enabled" do
resource[:managehome] = true
expect(provider).to receive(:execute).with(include("-m"), kind_of(Hash))
provider.create
end
it "should call the password set function with the correct argument when the password property is set" do
resource[:password] = "*"
expect(provider).to receive(:execute)
expect(provider).to receive(:password=).with("*")
provider.create
end
it "should call execute with sensitive true when the password property is set" do
Puppet::Util::Log.level = :debug
resource[:password] = "abc123"
expect(provider).to receive(:execute).with(kind_of(Array), hash_including(sensitive: true))
popen = double("popen", :puts => nil, :close => nil)
expect(Open3).to receive(:popen3).and_return(popen)
expect(popen).to receive(:puts).with("abc123")
provider.create
expect(@logs).not_to be_any {|log| log.level == :debug and log.message =~ /abc123/}
end
it "should call execute with sensitive false when a non-sensitive property is set" do
resource[:managehome] = true
expect(provider).to receive(:execute).with(kind_of(Array), hash_including(sensitive: false))
provider.create
end
it "should use -s with the correct argument when the shell property is set" do
resource[:shell] = "/bin/sh"
expect(provider).to receive(:execute).with(include("-s").and(include("/bin/sh")), kind_of(Hash))
provider.create
end
it "should use -u with the correct argument when the uid property is set" do
resource[:uid] = 12345
expect(provider).to receive(:execute).with(include("-u").and(include(12345)), kind_of(Hash))
provider.create
end
# (#7500) -p should not be used to set a password (it means something else)
it "should not use -p when a password is given" do
resource[:password] = "*"
expect(provider.addcmd).not_to include("-p")
expect(provider).to receive(:password=)
expect(provider).to receive(:execute).with(excluding("-p"), kind_of(Hash))
provider.create
end
end
context "when deleting users" do
it "should run pw with no additional flags" do
provider = resource.provider
expect(provider).to receive(:exists?).and_return(true)
expect(provider.deletecmd).to eq([described_class.command(:pw), "userdel", "testuser"])
expect(provider).to receive(:execute).with([described_class.command(:pw), "userdel", "testuser"], hash_including(custom_environment: {}))
provider.delete
end
# The above test covers this, but given the consequences of
# accidentally deleting a user's home directory it seems better to
# have an explicit test.
it "should not use -r when managehome is not set" do
provider = resource.provider
expect(provider).to receive(:exists?).and_return(true)
resource[:managehome] = false
expect(provider).to receive(:execute).with(excluding("-r"), hash_including(custom_environment: {}))
provider.delete
end
it "should use -r when managehome is set" do
provider = resource.provider
expect(provider).to receive(:exists?).and_return(true)
resource[:managehome] = true
expect(provider).to receive(:execute).with(include("-r"), hash_including(custom_environment: {}))
provider.delete
end
end
context "when modifying users" do
let :provider do
resource.provider
end
it "should run pw with the correct arguments" do
expect(provider.modifycmd("uid", 12345)).to eq([described_class.command(:pw), "usermod", "testuser", "-u", 12345])
expect(provider).to receive(:execute).with([described_class.command(:pw), "usermod", "testuser", "-u", 12345], hash_including(custom_environment: {}))
provider.uid = 12345
end
it "should use -c with the correct argument when the comment property is changed" do
resource[:comment] = "Testuser Name"
expect(provider).to receive(:execute).with(include("-c").and(include("Testuser New Name")), hash_including(custom_environment: {}))
provider.comment = "Testuser New Name"
end
it "should use -e with the correct argument when the expiry property is changed" do
resource[:expiry] = "2010-02-19"
expect(provider).to receive(:execute).with(include("-e").and(include("19-02-2011")), hash_including(custom_environment: {}))
provider.expiry = "2011-02-19"
end
it "should use -e with the correct argument when the expiry property is removed" do
resource[:expiry] = :absent
expect(provider).to receive(:execute).with(include("-e").and(include("00-00-0000")), hash_including(custom_environment: {}))
provider.expiry = :absent
end
it "should use -g with the correct argument when the gid property is changed" do
resource[:gid] = 12345
expect(provider).to receive(:execute).with(include("-g").and(include(54321)), hash_including(custom_environment: {}))
provider.gid = 54321
end
it "should use -G with the correct argument when the groups property is changed" do
resource[:groups] = "group1"
expect(provider).to receive(:execute).with(include("-G").and(include("group2")), hash_including(custom_environment: {}))
provider.groups = "group2"
end
it "should use -G with all the given groups when the groups property is changed with an array" do
resource[:groups] = ["group1", "group2"]
expect(provider).to receive(:execute).with(include("-G").and(include("group3,group4")), hash_including(custom_environment: {}))
provider.groups = "group3,group4"
end
it "should use -d with the correct argument when the home property is changed" do
resource[:home] = "/home/testuser"
expect(provider).to receive(:execute).with(include("-d").and(include("/newhome/testuser")), hash_including(custom_environment: {}))
provider.home = "/newhome/testuser"
end
it "should use -m and -d with the correct argument when the home property is changed and managehome is enabled" do
resource[:home] = "/home/testuser"
resource[:managehome] = true
expect(provider).to receive(:execute).with(include("-d").and(include("/newhome/testuser")).and(include("-m")), hash_including(custom_environment: {}))
provider.home = "/newhome/testuser"
end
it "should call the password set function with the correct argument when the password property is changed" do
resource[:password] = "*"
expect(provider).to receive(:password=).with("!")
provider.password = "!"
end
it "should use -s with the correct argument when the shell property is changed" do
resource[:shell] = "/bin/sh"
expect(provider).to receive(:execute).with(include("-s").and(include("/bin/tcsh")), hash_including(custom_environment: {}))
provider.shell = "/bin/tcsh"
end
it "should use -u with the correct argument when the uid property is changed" do
resource[:uid] = 12345
expect(provider).to receive(:execute).with(include("-u").and(include(54321)), hash_including(custom_environment: {}))
provider.uid = 54321
end
it "should print a debug message with sensitive data redacted when the password property is set" do
Puppet::Util::Log.level = :debug
resource[:password] = "*"
popen = double("popen", :puts => nil, :close => nil)
expect(Open3).to receive(:popen3).and_return(popen)
expect(popen).to receive(:puts).with("abc123")
provider.password = "abc123"
expect(@logs).not_to be_any {|log| log.level == :debug and log.message =~ /abc123/}
end
it "should call execute with sensitive false when a non-sensitive property is set" do
Puppet::Util::Log.level = :debug
resource[:home] = "/home/testuser"
resource[:managehome] = true
expect(provider).to receive(:execute).with(kind_of(Array), hash_including(sensitive: false))
provider.home = "/newhome/testuser"
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/provider/user/ldap_spec.rb | spec/unit/provider/user/ldap_spec.rb | require 'spec_helper'
describe Puppet::Type.type(:user).provider(:ldap) do
it "should have the Ldap provider class as its baseclass" do
expect(described_class.superclass).to equal(Puppet::Provider::Ldap)
end
it "should manage :posixAccount and :person objectclasses" do
expect(described_class.manager.objectclasses).to eq([:posixAccount, :person])
end
it "should use 'ou=People' as its relative base" do
expect(described_class.manager.location).to eq("ou=People")
end
it "should use :uid as its rdn" do
expect(described_class.manager.rdn).to eq(:uid)
end
it "should be able to manage passwords" do
expect(described_class).to be_manages_passwords
end
{:name => "uid",
:password => "userPassword",
:comment => "cn",
:uid => "uidNumber",
:gid => "gidNumber",
:home => "homeDirectory",
:shell => "loginShell"
}.each do |puppet, ldap|
it "should map :#{puppet.to_s} to '#{ldap}'" do
expect(described_class.manager.ldap_name(puppet)).to eq(ldap)
end
end
context "when being created" do
before do
# So we don't try to actually talk to ldap
@connection = double('connection')
allow(described_class.manager).to receive(:connect).and_yield(@connection)
end
it "should generate the sn as the last field of the cn" do
expect(Puppet::Type.type(:group).provider(:ldap)).to receive(:name2id).with(["whatever"]).and_return([123])
resource = double('resource', :should => %w{whatever})
allow(resource).to receive(:should).with(:comment).and_return(["Luke Kanies"])
allow(resource).to receive(:should).with(:ensure).and_return(:present)
instance = described_class.new(:name => "luke", :ensure => :absent)
allow(instance).to receive(:resource).and_return(resource)
expect(@connection).to receive(:add).with(anything, hash_including("sn" => ["Kanies"]))
instance.create
instance.flush
end
it "should translate a group name to the numeric id" do
expect(Puppet::Type.type(:group).provider(:ldap)).to receive(:name2id).with("bar").and_return(101)
resource = double('resource', :should => %w{whatever})
allow(resource).to receive(:should).with(:gid).and_return('bar')
allow(resource).to receive(:should).with(:ensure).and_return(:present)
instance = described_class.new(:name => "luke", :ensure => :absent)
allow(instance).to receive(:resource).and_return(resource)
expect(@connection).to receive(:add).with(anything, hash_including("gidNumber" => ["101"]))
instance.create
instance.flush
end
context "with no uid specified" do
it "should pick the first available UID after the largest existing UID" do
expect(Puppet::Type.type(:group).provider(:ldap)).to receive(:name2id).with(["whatever"]).and_return([123])
low = {:name=>["luke"], :shell=>:absent, :uid=>["600"], :home=>["/h"], :gid=>["1000"], :password=>["blah"], :comment=>["l k"]}
high = {:name=>["testing"], :shell=>:absent, :uid=>["640"], :home=>["/h"], :gid=>["1000"], :password=>["blah"], :comment=>["t u"]}
expect(described_class.manager).to receive(:search).and_return([low, high])
resource = double('resource', :should => %w{whatever})
allow(resource).to receive(:should).with(:uid).and_return(nil)
allow(resource).to receive(:should).with(:ensure).and_return(:present)
instance = described_class.new(:name => "luke", :ensure => :absent)
allow(instance).to receive(:resource).and_return(resource)
expect(@connection).to receive(:add).with(anything, hash_including("uidNumber" => ["641"]))
instance.create
instance.flush
end
it "should pick 501 of no users exist" do
expect(Puppet::Type.type(:group).provider(:ldap)).to receive(:name2id).with(["whatever"]).and_return([123])
expect(described_class.manager).to receive(:search).and_return(nil)
resource = double('resource', :should => %w{whatever})
allow(resource).to receive(:should).with(:uid).and_return(nil)
allow(resource).to receive(:should).with(:ensure).and_return(:present)
instance = described_class.new(:name => "luke", :ensure => :absent)
allow(instance).to receive(:resource).and_return(resource)
expect(@connection).to receive(:add).with(anything, hash_including("uidNumber" => ["501"]))
instance.create
instance.flush
end
end
end
context "when flushing" do
before do
allow(described_class).to receive(:suitable?).and_return(true)
@instance = described_class.new(:name => "myname", :groups => %w{whatever}, :uid => "400")
end
it "should remove the :groups value before updating" do
expect(@instance.class.manager).to receive(:update).with(anything, anything, hash_excluding(:groups))
@instance.flush
end
it "should empty the property hash" do
allow(@instance.class.manager).to receive(:update)
@instance.flush
expect(@instance.uid).to eq(:absent)
end
it "should empty the ldap property hash" do
allow(@instance.class.manager).to receive(:update)
@instance.flush
expect(@instance.ldap_properties[:uid]).to be_nil
end
end
context "when checking group membership" do
before do
@groups = Puppet::Type.type(:group).provider(:ldap)
@group_manager = @groups.manager
allow(described_class).to receive(:suitable?).and_return(true)
@instance = described_class.new(:name => "myname")
end
it "should show its group membership as the sorted list of all groups returned by an ldap query of group memberships" do
one = {:name => "one"}
two = {:name => "two"}
expect(@group_manager).to receive(:search).with("memberUid=myname").and_return([two, one])
expect(@instance.groups).to eq("one,two")
end
it "should show its group membership as :absent if no matching groups are found in ldap" do
expect(@group_manager).to receive(:search).with("memberUid=myname").and_return(nil)
expect(@instance.groups).to eq(:absent)
end
it "should cache the group value" do
expect(@group_manager).to receive(:search).with("memberUid=myname").once.and_return(nil)
@instance.groups
expect(@instance.groups).to eq(:absent)
end
end
context "when modifying group membership" do
before do
@groups = Puppet::Type.type(:group).provider(:ldap)
@group_manager = @groups.manager
allow(described_class).to receive(:suitable?).and_return(true)
@one = {:name => "one", :gid => "500"}
allow(@group_manager).to receive(:find).with("one").and_return(@one)
@two = {:name => "one", :gid => "600"}
allow(@group_manager).to receive(:find).with("two").and_return(@two)
@instance = described_class.new(:name => "myname")
allow(@instance).to receive(:groups).and_return(:absent)
end
it "should fail if the group does not exist" do
expect(@group_manager).to receive(:find).with("mygroup").and_return(nil)
expect { @instance.groups = "mygroup" }.to raise_error(Puppet::Error)
end
it "should only pass the attributes it cares about to the group manager" do
expect(@group_manager).to receive(:update).with(anything, hash_excluding(:gid), anything)
@instance.groups = "one"
end
it "should always include :ensure => :present in the current values" do
expect(@group_manager).to receive(:update).with(anything, hash_including(ensure: :present), anything)
@instance.groups = "one"
end
it "should always include :ensure => :present in the desired values" do
expect(@group_manager).to receive(:update).with(anything, anything, hash_including(ensure: :present))
@instance.groups = "one"
end
it "should always pass the group's original member list" do
@one[:members] = %w{yay ness}
expect(@group_manager).to receive(:update).with(anything, hash_including(members: %w{yay ness}), anything)
@instance.groups = "one"
end
it "should find the group again when resetting its member list, so it has the full member list" do
expect(@group_manager).to receive(:find).with("one").and_return(@one)
allow(@group_manager).to receive(:update)
@instance.groups = "one"
end
context "for groups that have no members" do
it "should create a new members attribute with its value being the user's name" do
expect(@group_manager).to receive(:update).with(anything, anything, hash_including(members: %w{myname}))
@instance.groups = "one"
end
end
context "for groups it is being removed from" do
it "should replace the group's member list with one missing the user's name" do
@one[:members] = %w{myname a}
@two[:members] = %w{myname b}
expect(@group_manager).to receive(:update).with("two", anything, hash_including(members: %w{b}))
allow(@instance).to receive(:groups).and_return("one,two")
@instance.groups = "one"
end
it "should mark the member list as empty if there are no remaining members" do
@one[:members] = %w{myname}
@two[:members] = %w{myname b}
expect(@group_manager).to receive(:update).with("one", anything, hash_including(members: :absent))
allow(@instance).to receive(:groups).and_return("one,two")
@instance.groups = "two"
end
end
context "for groups that already have members" do
it "should replace each group's member list with a new list including the user's name" do
@one[:members] = %w{a b}
expect(@group_manager).to receive(:update).with(anything, anything, hash_including(members: %w{a b myname}))
@two[:members] = %w{b c}
expect(@group_manager).to receive(:update).with(anything, anything, hash_including(members: %w{b c myname}))
@instance.groups = "one,two"
end
end
context "for groups of which it is a member" do
it "should do nothing" do
@one[:members] = %w{a b}
expect(@group_manager).to receive(:update).with(anything, anything, hash_including(members: %w{a b myname}))
@two[:members] = %w{c myname}
expect(@group_manager).not_to receive(:update).with("two", any_args)
allow(@instance).to receive(:groups).and_return("two")
@instance.groups = "one,two"
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/provider/user/hpux_spec.rb | spec/unit/provider/user/hpux_spec.rb | require 'spec_helper'
require 'etc'
describe Puppet::Type.type(:user).provider(:hpuxuseradd),
unless: Puppet::Util::Platform.windows? do
let :resource do
Puppet::Type.type(:user).new(
:title => 'testuser',
:comment => 'Test J. User',
:provider => :hpuxuseradd
)
end
let(:provider) { resource.provider }
it "should add -F when modifying a user" do
allow(resource).to receive(:allowdupe?).and_return(true)
allow(provider).to receive(:trusted).and_return(true)
expect(provider).to receive(:execute).with(include("-F"), anything)
provider.uid = 1000
end
it "should add -F when deleting a user" do
allow(provider).to receive(:exists?).and_return(true)
expect(provider).to receive(:execute).with(include("-F"), anything)
provider.delete
end
context "managing passwords" do
let :pwent do
Etc::Passwd.new("testuser", "foopassword")
end
before :each do
allow(Etc).to receive(:getpwent).and_return(pwent)
allow(Etc).to receive(:getpwnam).and_return(pwent)
allow(provider).to receive(:command).with(:modify).and_return('/usr/sam/lbin/usermod.sam')
end
it "should have feature manages_passwords" do
expect(described_class).to be_manages_passwords
end
it "should return nil if user does not exist" do
allow(Etc).to receive(:getpwent).and_return(nil)
expect(provider.password).to be_nil
end
it "should return password entry if exists" do
expect(provider.password).to eq("foopassword")
end
end
context "check for trusted computing" do
before :each do
allow(provider).to receive(:command).with(:modify).and_return('/usr/sam/lbin/usermod.sam')
end
it "should add modprpw to modifycmd if Trusted System" do
allow(resource).to receive(:allowdupe?).and_return(true)
expect(provider).to receive(:exec_getprpw).with('root','-m uid').and_return('uid=0')
expect(provider).to receive(:execute).with(['/usr/sam/lbin/usermod.sam', '-F', '-u', 1000, '-o', 'testuser', ';', '/usr/lbin/modprpw', '-v', '-l', 'testuser'], hash_including(custom_environment: {}))
provider.uid = 1000
end
it "should not add modprpw if not Trusted System" do
allow(resource).to receive(:allowdupe?).and_return(true)
expect(provider).to receive(:exec_getprpw).with('root','-m uid').and_return('System is not trusted')
expect(provider).to receive(:execute).with(['/usr/sam/lbin/usermod.sam', '-F', '-u', 1000, '-o', 'testuser'], hash_including(custom_environment: {}))
provider.uid = 1000
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/provider/user/openbsd_spec.rb | spec/unit/provider/user/openbsd_spec.rb | require 'spec_helper'
describe Puppet::Type.type(:user).provider(:openbsd) do
before :each do
allow(described_class).to receive(:command).with(:password).and_return('/usr/sbin/passwd')
allow(described_class).to receive(:command).with(:add).and_return('/usr/sbin/useradd')
allow(described_class).to receive(:command).with(:modify).and_return('/usr/sbin/usermod')
allow(described_class).to receive(:command).with(:delete).and_return('/usr/sbin/userdel')
end
let(:resource) do
Puppet::Type.type(:user).new(
:name => 'myuser',
:managehome => :false,
:system => :false,
:loginclass => 'staff',
:provider => provider
)
end
let(:provider) { described_class.new(:name => 'myuser') }
let(:shadow_entry) {
return unless Puppet.features.libshadow?
entry = Etc::PasswdEntry.new
entry[:sp_namp] = 'myuser' # login name
entry[:sp_loginclass] = 'staff' # login class
entry
}
describe "#expiry=" do
it "should pass expiry to usermod as MM/DD/YY" do
resource[:expiry] = '2014-11-05'
expect(provider).to receive(:execute).with(['/usr/sbin/usermod', '-e', 'November 05 2014', 'myuser'], hash_including(custom_environment: {}))
provider.expiry = '2014-11-05'
end
it "should use -e with an empty string when the expiry property is removed" do
resource[:expiry] = :absent
expect(provider).to receive(:execute).with(['/usr/sbin/usermod', '-e', '', 'myuser'], hash_including(custom_environment: {}))
provider.expiry = :absent
end
end
describe "#addcmd" do
it "should return an array with the full command and expiry as MM/DD/YY" do
allow(Facter).to receive(:value).with('os.family').and_return('OpenBSD')
allow(Facter).to receive(:value).with('os.release.major')
resource[:expiry] = "1997-06-01"
expect(provider.addcmd).to eq(['/usr/sbin/useradd', '-e', 'June 01 1997', 'myuser'])
end
end
describe "#loginclass" do
before :each do
resource
end
it "should return the loginclass if set", :if => Puppet.features.libshadow? do
expect(Shadow::Passwd).to receive(:getspnam).with('myuser').and_return(shadow_entry)
provider.send(:loginclass).should == 'staff'
end
it "should return the empty string when loginclass isn't set", :if => Puppet.features.libshadow? do
shadow_entry[:sp_loginclass] = ''
expect(Shadow::Passwd).to receive(:getspnam).with('myuser').and_return(shadow_entry)
provider.send(:loginclass).should == ''
end
it "should return nil when loginclass isn't available", :if => Puppet.features.libshadow? do
shadow_entry[:sp_loginclass] = nil
expect(Shadow::Passwd).to receive(:getspnam).with('myuser').and_return(shadow_entry)
provider.send(:loginclass).should 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/provider/user/aix_spec.rb | spec/unit/provider/user/aix_spec.rb | require 'spec_helper'
describe 'Puppet::Type::User::Provider::Aix' do
let(:provider_class) { Puppet::Type.type(:user).provider(:aix) }
let(:group_provider_class) { Puppet::Type.type(:group).provider(:aix) }
let(:resource) do
Puppet::Type.type(:user).new(
:name => 'test_aix_user',
:ensure => :present
)
end
let(:provider) do
provider_class.new(resource)
end
describe '.pgrp_to_gid' do
it "finds the primary group's gid" do
allow(provider).to receive(:ia_module_args).and_return(['-R', 'module'])
expect(group_provider_class).to receive(:list_all)
.with(provider.ia_module_args)
.and_return([{ :name => 'group', :id => 1}])
expect(provider_class.pgrp_to_gid(provider, 'group')).to eql(1)
end
end
describe '.gid_to_pgrp' do
it "finds the gid's primary group" do
allow(provider).to receive(:ia_module_args).and_return(['-R', 'module'])
expect(group_provider_class).to receive(:list_all)
.with(provider.ia_module_args)
.and_return([{ :name => 'group', :id => 1}])
expect(provider_class.gid_to_pgrp(provider, 1)).to eql('group')
end
end
describe '.expires_to_expiry' do
it 'returns absent if expires is 0' do
expect(provider_class.expires_to_expiry(provider, '0')).to eql(:absent)
end
it 'returns absent if the expiry attribute is not formatted properly' do
expect(provider_class.expires_to_expiry(provider, 'bad_format')).to eql(:absent)
end
it 'returns the password expiration date' do
expect(provider_class.expires_to_expiry(provider, '0910122314')).to eql('2014-09-10')
end
end
describe '.expiry_to_expires' do
it 'returns 0 if the expiry date is 0000-00-00' do
expect(provider_class.expiry_to_expires('0000-00-00')).to eql('0')
end
it 'returns 0 if the expiry date is "absent"' do
expect(provider_class.expiry_to_expires('absent')).to eql('0')
end
it 'returns 0 if the expiry date is :absent' do
expect(provider_class.expiry_to_expires(:absent)).to eql('0')
end
it 'returns the expires attribute value' do
expect(provider_class.expiry_to_expires('2014-09-10')).to eql('0910000014')
end
end
describe '.groups_attribute_to_property' do
it "reads the user's groups from the etc/groups file" do
groups = ['system', 'adm']
allow(Puppet::Util::POSIX).to receive(:groups_of).with(resource[:name]).and_return(groups)
actual_groups = provider_class.groups_attribute_to_property(provider, 'unused_value')
expected_groups = groups.join(',')
expect(actual_groups).to eql(expected_groups)
end
end
describe '.groups_property_to_attribute' do
it 'raises an ArgumentError if the groups are space-separated' do
groups = "foo bar baz"
expect do
provider_class.groups_property_to_attribute(groups)
end.to raise_error do |error|
expect(error).to be_a(ArgumentError)
expect(error.message).to match(groups)
expect(error.message).to match("Groups")
end
end
end
describe '#gid=' do
let(:value) { 'new_pgrp' }
let(:old_pgrp) { 'old_pgrp' }
let(:cur_groups) { 'system,adm' }
before(:each) do
allow(provider).to receive(:gid).and_return(old_pgrp)
allow(provider).to receive(:groups).and_return(cur_groups)
allow(provider).to receive(:set)
end
it 'raises a Puppet::Error if it fails to set the groups property' do
allow(provider).to receive(:set)
.with(:groups, cur_groups)
.and_raise(Puppet::ExecutionFailure, 'failed to reset the groups!')
expect { provider.gid = value }.to raise_error do |error|
expect(error).to be_a(Puppet::Error)
expect(error.message).to match('groups')
expect(error.message).to match(cur_groups)
expect(error.message).to match(old_pgrp)
expect(error.message).to match(value)
end
end
end
describe '#parse_password' do
def call_parse_password
File.open(my_fixture('aix_passwd_file.out')) do |f|
provider.parse_password(f)
end
end
it "returns :absent if the user stanza doesn't exist" do
resource[:name] = 'nonexistent_user'
expect(call_parse_password).to eql(:absent)
end
it "returns absent if the user does not have a password" do
resource[:name] = 'no_password_user'
expect(call_parse_password).to eql(:absent)
end
it "returns the user's password" do
expect(call_parse_password).to eql('some_password')
end
it "returns the user's password with tabs" do
resource[:name] = 'tab_password_user'
expect(call_parse_password).to eql('some_password')
end
end
# TODO: If we move from using Mocha to rspec's mocks,
# or a better and more robust mocking library, we should
# remove #parse_password and copy over its tests to here.
describe '#password' do
end
describe '#password=' do
let(:mock_tempfile) do
mock_tempfile_obj = double()
allow(mock_tempfile_obj).to receive(:<<)
allow(mock_tempfile_obj).to receive(:close)
allow(mock_tempfile_obj).to receive(:delete)
allow(mock_tempfile_obj).to receive(:path).and_return('tempfile_path')
allow(Tempfile).to receive(:new)
.with("puppet_#{provider.name}_pw", {:encoding => Encoding::ASCII})
.and_return(mock_tempfile_obj)
mock_tempfile_obj
end
let(:cmd) do
[provider.class.command(:chpasswd), *provider.ia_module_args, '-e', '-c']
end
let(:execute_options) do
{
:failonfail => false,
:combine => true,
:stdinfile => mock_tempfile.path
}
end
it 'raises a Puppet::Error if chpasswd fails' do
allow(provider).to receive(:execute).with(cmd, execute_options).and_return("failed to change passwd!")
expect { provider.password = 'foo' }.to raise_error do |error|
expect(error).to be_a(Puppet::Error)
expect(error.message).to match("failed to change passwd!")
end
end
it "changes the user's password" do
expect(provider).to receive(:execute).with(cmd, execute_options).and_return("")
provider.password = 'foo'
end
it "closes and deletes the tempfile" do
allow(provider).to receive(:execute).with(cmd, execute_options).and_return("")
expect(mock_tempfile).to receive(:close).twice
expect(mock_tempfile).to receive(:delete)
provider.password = 'foo'
end
end
describe '#create' do
it 'should create the user' do
allow(provider.resource).to receive(:should).with(anything).and_return(nil)
allow(provider.resource).to receive(:should).with(:groups).and_return('g1,g2')
allow(provider.resource).to receive(:should).with(:password).and_return('password')
expect(provider).to receive(:execute)
expect(provider).to receive(:groups=).with('g1,g2')
expect(provider).to receive(:password=).with('password')
provider.create
end
end
describe '#list_all_homes' do
it "should return empty array and output debug on failure" do
allow(Puppet::Util::Execution).to receive(:execute).and_raise(Puppet::ExecutionFailure, 'Execution failed')
expect(Puppet).to receive(:debug).with('Could not list home of all users: Execution failed')
expect(provider.list_all_homes).to eql({})
end
end
describe '#delete' do
before(:each) do
allow(File).to receive(:realpath).and_call_original
allow(FileUtils).to receive(:remove_entry_secure).and_call_original
allow(provider.resource).to receive(:should).with(anything).and_return(nil)
allow(provider).to receive(:home).and_return(Dir.tmpdir)
allow(provider).to receive(:execute).and_return(nil)
allow(provider).to receive(:object_info).and_return(nil)
allow(FileUtils).to receive(:remove_entry_secure).with(Dir.tmpdir, true).and_return(nil)
end
context 'with managehome true' do
before(:each) do
allow(provider.resource).to receive(:managehome?).and_return(true)
allow(provider).to receive(:list_all_homes).and_return([])
end
it 'should delete the user without error' do
expect{ provider.delete }.not_to raise_error
end
it "should not remove home when relative" do
allow(provider).to receive(:home).and_return('relative_path')
expect(Puppet).to receive(:debug).with(/Please make sure the path is not relative, symlink or '\/'./)
provider.delete
end
it "should not remove home when '/'" do
allow(provider).to receive(:home).and_return('/')
expect(Puppet).to receive(:debug).with(/Please make sure the path is not relative, symlink or '\/'./)
provider.delete
end
it "should not remove home when symlink" do
allow(Puppet::FileSystem).to receive(:symlink?).with(Dir.tmpdir).and_return(true)
expect(Puppet).to receive(:debug).with(/Please make sure the path is not relative, symlink or '\/'./)
provider.delete
end
it "should not remove home when other users would be affected" do
allow(provider).to receive(:home).and_return('/special')
allow(File).to receive(:realpath).with('/special').and_return('/special')
allow(Puppet::Util).to receive(:absolute_path?).with('/special').and_return(true)
allow(provider).to receive(:list_all_homes).and_return([{:name => 'other_user', :home => '/special/other_user'}])
expect(Puppet).to receive(:debug).with(/it would remove the home directory '\/special\/other_user' of user 'other_user' also./)
provider.delete
end
it 'should remove homedir' do
expect(FileUtils).to receive(:remove_entry_secure).with(Dir.tmpdir, true)
provider.delete
end
end
context 'with managehome false' do
before(:each) do
allow(provider.resource).to receive(:managehome?).and_return(false)
end
it 'should delete the user without error' do
expect{ provider.delete }.not_to raise_error
end
it 'should not remove homedir' do
expect(FileUtils).not_to receive(:remove_entry_secure).with(Dir.tmpdir, true)
end
it 'should not print manage home debug messages' do
expect(Puppet).not_to receive(:debug).with(/Please make sure the path is not relative, symlink or '\/'./)
expect(Puppet).not_to receive(:debug).with(/it would remove the home directory '\/special\/other_user' of user 'other_user' also./)
provider.delete
end
end
end
describe '#deletecmd' do
it 'uses the -p flag when removing the user' do
allow(provider.class).to receive(:command).with(:delete).and_return('delete')
allow(provider).to receive(:ia_module_args).and_return(['ia_module_args'])
expect(provider.deletecmd).to eql(
['delete', '-p', 'ia_module_args', provider.resource.name]
)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/provider/user/windows_adsi_spec.rb | spec/unit/provider/user/windows_adsi_spec.rb | require 'spec_helper'
describe Puppet::Type.type(:user).provider(:windows_adsi), :if => Puppet::Util::Platform.windows? do
let(:resource) do
Puppet::Type.type(:user).new(
:title => 'testuser',
:comment => 'Test J. User',
:provider => :windows_adsi
)
end
let(:provider) { resource.provider }
let(:connection) { double('connection') }
before :each do
allow(Puppet::Util::Windows::ADSI).to receive(:computer_name).and_return('testcomputername')
allow(Puppet::Util::Windows::ADSI).to receive(:connect).and_return(connection)
# this would normally query the system, but not needed for these tests
allow(Puppet::Util::Windows::ADSI::User).to receive(:localized_domains).and_return([])
end
describe ".instances" do
it "should enumerate all users" do
names = ['user1', 'user2', 'user3']
stub_users = names.map {|n| double(:name => n)}
allow(connection).to receive(:execquery).with('select name from win32_useraccount where localaccount = "TRUE"').and_return(stub_users)
expect(described_class.instances.map(&:name)).to match(names)
end
end
it "should provide access to a Puppet::Util::Windows::ADSI::User object" do
expect(provider.user).to be_a(Puppet::Util::Windows::ADSI::User)
end
describe "when retrieving the password property" do
context "when the resource has a nil password" do
it "should never issue a logon attempt" do
allow(resource).to receive(:[]).with(eq(:name).or(eq(:password))).and_return(nil)
expect(Puppet::Util::Windows::User).not_to receive(:logon_user)
provider.password
end
end
end
describe "when managing groups" do
it 'should return the list of groups as an array of strings' do
allow(provider.user).to receive(:groups).and_return(nil)
groups = {'group1' => nil, 'group2' => nil, 'group3' => nil}
expect(Puppet::Util::Windows::ADSI::Group).to receive(:name_sid_hash).and_return(groups)
expect(provider.groups).to eq(groups.keys)
end
it "should return an empty array if there are no groups" do
allow(provider.user).to receive(:groups).and_return([])
expect(provider.groups).to eq([])
end
it 'should be able to add a user to a set of groups' do
resource[:membership] = :minimum
expect(provider.user).to receive(:set_groups).with('group1,group2', true)
provider.groups = 'group1,group2'
resource[:membership] = :inclusive
expect(provider.user).to receive(:set_groups).with('group1,group2', false)
provider.groups = 'group1,group2'
end
end
describe "when setting roles" do
context "when role_membership => minimum" do
before :each do
resource[:role_membership] = :minimum
end
it "should set the given role when user has no roles" do
allow(Puppet::Util::Windows::User).to receive(:get_rights).and_return('')
expect(Puppet::Util::Windows::User).to receive(:set_rights).with('testuser', ['givenRole1']).and_return(nil)
provider.roles = 'givenRole1'
end
it "should set only the misssing role when user already has other roles" do
allow(Puppet::Util::Windows::User).to receive(:get_rights).and_return('givenRole1')
expect(Puppet::Util::Windows::User).to receive(:set_rights).with('testuser', ['givenRole2']).and_return(nil)
provider.roles = 'givenRole1,givenRole2'
end
it "should never remove any roles" do
allow(Puppet::Util::Windows::User).to receive(:get_rights).and_return('givenRole1')
allow(Puppet::Util::Windows::User).to receive(:set_rights).and_return(nil)
expect(Puppet::Util::Windows::User).not_to receive(:remove_rights)
provider.roles = 'givenRole1,givenRole2'
end
end
context "when role_membership => inclusive" do
before :each do
resource[:role_membership] = :inclusive
end
it "should remove the unwanted role" do
allow(Puppet::Util::Windows::User).to receive(:get_rights).and_return('givenRole1,givenRole2')
expect(Puppet::Util::Windows::User).to receive(:remove_rights).with('testuser', ['givenRole2']).and_return(nil)
provider.roles = 'givenRole1'
end
it "should add the missing role and remove the unwanted one" do
allow(Puppet::Util::Windows::User).to receive(:get_rights).and_return('givenRole1,givenRole2')
expect(Puppet::Util::Windows::User).to receive(:set_rights).with('testuser', ['givenRole3']).and_return(nil)
expect(Puppet::Util::Windows::User).to receive(:remove_rights).with('testuser', ['givenRole2']).and_return(nil)
provider.roles = 'givenRole1,givenRole3'
end
it "should not set any roles when the user already has given role" do
allow(Puppet::Util::Windows::User).to receive(:get_rights).and_return('givenRole1,givenRole2')
allow(Puppet::Util::Windows::User).to receive(:remove_rights).with('testuser', ['givenRole2']).and_return(nil)
expect(Puppet::Util::Windows::User).not_to receive(:set_rights)
provider.roles = 'givenRole1'
end
it "should set the given role when user has no roles" do
allow(Puppet::Util::Windows::User).to receive(:get_rights).and_return('')
expect(Puppet::Util::Windows::User).to receive(:set_rights).with('testuser', ['givenRole1']).and_return(nil)
provider.roles = 'givenRole1'
end
it "should not remove any roles when user has no roles" do
allow(Puppet::Util::Windows::User).to receive(:get_rights).and_return('')
allow(Puppet::Util::Windows::User).to receive(:set_rights).with('testuser', ['givenRole1']).and_return(nil)
expect(Puppet::Util::Windows::User).not_to receive(:remove_rights)
provider.roles = 'givenRole1'
end
it "should remove all roles when none given" do
allow(Puppet::Util::Windows::User).to receive(:get_rights).and_return('givenRole1,givenRole2')
expect(Puppet::Util::Windows::User).not_to receive(:set_rights)
expect(Puppet::Util::Windows::User).to receive(:remove_rights).with('testuser', ['givenRole1', 'givenRole2']).and_return(nil)
provider.roles = ''
end
end
end
describe "#groups_insync?" do
let(:group1) { double(:account => 'group1', :domain => '.', :sid => 'group1sid') }
let(:group2) { double(:account => 'group2', :domain => '.', :sid => 'group2sid') }
let(:group3) { double(:account => 'group3', :domain => '.', :sid => 'group3sid') }
before :each do
allow(Puppet::Util::Windows::SID).to receive(:name_to_principal).with('group1', any_args).and_return(group1)
allow(Puppet::Util::Windows::SID).to receive(:name_to_principal).with('group2', any_args).and_return(group2)
allow(Puppet::Util::Windows::SID).to receive(:name_to_principal).with('group3', any_args).and_return(group3)
end
it "should return true for same lists of members" do
expect(provider.groups_insync?(['group1', 'group2'], ['group1', 'group2'])).to be_truthy
end
it "should return true for same lists of unordered members" do
expect(provider.groups_insync?(['group1', 'group2'], ['group2', 'group1'])).to be_truthy
end
it "should return true for same lists of members irrespective of duplicates" do
expect(provider.groups_insync?(['group1', 'group2', 'group2'], ['group2', 'group1', 'group1'])).to be_truthy
end
it "should return true when current group(s) and should group(s) are empty lists" do
expect(provider.groups_insync?([], [])).to be_truthy
end
it "should return true when current groups is empty and should groups is nil" do
expect(provider.groups_insync?([], nil)).to be_truthy
end
context "when membership => inclusive" do
before :each do
resource[:membership] = :inclusive
end
it "should return true when current and should contain the same groups in a different order" do
expect(provider.groups_insync?(['group1', 'group2', 'group3'], ['group3', 'group1', 'group2'])).to be_truthy
end
it "should return false when current contains different groups than should" do
expect(provider.groups_insync?(['group1'], ['group2'])).to be_falsey
end
it "should return false when current is nil" do
expect(provider.groups_insync?(nil, ['group2'])).to be_falsey
end
it "should return false when should is nil" do
expect(provider.groups_insync?(['group1'], nil)).to be_falsey
end
it "should return false when current contains members and should is empty" do
expect(provider.groups_insync?(['group1'], [])).to be_falsey
end
it "should return false when current is empty and should contains members" do
expect(provider.groups_insync?([], ['group2'])).to be_falsey
end
it "should return false when should groups(s) are not the only items in the current" do
expect(provider.groups_insync?(['group1', 'group2'], ['group1'])).to be_falsey
end
it "should return false when current group(s) is not empty and should is an empty list" do
expect(provider.groups_insync?(['group1','group2'], [])).to be_falsey
end
end
context "when membership => minimum" do
before :each do
# this is also the default
resource[:membership] = :minimum
end
it "should return false when current contains different groups than should" do
expect(provider.groups_insync?(['group1'], ['group2'])).to be_falsey
end
it "should return false when current is nil" do
expect(provider.groups_insync?(nil, ['group2'])).to be_falsey
end
it "should return true when should is nil" do
expect(provider.groups_insync?(['group1'], nil)).to be_truthy
end
it "should return true when current contains members and should is empty" do
expect(provider.groups_insync?(['group1'], [])).to be_truthy
end
it "should return false when current is empty and should contains members" do
expect(provider.groups_insync?([], ['group2'])).to be_falsey
end
it "should return true when current group(s) contains at least the should list" do
expect(provider.groups_insync?(['group1','group2'], ['group1'])).to be_truthy
end
it "should return true when current group(s) is not empty and should is an empty list" do
expect(provider.groups_insync?(['group1','group2'], [])).to be_truthy
end
it "should return true when current group(s) contains at least the should list, even unordered" do
expect(provider.groups_insync?(['group3','group1','group2'], ['group2','group1'])).to be_truthy
end
end
end
describe "when creating a user" do
it "should create the user on the system and set its other properties" do
resource[:groups] = ['group1', 'group2']
resource[:membership] = :inclusive
resource[:comment] = 'a test user'
resource[:home] = 'C:\Users\testuser'
user = double('user')
expect(Puppet::Util::Windows::ADSI::User).to receive(:create).with('testuser').and_return(user)
allow(user).to receive(:groups).and_return(['group2', 'group3'])
expect(user).to receive(:password=).ordered
expect(user).to receive(:commit).ordered
expect(user).to receive(:set_groups).with('group1,group2', false).ordered
expect(user).to receive(:[]=).with('Description', 'a test user')
expect(user).to receive(:[]=).with('HomeDirectory', 'C:\Users\testuser')
provider.create
end
it "should load the profile if managehome is set" do
resource[:password] = '0xDeadBeef'
resource[:managehome] = true
user = double('user')
allow(user).to receive(:password=)
allow(user).to receive(:commit)
allow(user).to receive(:[]=)
expect(Puppet::Util::Windows::ADSI::User).to receive(:create).with('testuser').and_return(user)
expect(Puppet::Util::Windows::User).to receive(:load_profile).with('testuser', '0xDeadBeef')
provider.create
end
it "should set a user's password" do
expect(provider.user).to receive(:disabled?).and_return(false)
expect(provider.user).to receive(:locked_out?).and_return(false)
expect(provider.user).to receive(:expired?).and_return(false)
expect(provider.user).to receive(:password=).with('plaintextbad')
provider.password = "plaintextbad"
end
it "should test a valid user password" do
resource[:password] = 'plaintext'
expect(provider.user).to receive(:password_is?).with('plaintext').and_return(true)
expect(provider.password).to eq('plaintext')
end
it "should test a bad user password" do
resource[:password] = 'plaintext'
expect(provider.user).to receive(:password_is?).with('plaintext').and_return(false)
expect(provider.password).to be_nil
end
it "should test a blank user password" do
resource[:password] = ''
expect(provider.user).to receive(:password_is?).with('').and_return(true)
expect(provider.password).to eq('')
end
it 'should not create a user if a group by the same name exists' do
expect(Puppet::Util::Windows::ADSI::User).to receive(:create).with('testuser').and_raise(Puppet::Error.new("Cannot create user if group 'testuser' exists."))
expect{ provider.create }.to raise_error( Puppet::Error,
/Cannot create user if group 'testuser' exists./ )
end
it "should fail with an actionable message when trying to create an active directory user" do
resource[:name] = 'DOMAIN\testdomainuser'
expect(Puppet::Util::Windows::ADSI::Group).to receive(:exists?).with(resource[:name]).and_return(false)
expect(connection).to receive(:Create)
expect(connection).to receive(:Get).with('UserFlags')
expect(connection).to receive(:Put).with('UserFlags', true)
expect(connection).to receive(:SetInfo).and_raise(WIN32OLERuntimeError.new("(in OLE method `SetInfo': )\n OLE error code:8007089A in Active Directory\n The specified username is invalid.\r\n\n HRESULT error code:0x80020009\n Exception occurred."))
expect{ provider.create }.to raise_error(Puppet::Error)
end
end
it 'should be able to test whether a user exists' do
allow(Puppet::Util::Windows::SID).to receive(:name_to_principal).and_return(nil)
allow(Puppet::Util::Windows::ADSI).to receive(:connect).and_return(double('connection', :Class => 'User'))
expect(provider).to be_exists
allow(Puppet::Util::Windows::ADSI).to receive(:connect).and_return(nil)
expect(provider).not_to be_exists
end
it 'should be able to delete a user' do
expect(connection).to receive(:Delete).with('user', 'testuser')
provider.delete
end
it 'should not run commit on a deleted user' do
expect(connection).to receive(:Delete).with('user', 'testuser')
expect(connection).not_to receive(:SetInfo)
provider.delete
provider.flush
end
it 'should delete the profile if managehome is set' do
resource[:managehome] = true
sid = 'S-A-B-C'
expect(Puppet::Util::Windows::SID).to receive(:name_to_sid).with('testuser').and_return(sid)
expect(Puppet::Util::Windows::ADSI::UserProfile).to receive(:delete).with(sid)
expect(connection).to receive(:Delete).with('user', 'testuser')
provider.delete
end
it "should commit the user when flushed" do
expect(provider.user).to receive(:commit)
provider.flush
end
it "should return the user's SID as uid" do
expect(Puppet::Util::Windows::SID).to receive(:name_to_sid).with('testuser').and_return('S-1-5-21-1362942247-2130103807-3279964888-1111')
expect(provider.uid).to eq('S-1-5-21-1362942247-2130103807-3279964888-1111')
end
it "should fail when trying to manage the uid property" do
expect(provider).to receive(:fail).with(/uid is read-only/)
provider.send(:uid=, 500)
end
[:gid, :shell].each do |prop|
it "should fail when trying to manage the #{prop} property" do
expect(provider).to receive(:fail).with(/No support for managing property #{prop}/)
provider.send("#{prop}=", 'foo')
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/provider/user/useradd_spec.rb | spec/unit/provider/user/useradd_spec.rb | require 'spec_helper'
RSpec::Matchers.define_negated_matcher :excluding, :include
describe Puppet::Type.type(:user).provider(:useradd) do
before :each do
allow(Puppet::Util::POSIX).to receive(:groups_of).and_return([])
allow(described_class).to receive(:command).with(:password).and_return('/usr/bin/chage')
allow(described_class).to receive(:command).with(:localpassword).and_return('/usr/sbin/lchage')
allow(described_class).to receive(:command).with(:add).and_return('/usr/sbin/useradd')
allow(described_class).to receive(:command).with(:localadd).and_return('/usr/sbin/luseradd')
allow(described_class).to receive(:command).with(:modify).and_return('/usr/sbin/usermod')
allow(described_class).to receive(:command).with(:localmodify).and_return('/usr/sbin/lusermod')
allow(described_class).to receive(:command).with(:delete).and_return('/usr/sbin/userdel')
allow(described_class).to receive(:command).with(:localdelete).and_return('/usr/sbin/luserdel')
allow(described_class).to receive(:command).with(:chpasswd).and_return('/usr/sbin/chpasswd')
end
let(:resource) do
Puppet::Type.type(:user).new(
:name => 'myuser',
:managehome => :false,
:system => :false,
:provider => provider
)
end
let(:provider) { described_class.new(:name => 'myuser') }
let(:shadow_entry) {
return unless Puppet.features.libshadow?
entry = Etc::PasswdEntry.new
entry[:sp_namp] = 'myuser' # login name
entry[:sp_pwdp] = '$6$FvW8Ib8h$qQMI/CR9m.QzIicZKutLpBgCBBdrch1IX0rTnxuI32K1pD9.RXZrmeKQlaC.RzODNuoUtPPIyQDufunvLOQWF0' # encrypted password
entry[:sp_lstchg] = 15573 # date of last password change
entry[:sp_min] = 10 # minimum password age
entry[:sp_max] = 20 # maximum password age
entry[:sp_warn] = 7 # password warning period
entry[:sp_inact] = -1 # password inactivity period
entry[:sp_expire] = 15706 # account expiration date
entry
}
describe "#create" do
before do
allow(provider).to receive(:exists?).and_return(false)
end
it "should not redact the command from debug logs if there is no password" do
described_class.has_feature :manages_passwords
resource[:ensure] = :present
expect(provider).to receive(:execute).with(kind_of(Array), hash_including(sensitive: false))
provider.create
end
it "should redact the command from debug logs if there is a password" do
described_class.has_feature :manages_passwords
resource2 = Puppet::Type.type(:user).new(
:name => 'myuser',
:password => 'a pass word',
:managehome => :false,
:system => :false,
:provider => provider,
)
resource2[:ensure] = :present
expect(provider).to receive(:execute).with(kind_of(Array), hash_including(sensitive: true)).twice
provider.create
end
it "should add -g when no gid is specified and group already exists" do
allow(Puppet::Util).to receive(:gid).and_return(true)
resource[:ensure] = :present
expect(provider).to receive(:execute).with(include('-g'), kind_of(Hash))
provider.create
end
context "when setting groups" do
it "uses -G to set groups" do
allow(Facter).to receive(:value).with('os.family').and_return('Solaris')
allow(Facter).to receive(:value).with('os.release.major')
resource[:ensure] = :present
resource[:groups] = ['group1', 'group2']
expect(provider).to receive(:execute).with(['/usr/sbin/useradd', '-G', 'group1,group2', 'myuser'], kind_of(Hash))
provider.create
end
it "uses -G to set groups with -M on supported systems" do
allow(Facter).to receive(:value).with('os.family').and_return('RedHat')
allow(Facter).to receive(:value).with('os.release.major')
resource[:ensure] = :present
resource[:groups] = ['group1', 'group2']
expect(provider).to receive(:execute).with(['/usr/sbin/useradd', '-G', 'group1,group2', '-M', 'myuser'], kind_of(Hash))
provider.create
end
end
it "should add -o when allowdupe is enabled and the user is being created" do
resource[:allowdupe] = true
expect(provider).to receive(:execute).with(include('-o'), kind_of(Hash))
provider.create
end
describe "on systems that support has_system", :if => described_class.system_users? do
it "should add -r when system is enabled" do
resource[:system] = :true
expect(provider).to be_system_users
expect(provider).to receive(:execute).with(include('-r'), kind_of(Hash))
provider.create
end
end
describe "on systems that do not support has_system", :unless => described_class.system_users? do
it "should not add -r when system is enabled" do
resource[:system] = :true
expect(provider).not_to be_system_users
expect(provider).to receive(:execute).with(['/usr/sbin/useradd', 'myuser'], kind_of(Hash))
provider.create
end
end
it "should set password age rules" do
described_class.has_feature :manages_password_age
resource[:password_min_age] = 5
resource[:password_max_age] = 10
resource[:password_warn_days] = 15
expect(provider).to receive(:execute).with(include('/usr/sbin/useradd'), kind_of(Hash))
expect(provider).to receive(:execute).with(['/usr/bin/chage', '-m', 5, '-M', 10, '-W', 15, 'myuser'], hash_including(failonfail: true, combine: true, custom_environment: {}))
provider.create
end
describe "on systems with the libuser and forcelocal=true" do
before do
described_class.has_feature :manages_local_users_and_groups
resource[:forcelocal] = true
end
it "should use luseradd instead of useradd" do
expect(provider).to receive(:execute).with(include('/usr/sbin/luseradd'), hash_including(custom_environment: hash_including('LIBUSER_CONF')))
provider.create
end
it "should NOT use -o when allowdupe=true" do
resource[:allowdupe] = :true
expect(provider).to receive(:execute).with(excluding('-o'), hash_including(custom_environment: hash_including('LIBUSER_CONF')))
provider.create
end
it "should raise an exception for duplicate UIDs" do
resource[:uid] = 505
allow(provider).to receive(:finduser).and_return(true)
expect { provider.create }.to raise_error(Puppet::Error, "UID 505 already exists, use allowdupe to force user creation")
end
it "should not use -G for luseradd and should call usermod with -G after luseradd when groups property is set" do
resource[:groups] = ['group1', 'group2']
allow(provider).to receive(:localgroups)
expect(provider).to receive(:execute).with(include('/usr/sbin/luseradd').and(excluding('-G')), hash_including(custom_environment: hash_including('LIBUSER_CONF')))
expect(provider).to receive(:execute).with(include('/usr/sbin/usermod').and(include('-G')), hash_including(custom_environment: hash_including('LIBUSER_CONF')))
provider.create
end
it "should not use -m when managehome set" do
resource[:managehome] = :true
expect(provider).to receive(:execute).with(excluding('-m'), hash_including(custom_environment: hash_including('LIBUSER_CONF')))
provider.create
end
it "should not use -e with luseradd, should call usermod with -e after luseradd when expiry is set" do
resource[:expiry] = '2038-01-24'
expect(provider).to receive(:execute).with(include('/usr/sbin/luseradd').and(excluding('-e')), hash_including(custom_environment: hash_including('LIBUSER_CONF')))
expect(provider).to receive(:execute).with(include('/usr/sbin/usermod').and(include('-e')), hash_including(custom_environment: hash_including('LIBUSER_CONF')))
provider.create
end
it 'should set password age rules locally' do
described_class.has_feature :manages_password_age
resource[:password_min_age] = 5
resource[:password_max_age] = 10
resource[:password_warn_days] = 15
expect(provider).to receive(:execute).with(include('/usr/sbin/luseradd'), hash_including(custom_environment: hash_including('LIBUSER_CONF')))
expect(provider).to receive(:execute).with(['/usr/sbin/lchage', '-m', 5, '-M', 10, '-W', 15, 'myuser'], hash_including(custom_environment: hash_including('LIBUSER_CONF')))
provider.create
end
end
describe "on systems that allow to set shell" do
it "should trigger shell validation" do
resource[:shell] = '/bin/bash'
expect(provider).to receive(:check_valid_shell)
expect(provider).to receive(:execute).with(include('-s'), kind_of(Hash))
provider.create
end
end
end
describe 'when modifying the password' do
before do
described_class.has_feature :manages_local_users_and_groups
described_class.has_feature :manages_passwords
#Setting any resource value here initializes needed variables and methods in the resource and provider
#Setting a password value here initializes the existence and management of the password parameter itself
#Otherwise, this value would not need to be initialized for the test
resource[:password] = ''
end
it "should not call execute with sensitive if non-sensitive data is changed" do
expect(provider).to receive(:execute).with(kind_of(Array), hash_including(sensitive: false))
provider.home = 'foo/bar'
end
it "should call execute with sensitive if sensitive data is changed" do
expect(provider).to receive(:execute).with(kind_of(Array), hash_including(sensitive: true)).and_return('')
provider.password = 'bird bird bird'
end
end
describe '#modify' do
describe "on systems with the libuser and forcelocal=false" do
before do
described_class.has_feature :manages_local_users_and_groups
resource[:forcelocal] = false
end
it "should use usermod" do
expect(provider).to receive(:execute).with(['/usr/sbin/usermod', '-u', 150, 'myuser'], hash_including(failonfail: true, combine: true, custom_environment: {}))
provider.uid = 150
end
it "should use -o when allowdupe=true" do
resource[:allowdupe] = :true
expect(provider).to receive(:execute).with(include('-o'), hash_including(failonfail: true, combine: true, custom_environment: {}))
provider.uid = 505
end
it 'should use chage for password_min_age' do
expect(provider).to receive(:execute).with(['/usr/bin/chage', '-m', 100, 'myuser'], hash_including(failonfail: true, combine: true, custom_environment: {}))
provider.password_min_age = 100
end
it 'should use chage for password_max_age' do
expect(provider).to receive(:execute).with(['/usr/bin/chage', '-M', 101, 'myuser'], hash_including(failonfail: true, combine: true, custom_environment: {}))
provider.password_max_age = 101
end
it 'should use chage for password_warn_days' do
expect(provider).to receive(:execute).with(['/usr/bin/chage', '-W', 99, 'myuser'], hash_including(failonfail: true, combine: true, custom_environment: {}))
provider.password_warn_days = 99
end
it 'should not call check_allow_dup if not modifying the uid' do
expect(provider).not_to receive(:check_allow_dup)
expect(provider).to receive(:execute)
provider.home = 'foo/bar'
end
end
describe "on systems with the libuser and forcelocal=true" do
before do
described_class.has_feature :libuser
resource[:forcelocal] = true
end
it "should use lusermod and not usermod" do
expect(provider).to receive(:execute).with(['/usr/sbin/lusermod', '-u', 150, 'myuser'], hash_including(custom_environment: hash_including('LIBUSER_CONF')))
provider.uid = 150
end
it "should NOT use -o when allowdupe=true" do
resource[:allowdupe] = :true
expect(provider).to receive(:execute).with(excluding('-o'), hash_including(custom_environment: hash_including('LIBUSER_CONF')))
provider.uid = 505
end
it "should raise an exception for duplicate UIDs" do
resource[:uid] = 505
allow(provider).to receive(:finduser).and_return(true)
expect { provider.uid = 505 }.to raise_error(Puppet::Error, "UID 505 already exists, use allowdupe to force user creation")
end
it 'should use lchage for password_warn_days' do
expect(provider).to receive(:execute).with(['/usr/sbin/lchage', '-W', 99, 'myuser'], hash_including(custom_environment: hash_including('LIBUSER_CONF')))
provider.password_warn_days = 99
end
it 'should use lchage for password_min_age' do
expect(provider).to receive(:execute).with(['/usr/sbin/lchage', '-m', 100, 'myuser'], hash_including(custom_environment: hash_including('LIBUSER_CONF')))
provider.password_min_age = 100
end
it 'should use lchage for password_max_age' do
expect(provider).to receive(:execute).with(['/usr/sbin/lchage', '-M', 101, 'myuser'], hash_including(custom_environment: hash_including('LIBUSER_CONF')))
provider.password_max_age = 101
end
end
end
describe "#uid=" do
it "should add -o when allowdupe is enabled and the uid is being modified" do
resource[:allowdupe] = :true
expect(provider).to receive(:execute).with(['/usr/sbin/usermod', '-u', 150, '-o', 'myuser'], hash_including(custom_environment: {}))
provider.uid = 150
end
end
describe "#expiry=" do
it "should pass expiry to usermod as MM/DD/YY when on Solaris" do
expect(Facter).to receive(:value).with('os.name').and_return('Solaris')
resource[:expiry] = '2012-10-31'
expect(provider).to receive(:execute).with(['/usr/sbin/usermod', '-e', '10/31/2012', 'myuser'], hash_including(custom_environment: {}))
provider.expiry = '2012-10-31'
end
it "should pass expiry to usermod as YYYY-MM-DD when not on Solaris" do
expect(Facter).to receive(:value).with('os.name').and_return('not_solaris')
resource[:expiry] = '2012-10-31'
expect(provider).to receive(:execute).with(['/usr/sbin/usermod', '-e', '2012-10-31', 'myuser'], hash_including(custom_environment: {}))
provider.expiry = '2012-10-31'
end
it "should use -e with an empty string when the expiry property is removed" do
resource[:expiry] = :absent
expect(provider).to receive(:execute).with(['/usr/sbin/usermod', '-e', '', 'myuser'], hash_including(custom_environment: {}))
provider.expiry = :absent
end
it "should use -e with -1 when the expiry property is removed on SLES11" do
allow(Facter).to receive(:value).with('os.name').and_return('SLES')
allow(Facter).to receive(:value).with('os.release.major').and_return('11')
resource[:expiry] = :absent
expect(provider).to receive(:execute).with(['/usr/sbin/usermod', '-e', -1, 'myuser'], hash_including(custom_environment: {}))
provider.expiry = :absent
end
end
describe "#comment" do
before { described_class.has_feature :manages_local_users_and_groups }
let(:content) { "myuser:x:x:x:local comment:x:x" }
it "should return the local comment string when forcelocal is true" do
resource[:forcelocal] = true
allow(Puppet::FileSystem).to receive(:exist?).with('/etc/passwd').and_return(true)
allow(Puppet::FileSystem).to receive(:each_line).with('/etc/passwd').and_yield(content)
expect(provider.comment).to eq('local comment')
end
it "should fall back to nameservice comment string when forcelocal is false" do
resource[:forcelocal] = false
allow(provider).to receive(:get).with(:comment).and_return('remote comment')
expect(provider).not_to receive(:localcomment)
expect(provider.comment).to eq('remote comment')
end
end
describe "#shell" do
before { described_class.has_feature :manages_local_users_and_groups }
let(:content) { "myuser:x:x:x:x:x:/bin/local_shell" }
it "should return the local shell string when forcelocal is true" do
resource[:forcelocal] = true
allow(Puppet::FileSystem).to receive(:exist?).with('/etc/passwd').and_return(true)
allow(Puppet::FileSystem).to receive(:each_line).with('/etc/passwd').and_yield(content)
expect(provider.shell).to eq('/bin/local_shell')
end
it "should fall back to nameservice shell string when forcelocal is false" do
resource[:forcelocal] = false
allow(provider).to receive(:get).with(:shell).and_return('/bin/remote_shell')
expect(provider).not_to receive(:localshell)
expect(provider.shell).to eq('/bin/remote_shell')
end
end
describe "#home" do
before { described_class.has_feature :manages_local_users_and_groups }
let(:content) { "myuser:x:x:x:x:/opt/local_home:x" }
it "should return the local home string when forcelocal is true" do
resource[:forcelocal] = true
allow(Puppet::FileSystem).to receive(:exist?).with('/etc/passwd').and_return(true)
allow(Puppet::FileSystem).to receive(:each_line).with('/etc/passwd').and_yield(content)
expect(provider.home).to eq('/opt/local_home')
end
it "should fall back to nameservice home string when forcelocal is false" do
resource[:forcelocal] = false
allow(provider).to receive(:get).with(:home).and_return('/opt/remote_home')
expect(provider).not_to receive(:localhome)
expect(provider.home).to eq('/opt/remote_home')
end
end
describe "#gid" do
before { described_class.has_feature :manages_local_users_and_groups }
let(:content) { "myuser:x:x:999:x:x:x" }
it "should return the local GID when forcelocal is true" do
resource[:forcelocal] = true
allow(Puppet::FileSystem).to receive(:exist?).with('/etc/passwd').and_return(true)
allow(Puppet::FileSystem).to receive(:each_line).with('/etc/passwd').and_yield(content)
expect(provider.gid).to eq(999)
end
it "should fall back to nameservice GID when forcelocal is false" do
resource[:forcelocal] = false
allow(provider).to receive(:get).with(:gid).and_return(1234)
expect(provider).not_to receive(:localgid)
expect(provider.gid).to eq(1234)
end
end
describe "#groups" do
before { described_class.has_feature :manages_local_users_and_groups }
let(:content) do
StringIO.new(<<~EOF)
group1:x:0:myuser
group2:x:999:
group3:x:998:myuser
EOF
end
let(:content_with_empty_line) do
StringIO.new(<<~EOF)
group1:x:0:myuser
group2:x:999:
group3:x:998:myuser
EOF
end
it "should return the local groups string when forcelocal is true" do
resource[:forcelocal] = true
allow(Puppet::FileSystem).to receive(:exist?).with('/etc/group').and_return(true)
allow(File).to receive(:open).with(Pathname.new('/etc/group')).and_yield(content)
expect(provider.groups).to eq(['group1', 'group3'])
end
it "does not raise when parsing empty lines in /etc/group" do
resource[:forcelocal] = true
allow(Puppet::FileSystem).to receive(:exist?).with('/etc/group').and_return(true)
allow(File).to receive(:open).with(Pathname.new('/etc/group')).and_yield(content_with_empty_line)
expect { provider.groups }.not_to raise_error
end
it "should fall back to nameservice groups when forcelocal is false" do
resource[:forcelocal] = false
allow(Puppet::Util::POSIX).to receive(:groups_of).with('myuser').and_return(['remote groups'])
expect(provider).not_to receive(:localgroups)
expect(provider.groups).to eq('remote groups')
end
end
describe "#finduser" do
before do
allow(Puppet::FileSystem).to receive(:exist?).with('/etc/passwd').and_return(true)
allow(Puppet::FileSystem).to receive(:each_line).with('/etc/passwd').and_yield(content)
end
let(:content) { "sample_account:sample_password:sample_uid:sample_gid:sample_gecos:sample_directory:sample_shell" }
let(:output) do
{
account: 'sample_account',
password: 'sample_password',
uid: 'sample_uid',
gid: 'sample_gid',
gecos: 'sample_gecos',
directory: 'sample_directory',
shell: 'sample_shell',
}
end
[:account, :password, :uid, :gid, :gecos, :directory, :shell].each do |key|
it "finds an user by #{key} when asked" do
expect(provider.finduser(key, "sample_#{key}")).to eq(output)
end
end
it "returns false when specified key/value pair is not found" do
expect(provider.finduser(:account, 'invalid_account')).to eq(false)
end
it "reads the user file only once per resource" do
expect(Puppet::FileSystem).to receive(:each_line).with('/etc/passwd').once
5.times { provider.finduser(:account, 'sample_account') }
end
end
describe "#check_allow_dup" do
it "should return an array with a flag if dup is allowed" do
resource[:allowdupe] = :true
expect(provider.check_allow_dup).to eq(["-o"])
end
it "should return an empty array if no dup is allowed" do
resource[:allowdupe] = :false
expect(provider.check_allow_dup).to eq([])
end
end
describe "#check_system_users" do
it "should check system users" do
expect(described_class).to receive(:system_users?).and_return(true)
expect(resource).to receive(:system?)
provider.check_system_users
end
it "should return an array with a flag if it's a system user" do
expect(described_class).to receive(:system_users?).and_return(true)
resource[:system] = :true
expect(provider.check_system_users).to eq(["-r"])
end
it "should return an empty array if it's not a system user" do
expect(described_class).to receive(:system_users?).and_return(true)
resource[:system] = :false
expect(provider.check_system_users).to eq([])
end
it "should return an empty array if system user is not featured" do
expect(described_class).to receive(:system_users?).and_return(false)
resource[:system] = :true
expect(provider.check_system_users).to eq([])
end
end
describe "#check_manage_home" do
it "should return an array with -m flag if home is managed" do
resource[:managehome] = :true
expect(provider).to receive(:execute).with(include('-m'), hash_including(custom_environment: {}))
provider.create
end
it "should return an array with -r flag if home is managed" do
resource[:managehome] = :true
resource[:ensure] = :absent
allow(provider).to receive(:exists?).and_return(true)
expect(provider).to receive(:execute).with(include('-r'), hash_including(custom_environment: {}))
provider.delete
end
it "should use -M flag if home is not managed on a supported system" do
allow(Facter).to receive(:value).with('os.family').and_return("RedHat")
allow(Facter).to receive(:value).with('os.release.major')
resource[:managehome] = :false
expect(provider).to receive(:execute).with(include('-M'), kind_of(Hash))
provider.create
end
it "should not use -M flag if home is not managed on an unsupported system" do
allow(Facter).to receive(:value).with('os.family').and_return("Suse")
allow(Facter).to receive(:value).with('os.release.major').and_return("11")
resource[:managehome] = :false
expect(provider).to receive(:execute).with(excluding('-M'), kind_of(Hash))
provider.create
end
end
describe "#addcmd" do
before do
resource[:allowdupe] = :true
resource[:managehome] = :true
resource[:system] = :true
resource[:groups] = [ 'somegroup' ]
end
it "should call command with :add" do
expect(provider).to receive(:command).with(:add)
provider.addcmd
end
it "should add properties" do
expect(provider).to receive(:add_properties).and_return(['-foo_add_properties'])
expect(provider.addcmd).to include '-foo_add_properties'
end
it "should check and add if dup allowed" do
expect(provider).to receive(:check_allow_dup).and_return(['-allow_dup_flag'])
expect(provider.addcmd).to include '-allow_dup_flag'
end
it "should check and add if home is managed" do
expect(provider).to receive(:check_manage_home).and_return(['-manage_home_flag'])
expect(provider.addcmd).to include '-manage_home_flag'
end
it "should add the resource :name" do
expect(provider.addcmd).to include 'myuser'
end
describe "on systems featuring system_users", :if => described_class.system_users? do
it "should return an array with -r if system? is true" do
resource[:system] = :true
expect(provider.addcmd).to include("-r")
end
it "should return an array without -r if system? is false" do
resource[:system] = :false
expect(provider.addcmd).not_to include("-r")
end
end
describe "on systems not featuring system_users", :unless => described_class.system_users? do
[:false, :true].each do |system|
it "should return an array without -r if system? is #{system}" do
resource[:system] = system
expect(provider.addcmd).not_to include("-r")
end
end
end
it "should return an array with the full command and expiry as MM/DD/YY when on Solaris" do
allow(Facter).to receive(:value).with('os.name').and_return('Solaris')
expect(described_class).to receive(:system_users?).and_return(true)
resource[:expiry] = "2012-08-18"
expect(provider.addcmd).to eq(['/usr/sbin/useradd', '-e', '08/18/2012', '-G', 'somegroup', '-o', '-m', '-r', 'myuser'])
end
it "should return an array with the full command and expiry as YYYY-MM-DD when not on Solaris" do
allow(Facter).to receive(:value).with('os.name').and_return('not_solaris')
expect(described_class).to receive(:system_users?).and_return(true)
resource[:expiry] = "2012-08-18"
expect(provider.addcmd).to eq(['/usr/sbin/useradd', '-e', '2012-08-18', '-G', 'somegroup', '-o', '-m', '-r', 'myuser'])
end
it "should return an array without -e if expiry is undefined full command" do
expect(described_class).to receive(:system_users?).and_return(true)
expect(provider.addcmd).to eq(["/usr/sbin/useradd", "-G", "somegroup", "-o", "-m", "-r", "myuser"])
end
it "should pass -e \"\" if the expiry has to be removed" do
expect(described_class).to receive(:system_users?).and_return(true)
resource[:expiry] = :absent
expect(provider.addcmd).to eq(['/usr/sbin/useradd', '-e', '', '-G', 'somegroup', '-o', '-m', '-r', 'myuser'])
end
it "should use lgroupadd with forcelocal=true" do
resource[:forcelocal] = :true
expect(provider.addcmd[0]).to eq('/usr/sbin/luseradd')
end
it "should not pass -o with forcelocal=true and allowdupe=true" do
resource[:forcelocal] = :true
resource[:allowdupe] = :true
expect(provider.addcmd).not_to include("-o")
end
context 'when forcelocal=true' do
before do
resource[:forcelocal] = :true
end
it 'does not pass lchage options to luseradd for password_max_age' do
resource[:password_max_age] = 100
expect(provider.addcmd).not_to include('-M')
end
it 'does not pass lchage options to luseradd for password_min_age' do
resource[:managehome] = false # This needs to be set so that we don't pass in -m to create the home
resource[:password_min_age] = 100
expect(provider.addcmd).not_to include('-m')
end
it 'does not pass lchage options to luseradd for password_warn_days' do
resource[:password_warn_days] = 100
expect(provider.addcmd).not_to include('-W')
end
end
end
{
:password_min_age => 10,
:password_max_age => 20,
:password_warn_days => 30,
:password => '$6$FvW8Ib8h$qQMI/CR9m.QzIicZKutLpBgCBBdrch1IX0rTnxuI32K1pD9.RXZrmeKQlaC.RzODNuoUtPPIyQDufunvLOQWF0'
}.each_pair do |property, expected_value|
describe "##{property}" do
before :each do
resource # just to link the resource to the provider
end
it "should return absent if libshadow feature is not present" do
allow(Puppet.features).to receive(:libshadow?).and_return(false)
# Shadow::Passwd.expects(:getspnam).never # if we really don't have libshadow we dont have Shadow::Passwd either
expect(provider.send(property)).to eq(:absent)
end
it "should return absent if user cannot be found", :if => Puppet.features.libshadow? do
expect(Shadow::Passwd).to receive(:getspnam).with('myuser').and_return(nil)
expect(provider.send(property)).to eq(:absent)
end
it "should return the correct value if libshadow is present", :if => Puppet.features.libshadow? do
expect(Shadow::Passwd).to receive(:getspnam).with('myuser').and_return(shadow_entry)
expect(provider.send(property)).to eq(expected_value)
end
# nameservice provider instances are initialized with a @canonical_name
# instance variable to track the original name of the instance on disk
# before converting it to UTF-8 if appropriate. When re-querying the
# system for attributes of this user such as password info, we need to
# supply the pre-UTF8-converted value.
it "should query using the canonical_name attribute of the user", :if => Puppet.features.libshadow? do
canonical_name = [253, 241].pack('C*').force_encoding(Encoding::EUC_KR)
provider = described_class.new(:name => '??', :canonical_name => canonical_name)
expect(Shadow::Passwd).to receive(:getspnam).with(canonical_name).and_return(shadow_entry)
provider.password
end
end
end
describe '#expiry' do
before :each do
resource # just to link the resource to the provider
end
it "should return absent if libshadow feature is not present" do
allow(Puppet.features).to receive(:libshadow?).and_return(false)
expect(provider.expiry).to eq(:absent)
end
it "should return absent if user cannot be found", :if => Puppet.features.libshadow? do
expect(Shadow::Passwd).to receive(:getspnam).with('myuser').and_return(nil)
expect(provider.expiry).to eq(:absent)
end
it "should return absent if expiry is -1", :if => Puppet.features.libshadow? do
shadow_entry.sp_expire = -1
expect(Shadow::Passwd).to receive(:getspnam).with('myuser').and_return(shadow_entry)
expect(provider.expiry).to eq(:absent)
end
it "should convert to YYYY-MM-DD", :if => Puppet.features.libshadow? do
expect(Shadow::Passwd).to receive(:getspnam).with('myuser').and_return(shadow_entry)
expect(provider.expiry).to eq('2013-01-01')
end
end
describe "#passcmd" do
before do
resource[:allowdupe] = :true
resource[:managehome] = :true
resource[:system] = :true
described_class.has_feature :manages_password_age
end
it "should call command with :pass" do
# command(:password) is only called inside passcmd if
# password_min_age or password_max_age is set
resource[:password_min_age] = 123
expect(provider).to receive(:command).with(:password)
provider.passcmd
end
it "should return nil if neither min nor max is set" do
expect(provider.passcmd).to be_nil
end
it "should return a chage command array with -m <value> and the user name if password_min_age is set" do
resource[:password_min_age] = 123
expect(provider.passcmd).to eq(['/usr/bin/chage', '-m', 123, 'myuser'])
end
it "should return a chage command array with -M <value> if password_max_age is set" do
resource[:password_max_age] = 999
expect(provider.passcmd).to eq(['/usr/bin/chage', '-M', 999, 'myuser'])
end
it "should return a chage command array with -W <value> if password_warn_days is set" do
resource[:password_warn_days] = 999
expect(provider.passcmd).to eq(['/usr/bin/chage', '-W', 999, 'myuser'])
end
it "should return a chage command array with -M <value> -m <value> if both password_min_age and password_max_age are set" do
resource[:password_min_age] = 123
resource[:password_max_age] = 999
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | true |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/provider/user/user_role_add_spec.rb | spec/unit/provider/user/user_role_add_spec.rb | require 'spec_helper'
require 'puppet_spec/files'
require 'tempfile'
describe Puppet::Type.type(:user).provider(:user_role_add), :unless => Puppet::Util::Platform.windows? do
include PuppetSpec::Files
let(:resource) { Puppet::Type.type(:user).new(:name => 'myuser', :managehome => false, :allowdupe => false) }
let(:provider) { described_class.new(resource) }
before do
allow(resource).to receive(:should).and_return("fakeval")
allow(resource).to receive(:should).with(:keys).and_return(Hash.new)
allow(resource).to receive(:[]).and_return("fakeval")
end
describe "#command" do
before do
klass = double("provider")
allow(klass).to receive(:superclass)
allow(klass).to receive(:command).with(:foo).and_return("userfoo")
allow(klass).to receive(:command).with(:role_foo).and_return("rolefoo")
allow(provider).to receive(:class).and_return(klass)
end
it "should use the command if not a role and ensure!=role" do
allow(provider).to receive(:is_role?).and_return(false)
allow(provider).to receive(:exists?).and_return(false)
allow(resource).to receive(:[]).with(:ensure).and_return(:present)
allow(provider.class).to receive(:foo)
expect(provider.command(:foo)).to eq("userfoo")
end
it "should use the role command when a role" do
allow(provider).to receive(:is_role?).and_return(true)
expect(provider.command(:foo)).to eq("rolefoo")
end
it "should use the role command when !exists and ensure=role" do
allow(provider).to receive(:is_role?).and_return(false)
allow(provider).to receive(:exists?).and_return(false)
allow(resource).to receive(:[]).with(:ensure).and_return(:role)
expect(provider.command(:foo)).to eq("rolefoo")
end
end
describe "#transition" do
it "should return the type set to whatever is passed in" do
expect(provider).to receive(:command).with(:modify).and_return("foomod")
provider.transition("bar").include?("type=bar")
end
end
describe "#create" do
before do
allow(provider).to receive(:password=)
end
it "should use the add command when the user is not a role" do
allow(provider).to receive(:is_role?).and_return(false)
expect(provider).to receive(:addcmd).and_return("useradd")
expect(provider).to receive(:run).at_least(:once)
provider.create
end
it "should use transition(normal) when the user is a role" do
allow(provider).to receive(:is_role?).and_return(true)
expect(provider).to receive(:transition).with("normal")
expect(provider).to receive(:run)
provider.create
end
it "should set password age rules" do
resource = Puppet::Type.type(:user).new :name => "myuser", :password_min_age => 5, :password_max_age => 10, :password_warn_days => 15, :provider => :user_role_add
provider = described_class.new(resource)
allow(provider).to receive(:user_attributes)
allow(provider).to receive(:execute)
expect(provider).to receive(:execute).with([anything, "-n", 5, "-x", 10, '-w', 15, "myuser"])
provider.create
end
end
describe "#destroy" do
it "should use the delete command if the user exists and is not a role" do
allow(provider).to receive(:exists?).and_return(true)
allow(provider).to receive(:is_role?).and_return(false)
expect(provider).to receive(:deletecmd)
expect(provider).to receive(:run)
provider.destroy
end
it "should use the delete command if the user is a role" do
allow(provider).to receive(:exists?).and_return(true)
allow(provider).to receive(:is_role?).and_return(true)
expect(provider).to receive(:deletecmd)
expect(provider).to receive(:run)
provider.destroy
end
end
describe "#create_role" do
it "should use the transition(role) if the user exists" do
allow(provider).to receive(:exists?).and_return(true)
allow(provider).to receive(:is_role?).and_return(false)
expect(provider).to receive(:transition).with("role")
expect(provider).to receive(:run)
provider.create_role
end
it "should use the add command when role doesn't exists" do
allow(provider).to receive(:exists?).and_return(false)
expect(provider).to receive(:addcmd)
expect(provider).to receive(:run)
provider.create_role
end
end
describe "with :allow_duplicates" do
before do
allow(resource).to receive(:allowdupe?).and_return(true)
allow(provider).to receive(:is_role?).and_return(false)
allow(provider).to receive(:execute)
allow(resource).to receive(:system?).and_return(false)
expect(provider).to receive(:execute).with(include("-o"), any_args)
end
it "should add -o when the user is being created" do
allow(provider).to receive(:password=)
provider.create
end
it "should add -o when the uid is being modified" do
provider.uid = 150
end
end
[:roles, :auths, :profiles].each do |val|
context "#send" do
describe "when getting #{val}" do
it "should get the user_attributes" do
expect(provider).to receive(:user_attributes)
provider.send(val)
end
it "should get the #{val} attribute" do
attributes = double("attributes")
expect(attributes).to receive(:[]).with(val)
allow(provider).to receive(:user_attributes).and_return(attributes)
provider.send(val)
end
end
end
end
describe "#keys" do
it "should get the user_attributes" do
expect(provider).to receive(:user_attributes)
provider.keys
end
it "should call removed_managed_attributes" do
allow(provider).to receive(:user_attributes).and_return({ :type => "normal", :foo => "something" })
expect(provider).to receive(:remove_managed_attributes)
provider.keys
end
it "should removed managed attribute (type, auths, roles, etc)" do
allow(provider).to receive(:user_attributes).and_return({ :type => "normal", :foo => "something" })
expect(provider.keys).to eq({ :foo => "something" })
end
end
describe "#add_properties" do
it "should call build_keys_cmd" do
allow(resource).to receive(:should).and_return("")
expect(resource).to receive(:should).with(:keys).and_return({ :foo => "bar" })
expect(provider).to receive(:build_keys_cmd).and_return([])
provider.add_properties
end
it "should add the elements of the keys hash to an array" do
allow(resource).to receive(:should).and_return("")
expect(resource).to receive(:should).with(:keys).and_return({ :foo => "bar"})
expect(provider.add_properties).to eq(["-K", "foo=bar"])
end
end
describe "#build_keys_cmd" do
it "should build cmd array with keypairs separated by -K ending with user" do
expect(provider.build_keys_cmd({"foo" => "bar", "baz" => "boo"})).to eq(["-K", "foo=bar", "-K", "baz=boo"])
end
end
describe "#keys=" do
before do
allow(provider).to receive(:is_role?).and_return(false)
end
it "should run a command" do
expect(provider).to receive(:run)
provider.keys=({})
end
it "should build the command" do
allow(resource).to receive(:[]).with(:name).and_return("someuser")
allow(provider).to receive(:command).and_return("usermod")
expect(provider).to receive(:build_keys_cmd).and_return(["-K", "foo=bar"])
expect(provider).to receive(:run).with(["usermod", "-K", "foo=bar", "someuser"], "modify attribute key pairs")
provider.keys=({})
end
end
describe "#password" do
before do
@array = double("array")
end
it "should readlines of /etc/shadow" do
expect(File).to receive(:readlines).with("/etc/shadow").and_return([])
provider.password
end
it "should reject anything that doesn't start with alpha numerics" do
expect(@array).to receive(:reject).and_return([])
allow(File).to receive(:readlines).with("/etc/shadow").and_return(@array)
provider.password
end
it "should collect splitting on ':'" do
allow(@array).to receive(:reject).and_return(@array)
expect(@array).to receive(:collect).and_return([])
allow(File).to receive(:readlines).with("/etc/shadow").and_return(@array)
provider.password
end
it "should find the matching user" do
allow(resource).to receive(:[]).with(:name).and_return("username")
allow(@array).to receive(:reject).and_return(@array)
allow(@array).to receive(:collect).and_return([["username", "hashedpassword"], ["someoneelse", "theirpassword"]])
allow(File).to receive(:readlines).with("/etc/shadow").and_return(@array)
expect(provider.password).to eq("hashedpassword")
end
it "should get the right password" do
allow(resource).to receive(:[]).with(:name).and_return("username")
allow(File).to receive(:readlines).with("/etc/shadow").and_return(["#comment", " nonsense", " ", "username:hashedpassword:stuff:foo:bar:::", "other:pword:yay:::"])
expect(provider.password).to eq("hashedpassword")
end
end
describe "#password=" do
let(:path) { tmpfile('etc-shadow') }
before :each do
allow(provider).to receive(:target_file_path).and_return(path)
end
def write_fixture(content)
File.open(path, 'w') { |f| f.print(content) }
end
it "should update the target user" do
write_fixture <<FIXTURE
fakeval:seriously:15315:0:99999:7:::
FIXTURE
provider.password = "totally"
expect(File.read(path)).to match(/^fakeval:totally:/)
end
it "should only update the target user" do
expect(Date).to receive(:today).and_return(Date.new(2011,12,07))
write_fixture <<FIXTURE
before:seriously:15315:0:99999:7:::
fakeval:seriously:15315:0:99999:7:::
fakevalish:seriously:15315:0:99999:7:::
after:seriously:15315:0:99999:7:::
FIXTURE
provider.password = "totally"
expect(File.read(path)).to eq <<EOT
before:seriously:15315:0:99999:7:::
fakeval:totally:15315:0:99999:7:::
fakevalish:seriously:15315:0:99999:7:::
after:seriously:15315:0:99999:7:::
EOT
end
# This preserves the current semantics, but is it right? --daniel 2012-02-05
it "should do nothing if the target user is missing" do
fixture = <<FIXTURE
before:seriously:15315:0:99999:7:::
fakevalish:seriously:15315:0:99999:7:::
after:seriously:15315:0:99999:7:::
FIXTURE
write_fixture fixture
provider.password = "totally"
expect(File.read(path)).to eq(fixture)
end
it "should update the lastchg field" do
expect(Date).to receive(:today).and_return(Date.new(2013,5,12)) # 15837 days after 1970-01-01
write_fixture <<FIXTURE
before:seriously:15315:0:99999:7:::
fakeval:seriously:15629:0:99999:7:::
fakevalish:seriously:15315:0:99999:7:::
after:seriously:15315:0:99999:7:::
FIXTURE
provider.password = "totally"
expect(File.read(path)).to eq <<EOT
before:seriously:15315:0:99999:7:::
fakeval:totally:15837:0:99999:7:::
fakevalish:seriously:15315:0:99999:7:::
after:seriously:15315:0:99999:7:::
EOT
end
end
describe "#shadow_entry" do
it "should return the line for the right user" do
allow(File).to receive(:readlines).and_return(["someuser:!:10:5:20:7:1::\n", "fakeval:*:20:10:30:7:2::\n", "testuser:*:30:15:40:7:3::\n"])
expect(provider.shadow_entry).to eq(["fakeval", "*", "20", "10", "30", "7", "2", "", ""])
end
end
describe "#password_max_age" do
it "should return a maximum age number" do
allow(File).to receive(:readlines).and_return(["fakeval:NP:12345:0:50::::\n"])
expect(provider.password_max_age).to eq("50")
end
it "should return -1 for no maximum" do
allow(File).to receive(:readlines).and_return(["fakeval:NP:12345::::::\n"])
expect(provider.password_max_age).to eq(-1)
end
it "should return -1 for no maximum when failed attempts are present" do
allow(File).to receive(:readlines).and_return(["fakeval:NP:12345::::::3\n"])
expect(provider.password_max_age).to eq(-1)
end
end
describe "#password_min_age" do
it "should return a minimum age number" do
allow(File).to receive(:readlines).and_return(["fakeval:NP:12345:10:50::::\n"])
expect(provider.password_min_age).to eq("10")
end
it "should return -1 for no minimum" do
allow(File).to receive(:readlines).and_return(["fakeval:NP:12345::::::\n"])
expect(provider.password_min_age).to eq(-1)
end
it "should return -1 for no minimum when failed attempts are present" do
allow(File).to receive(:readlines).and_return(["fakeval:NP:12345::::::3\n"])
expect(provider.password_min_age).to eq(-1)
end
end
describe "#password_warn_days" do
it "should return a warn days number" do
allow(File).to receive(:readlines).and_return(["fakeval:NP:12345:10:50:30:::\n"])
expect(provider.password_warn_days).to eq("30")
end
it "should return -1 for no warn days" do
allow(File).to receive(:readlines).and_return(["fakeval:NP:12345::::::\n"])
expect(provider.password_warn_days).to eq(-1)
end
it "should return -1 for no warn days when failed attempts are present" do
allow(File).to receive(:readlines).and_return(["fakeval:NP:12345::::::3\n"])
expect(provider.password_warn_days).to eq(-1)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/provider/user/directoryservice_spec.rb | spec/unit/provider/user/directoryservice_spec.rb | # encoding: ASCII-8BIT
require 'spec_helper'
module Puppet::Util::Plist
end
describe Puppet::Type.type(:user).provider(:directoryservice), :if => Puppet.features.cfpropertylist? do
let(:username) { 'nonexistent_user' }
let(:user_path) { "/Users/#{username}" }
let(:resource) do
Puppet::Type.type(:user).new(
:name => username,
:provider => :directoryservice
)
end
let(:provider) { resource.provider }
let(:users_plist_dir) { '/var/db/dslocal/nodes/Default/users' }
# This is the output of doing `dscl -plist . read /Users/<username>` which
# will return a hash of keys whose values are all arrays.
let(:user_plist_xml) 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>dsAttrTypeStandard:NFSHomeDirectory</key>
<array>
<string>/Users/nonexistent_user</string>
</array>
<key>dsAttrTypeStandard:RealName</key>
<array>
<string>nonexistent_user</string>
</array>
<key>dsAttrTypeStandard:PrimaryGroupID</key>
<array>
<string>22</string>
</array>
<key>dsAttrTypeStandard:UniqueID</key>
<array>
<string>1000</string>
</array>
<key>dsAttrTypeStandard:RecordName</key>
<array>
<string>nonexistent_user</string>
</array>
</dict>
</plist>'
end
# This is the same as above, however in a native Ruby hash instead
# of XML
let(:user_plist_hash) do
{
"dsAttrTypeStandard:RealName" => [username],
"dsAttrTypeStandard:NFSHomeDirectory" => [user_path],
"dsAttrTypeStandard:PrimaryGroupID" => ["22"],
"dsAttrTypeStandard:UniqueID" => ["1000"],
"dsAttrTypeStandard:RecordName" => [username]
}
end
let(:sha512_shadowhashdata_array) do
['62706c69 73743030 d101025d 53414c54 45442d53 48413531 324f1044 7ea7d592 131f57b2 c8f8bdbc '\
'ec8d9df1 2128a386 393a4f00 c7619bac 2622a44d 451419d1 1da512d5 915ab98e 39718ac9 4083fe2e '\
'fd6bf710 a54d477f 8ff735b1 2587192d 080b1900 00000000 00010100 00000000 00000300 00000000 '\
'00000000 00000000 000060']
end
# The below value is the result of executing
# `dscl -plist . read /Users/<username> ShadowHashData` on a 10.7
# system and converting it to a native Ruby Hash with Plist.parse_xml
let(:sha512_shadowhashdata_hash) do
{
'dsAttrTypeNative:ShadowHashData' => sha512_shadowhashdata_array
}
end
# The below is a binary plist that is stored in the ShadowHashData key
# on a 10.7 system.
let(:sha512_embedded_bplist) do
"bplist00\321\001\002]SALTED-SHA512O\020D~\247\325\222\023\037W\262\310\370\275\274\354\215\235\361!(\243\2069:O\000\307a\233\254&\"\244ME\024\031\321\035\245\022\325\221Z\271\2169q\212\311@\203\376.\375k\367\020\245MG\177\217\3675\261%\207\031-\b\v\031\000\000\000\000\000\000\001\001\000\000\000\000\000\000\000\003\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000`"
end
# The below is a Base64 encoded string representing a salted-SHA512 password
# hash.
let(:sha512_pw_string) do
"~\247\325\222\023\037W\262\310\370\275\274\354\215\235\361!(\243\2069:O\000\307a\233\254&\"\244ME\024\031\321\035\245\022\325\221Z\271\2169q\212\311@\203\376.\375k\367\020\245MG\177\217\3675\261%\207\031-"
end
# The below is the result of converting sha512_embedded_bplist to XML and
# parsing it with Plist.parse_xml. It is a Ruby Hash whose value is a
# Base64 encoded salted-SHA512 password hash.
let(:sha512_embedded_bplist_hash) do
{ 'SALTED-SHA512' => sha512_pw_string }
end
# The value below is the result of converting sha512_pw_string to Hex.
let(:sha512_password_hash) do
'7ea7d592131f57b2c8f8bdbcec8d9df12128a386393a4f00c7619bac2622a44d451419d11da512d5915ab98e39718ac94083fe2efd6bf710a54d477f8ff735b12587192d'
end
let(:pbkdf2_shadowhashdata_array) do
['62706c69 73743030 d101025f 10145341 4c544544 2d534841 3531322d 50424b44 4632d303 04050607 '\
'0857656e 74726f70 79547361 6c745a69 74657261 74696f6e 734f1080 0590ade1 9e6953c1 35ae872a '\
'e7761823 5df7d46c 63de7f9a 0fcdf2cd 9e7d85e4 b7ca8681 01235b61 58e05a30 9805ee48 14b027a4 '\
'be9c23ec 2926bc81 72269aff ba5c9a59 85e81091 fa689807 6d297f1f aa75fa61 7551ef16 71d75200 '\
'55c4a0d9 7b9b9c58 05aa322b aedbcd8e e9c52381 1653ac2e a9e9c8d8 f1ac519a 0f2b595e 4f102093 '\
'77c46908 a1c8ac2c 3e45c0d4 4da8ad0f cd85ec5c 14d9a59f fc40c9da 31f0ec11 60b0080b 22293136 '\
'41c4e700 00000000 00010100 00000000 00000900 00000000 00000000 00000000 0000ea']
end
# The below value is the result of executing
# `dscl -plist . read /Users/<username> ShadowHashData` on a 10.8
# system and converting it to a native Ruby Hash with Plist.parse_xml
let(:pbkdf2_shadowhashdata_hash) do
{
"dsAttrTypeNative:ShadowHashData"=> pbkdf2_shadowhashdata_array
}
end
# The below value is the result of converting pbkdf2_embedded_bplist to XML and
# parsing it with Plist.parse_xml.
let(:pbkdf2_embedded_bplist_hash) do
{
'SALTED-SHA512-PBKDF2' => {
'entropy' => pbkdf2_pw_string,
'salt' => pbkdf2_salt_string,
'iterations' => pbkdf2_iterations_value
}
}
end
# The value below is the result of converting pbkdf2_pw_string to Hex.
let(:pbkdf2_password_hash) do
'0590ade19e6953c135ae872ae77618235df7d46c63de7f9a0fcdf2cd9e7d85e4b7ca868101235b6158e05a309805ee4814b027a4be9c23ec2926bc8172269affba5c9a5985e81091fa6898076d297f1faa75fa617551ef1671d7520055c4a0d97b9b9c5805aa322baedbcd8ee9c523811653ac2ea9e9c8d8f1ac519a0f2b595e'
end
# The below is a binary plist that is stored in the ShadowHashData key
# of a 10.8 system.
let(:pbkdf2_embedded_plist) do
"bplist00\321\001\002_\020\024SALTED-SHA512-PBKDF2\323\003\004\005\006\a\bWentropyTsaltZiterationsO\020\200\005\220\255\341\236iS\3015\256\207*\347v\030#]\367\324lc\336\177\232\017\315\362\315\236}\205\344\267\312\206\201\001#[aX\340Z0\230\005\356H\024\260'\244\276\234#\354)&\274\201r&\232\377\272\\\232Y\205\350\020\221\372h\230\am)\177\037\252u\372auQ\357\026q\327R\000U\304\240\331{\233\234X\005\2522+\256\333\315\216\351\305#\201\026S\254.\251\351\310\330\361\254Q\232\017+Y^O\020 \223w\304i\b\241\310\254,>E\300\324M\250\255\017\315\205\354\\\024\331\245\237\374@\311\3321\360\354\021`\260\b\v\")16A\304\347\000\000\000\000\000\000\001\001\000\000\000\000\000\000\000\t\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\352"
end
# The below value is a Base64 encoded string representing a PBKDF2 password
# hash.
let(:pbkdf2_pw_string) do
"\005\220\255\341\236iS\3015\256\207*\347v\030#]\367\324lc\336\177\232\017\315\362\315\236}\205\344\267\312\206\201\001#[aX\340Z0\230\005\356H\024\260'\244\276\234#\354)&\274\201r&\232\377\272\\\232Y\205\350\020\221\372h\230\am)\177\037\252u\372auQ\357\026q\327R\000U\304\240\331{\233\234X\005\2522+\256\333\315\216\351\305#\201\026S\254.\251\351\310\330\361\254Q\232\017+Y^"
end
# The below value is a Base64 encoded string representing a PBKDF2 salt
# string.
let(:pbkdf2_salt_string) do
"\223w\304i\b\241\310\254,>E\300\324M\250\255\017\315\205\354\\\024\331\245\237\374@\311\3321\360\354"
end
# The below value represents the Hex value of a PBKDF2 salt string
let(:pbkdf2_salt_value) do
"9377c46908a1c8ac2c3e45c0d44da8ad0fcd85ec5c14d9a59ffc40c9da31f0ec"
end
# The below value is an Integer iterations value used in the PBKDF2
# key stretching algorithm
let(:pbkdf2_iterations_value) do
24752
end
let(:pbkdf2_and_ssha512_shadowhashdata_array) do
['62706c69 73743030 d2010203 0a5f1014 53414c54 45442d53 48413531 322d5042 4b444632 5d53414c '\
'5445442d 53484135 3132d304 05060708 0957656e 74726f70 79547361 6c745a69 74657261 74696f6e '\
'734f1080 0590ade1 9e6953c1 35ae872a e7761823 5df7d46c 63de7f9a 0fcdf2cd 9e7d85e4 b7ca8681 '\
'01235b61 58e05a30 9805ee48 14b027a4 be9c23ec 2926bc81 72269aff ba5c9a59 85e81091 fa689807 '\
'6d297f1f aa75fa61 7551ef16 71d75200 55c4a0d9 7b9b9c58 05aa322b aedbcd8e e9c52381 1653ac2e '\
'a9e9c8d8 f1ac519a 0f2b595e 4f102093 77c46908 a1c8ac2c 3e45c0d4 4da8ad0f cd85ec5c 14d9a59f '\
'fc40c9da 31f0ec11 60b04f10 447ea7d5 92131f57 b2c8f8bd bcec8d9d f12128a3 86393a4f 00c7619b '\
'ac2622a4 4d451419 d11da512 d5915ab9 8e39718a c94083fe 2efd6bf7 10a54d47 7f8ff735 b1258719 '\
'2d000800 0d002400 32003900 41004600 5100d400 f700fa00 00000000 00020100 00000000 00000b00 '\
'00000000 00000000 00000000 000141']
end
let(:pbkdf2_and_ssha512_shadowhashdata_hash) do
{
'dsAttrTypeNative:ShadowHashData' => pbkdf2_and_ssha512_shadowhashdata_array
}
end
let (:pbkdf2_and_ssha512_embedded_plist) do
"bplist00\xD2\x01\x02\x03\n_\x10\x14SALTED-SHA512-PBKDF2]SALTED-SHA512\xD3\x04\x05\x06\a\b\tWentropyTsaltZiterationsO\x10\x80\x05\x90\xAD\xE1\x9EiS\xC15\xAE\x87*\xE7v\x18#]\xF7\xD4lc\xDE\x7F\x9A\x0F\xCD\xF2\xCD\x9E}\x85\xE4\xB7\xCA\x86\x81\x01#[aX\xE0Z0\x98\x05\xEEH\x14\xB0'\xA4\xBE\x9C#\xEC)&\xBC\x81r&\x9A\xFF\xBA\\\x9AY\x85\xE8\x10\x91\xFAh\x98\am)\x7F\x1F\xAAu\xFAauQ\xEF\x16q\xD7R\x00U\xC4\xA0\xD9{\x9B\x9CX\x05\xAA2+\xAE\xDB\xCD\x8E\xE9\xC5#\x81\x16S\xAC.\xA9\xE9\xC8\xD8\xF1\xACQ\x9A\x0F+Y^O\x10 \x93w\xC4i\b\xA1\xC8\xAC,>E\xC0\xD4M\xA8\xAD\x0F\xCD\x85\xEC\\\x14\xD9\xA5\x9F\xFC@\xC9\xDA1\xF0\xEC\x11`\xB0O\x10D~\xA7\xD5\x92\x13\x1FW\xB2\xC8\xF8\xBD\xBC\xEC\x8D\x9D\xF1!(\xA3\x869:O\x00\xC7a\x9B\xAC&\"\xA4ME\x14\x19\xD1\x1D\xA5\x12\xD5\x91Z\xB9\x8E9q\x8A\xC9@\x83\xFE.\xFDk\xF7\x10\xA5MG\x7F\x8F\xF75\xB1%\x87\x19-\x00\b\x00\r\x00$\x002\x009\x00A\x00F\x00Q\x00\xD4\x00\xF7\x00\xFA\x00\x00\x00\x00\x00\x00\x02\x01\x00\x00\x00\x00\x00\x00\x00\v\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01A"
end
let (:pbkdf2_and_ssha512_embedded_bplist_hash) do
{
"SALTED-SHA512-PBKDF2" => {
"entropy" => pbkdf2_pw_string,
"salt" => pbkdf2_salt_value,
"iterations" => pbkdf2_iterations_value,
},
"SALTED-SHA512" => sha512_password_hash
}
end
let (:dsimport_preamble) do
'0x0A 0x5C 0x3A 0x2C dsRecTypeStandard:Users 2 dsAttrTypeStandard:RecordName base64:dsAttrTypeNative:ShadowHashData'
end
let (:dsimport_contents) do
<<-DSIMPORT
#{dsimport_preamble}
#{username}:#{Base64.strict_encode64(sha512_embedded_bplist)}
DSIMPORT
end
# The below represents output of 'dscl -plist . readall /Users' converted to
# a native Ruby hash if only one user were installed on the system.
# This lets us check the behavior of all the methods necessary to return a
# user's groups property by controlling the data provided by dscl
let(:testuser_base) do
{
"dsAttrTypeStandard:RecordName" =>["nonexistent_user"],
"dsAttrTypeStandard:UniqueID" =>["1000"],
"dsAttrTypeStandard:AuthenticationAuthority"=>
[";Kerberosv5;;testuser@LKDC:SHA1.4383E152D9D394AA32D13AE98F6F6E1FE8D00F81;LKDC:SHA1.4383E152D9D394AA32D13AE98F6F6E1FE8D00F81",
";ShadowHash;HASHLIST:<SALTED-SHA512>"],
"dsAttrTypeStandard:AppleMetaNodeLocation" =>["/Local/Default"],
"dsAttrTypeStandard:NFSHomeDirectory" =>["/Users/nonexistent_user"],
"dsAttrTypeStandard:RecordType" =>["dsRecTypeStandard:Users"],
"dsAttrTypeStandard:RealName" =>["nonexistent_user"],
"dsAttrTypeStandard:Password" =>["********"],
"dsAttrTypeStandard:PrimaryGroupID" =>["22"],
"dsAttrTypeStandard:GeneratedUID" =>["0A7D5B63-3AD4-4CA7-B03E-85876F1D1FB3"],
"dsAttrTypeStandard:AuthenticationHint" =>[""],
"dsAttrTypeNative:KerberosKeys" =>
["30820157 a1030201 02a08201 4e308201 4a3074a1 2b3029a0 03020112 a1220420 54af3992 1c198bf8 94585a6b 2fba445b c8482228 0dcad666 ea62e038 99e59c45 a2453043 a0030201 03a13c04 3a4c4b44 433a5348 41312e34 33383345 31353244 39443339 34414133 32443133 41453938 46364636 45314645 38443030 46383174 65737475 73657230 64a11b30 19a00302 0111a112 04106375 7d97b2ce ca8343a6 3b0f73d5 1001a245 3043a003 020103a1 3c043a4c 4b44433a 53484131 2e343338 33453135 32443944 33393441 41333244 31334145 39384636 46364531 46453844 30304638 31746573 74757365 72306ca1 233021a0 03020110 a11a0418 67b09be3 5131b670 f8e9265e 62459b4c 19435419 fe918519 a2453043 a0030201 03a13c04 3a4c4b44 433a5348 41312e34 33383345 31353244 39443339 34414133 32443133 41453938 46364636 45314645 38443030 46383174 65737475 736572"],
"dsAttrTypeStandard:PasswordPolicyOptions" =>
["<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n <plist version=\"1.0\">\n <dict>\n <key>failedLoginCount</key>\n <integer>0</integer>\n <key>failedLoginTimestamp</key>\n <date>2001-01-01T00:00:00Z</date>\n <key>lastLoginTimestamp</key>\n <date>2001-01-01T00:00:00Z</date>\n <key>passwordTimestamp</key>\n <date>2012-08-10T23:53:50Z</date>\n </dict>\n </plist>\n "],
"dsAttrTypeStandard:UserShell" =>["/bin/bash"],
"dsAttrTypeNative:ShadowHashData" =>
["62706c69 73743030 d101025d 53414c54 45442d53 48413531 324f1044 7ea7d592 131f57b2 c8f8bdbc ec8d9df1 2128a386 393a4f00 c7619bac 2622a44d 451419d1 1da512d5 915ab98e 39718ac9 4083fe2e fd6bf710 a54d477f 8ff735b1 2587192d 080b1900 00000000 00010100 00000000 00000300 00000000 00000000 00000000 000060"]
}
end
let(:testuser_hash) do
[
testuser_base.merge(sha512_shadowhashdata_hash),
testuser_base.merge(pbkdf2_shadowhashdata_hash),
]
end
# The below represents the result of running Plist.parse_xml on XML
# data returned from the `dscl -plist . readall /Groups` command.
# (AKA: What the get_list_of_groups method returns)
let(:group_plist_hash_guid) do
[{
'dsAttrTypeStandard:RecordName' => ['testgroup'],
'dsAttrTypeStandard:GroupMembership' => [
username,
'jeff',
'zack'
],
'dsAttrTypeStandard:GroupMembers' => [
"guid#{username}",
'guidtestuser',
'guidjeff',
'guidzack'
],
},
{
'dsAttrTypeStandard:RecordName' => ['second'],
'dsAttrTypeStandard:GroupMembership' => [
'jeff',
'zack'
],
'dsAttrTypeStandard:GroupMembers' => [
"guid#{username}",
'guidjeff',
'guidzack'
],
},
{
'dsAttrTypeStandard:RecordName' => ['third'],
'dsAttrTypeStandard:GroupMembership' => [
username,
'jeff',
'zack'
],
'dsAttrTypeStandard:GroupMembers' => [
"guid#{username}",
'guidtestuser',
'guidjeff',
'guidzack'
],
}]
end
describe 'Creating a user that does not exist' do
# These are the defaults that the provider will use if a user does
# not provide a value
let(:defaults) do
{
'UniqueID' => '1000',
'RealName' => resource[:name],
'PrimaryGroupID' => 20,
'UserShell' => '/bin/bash',
'NFSHomeDirectory' => "/Users/#{resource[:name]}"
}
end
before :each do
# Stub out all calls to dscl with default values from above
defaults.each do |key, val|
allow(provider).to receive(:create_attribute_with_dscl).with('Users', username, key, val)
end
# Mock the rest of the dscl calls. We can't assume that our Linux
# build system will have the dscl binary
allow(provider).to receive(:create_new_user).with(username)
allow(provider.class).to receive(:get_attribute_from_dscl).with('Users', username, 'GeneratedUID').and_return({'dsAttrTypeStandard:GeneratedUID' => ['GUID']})
allow(provider).to receive(:next_system_id).and_return('1000')
end
it 'should not raise any errors when creating a user with default values' do
provider.create
end
%w{password iterations salt}.each do |value|
it "should call ##{value}= if a #{value} attribute is specified" do
resource[value.intern] = 'somevalue'
setter = (value << '=').intern
expect(provider).to receive(setter).with('somevalue')
provider.create
end
end
it 'should merge the GroupMembership and GroupMembers dscl values if a groups attribute is specified' do
resource[:groups] = 'somegroup'
expect(provider).to receive(:merge_attribute_with_dscl).with('Groups', 'somegroup', 'GroupMembership', username)
expect(provider).to receive(:merge_attribute_with_dscl).with('Groups', 'somegroup', 'GroupMembers', 'GUID')
provider.create
end
it 'should convert group names into integers' do
resource[:gid] = 'somegroup'
expect(Puppet::Util).to receive(:gid).with('somegroup').and_return(21)
expect(provider).to receive(:create_attribute_with_dscl).with('Users', username, 'PrimaryGroupID', 21)
provider.create
end
end
describe 'Update existing user' do
describe 'home=' do
context 'on OS X 10.14' do
before do
provider.instance_variable_set(:@property_hash, { home: 'value' })
allow(provider.class).to receive(:get_os_version).and_return('10.14')
end
it 'raises error' do
expect { provider.home = 'new' }.to \
raise_error(Puppet::Error, "OS X version 10.14 does not allow changing home using puppet")
end
end
end
describe 'uid=' do
context 'on OS X 10.14' do
before do
provider.instance_variable_set(:@property_hash, { uid: 'value' })
allow(provider.class).to receive(:get_os_version).and_return('10.14')
end
it 'raises error' do
expect { provider.uid = 'new' }.to \
raise_error(Puppet::Error, "OS X version 10.14 does not allow changing uid using puppet")
end
end
end
end
describe 'self#instances' do
it 'should create an array of provider instances' do
expect(provider.class).to receive(:get_all_users).and_return(['foo', 'bar'])
['foo', 'bar'].each do |user|
expect(provider.class).to receive(:generate_attribute_hash).with(user).and_return({})
end
instances = provider.class.instances
expect(instances).to be_a_kind_of Array
instances.each do |instance|
expect(instance).to be_a_kind_of Puppet::Provider
end
end
end
describe 'self#get_all_users', :if => Puppet.features.cfpropertylist? do
let(:empty_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>
</dict>
</plist>'
end
it 'should return a hash of user attributes' do
expect(provider.class).to receive(:dscl).with('-plist', '.', 'readall', '/Users').and_return(user_plist_xml)
expect(provider.class.get_all_users).to eq(user_plist_hash)
end
it 'should return a hash when passed an empty plist' do
expect(provider.class).to receive(:dscl).with('-plist', '.', 'readall', '/Users').and_return(empty_plist)
expect(provider.class.get_all_users).to eq({})
end
end
describe 'self#generate_attribute_hash' do
let(:user_plist_resource) do
{
:ensure => :present,
:provider => :directoryservice,
:groups => 'testgroup,third',
:comment => username,
:password => sha512_password_hash,
:shadowhashdata => sha512_shadowhashdata_array,
:name => username,
:uid => 1000,
:gid => 22,
:home => user_path
}
end
before :each do
allow(provider.class).to receive(:get_os_version).and_return('10.7')
allow(provider.class).to receive(:get_all_users).and_return(testuser_hash)
allow(provider.class).to receive(:get_list_of_groups).and_return(group_plist_hash_guid)
allow(provider.class).to receive(:convert_binary_to_hash).with(sha512_embedded_bplist).and_return(sha512_embedded_bplist_hash)
allow(provider.class).to receive(:convert_binary_to_hash).with(pbkdf2_embedded_plist).and_return(pbkdf2_embedded_bplist_hash)
provider.class.prefetch({})
end
it 'should return :uid values as an Integer' do
expect(provider.class.generate_attribute_hash(user_plist_hash)[:uid]).to be_a Integer
end
it 'should return :gid values as an Integer' do
expect(provider.class.generate_attribute_hash(user_plist_hash)[:gid]).to be_a Integer
end
it 'should return a hash of resource attributes' do
expect(provider.class.generate_attribute_hash(user_plist_hash.merge(sha512_shadowhashdata_hash))).to eq(user_plist_resource)
end
end
describe 'self#generate_attribute_hash with pbkdf2 and ssha512' do
let(:user_plist_resource) do
{
:ensure => :present,
:provider => :directoryservice,
:groups => 'testgroup,third',
:comment => username,
:password => pbkdf2_password_hash,
:iterations => pbkdf2_iterations_value,
:salt => pbkdf2_salt_value,
:shadowhashdata => pbkdf2_and_ssha512_shadowhashdata_array,
:name => username,
:uid => 1000,
:gid => 22,
:home => user_path
}
end
before :each do
allow(provider.class).to receive(:get_os_version).and_return('10.7')
allow(provider.class).to receive(:get_all_users).and_return(testuser_hash)
allow(provider.class).to receive(:get_list_of_groups).and_return(group_plist_hash_guid)
provider.class.prefetch({})
end
it 'should return a hash of resource attributes' do
expect(provider.class.generate_attribute_hash(user_plist_hash.merge(pbkdf2_and_ssha512_shadowhashdata_hash))).to eq(user_plist_resource)
end
end
describe 'self#generate_attribute_hash empty shadowhashdata' do
let(:user_plist_resource) do
{
:ensure => :present,
:provider => :directoryservice,
:groups => 'testgroup,third',
:comment => username,
:password => '*',
:shadowhashdata => nil,
:name => username,
:uid => 1000,
:gid => 22,
:home => user_path
}
end
it 'should handle empty shadowhashdata' do
allow(provider.class).to receive(:get_os_version).and_return('10.7')
allow(provider.class).to receive(:get_all_users).and_return([testuser_base])
allow(provider.class).to receive(:get_list_of_groups).and_return(group_plist_hash_guid)
provider.class.prefetch({})
expect(provider.class.generate_attribute_hash(user_plist_hash)).to eq(user_plist_resource)
end
end
describe '#delete' do
it 'should call dscl when destroying/deleting a resource' do
expect(provider).to receive(:dscl).with('.', '-delete', user_path)
provider.delete
end
end
describe 'the groups property' do
# The below represents the result of running Plist.parse_xml on XML
# data returned from the `dscl -plist . readall /Groups` command.
# (AKA: What the get_list_of_groups method returns)
let(:group_plist_hash) do
[{
'dsAttrTypeStandard:RecordName' => ['testgroup'],
'dsAttrTypeStandard:GroupMembership' => [
'testuser',
username,
'jeff',
'zack'
],
'dsAttrTypeStandard:GroupMembers' => [
'guidtestuser',
'guidjeff',
'guidzack'
],
},
{
'dsAttrTypeStandard:RecordName' => ['second'],
'dsAttrTypeStandard:GroupMembership' => [
username,
'testuser',
'jeff',
],
'dsAttrTypeStandard:GroupMembers' => [
'guidtestuser',
'guidjeff',
],
},
{
'dsAttrTypeStandard:RecordName' => ['third'],
'dsAttrTypeStandard:GroupMembership' => [
'jeff',
'zack'
],
'dsAttrTypeStandard:GroupMembers' => [
'guidjeff',
'guidzack'
],
}]
end
before :each do
allow(provider.class).to receive(:get_all_users).and_return(testuser_hash)
allow(provider.class).to receive(:get_os_version).and_return('10.7')
end
it "should return a list of groups if the user's name matches GroupMembership" do
expect(provider.class).to receive(:get_list_of_groups).and_return(group_plist_hash)
expect(provider.class).to receive(:get_list_of_groups).and_return(group_plist_hash)
expect(provider.class.prefetch({}).first.groups).to eq('second,testgroup')
end
it "should return a list of groups if the user's GUID matches GroupMembers" do
expect(provider.class).to receive(:get_list_of_groups).and_return(group_plist_hash_guid)
expect(provider.class).to receive(:get_list_of_groups).and_return(group_plist_hash_guid)
expect(provider.class.prefetch({}).first.groups).to eq('testgroup,third')
end
end
describe '#groups=' do
let(:group_plist_one_two_three) do
[{
'dsAttrTypeStandard:RecordName' => ['one'],
'dsAttrTypeStandard:GroupMembership' => [
'jeff',
'zack'
],
'dsAttrTypeStandard:GroupMembers' => [
'guidjeff',
'guidzack'
],
},
{
'dsAttrTypeStandard:RecordName' => ['two'],
'dsAttrTypeStandard:GroupMembership' => [
'jeff',
'zack',
username
],
'dsAttrTypeStandard:GroupMembers' => [
'guidjeff',
'guidzack'
],
},
{
'dsAttrTypeStandard:RecordName' => ['three'],
'dsAttrTypeStandard:GroupMembership' => [
'jeff',
'zack',
username
],
'dsAttrTypeStandard:GroupMembers' => [
'guidjeff',
'guidzack'
],
}]
end
before :each do
allow(provider.class).to receive(:get_all_users).and_return(testuser_hash)
allow(provider.class).to receive(:get_list_of_groups).and_return(group_plist_one_two_three)
end
it 'should call dscl to add necessary groups' do
expect(provider.class).to receive(:get_attribute_from_dscl).with('Users', username, 'GeneratedUID').and_return({'dsAttrTypeStandard:GeneratedUID' => ['guidnonexistent_user']})
expect(provider).to receive(:groups).and_return('two,three')
expect(provider).to receive(:dscl).with('.', '-merge', '/Groups/one', 'GroupMembership', 'nonexistent_user')
expect(provider).to receive(:dscl).with('.', '-merge', '/Groups/one', 'GroupMembers', 'guidnonexistent_user')
provider.class.prefetch({})
provider.groups= 'one,two,three'
end
it 'should call the get_salted_sha512 method on 10.7 and return the correct hash' do
expect(provider.class).to receive(:convert_binary_to_hash).with(sha512_embedded_bplist).and_return(sha512_embedded_bplist_hash)
expect(provider.class).to receive(:convert_binary_to_hash).with(pbkdf2_embedded_plist).and_return(pbkdf2_embedded_bplist_hash)
expect(provider.class.prefetch({}).first.password).to eq(sha512_password_hash)
end
it 'should call the get_salted_sha512_pbkdf2 method on 10.8 and return the correct hash' do
expect(provider.class).to receive(:convert_binary_to_hash).with(sha512_embedded_bplist).and_return(sha512_embedded_bplist_hash)
expect(provider.class).to receive(:convert_binary_to_hash).with(pbkdf2_embedded_plist).and_return(pbkdf2_embedded_bplist_hash)
expect(provider.class.prefetch({}).last.password).to eq(pbkdf2_password_hash)
end
end
describe '#password=' do
before :each do
allow(provider).to receive(:sleep)
allow(provider).to receive(:flush_dscl_cache)
end
it 'should call write_password_to_users_plist when setting the password' do
allow(provider.class).to receive(:get_os_version).and_return('10.7')
expect(provider).to receive(:write_password_to_users_plist).with(sha512_password_hash)
provider.password = sha512_password_hash
end
it 'should call write_password_to_users_plist when setting the password' do
allow(provider.class).to receive(:get_os_version).and_return('10.8')
resource[:salt] = pbkdf2_salt_value
resource[:iterations] = pbkdf2_iterations_value
resource[:password] = pbkdf2_password_hash
expect(provider).to receive(:write_password_to_users_plist).with(pbkdf2_password_hash)
provider.password = resource[:password]
end
it "should raise an error on 10.7 if a password hash that doesn't contain 136 characters is passed" do
allow(provider.class).to receive(:get_os_version).and_return('10.7')
expect { provider.password = 'password' }.to raise_error Puppet::Error, /OS X 10\.7 requires a Salted SHA512 hash password of 136 characters\. Please check your password and try again/
end
end
describe "passwords on 10.8" do
before :each do
allow(provider.class).to receive(:get_os_version).and_return('10.8')
end
it "should raise an error on 10.8 if a password hash that doesn't contain 256 characters is passed" do
expect do
provider.password = 'password'
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | true |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/provider/exec/posix_spec.rb | spec/unit/provider/exec/posix_spec.rb | require 'spec_helper'
describe Puppet::Type.type(:exec).provider(:posix), :if => Puppet.features.posix? do
include PuppetSpec::Files
def make_exe
cmdpath = tmpdir('cmdpath')
exepath = tmpfile('my_command', cmdpath)
FileUtils.touch(exepath)
File.chmod(0755, exepath)
exepath
end
let(:resource) { Puppet::Type.type(:exec).new(:title => '/foo', :provider => :posix) }
let(:provider) { described_class.new(resource) }
describe "#validatecmd" do
it "should fail if no path is specified and the command is not fully qualified" do
expect { provider.validatecmd("foo") }.to raise_error(
Puppet::Error,
"'foo' is not qualified and no path was specified. Please qualify the command or specify a path."
)
end
it "should pass if a path is given" do
provider.resource[:path] = ['/bogus/bin']
provider.validatecmd("../foo")
end
it "should pass if command is fully qualifed" do
provider.resource[:path] = ['/bogus/bin']
provider.validatecmd("/bin/blah/foo")
end
end
describe "#run" do
describe "when the command is an absolute path" do
let(:command) { tmpfile('foo') }
it "should fail if the command doesn't exist" do
expect { provider.run(command) }.to raise_error(ArgumentError, "Could not find command '#{command}'")
end
it "should fail if the command isn't a file" do
FileUtils.mkdir(command)
FileUtils.chmod(0755, command)
expect { provider.run(command) }.to raise_error(ArgumentError, "'#{command}' is a directory, not a file")
end
it "should fail if the command isn't executable" do
FileUtils.touch(command)
allow(File).to receive(:executable?).with(command).and_return(false)
expect { provider.run(command) }.to raise_error(ArgumentError, "'#{command}' is not executable")
end
end
describe "when the command is a relative path" do
it "should execute the command if it finds it in the path and is executable" do
command = make_exe
provider.resource[:path] = [File.dirname(command)]
filename = File.basename(command)
expect(Puppet::Util::Execution).to receive(:execute).with(filename, instance_of(Hash)).and_return(Puppet::Util::Execution::ProcessOutput.new('', 0))
provider.run(filename)
end
it "should fail if the command isn't in the path" do
resource[:path] = ["/fake/path"]
expect { provider.run('foo') }.to raise_error(ArgumentError, "Could not find command 'foo'")
end
it "should fail if the command is in the path but not executable" do
command = make_exe
File.chmod(0644, command)
allow(FileTest).to receive(:executable?).with(command).and_return(false)
resource[:path] = [File.dirname(command)]
filename = File.basename(command)
expect { provider.run(filename) }.to raise_error(ArgumentError, "Could not find command '#{filename}'")
end
end
it "should not be able to execute shell builtins" do
provider.resource[:path] = ['/bogus/bin']
expect { provider.run("cd ..") }.to raise_error(ArgumentError, "Could not find command 'cd'")
end
it "should execute the command if the command given includes arguments or subcommands" do
provider.resource[:path] = ['/bogus/bin']
command = make_exe
expect(Puppet::Util::Execution).to receive(:execute).with("#{command} bar --sillyarg=true --blah", instance_of(Hash)).and_return(Puppet::Util::Execution::ProcessOutput.new('', 0))
provider.run("#{command} bar --sillyarg=true --blah")
end
it "should fail if quoted command doesn't exist" do
provider.resource[:path] = ['/bogus/bin']
command = "/foo bar --sillyarg=true --blah"
expect { provider.run(%Q["#{command}"]) }.to raise_error(ArgumentError, "Could not find command '#{command}'")
end
it "should warn if you're overriding something in environment" do
provider.resource[:environment] = ['WHATEVER=/something/else', 'WHATEVER=/foo']
command = make_exe
expect(Puppet::Util::Execution).to receive(:execute).with(command, instance_of(Hash)).and_return(Puppet::Util::Execution::ProcessOutput.new('', 0))
provider.run(command)
expect(@logs.map {|l| "#{l.level}: #{l.message}" }).to eq(["warning: Overriding environment setting 'WHATEVER' with '/foo'"])
end
it "should warn when setting an empty environment variable" do
provider.resource[:environment] = ['WHATEVER=']
command = make_exe
expect(Puppet::Util::Execution).to receive(:execute).with(command, instance_of(Hash)).and_return(Puppet::Util::Execution::ProcessOutput.new('', 0))
provider.run(command)
expect(@logs.map(&:to_s).join).to match(/Empty environment setting 'WHATEVER'\n\s+\(file & line not available\)/m)
end
it "should warn when setting an empty environment variable (within a manifest)" do
provider.resource[:environment] = ['WHATEVER=']
provider.resource.file = '/tmp/foobar'
provider.resource.line = 42
command = make_exe
expect(Puppet::Util::Execution).to receive(:execute).with(command, instance_of(Hash)).and_return(Puppet::Util::Execution::ProcessOutput.new('', 0))
provider.run(command)
expect(@logs.map(&:to_s).join).to match(/Empty environment setting 'WHATEVER'\n\s+\(file: \/tmp\/foobar, line: 42\)/m)
end
it "should set umask before execution if umask parameter is in use" do
provider.resource[:umask] = '0027'
expect(Puppet::Util).to receive(:withumask).with(0027)
provider.run(provider.resource[:command])
end
describe "posix locale settings", :unless => RUBY_PLATFORM == 'java' do
# 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
# "exec"
locale_sentinel_env = {}
Puppet::Util::POSIX::LOCALE_ENV_VARS.each { |var| locale_sentinel_env[var] = lang_sentinel_value }
command = "/bin/echo $%s"
it "should not override user's locale during execution" do
# we'll do this once without any sentinel values, to give us a little more test coverage
orig_env = {}
Puppet::Util::POSIX::LOCALE_ENV_VARS.each { |var| orig_env[var] = ENV[var] if ENV[var] }
orig_env.keys.each do |var|
output, _ = provider.run(command % var)
expect(output.strip).to eq(orig_env[var])
end
# now, once more... but with our sentinel values
Puppet::Util.withenv(locale_sentinel_env) do
Puppet::Util::POSIX::LOCALE_ENV_VARS.each do |var|
output, _ = provider.run(command % var)
expect(output.strip).to eq(locale_sentinel_env[var])
end
end
end
it "should respect locale overrides in user's 'environment' configuration" do
provider.resource[:environment] = ['LANG=C', 'LC_ALL=C']
output, _ = provider.run(command % 'LANG')
expect(output.strip).to eq('C')
output, _ = provider.run(command % 'LC_ALL')
expect(output.strip).to eq('C')
end
end
describe "posix user-related environment vars", :unless => RUBY_PLATFORM == 'java' do
# a temporary hash that contains sentinel values for each of the user-related environment variables that we
# are expected to unset during an "exec"
user_sentinel_env = {}
Puppet::Util::POSIX::USER_ENV_VARS.each { |var| user_sentinel_env[var] = "Abracadabra" }
command = "/bin/echo $%s"
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
output, _ = provider.run(command % var)
expect(output.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 respect overrides to user-related environment vars in caller's 'environment' configuration" do
sentinel_value = "Abracadabra"
# set the "environment" property of the resource, populating it with a hash containing sentinel values for
# each of the user-related posix environment variables
provider.resource[:environment] = Puppet::Util::POSIX::USER_ENV_VARS.collect { |var| "#{var}=#{sentinel_value}"}
# loop over the posix user-related environment variables
Puppet::Util::POSIX::USER_ENV_VARS.each do |var|
# run an 'exec' to get the value of each variable
output, _ = provider.run(command % var)
# ensure that it matches our expected sentinel value
expect(output.strip).to eq(sentinel_value)
end
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/provider/exec/windows_spec.rb | spec/unit/provider/exec/windows_spec.rb | require 'spec_helper'
describe Puppet::Type.type(:exec).provider(:windows), :if => Puppet::Util::Platform.windows? do
include PuppetSpec::Files
let(:resource) { Puppet::Type.type(:exec).new(:title => 'C:\foo', :provider => :windows) }
let(:provider) { described_class.new(resource) }
after :all do
# This provider may not be suitable on some machines, so we want to reset
# the default so it isn't used by mistake in future specs.
Puppet::Type.type(:exec).defaultprovider = nil
end
describe "#extractexe" do
describe "when the command has no arguments" do
it "should return the command if it's quoted" do
expect(provider.extractexe('"foo"')).to eq('foo')
end
it "should return the command if it's quoted and contains spaces" do
expect(provider.extractexe('"foo bar"')).to eq('foo bar')
end
it "should return the command if it's not quoted" do
expect(provider.extractexe('foo')).to eq('foo')
end
end
describe "when the command has arguments" do
it "should return the command if it's quoted" do
expect(provider.extractexe('"foo" bar baz')).to eq('foo')
end
it "should return the command if it's quoted and contains spaces" do
expect(provider.extractexe('"foo bar" baz "quux quiz"')).to eq('foo bar')
end
it "should return the command if it's not quoted" do
expect(provider.extractexe('foo bar baz')).to eq('foo')
end
end
end
describe "#checkexe" do
describe "when the command is absolute", :if => Puppet::Util::Platform.windows? do
it "should return if the command exists and is a file" do
command = tmpfile('command')
FileUtils.touch(command)
expect(provider.checkexe(command)).to eq(nil)
end
it "should fail if the command doesn't exist" do
command = tmpfile('command')
expect { provider.checkexe(command) }.to raise_error(ArgumentError, "Could not find command '#{command}'")
end
it "should fail if the command isn't a file" do
command = tmpfile('command')
FileUtils.mkdir(command)
expect { provider.checkexe(command) }.to raise_error(ArgumentError, "'#{command}' is a directory, not a file")
end
end
describe "when the command is relative" do
describe "and a path is specified" do
before :each do
allow(provider).to receive(:which)
end
it "should search for executables with no extension" do
provider.resource[:path] = [File.expand_path('/bogus/bin')]
expect(provider).to receive(:which).with('foo').and_return('foo')
provider.checkexe('foo')
end
it "should fail if the command isn't in the path" do
expect { provider.checkexe('foo') }.to raise_error(ArgumentError, "Could not find command 'foo'")
end
end
it "should fail if no path is specified" do
expect { provider.checkexe('foo') }.to raise_error(ArgumentError, "Could not find command 'foo'")
end
end
end
describe "#validatecmd" do
it "should fail if the command isn't absolute and there is no path" do
expect { provider.validatecmd('foo') }.to raise_error(Puppet::Error, /'foo' is not qualified and no path was specified/)
end
it "should not fail if the command is absolute and there is no path" do
expect(provider.validatecmd('C:\foo')).to eq(nil)
end
it "should not fail if the command is not absolute and there is a path" do
resource[:path] = 'C:\path;C:\another_path'
expect(provider.validatecmd('foo')).to eq(nil)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/provider/exec/shell_spec.rb | spec/unit/provider/exec/shell_spec.rb | require 'spec_helper'
describe Puppet::Type.type(:exec).provider(:shell),
unless: Puppet::Util::Platform.windows? || Puppet::Util::Platform.jruby? do
let(:resource) { Puppet::Type.type(:exec).new(:title => 'foo', :provider => 'shell') }
let(:provider) { described_class.new(resource) }
describe "#run" do
it "should be able to run builtin shell commands" do
output, status = provider.run("if [ 1 = 1 ]; then echo 'blah'; fi")
expect(status.exitstatus).to eq(0)
expect(output).to eq("blah\n")
end
it "should be able to run commands with single quotes in them" do
output, status = provider.run("echo 'foo bar'")
expect(status.exitstatus).to eq(0)
expect(output).to eq("foo bar\n")
end
it "should be able to run commands with double quotes in them" do
output, status = provider.run('echo "foo bar"')
expect(status.exitstatus).to eq(0)
expect(output).to eq("foo bar\n")
end
it "should be able to run multiple commands separated by a semicolon" do
output, status = provider.run("echo 'foo' ; echo 'bar'")
expect(status.exitstatus).to eq(0)
expect(output).to eq("foo\nbar\n")
end
it "should be able to read values from the environment parameter" do
resource[:environment] = "FOO=bar"
output, status = provider.run("echo $FOO")
expect(status.exitstatus).to eq(0)
expect(output).to eq("bar\n")
end
it "#14060: should interpolate inside the subshell, not outside it" do
resource[:environment] = "foo=outer"
output, status = provider.run("foo=inner; echo \"foo is $foo\"")
expect(status.exitstatus).to eq(0)
expect(output).to eq("foo is inner\n")
end
end
describe "#validatecmd" do
it "should always return true because builtins don't need path or to be fully qualified" do
expect(provider.validatecmd('whateverdoesntmatter')).to eq(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/provider/group/pw_spec.rb | spec/unit/provider/group/pw_spec.rb | require 'spec_helper'
describe Puppet::Type.type(:group).provider(:pw) do
let :resource do
Puppet::Type.type(:group).new(:name => "testgroup", :provider => :pw)
end
let :provider do
resource.provider
end
describe "when creating groups" do
let :provider do
prov = resource.provider
expect(prov).to receive(:exists?).and_return(nil)
prov
end
it "should run pw with no additional flags when no properties are given" do
expect(provider.addcmd).to eq([described_class.command(:pw), "groupadd", "testgroup"])
expect(provider).to receive(:execute).with([described_class.command(:pw), "groupadd", "testgroup"], kind_of(Hash))
provider.create
end
it "should use -o when allowdupe is enabled" do
resource[:allowdupe] = true
expect(provider).to receive(:execute).with(include("-o"), kind_of(Hash))
provider.create
end
it "should use -g with the correct argument when the gid property is set" do
resource[:gid] = 12345
expect(provider).to receive(:execute).with(include("-g") & include(12345), kind_of(Hash))
provider.create
end
it "should use -M with the correct argument when the members property is set" do
resource[:members] = "user1"
expect(provider).to receive(:execute).with(include("-M") & include("user1"), kind_of(Hash))
provider.create
end
it "should use -M with all the given users when the members property is set to an array" do
resource[:members] = ["user1", "user2"]
expect(provider).to receive(:execute).with(include("-M") & include("user1,user2"), kind_of(Hash))
provider.create
end
end
describe "when deleting groups" do
it "should run pw with no additional flags" do
expect(provider).to receive(:exists?).and_return(true)
expect(provider.deletecmd).to eq([described_class.command(:pw), "groupdel", "testgroup"])
expect(provider).to receive(:execute).with([described_class.command(:pw), "groupdel", "testgroup"], hash_including(:custom_environment => {}))
provider.delete
end
end
describe "when modifying groups" do
it "should run pw with the correct arguments" do
expect(provider.modifycmd("gid", 12345)).to eq([described_class.command(:pw), "groupmod", "testgroup", "-g", 12345])
expect(provider).to receive(:execute).with([described_class.command(:pw), "groupmod", "testgroup", "-g", 12345], hash_including(:custom_environment => {}))
provider.gid = 12345
end
it "should use -M with the correct argument when the members property is changed" do
resource[:members] = "user1"
expect(provider).to receive(:execute).with(include("-M") & include("user2"), hash_including(:custom_environment, {}))
provider.members = "user2"
end
it "should use -M with all the given users when the members property is changed with an array" do
resource[:members] = ["user1", "user2"]
expect(provider).to receive(:execute).with(include("-M") & include("user3,user4"), hash_including(:custom_environment, {}))
provider.members = ["user3", "user4"]
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/provider/group/ldap_spec.rb | spec/unit/provider/group/ldap_spec.rb | require 'spec_helper'
describe Puppet::Type.type(:group).provider(:ldap) do
it "should have the Ldap provider class as its baseclass" do
expect(described_class.superclass).to equal(Puppet::Provider::Ldap)
end
it "should manage :posixGroup objectclass" do
expect(described_class.manager.objectclasses).to eq([:posixGroup])
end
it "should use 'ou=Groups' as its relative base" do
expect(described_class.manager.location).to eq("ou=Groups")
end
it "should use :cn as its rdn" do
expect(described_class.manager.rdn).to eq(:cn)
end
it "should map :name to 'cn'" do
expect(described_class.manager.ldap_name(:name)).to eq('cn')
end
it "should map :gid to 'gidNumber'" do
expect(described_class.manager.ldap_name(:gid)).to eq('gidNumber')
end
it "should map :members to 'memberUid', to be used by the user ldap provider" do
expect(described_class.manager.ldap_name(:members)).to eq('memberUid')
end
describe "when being created" do
before do
# So we don't try to actually talk to ldap
@connection = double('connection')
allow(described_class.manager).to receive(:connect).and_yield(@connection)
end
describe "with no gid specified" do
it "should pick the first available GID after the largest existing GID" do
low = {:name=>["luke"], :gid=>["600"]}
high = {:name=>["testing"], :gid=>["640"]}
expect(described_class.manager).to receive(:search).and_return([low, high])
resource = double('resource', :should => %w{whatever})
allow(resource).to receive(:should).with(:gid).and_return(nil)
allow(resource).to receive(:should).with(:ensure).and_return(:present)
instance = described_class.new(:name => "luke", :ensure => :absent)
allow(instance).to receive(:resource).and_return(resource)
expect(@connection).to receive(:add).with(anything, hash_including("gidNumber" => ["641"]))
instance.create
instance.flush
end
it "should pick '501' as its GID if no groups are found" do
expect(described_class.manager).to receive(:search).and_return(nil)
resource = double('resource', :should => %w{whatever})
allow(resource).to receive(:should).with(:gid).and_return(nil)
allow(resource).to receive(:should).with(:ensure).and_return(:present)
instance = described_class.new(:name => "luke", :ensure => :absent)
allow(instance).to receive(:resource).and_return(resource)
expect(@connection).to receive(:add).with(anything, hash_including("gidNumber" => ["501"]))
instance.create
instance.flush
end
end
end
it "should have a method for converting group names to GIDs" do
expect(described_class).to respond_to(:name2id)
end
describe "when converting from a group name to GID" do
it "should use the ldap manager to look up the GID" do
expect(described_class.manager).to receive(:search).with("cn=foo")
described_class.name2id("foo")
end
it "should return nil if no group is found" do
expect(described_class.manager).to receive(:search).with("cn=foo").and_return(nil)
expect(described_class.name2id("foo")).to be_nil
expect(described_class.manager).to receive(:search).with("cn=bar").and_return([])
expect(described_class.name2id("bar")).to be_nil
end
# We shouldn't ever actually have more than one gid, but it doesn't hurt
# to test for the possibility.
it "should return the first gid from the first returned group" do
expect(described_class.manager).to receive(:search).with("cn=foo").and_return([{:name => "foo", :gid => [10, 11]}, {:name => :bar, :gid => [20, 21]}])
expect(described_class.name2id("foo")).to eq(10)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/provider/group/aix_spec.rb | spec/unit/provider/group/aix_spec.rb | require 'spec_helper'
describe 'Puppet::Type::Group::Provider::Aix' do
let(:provider_class) { Puppet::Type.type(:group).provider(:aix) }
let(:resource) do
Puppet::Type.type(:group).new(
:name => 'test_aix_user',
:ensure => :present
)
end
let(:provider) do
provider_class.new(resource)
end
describe '.find' do
let(:groups) do
objects = [
{ :name => 'group1', :id => '1' },
{ :name => 'group2', :id => '2' }
]
objects
end
let(:ia_module_args) { [ '-R', 'module' ] }
let(:expected_group) do
{
:name => 'group1',
:gid => 1
}
end
before(:each) do
allow(provider_class).to receive(:list_all).with(ia_module_args).and_return(groups)
end
it 'raises an ArgumentError if the group does not exist' do
expect do
provider_class.find('non_existent_group', ia_module_args)
end.to raise_error do |error|
expect(error).to be_a(ArgumentError)
expect(error.message).to match('non_existent_group')
end
end
it 'can find the group when passed-in a group name' do
expect(provider_class.find('group1', ia_module_args)).to eql(expected_group)
end
it 'can find the group when passed-in the gid' do
expect(provider_class.find(1, ia_module_args)).to eql(expected_group)
end
end
describe '.users_to_members' do
it 'converts the users attribute to the members property' do
expect(provider_class.users_to_members('foo,bar'))
.to eql(['foo', 'bar'])
end
end
describe '.members_to_users' do
context 'when auth_membership == true' do
before(:each) do
resource[:auth_membership] = true
end
it 'returns only the passed-in members' do
expect(provider_class.members_to_users(provider, ['user1', 'user2']))
.to eql('user1,user2')
end
end
context 'when auth_membership == false' do
before(:each) do
resource[:auth_membership] = false
allow(provider).to receive(:members).and_return(['user3', 'user1'])
end
it 'adds the passed-in members to the current list of members, filtering out any duplicates' do
expect(provider_class.members_to_users(provider, ['user1', 'user2']))
.to eql('user1,user2,user3')
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/provider/group/windows_adsi_spec.rb | spec/unit/provider/group/windows_adsi_spec.rb | require 'spec_helper'
describe Puppet::Type.type(:group).provider(:windows_adsi), :if => Puppet::Util::Platform.windows? do
let(:resource) do
Puppet::Type.type(:group).new(
:title => 'testers',
:provider => :windows_adsi
)
end
let(:provider) { resource.provider }
let(:connection) { double('connection') }
before :each do
allow(Puppet::Util::Windows::ADSI).to receive(:computer_name).and_return('testcomputername')
allow(Puppet::Util::Windows::ADSI).to receive(:connect).and_return(connection)
# this would normally query the system, but not needed for these tests
allow(Puppet::Util::Windows::ADSI::Group).to receive(:localized_domains).and_return([])
end
describe ".instances" do
it "should enumerate all groups" do
names = ['group1', 'group2', 'group3']
stub_groups = names.map{|n| double(:name => n)}
allow(connection).to receive(:execquery).with('select name from win32_group where localaccount = "TRUE"').and_return(stub_groups)
expect(described_class.instances.map(&:name)).to match(names)
end
end
describe "group type :members property helpers" do
let(:user1) { double(:account => 'user1', :domain => '.', :sid => 'user1sid') }
let(:user2) { double(:account => 'user2', :domain => '.', :sid => 'user2sid') }
let(:user3) { double(:account => 'user3', :domain => '.', :sid => 'user3sid') }
let(:user_without_domain) { double(:account => 'user_without_domain', :domain => nil, :sid => 'user_without_domain_sid') }
let(:invalid_user) { SecureRandom.uuid }
let(:invalid_user_principal) { double(:account => "#{invalid_user}", :domain => nil, :sid => "#{invalid_user}") }
before :each do
allow(Puppet::Util::Windows::SID).to receive(:name_to_principal).with('user1', any_args).and_return(user1)
allow(Puppet::Util::Windows::SID).to receive(:name_to_principal).with('user2', any_args).and_return(user2)
allow(Puppet::Util::Windows::SID).to receive(:name_to_principal).with('user3', any_args).and_return(user3)
allow(Puppet::Util::Windows::SID).to receive(:name_to_principal).with('user_without_domain', any_args).and_return(user_without_domain)
allow(Puppet::Util::Windows::SID).to receive(:name_to_principal).with(invalid_user).and_return(nil)
allow(Puppet::Util::Windows::SID).to receive(:name_to_principal).with(invalid_user, true).and_return(invalid_user_principal)
end
describe "#members_insync?" do
it "should return true for same lists of members" do
current = [
'user1',
'user2',
]
expect(provider.members_insync?(current, ['user1', 'user2'])).to be_truthy
end
it "should return true for same lists of unordered members" do
current = [
'user1',
'user2',
]
expect(provider.members_insync?(current, ['user2', 'user1'])).to be_truthy
end
it "should return true for same lists of members irrespective of duplicates" do
current = [
'user1',
'user2',
'user2',
]
expect(provider.members_insync?(current, ['user2', 'user1', 'user1'])).to be_truthy
end
it "should return true when current and should members are empty lists" do
expect(provider.members_insync?([], [])).to be_truthy
end
# invalid scenarios
#it "should return true when current and should members are nil lists" do
#it "should return true when current members is nil and should members is empty" do
it "should return true when current members is empty and should members is nil" do
expect(provider.members_insync?([], nil)).to be_truthy
end
context "when auth_membership => true" do
before :each do
resource[:auth_membership] = true
end
it "should return true when current and should contain the same users in a different order" do
current = [
'user1',
'user2',
'user3',
]
expect(provider.members_insync?(current, ['user3', 'user1', 'user2'])).to be_truthy
end
it "should return false when current is nil" do
expect(provider.members_insync?(nil, ['user2'])).to be_falsey
end
it "should return false when should is nil" do
current = [
'user1',
]
expect(provider.members_insync?(current, nil)).to be_falsey
end
it "should return false when current contains different users than should" do
current = [
'user1',
]
expect(provider.members_insync?(current, ['user2'])).to be_falsey
end
it "should return false when current contains members and should is empty" do
current = [
'user1',
]
expect(provider.members_insync?(current, [])).to be_falsey
end
it "should return false when current is empty and should contains members" do
expect(provider.members_insync?([], ['user2'])).to be_falsey
end
it "should return false when should user(s) are not the only items in the current" do
current = [
'user1',
'user2',
]
expect(provider.members_insync?(current, ['user1'])).to be_falsey
end
it "should return false when current user(s) is not empty and should is an empty list" do
current = [
'user1',
'user2',
]
expect(provider.members_insync?(current, [])).to be_falsey
end
end
context "when auth_membership => false" do
before :each do
# this is also the default
resource[:auth_membership] = false
end
it "should return false when current is nil" do
expect(provider.members_insync?(nil, ['user2'])).to be_falsey
end
it "should return true when should is nil" do
current = [
'user1',
]
expect(provider.members_insync?(current, nil)).to be_truthy
end
it "should return false when current contains different users than should" do
current = [
'user1',
]
expect(provider.members_insync?(current, ['user2'])).to be_falsey
end
it "should return true when current contains members and should is empty" do
current = [
'user1',
]
expect(provider.members_insync?(current, [])).to be_truthy
end
it "should return false when current is empty and should contains members" do
expect(provider.members_insync?([], ['user2'])).to be_falsey
end
it "should return true when current user(s) contains at least the should list" do
current = [
'user1',
'user2',
]
expect(provider.members_insync?(current, ['user1'])).to be_truthy
end
it "should return true when current user(s) is not empty and should is an empty list" do
current = [
'user1',
'user2',
]
expect(provider.members_insync?(current, [])).to be_truthy
end
it "should return true when current user(s) contains at least the should list, even unordered" do
current = [
'user3',
'user1',
'user2',
]
expect(provider.members_insync?(current, ['user2','user1'])).to be_truthy
end
it "should return true even if a current user is unresolvable if should is included" do
current = [
"#{invalid_user}",
'user2',
]
expect(provider.members_insync?(current, ['user2'])).to be_truthy
end
end
end
describe "#members_to_s" do
it "should return an empty string on non-array input" do
[Object.new, {}, 1, :symbol, ''].each do |input|
expect(provider.members_to_s(input)).to be_empty
end
end
it "should return an empty string on empty or nil users" do
expect(provider.members_to_s([])).to be_empty
expect(provider.members_to_s(nil)).to be_empty
end
it "should return a user string like DOMAIN\\USER" do
expect(provider.members_to_s(['user1'])).to eq('.\user1')
end
it "should return a user string like DOMAIN\\USER,DOMAIN2\\USER2" do
expect(provider.members_to_s(['user1', 'user2'])).to eq('.\user1,.\user2')
end
it "should return a user string without domain if domain is not set" do
expect(provider.members_to_s(['user_without_domain'])).to eq('user_without_domain')
end
it "should return the username when it cannot be resolved to a SID (for the sake of resource_harness error messages)" do
expect(provider.members_to_s([invalid_user])).to eq("#{invalid_user}")
end
end
end
describe "when managing members" do
let(:user1) { double(:account => 'user1', :domain => '.', :sid => 'user1sid') }
let(:user2) { double(:account => 'user2', :domain => '.', :sid => 'user2sid') }
let(:user3) { double(:account => 'user3', :domain => '.', :sid => 'user3sid') }
let(:invalid_user) { SecureRandom.uuid }
let(:invalid_user_principal) { double(:account => "#{invalid_user}", :domain => nil, :sid => "#{invalid_user}") }
before :each do
allow(Puppet::Util::Windows::SID).to receive(:name_to_principal).with('user1', any_args).and_return(user1)
allow(Puppet::Util::Windows::SID).to receive(:name_to_principal).with('user2', any_args).and_return(user2)
allow(Puppet::Util::Windows::SID).to receive(:name_to_principal).with('user3', any_args).and_return(user3)
allow(Puppet::Util::Windows::SID).to receive(:name_to_principal).with(invalid_user, true).and_return(invalid_user_principal)
resource[:auth_membership] = true
end
it "should be able to provide a list of members" do
allow(provider.group).to receive(:members).and_return([
'user1',
'user2',
'user3',
])
expected_member_sids = [user1.sid, user2.sid, user3.sid]
expected_members = ['user1', 'user2', 'user3']
allow(provider).to receive(:members_to_s)
.with(expected_member_sids)
.and_return(expected_members.join(','))
expect(provider.members).to match_array(expected_members)
end
it "should be able to handle unresolvable SID in list of members" do
allow(provider.group).to receive(:members).and_return([
'user1',
"#{invalid_user}",
'user3',
])
expected_member_sids = [user1.sid, invalid_user_principal.sid, user3.sid]
expected_members = ['user1', "#{invalid_user}", 'user3']
allow(provider).to receive(:members_to_s)
.with(expected_member_sids)
.and_return(expected_members.join(','))
expect(provider.members).to match_array(expected_members)
end
it "should be able to set group members" do
allow(provider.group).to receive(:members).and_return(['user1', 'user2'])
member_sids = [
double(:account => 'user1', :domain => 'testcomputername', :sid => 1),
double(:account => 'user2', :domain => 'testcomputername', :sid => 2),
double(:account => 'user3', :domain => 'testcomputername', :sid => 3),
]
allow(provider.group).to receive(:member_sids).and_return(member_sids[0..1])
expect(Puppet::Util::Windows::SID).to receive(:name_to_principal).with('user2', any_args).and_return(member_sids[1])
expect(Puppet::Util::Windows::SID).to receive(:name_to_principal).with('user3', any_args).and_return(member_sids[2])
expect(provider.group).to receive(:remove_member_sids).with(member_sids[0])
expect(provider.group).to receive(:add_member_sids).with(member_sids[2])
provider.members = ['user2', 'user3']
end
end
describe 'when creating groups' do
it "should be able to create a group" do
resource[:members] = ['user1', 'user2']
group = double('group')
expect(Puppet::Util::Windows::ADSI::Group).to receive(:create).with('testers').and_return(group)
expect(group).to receive(:commit).ordered
# due to PUP-1967, defaultto false will set the default to nil
expect(group).to receive(:set_members).with(['user1', 'user2'], nil).ordered
provider.create
end
it 'should not create a group if a user by the same name exists' do
expect(Puppet::Util::Windows::ADSI::Group).to receive(:create).with('testers').and_raise(Puppet::Error.new("Cannot create group if user 'testers' exists."))
expect{ provider.create }.to raise_error( Puppet::Error,
/Cannot create group if user 'testers' exists./ )
end
it "should fail with an actionable message when trying to create an active directory group" do
resource[:name] = 'DOMAIN\testdomaingroup'
expect(Puppet::Util::Windows::ADSI::User).to receive(:exists?).with(resource[:name]).and_return(false)
expect(connection).to receive(:Create)
expect(connection).to receive(:SetInfo).and_raise( WIN32OLERuntimeError.new("(in OLE method `SetInfo': )\n OLE error code:8007089A in Active Directory\n The specified username is invalid.\r\n\n HRESULT error code:0x80020009\n Exception occurred."))
expect{ provider.create }.to raise_error(Puppet::Error)
end
it 'should commit a newly created group' do
expect(provider.group).to receive( :commit )
provider.flush
end
end
it "should be able to test whether a group exists" do
allow(Puppet::Util::Windows::SID).to receive(:name_to_principal).and_return(nil)
allow(Puppet::Util::Windows::ADSI).to receive(:connect).and_return(double('connection', :Class => 'Group'))
expect(provider).to be_exists
allow(Puppet::Util::Windows::ADSI).to receive(:connect).and_return(nil)
expect(provider).not_to be_exists
end
it "should be able to delete a group" do
expect(connection).to receive(:Delete).with('group', 'testers')
provider.delete
end
it 'should not run commit on a deleted group' do
expect(connection).to receive(:Delete).with('group', 'testers')
expect(connection).not_to receive(:SetInfo)
provider.delete
provider.flush
end
it "should report the group's SID as gid" do
expect(Puppet::Util::Windows::SID).to receive(:name_to_sid).with('testers').and_return('S-1-5-32-547')
expect(provider.gid).to eq('S-1-5-32-547')
end
it "should fail when trying to manage the gid property" do
expect(provider).to receive(:fail).with(/gid is read-only/)
provider.send(:gid=, 500)
end
it "should prefer the domain component from the resolved SID" do
# must lookup well known S-1-5-32-544 as actual 'Administrators' name may be localized
admins_sid_bytes = [1, 2, 0, 0, 0, 0, 0, 5, 32, 0, 0, 0, 32, 2, 0, 0]
admins_group = Puppet::Util::Windows::SID::Principal.lookup_account_sid(admins_sid_bytes)
# prefix just the name like .\Administrators
converted = provider.members_to_s([".\\#{admins_group.account}"])
# and ensure equivalent of BUILTIN\Administrators, without a leading .
expect(converted).to eq(admins_group.domain_account)
expect(converted[0]).to_not eq('.')
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/provider/group/groupadd_spec.rb | spec/unit/provider/group/groupadd_spec.rb | require 'spec_helper'
RSpec::Matchers.define_negated_matcher :excluding, :include
describe Puppet::Type.type(:group).provider(:groupadd) do
before do
allow(described_class).to receive(:command).with(:add).and_return('/usr/sbin/groupadd')
allow(described_class).to receive(:command).with(:delete).and_return('/usr/sbin/groupdel')
allow(described_class).to receive(:command).with(:modify).and_return('/usr/sbin/groupmod')
allow(described_class).to receive(:command).with(:localadd).and_return('/usr/sbin/lgroupadd')
allow(described_class).to receive(:command).with(:localdelete).and_return('/usr/sbin/lgroupdel')
allow(described_class).to receive(:command).with(:localmodify).and_return('/usr/sbin/lgroupmod')
end
let(:resource) { Puppet::Type.type(:group).new(:name => 'mygroup', :provider => provider) }
let(:provider) { described_class.new(:name => 'mygroup') }
let(:members) { ['user2', 'user1', 'user3'] }
describe "#create" do
before do
allow(provider).to receive(:exists?).and_return(false)
end
it "should add -o when allowdupe is enabled and the group is being created" do
resource[:allowdupe] = :true
expect(provider).to receive(:execute).with(['/usr/sbin/groupadd', '-o', 'mygroup'], kind_of(Hash))
provider.create
end
describe "on system that feature system_groups", :if => described_class.system_groups? do
it "should add -r when system is enabled and the group is being created" do
resource[:system] = :true
expect(provider).to receive(:execute).with(['/usr/sbin/groupadd', '-r', 'mygroup'], kind_of(Hash))
provider.create
end
end
describe "on system that do not feature system_groups", :unless => described_class.system_groups? do
it "should not add -r when system is enabled and the group is being created" do
resource[:system] = :true
expect(provider).to receive(:execute).with(['/usr/sbin/groupadd', 'mygroup'], kind_of(Hash))
provider.create
end
end
describe "on systems with libuser" do
before do
allow(Puppet.features).to receive(:libuser?).and_return(true)
end
describe "with forcelocal=true" do
before do
described_class.has_feature(:manages_local_users_and_groups)
resource[:forcelocal] = :true
end
it "should use lgroupadd instead of groupadd" do
expect(provider).to receive(:execute).with(including('/usr/sbin/lgroupadd'), hash_including(:custom_environment => hash_including('LIBUSER_CONF')))
provider.create
end
it "should NOT pass -o to lgroupadd" do
resource[:allowdupe] = :true
expect(provider).to receive(:execute).with(excluding('-o'), hash_including(:custom_environment => hash_including('LIBUSER_CONF')))
provider.create
end
it "should raise an exception for duplicate GID if allowdupe is not set and duplicate GIDs exist" do
resource[:gid] = 505
allow(provider).to receive(:findgroup).and_return(true)
expect { provider.create }.to raise_error(Puppet::Error, "GID 505 already exists, use allowdupe to force group creation")
end
end
describe "with a list of members" do
before do
members.each { |m| allow(Etc).to receive(:getpwnam).with(m).and_return(true) }
allow(provider).to receive(:flag).and_return('-M')
described_class.has_feature(:manages_members)
resource[:forcelocal] = false
resource[:members] = members
end
it "should use lgroupmod to add the members" do
allow(provider).to receive(:execute).with(['/usr/sbin/groupadd', 'mygroup'], hash_including({:failonfail => true, :combine => true, :custom_environment => {}})).and_return(true)
expect(provider).to receive(:execute).with(['/usr/sbin/lgroupmod', '-M', members.join(','), 'mygroup'], hash_including(:custom_environment => hash_including('LIBUSER_CONF')))
provider.create
end
end
end
end
describe "#modify" do
before do
allow(provider).to receive(:exists?).and_return(true)
end
describe "on systems with libuser" do
before do
allow(Puppet.features).to receive(:libuser?).and_return(true)
end
describe "with forcelocal=false" do
before do
described_class.has_feature(:manages_local_users_and_groups)
resource[:forcelocal] = :false
end
it "should use groupmod" do
expect(provider).to receive(:execute).with(['/usr/sbin/groupmod', '-g', 150, 'mygroup'], hash_including({:failonfail => true, :combine => true, :custom_environment => {}}))
provider.gid = 150
end
it "should pass -o to groupmod" do
resource[:allowdupe] = :true
expect(provider).to receive(:execute).with(['/usr/sbin/groupmod', '-g', 150, '-o', 'mygroup'], hash_including({:failonfail => true, :combine => true, :custom_environment => {}}))
provider.gid = 150
end
end
describe "with forcelocal=true" do
before do
described_class.has_feature(:manages_local_users_and_groups)
resource[:forcelocal] = :true
end
it "should use lgroupmod instead of groupmod" do
expect(provider).to receive(:execute).with(['/usr/sbin/lgroupmod', '-g', 150, 'mygroup'], hash_including(:custom_environment => hash_including('LIBUSER_CONF')))
provider.gid = 150
end
it "should NOT pass -o to lgroupmod" do
resource[:allowdupe] = :true
expect(provider).to receive(:execute).with(['/usr/sbin/lgroupmod', '-g', 150, 'mygroup'], hash_including(:custom_environment => hash_including('LIBUSER_CONF')))
provider.gid = 150
end
it "should raise an exception for duplicate GID if allowdupe is not set and duplicate GIDs exist" do
resource[:gid] = 150
resource[:allowdupe] = :false
allow(provider).to receive(:findgroup).and_return(true)
expect { provider.gid = 150 }.to raise_error(Puppet::Error, "GID 150 already exists, use allowdupe to force group creation")
end
end
describe "with members=something" do
before do
described_class.has_feature(:manages_members)
allow(Etc).to receive(:getpwnam).and_return(true)
resource[:members] = members
end
describe "with auth_membership on" do
before { resource[:auth_membership] = true }
it "should purge existing users before adding" do
allow(provider).to receive(:members).and_return(members)
expect(provider).to receive(:localmodify).with('-m', members.join(','), 'mygroup')
provider.modifycmd(:members, ['user1'])
end
end
describe "with auth_membership off" do
before { resource[:auth_membership] = false }
it "should add to the existing users" do
allow(provider).to receive(:flag).and_return('-M')
new_members = ['user1', 'user2', 'user3', 'user4']
allow(provider).to receive(:members).and_return(members)
expect(provider).not_to receive(:localmodify).with('-m', members.join(','), 'mygroup')
expect(provider).to receive(:execute).with(['/usr/sbin/lgroupmod', '-M', new_members.join(','), 'mygroup'], kind_of(Hash))
provider.members = new_members
end
end
it "should validate members" do
expect(Etc).to receive(:getpwnam).with('user3').and_return(true)
provider.modifycmd(:members, ['user3'])
end
it "should validate members list " do
expect(Etc).to receive(:getpwnam).with('user3').and_return(true)
expect(Etc).to receive(:getpwnam).with('user4').and_return(true)
provider.modifycmd(:members, ['user3', 'user4'])
end
it "should validate members list separated by commas" do
expect(Etc).to receive(:getpwnam).with('user3').and_return(true)
expect(Etc).to receive(:getpwnam).with('user4').and_return(true)
provider.modifycmd(:members, ['user3, user4'])
end
it "should raise is validation fails" do
expect(Etc).to receive(:getpwnam).with('user3').and_throw(ArgumentError)
expect { provider.modifycmd(:members, ['user3']) }.to raise_error(ArgumentError)
end
end
end
end
describe "#gid=" do
it "should add -o when allowdupe is enabled and the gid is being modified" do
resource[:allowdupe] = :true
expect(provider).to receive(:execute).with(['/usr/sbin/groupmod', '-g', 150, '-o', 'mygroup'], hash_including({:failonfail => true, :combine => true, :custom_environment => {}}))
provider.gid = 150
end
end
describe "#findgroup" do
before do
allow(Puppet::FileSystem).to receive(:exist?).with('/etc/group').and_return(true)
allow(Puppet::FileSystem).to receive(:each_line).with('/etc/group').and_yield(content)
end
let(:content) { "sample_group_name:sample_password:sample_gid:sample_user_list" }
let(:output) do
{
group_name: 'sample_group_name',
password: 'sample_password',
gid: 'sample_gid',
user_list: 'sample_user_list',
}
end
[:group_name, :password, :gid, :user_list].each do |key|
it "finds a group by #{key} when asked" do
expect(provider.send(:findgroup, key, "sample_#{key}")).to eq(output)
end
end
it "returns false when specified key/value pair is not found" do
expect(provider.send(:findgroup, :group_name, 'invalid_group_name')).to eq(false)
end
it "reads the group file only once per resource" do
expect(Puppet::FileSystem).to receive(:each_line).with('/etc/group').once
5.times { provider.send(:findgroup, :group_name, 'sample_group_name') }
end
end
describe "#delete" do
before do
allow(provider).to receive(:exists?).and_return(true)
end
describe "on systems with the libuser and forcelocal=false" do
before do
allow(Puppet.features).to receive(:libuser?).and_return(true)
end
before do
described_class.has_feature(:manages_local_users_and_groups)
resource[:forcelocal] = :false
end
it "should use groupdel" do
expect(provider).to receive(:execute).with(['/usr/sbin/groupdel', 'mygroup'], hash_including({:failonfail => true, :combine => true, :custom_environment => {}}))
provider.delete
end
end
describe "on systems with the libuser and forcelocal=true" do
before do
allow(Puppet.features).to receive(:libuser?).and_return(true)
end
before do
described_class.has_feature(:manages_local_users_and_groups)
resource[:forcelocal] = :true
end
it "should use lgroupdel instead of groupdel" do
expect(provider).to receive(:execute).with(['/usr/sbin/lgroupdel', 'mygroup'], hash_including(:custom_environment => hash_including('LIBUSER_CONF')))
provider.delete
end
end
end
describe "group type :members property helpers" do
describe "#members_to_s" do
it "should return an empty string on non-array input" do
[Object.new, {}, 1, :symbol, ''].each do |input|
expect(provider.members_to_s(input)).to be_empty
end
end
it "should return an empty string on empty or nil users" do
expect(provider.members_to_s([])).to be_empty
expect(provider.members_to_s(nil)).to be_empty
end
it "should return a user string for a single user" do
expect(provider.members_to_s(['user1'])).to eq('user1')
end
it "should return a user string for multiple users" do
expect(provider.members_to_s(['user1', 'user2'])).to eq('user1,user2')
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/provider/group/directoryservice_spec.rb | spec/unit/provider/group/directoryservice_spec.rb | require 'spec_helper'
describe Puppet::Type.type(:group).provider(:directoryservice) do
let :resource do
Puppet::Type.type(:group).new(
:title => 'testgroup',
:provider => :directoryservice,
)
end
let(:provider) { resource.provider }
it 'should return true for same lists of unordered members' do
expect(provider.members_insync?(['user1', 'user2'], ['user2', 'user1'])).to be_truthy
end
it 'should return false when the group currently has no members' do
expect(provider.members_insync?([], ['user2', 'user1'])).to be_falsey
end
it 'should return true for the same lists of members irrespective of duplicates' do
expect(provider.members_insync?(['user1', 'user2', 'user2'], ['user1', 'user2'])).to be_truthy
end
it "should return true when current and should members are empty lists" do
expect(provider.members_insync?([], [])).to be_truthy
end
it "should return true when current is :absent and should members is empty list" do
expect(provider.members_insync?(:absent, [])).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/provider/nameservice/directoryservice_spec.rb | spec/unit/provider/nameservice/directoryservice_spec.rb | require 'spec_helper'
module Puppet::Util::Plist
end
# We use this as a reasonable way to obtain all the support infrastructure.
[:group].each do |type_for_this_round|
describe Puppet::Type.type(type_for_this_round).provider(:directoryservice) do
before do
@resource = double("resource")
allow(@resource).to receive(:[]).with(:name)
@provider = described_class.new(@resource)
end
it "[#6009] should handle nested arrays of members" do
current = ["foo", "bar", "baz"]
desired = ["foo", ["quux"], "qorp"]
group = 'example'
allow(@resource).to receive(:[]).with(:name).and_return(group)
allow(@resource).to receive(:[]).with(:auth_membership).and_return(true)
@provider.instance_variable_set(:@property_value_cache_hash,
{ :members => current })
%w{bar baz}.each do |del|
expect(@provider).to receive(:execute).once.
with([:dseditgroup, '-o', 'edit', '-n', '.', '-d', del, group])
end
%w{quux qorp}.each do |add|
expect(@provider).to receive(:execute).once.
with([:dseditgroup, '-o', 'edit', '-n', '.', '-a', add, group])
end
expect { @provider.set(:members, desired) }.to_not raise_error
end
end
end
describe Puppet::Provider::NameService::DirectoryService do
context '.single_report' do
it 'should use plist data' do
allow(Puppet::Provider::NameService::DirectoryService).to receive(:get_ds_path).and_return('Users')
allow(Puppet::Provider::NameService::DirectoryService).to receive(:list_all_present).and_return(
['root', 'user1', 'user2', 'resource_name']
)
allow(Puppet::Provider::NameService::DirectoryService).to receive(:generate_attribute_hash)
allow(Puppet::Provider::NameService::DirectoryService).to receive(:execute)
expect(Puppet::Provider::NameService::DirectoryService).to receive(:parse_dscl_plist_data)
Puppet::Provider::NameService::DirectoryService.single_report('resource_name')
end
end
context '.get_exec_preamble' do
it 'should use plist data' do
allow(Puppet::Provider::NameService::DirectoryService).to receive(:get_ds_path).and_return('Users')
expect(Puppet::Provider::NameService::DirectoryService.get_exec_preamble('-list')).to include("-plist")
end
end
context 'password behavior' do
# The below is a binary plist containing a ShadowHashData key which CONTAINS
# another binary plist. The nested binary plist contains a 'SALTED-SHA512'
# key that contains a base64 encoded salted-SHA512 password hash...
let (:binary_plist) { "bplist00\324\001\002\003\004\005\006\a\bXCRAM-MD5RNT]SALTED-SHA512[RECOVERABLEO\020 \231k2\3360\200GI\201\355J\216\202\215y\243\001\206J\300\363\032\031\022\006\2359\024\257\217<\361O\020\020F\353\at\377\277\226\276c\306\254\031\037J(\235O\020D\335\006{\3744g@\377z\204\322\r\332t\021\330\n\003\246K\223\356\034!P\261\305t\035\346\352p\206\003n\247MMA\310\301Z<\366\246\023\0161W3\340\357\000\317T\t\301\311+\204\246L7\276\370\320*\245O\021\002\000k\024\221\270x\353\001\237\346D}\377?\265]\356+\243\v[\350\316a\340h\376<\322\266\327\016\306n\272r\t\212A\253L\216\214\205\016\241 [\360/\335\002#\\A\372\241a\261\346\346\\\251\330\312\365\016\n\341\017\016\225&;\322\\\004*\ru\316\372\a \362?8\031\247\231\030\030\267\315\023\v\343{@\227\301s\372h\212\000a\244&\231\366\nt\277\2036,\027bZ+\223W\212g\333`\264\331N\306\307\362\257(^~ b\262\247&\231\261t\341\231%\244\247\203eOt\365\271\201\273\330\350\363C^A\327F\214!\217hgf\e\320k\260n\315u~\336\371M\t\235k\230S\375\311\303\240\351\037d\273\321y\335=K\016`_\317\230\2612_\023K\036\350\v\232\323Y\310\317_\035\227%\237\v\340\023\016\243\233\025\306:\227\351\370\364x\234\231\266\367\016w\275\333-\351\210}\375x\034\262\272kRuHa\362T/F!\347B\231O`K\304\037'k$$\245h)e\363\365mT\b\317\\2\361\026\351\254\375Jl1~\r\371\267\352\2322I\341\272\376\243^Un\266E7\230[VocUJ\220N\2116D/\025f=\213\314\325\vG}\311\360\377DT\307m\261&\263\340\272\243_\020\271rG^BW\210\030l\344\0324\335\233\300\023\272\225Im\330\n\227*Yv[\006\315\330y'\a\321\373\273A\240\305F{S\246I#/\355\2425\031\031GGF\270y\n\331\004\023G@\331\000\361\343\350\264$\032\355_\210y\000\205\342\375\212q\024\004\026W:\205 \363v?\035\270L-\270=\022\323\2003\v\336\277\t\237\356\374\n\267n\003\367\342\330;\371S\326\016`B6@Njm>\240\021%\336\345\002(P\204Yn\3279l\0228\264\254\304\2528t\372h\217\347sA\314\345\245\337)]\000\b\000\021\000\032\000\035\000+\0007\000Z\000m\000\264\000\000\000\000\000\000\002\001\000\000\000\000\000\000\000\t\000\000\000\000\000\000\000\000\000\000\000\000\000\000\002\270" }
# The below is a base64 encoded salted-SHA512 password hash.
let (:pw_string) { "\335\006{\3744g@\377z\204\322\r\332t\021\330\n\003\246K\223\356\034!P\261\305t\035\346\352p\206\003n\247MMA\310\301Z<\366\246\023\0161W3\340\357\000\317T\t\301\311+\204\246L7\276\370\320*\245" }
# The below is a salted-SHA512 password hash in hex.
let (:sha512_hash) { 'dd067bfc346740ff7a84d20dda7411d80a03a64b93ee1c2150b1c5741de6ea7086036ea74d4d41c8c15a3cf6a6130e315733e0ef00cf5409c1c92b84a64c37bef8d02aa5' }
let :plist_path do
'/var/db/dslocal/nodes/Default/users/jeff.plist'
end
let :ds_provider do
described_class
end
let :shadow_hash_data do
{'ShadowHashData' => [binary_plist]}
end
it 'should execute convert_binary_to_hash once when getting the password' do
expect(described_class).to receive(:convert_binary_to_hash).and_return({'SALTED-SHA512' => pw_string})
expect(Puppet::FileSystem).to receive(:exist?).with(plist_path).once.and_return(true)
expect(Puppet::Util::Plist).to receive(:read_plist_file).and_return(shadow_hash_data)
described_class.get_password('uid', 'jeff')
end
it 'should fail if a salted-SHA512 password hash is not passed in' do
expect {
described_class.set_password('jeff', 'uid', 'badpassword')
}.to raise_error(RuntimeError, /OS X 10.7 requires a Salted SHA512 hash password of 136 characters./)
end
it 'should convert xml-to-binary and binary-to-xml when setting the pw on >= 10.7' do
expect(described_class).to receive(:convert_binary_to_hash).and_return({'SALTED-SHA512' => pw_string})
expect(described_class).to receive(:convert_hash_to_binary).and_return(binary_plist)
expect(Puppet::FileSystem).to receive(:exist?).with(plist_path).once.and_return(true)
expect(Puppet::Util::Plist).to receive(:read_plist_file).and_return(shadow_hash_data)
expect(Puppet::Util::Plist).to receive(:write_plist_file).with(shadow_hash_data, plist_path, :binary)
described_class.set_password('jeff', 'uid', sha512_hash)
end
it '[#13686] should handle an empty ShadowHashData field in the users plist' do
expect(described_class).to receive(:convert_hash_to_binary).and_return(binary_plist)
expect(Puppet::FileSystem).to receive(:exist?).with(plist_path).once.and_return(true)
expect(Puppet::Util::Plist).to receive(:read_plist_file).and_return({'ShadowHashData' => nil})
expect(Puppet::Util::Plist).to receive(:write_plist_file)
described_class.set_password('jeff', 'uid', sha512_hash)
end
end
context '(#4855) directoryservice group resource failure' do
let :provider_class do
Puppet::Type.type(:group).provider(:directoryservice)
end
let :group_members do
['root','jeff']
end
let :user_account do
['root']
end
let :stub_resource do
double('resource')
end
subject do
provider_class.new(stub_resource)
end
before :each do
@resource = double("resource")
allow(@resource).to receive(:[]).with(:name)
@provider = provider_class.new(@resource)
end
it 'should delete a group member if the user does not exist' do
allow(stub_resource).to receive(:[]).with(:name).and_return('fake_group')
allow(stub_resource).to receive(:name).and_return('fake_group')
expect(subject).to receive(:execute).with([:dseditgroup, '-o', 'edit', '-n', '.',
'-d', 'jeff',
'fake_group']).and_raise(Puppet::ExecutionFailure, 'it broke')
expect(subject).to receive(:execute).with([:dscl, '.', '-delete',
'/Groups/fake_group', 'GroupMembership',
'jeff'])
subject.remove_unwanted_members(group_members, user_account)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/provider/package/pkgdmg_spec.rb | spec/unit/provider/package/pkgdmg_spec.rb | require 'spec_helper'
describe Puppet::Type.type(:package).provider(:pkgdmg) do
let(:resource) { Puppet::Type.type(:package).new(:name => 'foo', :provider => :pkgdmg) }
let(:provider) { described_class.new(resource) }
it { is_expected.not_to be_versionable }
it { is_expected.not_to be_uninstallable }
describe "when installing it should fail when" do
it "no source is specified" do
expect { provider.install }.to raise_error(Puppet::Error, /must specify a package source/)
end
it "the source does not end in .dmg or .pkg" do
resource[:source] = "bar"
expect { provider.install }.to raise_error(Puppet::Error, /must specify a source string ending in .*dmg.*pkg/)
end
end
# These tests shouldn't be this messy. The pkgdmg provider needs work...
describe "when installing a pkgdmg" do
let(:fake_mountpoint) { "/tmp/dmg.foo" }
let(:fake_hdiutil_plist) { {"system-entities" => [{"mount-point" => fake_mountpoint}]} }
before do
fh = double('filehandle')
allow(fh).to receive(:path).and_return("/tmp/foo")
resource[:source] = "foo.dmg"
allow(File).to receive(:open).and_yield(fh)
allow(Dir).to receive(:mktmpdir).and_return("/tmp/testtmp123")
allow(FileUtils).to receive(:remove_entry_secure)
end
it "should fail when a disk image with no system entities is mounted" do
allow(described_class).to receive(:hdiutil).and_return('empty plist')
expect(Puppet::Util::Plist).to receive(:parse_plist).with('empty plist').and_return({})
expect { provider.install }.to raise_error(Puppet::Error, /No disk entities/)
end
it "should call hdiutil to mount and eject the disk image" do
allow(Dir).to receive(:entries).and_return([])
expect(provider.class).to receive(:hdiutil).with("eject", fake_mountpoint).and_return(0)
expect(provider.class).to receive(:hdiutil).with("mount", "-plist", "-nobrowse", "-readonly", "-mountrandom", "/tmp", '/tmp/foo').and_return('a plist')
expect(Puppet::Util::Plist).to receive(:parse_plist).with('a plist').and_return(fake_hdiutil_plist)
provider.install
end
it "should call installpkg if a pkg/mpkg is found on the dmg" do
allow(Dir).to receive(:entries).and_return(["foo.pkg"])
allow(provider.class).to receive(:hdiutil).and_return('a plist')
expect(Puppet::Util::Plist).to receive(:parse_plist).with('a plist').and_return(fake_hdiutil_plist)
expect(provider.class).to receive(:installpkg).with("#{fake_mountpoint}/foo.pkg", resource[:name], "foo.dmg").and_return("")
provider.install
end
describe "from a remote source" do
let(:tmpdir) { "/tmp/good123" }
before :each do
resource[:source] = "http://fake.puppetlabs.com/foo.dmg"
end
it "should call tmpdir and then call curl with that directory" do
expect(Dir).to receive(:mktmpdir).and_return(tmpdir)
allow(Dir).to receive(:entries).and_return(["foo.pkg"])
expect(described_class).to receive(:curl) do |*args|
expect(args[0]).to eq("-o")
expect(args[1]).to include(tmpdir)
expect(args).to include("--fail")
expect(args).not_to include("-k")
end
allow(described_class).to receive(:hdiutil).and_return('a plist')
expect(Puppet::Util::Plist).to receive(:parse_plist).with('a plist').and_return(fake_hdiutil_plist)
expect(described_class).to receive(:installpkg)
provider.install
end
it "should use an http proxy host and port if specified" do
expect(Puppet::Util::HttpProxy).to receive(:no_proxy?).and_return(false)
expect(Puppet::Util::HttpProxy).to receive(:http_proxy_host).and_return('some_host')
expect(Puppet::Util::HttpProxy).to receive(:http_proxy_port).and_return('some_port')
expect(Dir).to receive(:mktmpdir).and_return(tmpdir)
allow(Dir).to receive(:entries).and_return(["foo.pkg"])
expect(described_class).to receive(:curl) do |*args|
expect(args).to include('some_host:some_port')
expect(args).to include('--proxy')
end
allow(described_class).to receive(:hdiutil).and_return('a plist')
expect(Puppet::Util::Plist).to receive(:parse_plist).with('a plist').and_return(fake_hdiutil_plist)
expect(described_class).to receive(:installpkg)
provider.install
end
it "should use an http proxy host only if specified" do
expect(Puppet::Util::HttpProxy).to receive(:no_proxy?).and_return(false)
expect(Puppet::Util::HttpProxy).to receive(:http_proxy_host).and_return('some_host')
expect(Puppet::Util::HttpProxy).to receive(:http_proxy_port).and_return(nil)
expect(Dir).to receive(:mktmpdir).and_return(tmpdir)
allow(Dir).to receive(:entries).and_return(["foo.pkg"])
expect(described_class).to receive(:curl) do |*args|
expect(args).to include('some_host')
expect(args).to include('--proxy')
end
allow(described_class).to receive(:hdiutil).and_return('a plist')
expect(Puppet::Util::Plist).to receive(:parse_plist).with('a plist').and_return(fake_hdiutil_plist)
expect(described_class).to receive(:installpkg)
provider.install
end
it "should not use the configured proxy if no_proxy contains a match for the destination" do
expect(Puppet::Util::HttpProxy).to receive(:no_proxy?).and_return(true)
expect(Puppet::Util::HttpProxy).not_to receive(:http_proxy_host)
expect(Puppet::Util::HttpProxy).not_to receive(:http_proxy_port)
expect(Dir).to receive(:mktmpdir).and_return(tmpdir)
allow(Dir).to receive(:entries).and_return(["foo.pkg"])
expect(described_class).to receive(:curl) do |*args|
expect(args).not_to include('some_host:some_port')
expect(args).not_to include('--proxy')
true
end
allow(described_class).to receive(:hdiutil).and_return('a plist')
expect(Puppet::Util::Plist).to receive(:parse_plist).with('a plist').and_return(fake_hdiutil_plist)
expect(described_class).to receive(:installpkg)
provider.install
end
end
end
describe "when installing flat pkg file" do
describe "with a local source" do
it "should call installpkg if a flat pkg file is found instead of a .dmg image" do
resource[:source] = "/tmp/test.pkg"
resource[:name] = "testpkg"
expect(provider.class).to receive(:installpkgdmg).with("/tmp/test.pkg", "testpkg").and_return("")
provider.install
end
end
describe "with a remote source" do
let(:remote_source) { 'http://fake.puppetlabs.com/test.pkg' }
let(:tmpdir) { '/path/to/tmpdir' }
let(:tmpfile) { File.join(tmpdir, 'testpkg.pkg') }
before do
resource[:name] = 'testpkg'
resource[:source] = remote_source
allow(Dir).to receive(:mktmpdir).and_return(tmpdir)
end
it "should call installpkg if a flat pkg file is found instead of a .dmg image" do
expect(described_class).to receive(:curl) do |*args|
expect(args).to include(tmpfile)
expect(args).to include(remote_source)
end
expect(provider.class).to receive(:installpkg).with(tmpfile, 'testpkg', remote_source)
provider.install
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/provider/package/puppetserver_gem_spec.rb | spec/unit/provider/package/puppetserver_gem_spec.rb | require 'spec_helper'
describe Puppet::Type.type(:package).provider(:puppetserver_gem) do
let(:resource) do
Puppet::Type.type(:package).new(
name: 'myresource',
ensure: :installed
)
end
let(:provider) do
provider = described_class.new
provider.resource = resource
provider
end
let(:provider_gem_cmd) { '/opt/puppetlabs/bin/puppetserver' }
let(:execute_options) do
{ failonfail: true, combine: true, custom_environment: { 'HOME' => ENV['HOME'] } }
end
before :each do
resource.provider = provider
allow(Puppet::Util).to receive(:which).with(provider_gem_cmd).and_return(provider_gem_cmd)
allow(File).to receive(:file?).with(provider_gem_cmd).and_return(true)
end
describe "#install" do
it "uses the path to the gem command" do
expect(Puppet::Util::Execution).to receive(:execute).with([provider_gem_cmd, be_an(Array)], be_a(Hash)).and_return('')
provider.install
end
it "appends version if given" do
resource[:ensure] = ['1.2.1']
expect(Puppet::Util::Execution).to receive(:execute).with([provider_gem_cmd, %w{gem install -v 1.2.1 --no-document myresource}], anything).and_return('')
provider.install
end
context "with install_options" do
it "does not append the parameter by default" do
expect(Puppet::Util::Execution).to receive(:execute).with([provider_gem_cmd, %w{gem install --no-document myresource}], anything).and_return('')
provider.install
end
it "allows setting the parameter" do
resource[:install_options] = [ '--force', {'--bindir' => '/usr/bin' } ]
expect(Puppet::Util::Execution).to receive(:execute).with([provider_gem_cmd, %w{gem install --force --bindir=/usr/bin --no-document myresource}], anything).and_return('')
provider.install
end
end
context "with source" do
it "correctly sets http source" do
resource[:source] = 'http://rubygems.com'
expect(Puppet::Util::Execution).to receive(:execute).with([provider_gem_cmd, %w{gem install --no-document --source http://rubygems.com myresource}], anything).and_return('')
provider.install
end
it "correctly sets local file source" do
resource[:source] = 'paint-2.2.0.gem'
expect(Puppet::Util::Execution).to receive(:execute).with([provider_gem_cmd, %w{gem install --no-document paint-2.2.0.gem}], anything).and_return('')
provider.install
end
it "correctly sets local file source with URI scheme" do
resource[:source] = 'file:///root/paint-2.2.0.gem'
expect(Puppet::Util::Execution).to receive(:execute).with([provider_gem_cmd, %w{gem install --no-document /root/paint-2.2.0.gem}], anything).and_return('')
provider.install
end
it "raises if given a puppet URI scheme" do
resource[:source] = 'puppet:///paint-2.2.0.gem'
expect { provider.install }.to raise_error(Puppet::Error, 'puppet:// URLs are not supported as gem sources')
end
it "raises if given an invalid URI" do
resource[:source] = 'h;ttp://rubygems.com'
expect { provider.install }.to raise_error(Puppet::Error, /Invalid source '': bad URI ?\(is not URI\?\): "h;ttp:\/\/rubygems\.com"/)
end
end
end
describe "#uninstall" do
it "uses the path to the gem command" do
expect(Puppet::Util::Execution).to receive(:execute).with([provider_gem_cmd, be_an(Array)], be_a(Hash)).and_return('')
provider.uninstall
end
context "with uninstall_options" do
it "does not append the parameter by default" do
expect(Puppet::Util::Execution).to receive(:execute).with([provider_gem_cmd, %w{gem uninstall --executables --all myresource}], anything).and_return('')
provider.uninstall
end
it "allows setting the parameter" do
resource[:uninstall_options] = [ '--force', {'--bindir' => '/usr/bin' } ]
expect(Puppet::Util::Execution).to receive(:execute).with([provider_gem_cmd, %w{gem uninstall --executables --all myresource --force --bindir=/usr/bin}], anything).and_return('')
provider.uninstall
end
end
end
describe ".gemlist" do
context "listing installed packages" do
it "uses the puppet_gem provider_command to list local gems" do
allow(Puppet::Type::Package::ProviderPuppet_gem).to receive(:provider_command).and_return('/opt/puppetlabs/puppet/bin/gem')
allow(described_class).to receive(:validate_command).with('/opt/puppetlabs/puppet/bin/gem')
expected = { name: 'world_airports', provider: :puppetserver_gem, ensure: ['1.1.3'] }
expect(Puppet::Util::Execution).to receive(:execute).with(['/opt/puppetlabs/puppet/bin/gem', %w[list --local]], anything).and_return(File.read(my_fixture('gem-list-local-packages')))
expect(described_class.gemlist({ local: true })).to include(expected)
end
end
it "appends the gem source if given" do
expect(Puppet::Util::Execution).to receive(:execute).with([provider_gem_cmd, %w{gem list --remote --source https://rubygems.com}], anything).and_return('')
described_class.gemlist({ source: 'https://rubygems.com' })
end
end
context 'calculated specificity' do
include_context 'provider specificity'
context 'when is not defaultfor' do
subject { described_class.specificity }
it { is_expected.to eql 1 }
end
context 'when is defaultfor' do
let(:os) { Puppet.runtime[:facter].value('os.name') }
subject do
described_class.defaultfor('os.name': os)
described_class.specificity
end
it { is_expected.to be > 100 }
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/provider/package/apt_spec.rb | spec/unit/provider/package/apt_spec.rb | require 'spec_helper'
describe Puppet::Type.type(:package).provider(:apt) do
let(:name) { 'asdf' }
let(:resource) do
Puppet::Type.type(:package).new(
:name => name,
:provider => 'apt'
)
end
let(:provider) do
resource.provider
end
it "should be the default provider on 'os.family' => Debian" do
expect(Facter).to receive(:value).with('os.family').and_return("Debian")
expect(described_class.default?).to be_truthy
end
it "should be versionable" do
expect(described_class).to be_versionable
end
it "should use :install to update" do
expect(provider).to receive(:install)
provider.update
end
it "should use 'apt-get remove' to uninstall" do
expect(provider).to receive(:aptget).with("-y", "-q", :remove, name)
expect(provider).to receive(:properties).and_return({:mark => :none})
provider.uninstall
end
it "should use 'apt-get purge' and 'dpkg purge' to purge" do
expect(provider).to receive(:aptget).with("-y", "-q", :remove, "--purge", name)
expect(provider).to receive(:dpkg).with("--purge", name)
expect(provider).to receive(:properties).and_return({:mark => :none})
provider.purge
end
it "should use 'apt-cache policy' to determine the latest version of a package" do
expect(provider).to receive(:aptcache).with(:policy, name).and_return(<<-HERE)
#{name}:
Installed: 1:1.0
Candidate: 1:1.1
Version table:
1:1.0
650 http://ftp.osuosl.org testing/main Packages
*** 1:1.1
100 /var/lib/dpkg/status
HERE
expect(provider.latest).to eq("1:1.1")
end
it "should print and error and return nil if no policy is found" do
expect(provider).to receive(:aptcache).with(:policy, name).and_return("#{name}:")
expect(provider).to receive(:err)
expect(provider.latest).to be_nil
end
it "should be able to preseed" do
expect(provider).to respond_to(:run_preseed)
end
it "should preseed with the provided responsefile when preseeding is called for" do
resource[:responsefile] = '/my/file'
expect(Puppet::FileSystem).to receive(:exist?).with('/my/file').and_return(true)
expect(provider).to receive(:info)
expect(provider).to receive(:preseed).with('/my/file')
provider.run_preseed
end
it "should not preseed if no responsefile is provided" do
expect(provider).to receive(:info)
expect(provider).not_to receive(:preseed)
provider.run_preseed
end
describe ".instances" do
before do
allow(Puppet::Type::Package::ProviderDpkg).to receive(:instances).and_return([provider])
end
context "when package is manual marked" do
before do
allow(described_class).to receive(:aptmark).with('showmanual').and_return("#{resource.name}\n")
end
it 'sets mark to manual' do
expect(described_class.instances.map(&:mark)).to eq([:manual])
end
end
context 'when package is not manual marked ' do
before do
allow(described_class).to receive(:aptmark).with('showmanual').and_return('')
end
it 'does not set mark to manual' do
expect(described_class.instances.map(&:mark)).to eq([nil])
end
end
end
describe 'query' do
before do
allow(provider).to receive(:dpkgquery).and_return("name: #{resource.name}" )
end
context 'when package is not installed on the system' do
it 'does not set mark to manual' do
result = provider.query
expect(described_class).not_to receive(:aptmark)
expect(result[:mark]).to be_nil
end
end
end
describe 'flush' do
context "when package is manual marked" do
before do
provider.mark = :manual
end
it 'does not call aptmark' do
expect(provider).not_to receive(:aptmark)
provider.flush
end
end
context 'when package is not manual marked ' do
it 'calls aptmark' do
expect(described_class).to receive(:aptmark).with('manual', resource.name)
provider.flush
end
end
end
describe "when installing" do
it "should preseed if a responsefile is provided" do
resource[:responsefile] = "/my/file"
expect(provider).to receive(:run_preseed)
expect(provider).to receive(:properties).and_return({:mark => :none})
allow(provider).to receive(:aptget)
provider.install
end
it "should check for a cdrom" do
expect(provider).to receive(:checkforcdrom)
expect(provider).to receive(:properties).and_return({:mark => :none})
allow(provider).to receive(:aptget)
provider.install
end
it "should use 'apt-get install' with the package name if no version is asked for" do
resource[:ensure] = :installed
expect(provider).to receive(:aptget) do |*command|
expect(command[-1]).to eq(name)
expect(command[-2]).to eq(:install)
end
expect(provider).to receive(:properties).and_return({:mark => :none})
provider.install
end
it "should specify the package version if one is asked for" do
resource[:ensure] = '1.0'
expect(provider).to receive(:aptget) do |*command|
expect(command[-1]).to eq("#{name}=1.0")
end
expect(provider).to receive(:properties).and_return({:mark => :none})
provider.install
end
it "should select latest available version if range is specified" do
resource[:ensure] = '>60.0'
expect(provider).to receive(:aptget) do |*command|
expect(command[-1]).to eq("#{name}=72.0.1+build1-0ubuntu0.19.04.1")
end
expect(provider).to receive(:aptcache).with(:madison, name).and_return(<<-HERE)
#{name} | 72.0.1+build1-0ubuntu0.19.04.1 | http://ro.archive.ubuntu.com/ubuntu disco-updates/main amd64 Packages
#{name} | 72.0.1+build1-0ubuntu0.19.04.1 | http://security.ubuntu.com/ubuntu disco-security/main amd64 Packages
#{name} | 66.0.3+build1-0ubuntu1 | http://ro.archive.ubuntu.com/ubuntu disco/main amd64 Packages
HERE
expect(provider).to receive(:properties).and_return({:mark => :none})
provider.install
end
it "should pass through ensure is no version can be selected" do
resource[:ensure] = '>74.0'
expect(provider).to receive(:aptget) do |*command|
expect(command[-1]).to eq("#{name}=>74.0")
end
expect(provider).to receive(:aptcache).with(:madison, name).and_return(<<-HERE)
#{name} | 72.0.1+build1-0ubuntu0.19.04.1 | http://ro.archive.ubuntu.com/ubuntu disco-updates/main amd64 Packages
#{name} | 72.0.1+build1-0ubuntu0.19.04.1 | http://security.ubuntu.com/ubuntu disco-security/main amd64 Packages
#{name} | 66.0.3+build1-0ubuntu1 | http://ro.archive.ubuntu.com/ubuntu disco/main amd64 Packages
HERE
expect(provider).to receive(:properties).and_return({:mark => :none})
provider.install
end
it "should use --force-yes if a package version is specified" do
resource[:ensure] = '1.0'
expect(provider).to receive(:aptget) do |*command|
expect(command).to include("--force-yes")
end
expect(provider).to receive(:properties).and_return({:mark => :none})
provider.install
end
it "should do a quiet install" do
expect(provider).to receive(:aptget) do |*command|
expect(command).to include("-q")
end
expect(provider).to receive(:properties).and_return({:mark => :none})
provider.install
end
it "should default to 'yes' for all questions" do
expect(provider).to receive(:aptget) do |*command|
expect(command).to include("-y")
end
expect(provider).to receive(:properties).and_return({:mark => :none})
provider.install
end
it "should keep config files if asked" do
resource[:configfiles] = :keep
expect(provider).to receive(:aptget) do |*command|
expect(command).to include("DPkg::Options::=--force-confold")
end
expect(provider).to receive(:properties).and_return({:mark => :none})
provider.install
end
it "should replace config files if asked" do
resource[:configfiles] = :replace
expect(provider).to receive(:aptget) do |*command|
expect(command).to include("DPkg::Options::=--force-confnew")
end
expect(provider).to receive(:properties).and_return({:mark => :none})
provider.install
end
it 'should support string install options' do
resource[:install_options] = ['--foo', '--bar']
expect(provider).to receive(:aptget).with('-q', '-y', '-o', 'DPkg::Options::=--force-confold', '--foo', '--bar', :install, name)
expect(provider).to receive(:properties).and_return({:mark => :none})
provider.install
end
it 'should support hash install options' do
resource[:install_options] = ['--foo', { '--bar' => 'baz', '--baz' => 'foo' }]
expect(provider).to receive(:aptget).with('-q', '-y', '-o', 'DPkg::Options::=--force-confold', '--foo', '--bar=baz', '--baz=foo', :install, name)
expect(provider).to receive(:properties).and_return({:mark => :none})
provider.install
end
it "should install using the source attribute if present" do
resource[:ensure] = :installed
resource[:source] = '/my/local/package/file'
expect(provider).to receive(:aptget).with(any_args, :install, resource[:source])
expect(provider).to receive(:properties).and_return({:mark => :none})
provider.install
end
it "should install specific version using the source attribute if present" do
resource[:ensure] = '1.2.3'
resource[:source] = '/my/local/package/file'
expect(provider).to receive(:aptget).with(any_args, :install, resource[:source])
expect(provider).to receive(:properties).and_return({:mark => :none})
expect(provider).to receive(:query).and_return({:ensure => '1.2.3'})
provider.install
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/provider/package/pkgutil_spec.rb | spec/unit/provider/package/pkgutil_spec.rb | require 'spec_helper'
describe Puppet::Type.type(:package).provider(:pkgutil) do
before(:each) do
@resource = Puppet::Type.type(:package).new(
:name => "TESTpkg",
:ensure => :present,
:provider => :pkgutil
)
@provider = described_class.new(@resource)
# Stub all file and config tests
allow(described_class).to receive(:healthcheck)
end
it "should have an install method" do
expect(@provider).to respond_to(:install)
end
it "should have a latest method" do
expect(@provider).to respond_to(:uninstall)
end
it "should have an update method" do
expect(@provider).to respond_to(:update)
end
it "should have a latest method" do
expect(@provider).to respond_to(:latest)
end
describe "when installing" do
it "should use a command without versioned package" do
@resource[:ensure] = :latest
expect(@provider).to receive(:pkguti).with('-y', '-i', 'TESTpkg')
@provider.install
end
it "should support a single temp repo URL" do
@resource[:ensure] = :latest
@resource[:source] = "http://example.net/repo"
expect(@provider).to receive(:pkguti).with('-t', 'http://example.net/repo', '-y', '-i', 'TESTpkg')
@provider.install
end
it "should support multiple temp repo URLs as array" do
@resource[:ensure] = :latest
@resource[:source] = [ 'http://example.net/repo', 'http://example.net/foo' ]
expect(@provider).to receive(:pkguti).with('-t', 'http://example.net/repo', '-t', 'http://example.net/foo', '-y', '-i', 'TESTpkg')
@provider.install
end
end
describe "when updating" do
it "should use a command without versioned package" do
expect(@provider).to receive(:pkguti).with('-y', '-u', 'TESTpkg')
@provider.update
end
it "should support a single temp repo URL" do
@resource[:source] = "http://example.net/repo"
expect(@provider).to receive(:pkguti).with('-t', 'http://example.net/repo', '-y', '-u', 'TESTpkg')
@provider.update
end
it "should support multiple temp repo URLs as array" do
@resource[:source] = [ 'http://example.net/repo', 'http://example.net/foo' ]
expect(@provider).to receive(:pkguti).with('-t', 'http://example.net/repo', '-t', 'http://example.net/foo', '-y', '-u', 'TESTpkg')
@provider.update
end
end
describe "when uninstalling" do
it "should call the remove operation" do
expect(@provider).to receive(:pkguti).with('-y', '-r', 'TESTpkg')
@provider.uninstall
end
it "should support a single temp repo URL" do
@resource[:source] = "http://example.net/repo"
expect(@provider).to receive(:pkguti).with('-t', 'http://example.net/repo', '-y', '-r', 'TESTpkg')
@provider.uninstall
end
it "should support multiple temp repo URLs as array" do
@resource[:source] = [ 'http://example.net/repo', 'http://example.net/foo' ]
expect(@provider).to receive(:pkguti).with('-t', 'http://example.net/repo', '-t', 'http://example.net/foo', '-y', '-r', 'TESTpkg')
@provider.uninstall
end
end
describe "when getting latest version" do
it "should return TESTpkg's version string" do
fake_data = "
noisy output here
TESTpkg 1.4.5,REV=2007.11.18 1.4.5,REV=2007.11.20"
expect(described_class).to receive(:pkguti).with('-c', '--single', 'TESTpkg').and_return(fake_data)
expect(@provider.latest).to eq("1.4.5,REV=2007.11.20")
end
it "should support a temp repo URL" do
@resource[:source] = "http://example.net/repo"
fake_data = "
noisy output here
TESTpkg 1.4.5,REV=2007.11.18 1.4.5,REV=2007.11.20"
expect(described_class).to receive(:pkguti).with('-t', 'http://example.net/repo', '-c', '--single', 'TESTpkg').and_return(fake_data)
expect(@provider.latest).to eq("1.4.5,REV=2007.11.20")
end
it "should handle TESTpkg's 'SAME' version string" do
fake_data = "
noisy output here
TESTpkg 1.4.5,REV=2007.11.18 SAME"
expect(described_class).to receive(:pkguti).with('-c', '--single', 'TESTpkg').and_return(fake_data)
expect(@provider.latest).to eq("1.4.5,REV=2007.11.18")
end
it "should handle a non-existent package" do
fake_data = "noisy output here
Not in catalog"
expect(described_class).to receive(:pkguti).with('-c', '--single', 'TESTpkg').and_return(fake_data)
expect(@provider.latest).to eq(nil)
end
it "should warn on unknown pkgutil noise" do
expect(described_class).to receive(:pkguti).with('-c', '--single', 'TESTpkg').and_return("testingnoise")
expect(@provider.latest).to eq(nil)
end
it "should ignore pkgutil noise/headers to find TESTpkg" do
fake_data = "# stuff
=> Fetching new catalog and descriptions (http://mirror.opencsw.org/opencsw/unstable/i386/5.11) if available ...
2011-02-19 23:05:46 URL:http://mirror.opencsw.org/opencsw/unstable/i386/5.11/catalog [534635/534635] -> \"/var/opt/csw/pkgutil/catalog.mirror.opencsw.org_opencsw_unstable_i386_5.11.tmp\" [1]
Checking integrity of /var/opt/csw/pkgutil/catalog.mirror.opencsw.org_opencsw_unstable_i386_5.11 with gpg.
gpg: Signature made February 17, 2011 05:27:53 PM GMT using DSA key ID E12E9D2F
gpg: Good signature from \"Distribution Manager <dm@blastwave.org>\"
==> 2770 packages loaded from /var/opt/csw/pkgutil/catalog.mirror.opencsw.org_opencsw_unstable_i386_5.11
package installed catalog
TESTpkg 1.4.5,REV=2007.11.18 1.4.5,REV=2007.11.20"
expect(described_class).to receive(:pkguti).with('-c', '--single', 'TESTpkg').and_return(fake_data)
expect(@provider.latest).to eq("1.4.5,REV=2007.11.20")
end
it "should find REALpkg via an alias (TESTpkg)" do
fake_data = "
noisy output here
REALpkg 1.4.5,REV=2007.11.18 1.4.5,REV=2007.11.20"
expect(described_class).to receive(:pkguti).with('-c', '--single', 'TESTpkg').and_return(fake_data)
expect(@provider.query[:name]).to eq("TESTpkg")
end
end
describe "when querying current version" do
it "should return TESTpkg's version string" do
fake_data = "TESTpkg 1.4.5,REV=2007.11.18 1.4.5,REV=2007.11.20"
expect(described_class).to receive(:pkguti).with('-c', '--single', 'TESTpkg').and_return(fake_data)
expect(@provider.query[:ensure]).to eq("1.4.5,REV=2007.11.18")
end
it "should handle a package that isn't installed" do
fake_data = "TESTpkg notinst 1.4.5,REV=2007.11.20"
expect(described_class).to receive(:pkguti).with('-c', '--single', 'TESTpkg').and_return(fake_data)
expect(@provider.query[:ensure]).to eq(:absent)
end
it "should handle a non-existent package" do
fake_data = "noisy output here
Not in catalog"
expect(described_class).to receive(:pkguti).with('-c', '--single', 'TESTpkg').and_return(fake_data)
expect(@provider.query[:ensure]).to eq(:absent)
end
it "should support a temp repo URL" do
@resource[:source] = "http://example.net/repo"
fake_data = "TESTpkg 1.4.5,REV=2007.11.18 1.4.5,REV=2007.11.20"
expect(described_class).to receive(:pkguti).with('-t', 'http://example.net/repo', '-c', '--single', 'TESTpkg').and_return(fake_data)
expect(@provider.query[:ensure]).to eq("1.4.5,REV=2007.11.18")
end
end
describe "when querying current instances" do
it "should warn on unknown pkgutil noise" do
expect(described_class).to receive(:pkguti).with(['-a']).and_return("testingnoise")
expect(described_class).to receive(:pkguti).with(['-c']).and_return("testingnoise")
expect(Puppet).to receive(:warning).twice
expect(described_class).not_to receive(:new)
expect(described_class.instances).to eq([])
end
it "should return TESTpkg's version string" do
fake_data = "TESTpkg TESTpkg 1.4.5,REV=2007.11.20"
expect(described_class).to receive(:pkguti).with(['-a']).and_return(fake_data)
fake_data = "TESTpkg 1.4.5,REV=2007.11.18 1.4.5,REV=2007.11.20"
expect(described_class).to receive(:pkguti).with(['-c']).and_return(fake_data)
testpkg = double('pkg1')
expect(described_class).to receive(:new).with({:ensure => "1.4.5,REV=2007.11.18", :name => "TESTpkg", :provider => :pkgutil}).and_return(testpkg)
expect(described_class.instances).to eq([testpkg])
end
it "should also return both TESTpkg and mypkg alias instances" do
fake_data = "mypkg TESTpkg 1.4.5,REV=2007.11.20"
expect(described_class).to receive(:pkguti).with(['-a']).and_return(fake_data)
fake_data = "TESTpkg 1.4.5,REV=2007.11.18 1.4.5,REV=2007.11.20"
expect(described_class).to receive(:pkguti).with(['-c']).and_return(fake_data)
testpkg = double('pkg1')
expect(described_class).to receive(:new).with({:ensure => "1.4.5,REV=2007.11.18", :name => "TESTpkg", :provider => :pkgutil}).and_return(testpkg)
aliaspkg = double('pkg2')
expect(described_class).to receive(:new).with({:ensure => "1.4.5,REV=2007.11.18", :name => "mypkg", :provider => :pkgutil}).and_return(aliaspkg)
expect(described_class.instances).to eq([testpkg,aliaspkg])
end
it "shouldn't mind noise in the -a output" do
fake_data = "noisy output here"
expect(described_class).to receive(:pkguti).with(['-a']).and_return(fake_data)
fake_data = "TESTpkg 1.4.5,REV=2007.11.18 1.4.5,REV=2007.11.20"
expect(described_class).to receive(:pkguti).with(['-c']).and_return(fake_data)
testpkg = double('pkg1')
expect(described_class).to receive(:new).with({:ensure => "1.4.5,REV=2007.11.18", :name => "TESTpkg", :provider => :pkgutil}).and_return(testpkg)
expect(described_class.instances).to eq([testpkg])
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/unit/provider/package/pip_spec.rb | spec/unit/provider/package/pip_spec.rb | require 'spec_helper'
osfamilies = { 'windows' => ['pip.exe'], 'other' => ['pip', 'pip-python', 'pip2', 'pip-2'] }
pip_path_with_spaces = 'C:\Program Files (x86)\Python\Scripts\pip.exe'
describe Puppet::Type.type(:package).provider(:pip) do
it { is_expected.to be_installable }
it { is_expected.to be_uninstallable }
it { is_expected.to be_upgradeable }
it { is_expected.to be_versionable }
it { is_expected.to be_install_options }
it { is_expected.to be_targetable }
it { is_expected.to be_version_ranges }
before do
@resource = Puppet::Type.type(:package).new(name: "fake_package", provider: :pip)
@provider = @resource.provider
@client = double('client')
allow(@client).to receive(:call).with('package_releases', 'real_package').and_return(["1.3", "1.2.5", "1.2.4"])
allow(@client).to receive(:call).with('package_releases', 'fake_package').and_return([])
end
context "parse" do
it "should return a hash on valid input" do
expect(described_class.parse("real_package==1.2.5")).to eq({
:ensure => "1.2.5",
:name => "real_package",
:provider => :pip,
})
end
it "should correctly parse arbitrary equality" do
expect(described_class.parse("real_package===1.2.5")).to eq({
:ensure => "1.2.5",
:name => "real_package",
:provider => :pip,
})
end
it "should correctly parse URL format" do
expect(described_class.parse("real_package @ git+https://github.com/example/test.git@6b4e203b66c1de7345984882e2b13bf87c700095")).to eq({
:ensure => "6b4e203b66c1de7345984882e2b13bf87c700095",
:name => "real_package",
:provider => :pip,
})
end
it "should return nil on invalid input" do
expect(described_class.parse("foo")).to eq(nil)
end
end
context "cmd" do
it "should return 'pip.exe' by default on Windows systems" do
allow(Puppet::Util::Platform).to receive(:windows?).and_return(true)
expect(described_class.cmd[0]).to eq('pip.exe')
end
it "could return pip-python on legacy redhat systems which rename pip" do
allow(Puppet::Util::Platform).to receive(:windows?).and_return(false)
expect(described_class.cmd[1]).to eq('pip-python')
end
it "should return pip by default on other systems" do
allow(Puppet::Util::Platform).to receive(:windows?).and_return(false)
expect(described_class.cmd[0]).to eq('pip')
end
end
context "instances" do
osfamilies.each do |osfamily, pip_cmds|
it "should return an array on #{osfamily} systems when #{pip_cmds.join(' or ')} is present" do
allow(Puppet::Util::Platform).to receive(:windows?).and_return(osfamily == 'windows')
pip_cmds.each do |pip_cmd|
pip_cmds.each do |cmd|
unless cmd == pip_cmd
expect(described_class).to receive(:which).with(cmd).and_return(nil)
end
end
allow(described_class).to receive(:pip_version).with(pip_cmd).and_return('8.0.1')
expect(described_class).to receive(:which).with(pip_cmd).and_return(pip_cmd)
p = double("process")
expect(p).to receive(:collect).and_yield("real_package==1.2.5")
expect(described_class).to receive(:execpipe).with([pip_cmd, ["freeze"]]).and_yield(p)
described_class.instances
end
end
context "with pip version >= 8.1.0" do
versions = ['8.1.0', '9.0.1']
versions.each do |version|
it "should use the --all option when version is '#{version}'" do
allow(Puppet::Util::Platform).to receive(:windows?).and_return(osfamily == 'windows')
allow(described_class).to receive(:provider_command).and_return('/fake/bin/pip')
allow(described_class).to receive(:pip_version).with('/fake/bin/pip').and_return(version)
p = double("process")
expect(p).to receive(:collect).and_yield("real_package==1.2.5")
expect(described_class).to receive(:execpipe).with(["/fake/bin/pip", ["freeze", "--all"]]).and_yield(p)
described_class.instances
end
end
end
it "should return an empty array on #{osfamily} systems when #{pip_cmds.join(' and ')} are missing" do
allow(Puppet::Util::Platform).to receive(:windows?).and_return(osfamily == 'windows')
pip_cmds.each do |cmd|
expect(described_class).to receive(:which).with(cmd).and_return(nil)
end
expect(described_class.instances).to eq([])
end
end
context "when pip path location contains spaces" do
it "should quote the command before doing execpipe" do
allow(described_class).to receive(:which).and_return(pip_path_with_spaces)
allow(described_class).to receive(:pip_version).with(pip_path_with_spaces).and_return('8.0.1')
expect(described_class).to receive(:execpipe).with(["\"#{pip_path_with_spaces}\"", ["freeze"]])
described_class.instances
end
end
end
context "query" do
before do
@resource[:name] = "real_package"
allow(described_class).to receive(:provider_command).and_return('/fake/bin/pip')
allow(described_class).to receive(:validate_command).with('/fake/bin/pip')
end
it "should return a hash when pip and the package are present" do
expect(described_class).to receive(:instances).and_return([described_class.new({
:ensure => "1.2.5",
:name => "real_package",
:provider => :pip,
:command => '/fake/bin/pip',
})])
expect(@provider.query).to eq({
:ensure => "1.2.5",
:name => "real_package",
:provider => :pip,
:command => '/fake/bin/pip',
})
end
it "should return nil when the package is missing" do
expect(described_class).to receive(:instances).and_return([])
expect(@provider.query).to eq(nil)
end
it "should be case insensitive" do
@resource[:name] = "Real_Package"
expect(described_class).to receive(:instances).and_return([described_class.new({
:ensure => "1.2.5",
:name => "real_package",
:provider => :pip,
:command => '/fake/bin/pip',
})])
expect(@provider.query).to eq({
:ensure => "1.2.5",
:name => "real_package",
:provider => :pip,
:command => '/fake/bin/pip',
})
end
end
context "when comparing versions" do
it "an abnormal version should still be compared (using default implementation) but a debug message should also be printed regarding it" do
expect(Puppet).to receive(:debug).with("Cannot compare 1.0 and abnormal-version.0.1. abnormal-version.0.1 is not a valid python package version. Please refer to https://www.python.org/dev/peps/pep-0440/. Falling through default comparison mechanism.")
expect(Puppet::Util::Package).to receive(:versioncmp).with('1.0', 'abnormal-version.0.1')
expect{ described_class.compare_pip_versions('1.0', 'abnormal-version.0.1') }.not_to raise_error
end
end
context "latest" do
before do
allow(described_class).to receive(:pip_version).with(pip_path).and_return(pip_version)
allow(described_class).to receive(:which).with('pip').and_return(pip_path)
allow(described_class).to receive(:which).with('pip-python').and_return(pip_path)
allow(described_class).to receive(:which).with('pip.exe').and_return(pip_path)
allow(described_class).to receive(:provider_command).and_return(pip_path)
allow(described_class).to receive(:validate_command).with(pip_path)
end
context "with pip version < 1.5.4" do
let(:pip_version) { '1.0.1' }
let(:pip_path) { '/fake/bin/pip' }
it "should find a version number for new_pip_package" do
p = StringIO.new(
<<-EOS
Downloading/unpacking fake-package
Using version 0.10.1 (newest of versions: 0.10.1, 0.10, 0.9, 0.8.1, 0.8, 0.7.2, 0.7.1, 0.7, 0.6.1, 0.6, 0.5.2, 0.5.1, 0.5, 0.4, 0.3.1, 0.3, 0.2, 0.1)
Downloading real-package-0.10.1.tar.gz (544Kb): 544Kb downloaded
Saved ./foo/real-package-0.10.1.tar.gz
Successfully downloaded real-package
EOS
)
expect(Puppet::Util::Execution).to receive(:execpipe).and_yield(p).once
@resource[:name] = "real_package"
expect(@provider.latest).to eq('0.10.1')
end
it "should not find a version number for fake_package" do
p = StringIO.new(
<<-EOS
Downloading/unpacking fake-package
Could not fetch URL http://pypi.python.org/simple/fake_package: HTTP Error 404: Not Found
Will skip URL http://pypi.python.org/simple/fake_package when looking for download links for fake-package
Could not fetch URL http://pypi.python.org/simple/fake_package/: HTTP Error 404: Not Found
Will skip URL http://pypi.python.org/simple/fake_package/ when looking for download links for fake-package
Could not find any downloads that satisfy the requirement fake-package
No distributions at all found for fake-package
Exception information:
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/pip/basecommand.py", line 126, in main
self.run(options, args)
File "/usr/lib/python2.7/dist-packages/pip/commands/install.py", line 223, in run
requirement_set.prepare_files(finder, force_root_egg_info=self.bundle, bundle=self.bundle)
File "/usr/lib/python2.7/dist-packages/pip/req.py", line 948, in prepare_files
url = finder.find_requirement(req_to_install, upgrade=self.upgrade)
File "/usr/lib/python2.7/dist-packages/pip/index.py", line 152, in find_requirement
raise DistributionNotFound('No distributions at all found for %s' % req)
DistributionNotFound: No distributions at all found for fake-package
Storing complete log in /root/.pip/pip.log
EOS
)
expect(Puppet::Util::Execution).to receive(:execpipe).and_yield(p).once
@resource[:name] = "fake_package"
expect(@provider.latest).to eq(nil)
end
it "should handle out-of-order version numbers for real_package" do
p = StringIO.new(
<<-EOS
Downloading/unpacking fake-package
Using version 2!2.3.4.alpha5.rev6.dev7+abc89 (newest of versions: 1.11, 13.0.3, 1.6, 1!1.2.rev33+123456, 1.9, 1.3.2, 14.0.1, 12.0.7, 13.0.3, 1.7.2, 1.8.4, 1.2+123abc456, 1.6.1, 0.9.2, 1.3, 1.8.3, 12.1.1, 1.1, 1.11.6, 1.2+123456, 1.4.8, 1.6.3, 1!1.0b2.post345.dev456, 1.10.1, 14.0.2, 1.11.3, 14.0.3, 1.4rc1, 1.0b2.post345.dev456, 0.8.4, 1.0, 1!1.0.post456, 12.0.5, 14.0.6, 1.11.5, 1.0rc2, 1.7.1.1, 1.11.4, 13.0.1, 13.1.2, 1.3.3, 0.8.2, 14.0.0, 12.0, 1.8, 1.3.4, 12.0, 1.2, 12.0.6, 0.9.1, 13.1.1, 2!2.3.4.alpha5.rev6.dev7+abc89, 14.0.5, 15.0.2, 15.0.0, 1.4.5, 1.4.3, 13.1.1, 1.11.2, 13.1.2, 1.2+abc123def, 1.3.1, 13.1.0, 12.0.2, 1.11.1, 12.0.1, 12.1.0, 0.9, 1.4.4, 1.2+abc123, 13.0.0, 1.4.9, 1.1.dev1, 12.1.0, 1.7.1, 1.4.2, 14.0.5, 0.8.1, 1.4.6, 0.8.3, 1.11.3, 1.5.1, 1.4.7, 13.0.2, 12.0.7, 1!13.0, 0!13.0, 1.9.1, 1.0.post456.dev34, 1.8.2, 14.0.1, 14.0.0, 1.2.rev33+123456, 14.0.4, 1.6.2, 15.0.1, 13.1.0, 0.8, 1.2+1234.abc, 1.7, 15.0.2, 12.0.5, 13.0.1, 1.8.1, 1.11.6, 15.0.1, 12.0.4, 1.2+123abc, 12.1.1, 13.0.2, 1.11.4, 1.10, 1.2.r32+123456, 14.0.4, 14.0.6, 1.4.1, 1.4, 1.5.2, 12.0.2, 12.0.1, 14.0.3, 14.0.2, 1.11.1, 1.7.1.2, 15.0.0, 12.0.4, 1.6.4, 1.11.2, 1.5, 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, 1.0b2-346, 1.0c1.dev456, 1.0c1, 1.0c3, 1.0, 1.0.post456, 1.2+abc, 1!1.0, 1!1.0.post456.dev34)
Downloading real-package-2!2.3.4.alpha5.rev6.dev7+abc89.tar.gz (544Kb): 544Kb downloaded
Saved ./foo/real-package-2!2.3.4.alpha5.rev6.dev7+abc89.tar.gz
Successfully downloaded real-package
EOS
)
expect(Puppet::Util::Execution).to receive(:execpipe).and_yield(p).once
@resource[:name] = "real_package"
expect(@provider.latest).to eq('2!2.3.4.alpha5.rev6.dev7+abc89')
end
it "should use 'install_options' when specified" do
expect(Puppet::Util::Execution).to receive(:execpipe).with(array_including([["--index=https://fake.example.com"]])).once
@resource[:name] = "fake_package"
@resource[:install_options] = ['--index' => 'https://fake.example.com']
expect(@provider.latest).to eq(nil)
end
context "when pip path location contains spaces" do
let(:pip_path) { pip_path_with_spaces }
it "should quote the command before doing execpipe" do
expect(Puppet::Util::Execution).to receive(:execpipe).with(array_including("\"#{pip_path}\""))
@provider.latest
end
end
end
context "with pip version >= 1.5.4" do
# For Pip 1.5.4 and above, you can get a version list from CLI - which allows for native pip behavior
# with regards to custom repositories, proxies and the like
let(:pip_version) { '1.5.4' }
let(:pip_path) { '/fake/bin/pip' }
context "with pip version >= 20.3 and < 21.1" do
let(:pip_version) { '20.3.1' }
let(:pip_path) { '/fake/bin/pip' }
it "should use legacy-resolver argument" do
p = StringIO.new(
<<-EOS
Collecting real-package==9!0dev0+x
Could not find a version that satisfies the requirement real-package==9!0dev0+x (from versions: 1.1.3, 1.0, 1.9b1)
No matching distribution found for real-package==9!0dev0+x
EOS
)
expect(Puppet::Util::Execution).to receive(:execpipe).with(["/fake/bin/pip", "install", "real_package==9!0dev0+x",
"--use-deprecated=legacy-resolver"]).and_yield(p).once
@resource[:name] = "real_package"
@provider.latest
end
end
context "with pip version >= 21.1" do
let(:pip_version) { '21.1' }
let(:pip_path) { '/fake/bin/pip' }
it "should not use legacy-resolver argument" do
p = StringIO.new(
<<-EOS
Collecting real-package==9!0dev0+x
Could not find a version that satisfies the requirement real-package==9!0dev0+x (from versions: 1.1.3, 1.0, 1.9b1)
No matching distribution found for real-package==9!0dev0+x
EOS
)
expect(Puppet::Util::Execution).to receive(:execpipe).with(["/fake/bin/pip", "install", "real_package==9!0dev0+x"]).and_yield(p).once
@resource[:name] = "real_package"
@provider.latest
end
end
it "should find a version number for real_package" do
p = StringIO.new(
<<-EOS
Collecting real-package==9!0dev0+x
Could not find a version that satisfies the requirement real-package==9!0dev0+x (from versions: 1.1.3, 1.2, 1.9b1)
No matching distribution found for real-package==9!0dev0+x
EOS
)
expect(Puppet::Util::Execution).to receive(:execpipe).with(["/fake/bin/pip", "install", "real_package==9!0dev0+x"]).and_yield(p).once
@resource[:name] = "real_package"
latest = @provider.latest
expect(latest).to eq('1.9b1')
end
it "should not find a version number for fake_package" do
p = StringIO.new(
<<-EOS
Collecting fake-package==9!0dev0+x
Could not find a version that satisfies the requirement fake-package==9!0dev0+x (from versions: )
No matching distribution found for fake-package==9!0dev0+x
EOS
)
expect(Puppet::Util::Execution).to receive(:execpipe).with(["/fake/bin/pip", "install", "fake_package==9!0dev0+x"]).and_yield(p).once
@resource[:name] = "fake_package"
expect(@provider.latest).to eq(nil)
end
it "should handle out-of-order version numbers for real_package" do
p = StringIO.new(
<<-EOS
Collecting real-package==9!0dev0+x
Could not find a version that satisfies the requirement real-package==9!0dev0+x (from versions: 1.11, 13.0.3, 1.6, 1!1.2.rev33+123456, 1.9, 1.3.2, 14.0.1, 12.0.7, 13.0.3, 1.7.2, 1.8.4, 1.2+123abc456, 1.6.1, 0.9.2, 1.3, 1.8.3, 12.1.1, 1.1, 1.11.6, 1.2+123456, 1.4.8, 1.6.3, 1!1.0b2.post345.dev456, 1.10.1, 14.0.2, 1.11.3, 14.0.3, 1.4rc1, 1.0b2.post345.dev456, 0.8.4, 1.0, 1!1.0.post456, 12.0.5, 14.0.6, 1.11.5, 1.0rc2, 1.7.1.1, 1.11.4, 13.0.1, 13.1.2, 1.3.3, 0.8.2, 14.0.0, 12.0, 1.8, 1.3.4, 12.0, 1.2, 12.0.6, 0.9.1, 13.1.1, 2!2.3.4.alpha5.rev6.dev7+abc89, 14.0.5, 15.0.2, 15.0.0, 1.4.5, 1.4.3, 13.1.1, 1.11.2, 13.1.2, 1.2+abc123def, 1.3.1, 13.1.0, 12.0.2, 1.11.1, 12.0.1, 12.1.0, 0.9, 1.4.4, 1.2+abc123, 13.0.0, 1.4.9, 1.1.dev1, 12.1.0, 1.7.1, 1.4.2, 14.0.5, 0.8.1, 1.4.6, 0.8.3, 1.11.3, 1.5.1, 1.4.7, 13.0.2, 12.0.7, 1!13.0, 0!13.0, 1.9.1, 1.0.post456.dev34, 1.8.2, 14.0.1, 14.0.0, 1.2.rev33+123456, 14.0.4, 1.6.2, 15.0.1, 13.1.0, 0.8, 1.2+1234.abc, 1.7, 15.0.2, 12.0.5, 13.0.1, 1.8.1, 1.11.6, 15.0.1, 12.0.4, 1.2+123abc, 12.1.1, 13.0.2, 1.11.4, 1.10, 1.2.r32+123456, 14.0.4, 14.0.6, 1.4.1, 1.4, 1.5.2, 12.0.2, 12.0.1, 14.0.3, 14.0.2, 1.11.1, 1.7.1.2, 15.0.0, 12.0.4, 1.6.4, 1.11.2, 1.5, 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, 1.0b2-346, 1.0c1.dev456, 1.0c1, 1.0c3, 1.0, 1.0.post456, 1.2+abc, 1!1.0, 1!1.0.post456.dev34)
No distributions matching the version for real-package==9!0dev0+x
EOS
)
expect(Puppet::Util::Execution).to receive(:execpipe).with(["/fake/bin/pip", "install", "real_package==9!0dev0+x"]).and_yield(p).once
@resource[:name] = "real_package"
expect(@provider.latest).to eq('2!2.3.4.alpha5.rev6.dev7+abc89')
end
it "should use 'install_options' when specified" do
expect(Puppet::Util::Execution).to receive(:execpipe).with(array_including([["--index=https://fake.example.com"]])).once
@resource[:name] = "fake_package"
@resource[:install_options] = ['--index' => 'https://fake.example.com']
expect(@provider.latest).to eq(nil)
end
context "when pip path location contains spaces" do
let(:pip_path) { pip_path_with_spaces }
it "should quote the command before doing execpipe" do
expect(Puppet::Util::Execution).to receive(:execpipe).with(array_including("\"#{pip_path}\""))
@provider.latest
end
end
end
end
context "install" do
before do
@resource[:name] = "fake_package"
@url = "git+https://example.com/fake_package.git"
allow(described_class).to receive(:provider_command).and_return('/fake/bin/pip')
allow(described_class).to receive(:validate_command).with('/fake/bin/pip')
end
it "should install" do
@resource[:ensure] = :installed
expect(@provider).to receive(:execute).with(["/fake/bin/pip", ["install", "-q", "fake_package"]])
@provider.install
end
it "omits the -e flag (GH-1256)" do
# The -e flag makes the provider non-idempotent
@resource[:ensure] = :installed
@resource[:source] = @url
# TJK
expect(@provider).to receive(:execute) do |*args|
expect(args).not_to include("-e")
end
@provider.install
end
it "should install from SCM" do
@resource[:ensure] = :installed
@resource[:source] = @url
expect(@provider).to receive(:execute).with(["/fake/bin/pip", ["install", "-q", "#{@url}#egg=fake_package"]])
@provider.install
end
it "should install a particular SCM revision" do
@resource[:ensure] = "0123456"
@resource[:source] = @url
# TJK
expect(@provider).to receive(:execute).with(["/fake/bin/pip", ["install", "-q", "#{@url}@0123456#egg=fake_package"]])
@provider.install
end
it "should install a particular version" do
@resource[:ensure] = "0.0.0"
# TJK
expect(@provider).to receive(:execute).with(["/fake/bin/pip", ["install", "-q", "fake_package==0.0.0"]])
@provider.install
end
it "should upgrade" do
@resource[:ensure] = :latest
# TJK
expect(@provider).to receive(:execute).with(["/fake/bin/pip", ["install", "-q", "--upgrade", "fake_package"]])
@provider.install
end
it "should handle install options" do
@resource[:ensure] = :installed
@resource[:install_options] = [{"--timeout" => "10"}, "--no-index"]
expect(@provider).to receive(:execute).with(["/fake/bin/pip", ["install", "-q", "--timeout=10", "--no-index", "fake_package"]])
@provider.install
end
end
context "uninstall" do
before do
allow(described_class).to receive(:provider_command).and_return('/fake/bin/pip')
allow(described_class).to receive(:validate_command).with('/fake/bin/pip')
end
it "should uninstall" do
@resource[:name] = "fake_package"
expect(@provider).to receive(:execute).with(["/fake/bin/pip", ["uninstall", "-y", "-q", "fake_package"]])
@provider.uninstall
end
end
context "update" do
it "should just call install" do
expect(@provider).to receive(:install).and_return(nil)
@provider.update
end
end
context "pip_version" do
let(:pip) { '/fake/bin/pip' }
it "should look up version if pip is present" do
allow(described_class).to receive(:cmd).and_return(pip)
process = ['pip 8.0.2 from /usr/local/lib/python2.7/dist-packages (python 2.7)']
allow(described_class).to receive(:execpipe).with([pip, '--version']).and_yield(process)
expect(described_class.pip_version(pip)).to eq('8.0.2')
end
it "parses multiple lines of output" do
allow(described_class).to receive(:cmd).and_return(pip)
process = [
"/usr/local/lib/python2.7/dist-packages/urllib3/contrib/socks.py:37: DependencyWarning: SOCKS support in urllib3 requires the installation of optional dependencies: specifically, PySocks. For more information, see https://urllib3.readthedocs.io/en/latest/contrib.html#socks-proxies",
" DependencyWarning",
"pip 1.5.6 from /usr/lib/python2.7/dist-packages (python 2.7)"
]
allow(described_class).to receive(:execpipe).with([pip, '--version']).and_yield(process)
expect(described_class.pip_version(pip)).to eq('1.5.6')
end
it "raises if there isn't a version string" do
allow(described_class).to receive(:cmd).and_return(pip)
allow(described_class).to receive(:execpipe).with([pip, '--version']).and_yield([""])
expect {
described_class.pip_version(pip)
}.to raise_error(Puppet::Error, 'Cannot resolve pip version')
end
it "quotes commands with spaces" do
pip = 'C:\Program Files\Python27\Scripts\pip.exe'
allow(described_class).to receive(:cmd).and_return(pip)
process = ["pip 18.1 from c:\program files\python27\lib\site-packages\pip (python 2.7)\r\n"]
allow(described_class).to receive(:execpipe).with(["\"#{pip}\"", '--version']).and_yield(process)
expect(described_class.pip_version(pip)).to eq('18.1')
end
end
context 'calculated specificity' do
include_context 'provider specificity'
context 'when is not defaultfor' do
subject { described_class.specificity }
it { is_expected.to eql 1 }
end
context 'when is defaultfor' do
let(:os) { Puppet.runtime[:facter].value('os.name') }
subject do
described_class.defaultfor('os.name': os)
described_class.specificity
end
it { is_expected.to be > 100 }
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.