repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
true
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
true
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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\?\)/) 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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/provider/package/aptrpm_spec.rb
spec/unit/provider/package/aptrpm_spec.rb
require 'spec_helper' describe Puppet::Type.type(:package).provider(:aptrpm) do let :type do Puppet::Type.type(:package) end let :pkg do type.new(:name => 'faff', :provider => :aptrpm, :source => '/tmp/faff.rpm') end it { is_expected.to be_versionable } context "when retrieving ensure" do before(:each) do allow(Puppet::Util).to receive(:which).with("rpm").and_return("/bin/rpm") allow(pkg.provider).to receive(:which).with("rpm").and_return("/bin/rpm") expect(Puppet::Util::Execution).to receive(:execute).with(["/bin/rpm", "--version"], {:combine => true, :custom_environment => {}, :failonfail => true}).and_return(Puppet::Util::Execution::ProcessOutput.new("4.10.1\n", 0)).at_most(:once) end def rpm_args ['-q', 'faff', '--nosignature', '--nodigest', '--qf', "%{NAME} %|EPOCH?{%{EPOCH}}:{0}| %{VERSION} %{RELEASE} %{ARCH}\\n"] end it "should report purged packages" do expect(pkg.provider).to receive(:rpm).and_raise(Puppet::ExecutionFailure, "couldn't find rpm") expect(pkg.property(:ensure).retrieve).to eq(:purged) end it "should report present packages correctly" do expect(pkg.provider).to receive(:rpm).and_return("faff-1.2.3-1 0 1.2.3-1 5 i686\n") expect(pkg.property(:ensure).retrieve).to eq("1.2.3-1-5") end end it "should try and install when asked" do expect(pkg.provider).to receive(:aptget).with('-q', '-y', 'install', 'faff').and_return(0) pkg.provider.install end it "should try and purge when asked" do expect(pkg.provider).to receive(:aptget).with('-y', '-q', 'remove', '--purge', 'faff').and_return(0) pkg.provider.purge end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/provider/package/opkg_spec.rb
spec/unit/provider/package/opkg_spec.rb
require 'spec_helper' describe Puppet::Type.type(:package).provider(:opkg) do let(:resource) do Puppet::Type.type(:package).new(:name => 'package') end let(:provider) { described_class.new(resource) } before do allow(Puppet::Util).to receive(:which).with("opkg").and_return("/bin/opkg") allow(provider).to receive(:package_lists).and_return(['.', '..', 'packages']) end describe "when installing" do before do allow(provider).to receive(:query).and_return({ :ensure => '1.0' }) end context "when the package list is absent" do before do allow(provider).to receive(:package_lists).and_return(['.', '..']) #empty, no package list end it "fetches the package list when installing" do expect(provider).to receive(:opkg).with('update') expect(provider).to receive(:opkg).with("--force-overwrite", "install", resource[:name]) provider.install end end context "when the package list is present" do before do allow(provider).to receive(:package_lists).and_return(['.', '..', 'lists']) # With a pre-downloaded package list end it "fetches the package list when installing" do expect(provider).not_to receive(:opkg).with('update') expect(provider).to receive(:opkg).with("--force-overwrite", "install", resource[:name]) provider.install end end it "should call opkg install" do expect(Puppet::Util::Execution).to receive(:execute).with(["/bin/opkg", "--force-overwrite", "install", resource[:name]], {:failonfail => true, :combine => true, :custom_environment => {}}) provider.install end context "when :source is specified" do context "works on valid urls" do %w{ /some/package/file http://some.package.in/the/air ftp://some.package.in/the/air }.each do |source| it "should install #{source} directly" do resource[:source] = source expect(Puppet::Util::Execution).to receive(:execute).with(["/bin/opkg", "--force-overwrite", "install", resource[:source]], {:failonfail => true, :combine => true, :custom_environment => {}}) provider.install end end end context "as a file:// URL" do before do @package_file = "file:///some/package/file" @actual_file_path = "/some/package/file" resource[:source] = @package_file end it "should install from the path segment of the URL" do expect(Puppet::Util::Execution).to receive(:execute).and_return(Puppet::Util::Execution::ProcessOutput.new("", 0)) provider.install end end context "with invalid URL for opkg" do before do # Emulate the `opkg` command returning a non-zero exit value allow(Puppet::Util::Execution).to receive(:execute).and_raise(Puppet::ExecutionFailure, 'oops') end context "puppet://server/whatever" do before do resource[:source] = "puppet://server/whatever" end it "should fail" do expect { provider.install }.to raise_error Puppet::ExecutionFailure end end context "as a malformed URL" do before do resource[:source] = "blah://" end it "should fail" do expect { provider.install }.to raise_error Puppet::ExecutionFailure end end end end # end when source is specified end # end when installing describe "when updating" do it "should call install" do expect(provider).to receive(:install).and_return("install return value") expect(provider.update).to eq("install return value") end end describe "when uninstalling" do it "should run opkg remove bla" do expect(Puppet::Util::Execution).to receive(:execute).with(["/bin/opkg", "remove", resource[:name]], {:failonfail => true, :combine => true, :custom_environment => {}}) provider.uninstall end end describe "when querying" do describe "self.instances" do let (:packages) do <<-OPKG_OUTPUT dropbear - 2011.54-2 kernel - 3.3.8-1-ba5cdb2523b4fc7722698b4a7ece6702 uhttpd - 2012-10-30-e57bf6d8bfa465a50eea2c30269acdfe751a46fd OPKG_OUTPUT end it "returns an array of packages" do allow(Puppet::Util).to receive(:which).with("opkg").and_return("/bin/opkg") allow(described_class).to receive(:which).with("opkg").and_return("/bin/opkg") expect(described_class).to receive(:execpipe).with("/bin/opkg list-installed").and_yield(packages) installed_packages = described_class.instances expect(installed_packages.length).to eq(3) expect(installed_packages[0].properties).to eq( { :provider => :opkg, :name => "dropbear", :ensure => "2011.54-2" } ) expect(installed_packages[1].properties).to eq( { :provider => :opkg, :name => "kernel", :ensure => "3.3.8-1-ba5cdb2523b4fc7722698b4a7ece6702" } ) expect(installed_packages[2].properties).to eq( { :provider => :opkg, :name => "uhttpd", :ensure => "2012-10-30-e57bf6d8bfa465a50eea2c30269acdfe751a46fd" } ) end end it "should return a nil if the package isn't found" do expect(Puppet::Util::Execution).to receive(:execute).and_return(Puppet::Util::Execution::ProcessOutput.new("", 0)) expect(provider.query).to be_nil end it "should return a hash indicating that the package is missing on error" do expect(Puppet::Util::Execution).to receive(:execute).and_raise(Puppet::ExecutionFailure.new("ERROR!")) expect(provider.query).to eq({ :ensure => :purged, :status => 'missing', :name => resource[:name], :error => 'ok', }) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/provider/package/macports_spec.rb
spec/unit/provider/package/macports_spec.rb
require 'spec_helper' describe Puppet::Type.type(:package).provider(:macports) do let :resource_name do "foo" end let :resource do Puppet::Type.type(:package).new(:name => resource_name, :provider => :macports) end let :provider do prov = resource.provider expect(prov).not_to receive(:execute) prov end let :current_hash do {:name => resource_name, :ensure => "1.2.3", :revision => "1", :provider => :macports} end context "provider features" do subject { provider } it { is_expected.to be_installable } it { is_expected.to be_uninstallable } it { is_expected.to be_upgradeable } it { is_expected.to be_versionable } end context "when listing all instances" do it "should call port -q installed" do expect(described_class).to receive(:port).with("-q", :installed).and_return("") described_class.instances end it "should create instances from active ports" do expect(described_class).to receive(:port).and_return("foo @1.234.5_2 (active)") expect(described_class.instances.size).to eq(1) end it "should ignore ports that aren't activated" do expect(described_class).to receive(:port).and_return("foo @1.234.5_2") expect(described_class.instances.size).to eq(0) end it "should ignore variants" do expect(described_class.parse_installed_query_line("bar @1.0beta2_38_1+x11+java (active)")). to eq({:provider=>:macports, :revision=>"1", :name=>"bar", :ensure=>"1.0beta2_38"}) end end context "when installing" do it "should not specify a version when ensure is set to latest" do resource[:ensure] = :latest # version would be the 4th argument, if provided. expect(provider).to receive(:port).with(anything, anything, anything) provider.install end it "should not specify a version when ensure is set to present" do resource[:ensure] = :present # version would be the 4th argument, if provided. expect(provider).to receive(:port).with(anything, anything, anything) provider.install end it "should specify a version when ensure is set to a version" do resource[:ensure] = "1.2.3" expect(provider).to receive(:port).with(anything, anything, anything, '@1.2.3') provider.install end end context "when querying for the latest version" do # Redefine provider to avoid the "expect(prov).not_to receive(:execute)" # that was set in the original definition. let(:provider) { resource.provider } let(:new_info_line) do "1.2.3 2" end let(:infoargs) do ["/opt/local/bin/port", "-q", :info, "--line", "--version", "--revision", resource_name] end let(:arguments) do {:failonfail => false, :combine => false} end before :each do allow(provider).to receive(:command).with(:port).and_return("/opt/local/bin/port") end it "should return nil when the package cannot be found" do resource[:name] = resource_name expect(provider).to receive(:execute).with(infoargs, arguments).and_return("") expect(provider.latest).to eq(nil) end it "should return the current version if the installed port has the same revision" do current_hash[:revision] = "2" expect(provider).to receive(:execute).with(infoargs, arguments).and_return(new_info_line) expect(provider).to receive(:query).and_return(current_hash) expect(provider.latest).to eq(current_hash[:ensure]) end it "should return the new version_revision if the installed port has a lower revision" do current_hash[:revision] = "1" expect(provider).to receive(:execute).with(infoargs, arguments).and_return(new_info_line) expect(provider).to receive(:query).and_return(current_hash) expect(provider.latest).to eq("1.2.3_2") end it "should return the newest version if the port is not installed" do resource[:name] = resource_name expect(provider).to receive(:execute).with(infoargs, arguments).and_return(new_info_line) expect(provider).to receive(:execute).with(["/opt/local/bin/port", "-q", :installed, resource[:name]], arguments).and_return("") expect(provider.latest).to eq("1.2.3_2") end end context "when updating a port" do it "should execute port install if the port is installed" do resource[:name] = resource_name resource[:ensure] = :present allow(provider).to receive(:query).and_return(current_hash) expect(provider).to receive(:port).with("-q", :install, resource_name) provider.update end it "should execute port install if the port is not installed" do resource[:name] = resource_name resource[:ensure] = :present allow(provider).to receive(:query).and_return("") expect(provider).to receive(:port).with("-q", :install, resource_name) provider.update end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/provider/package/hpux_spec.rb
spec/unit/provider/package/hpux_spec.rb
require 'spec_helper' describe Puppet::Type.type(:package).provider(:hpux) do before(:each) do # Create a mock resource @resource = double('resource') # A catch all; no parameters set allow(@resource).to receive(:[]).and_return(nil) # But set name and source allow(@resource).to receive(:[]).with(:name).and_return("mypackage") allow(@resource).to receive(:[]).with(:source).and_return("mysource") allow(@resource).to receive(:[]).with(:ensure).and_return(:installed) @provider = subject() allow(@provider).to receive(:resource).and_return(@resource) end it "should have an install method" do @provider = subject() expect(@provider).to respond_to(:install) end it "should have an uninstall method" do @provider = subject() expect(@provider).to respond_to(:uninstall) end it "should have a swlist method" do @provider = subject() expect(@provider).to respond_to(:swlist) end context "when installing" do it "should use a command-line like 'swinstall -x mount_all_filesystems=false -s SOURCE PACKAGE-NAME'" do expect(@provider).to receive(:swinstall).with('-x', 'mount_all_filesystems=false', '-s', 'mysource', 'mypackage') @provider.install end end context "when uninstalling" do it "should use a command-line like 'swremove -x mount_all_filesystems=false PACKAGE-NAME'" do expect(@provider).to receive(:swremove).with('-x', 'mount_all_filesystems=false', 'mypackage') @provider.uninstall end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/provider/package/up2date_spec.rb
spec/unit/provider/package/up2date_spec.rb
require 'spec_helper' describe 'up2date package provider' do # This sets the class itself as the subject rather than # an instance of the class. subject do Puppet::Type.type(:package).provider(:up2date) end osfamilies = [ 'redhat' ] releases = [ '2.1', '3', '4' ] osfamilies.each do |osfamily| releases.each do |release| it "should be the default provider on #{osfamily} #{release}" do allow(Facter).to receive(:value).with('os.family').and_return(osfamily) allow(Facter).to receive(:value).with('os.distro.release.full').and_return(release) expect(subject.default?).to be_truthy end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/provider/package/sun_spec.rb
spec/unit/provider/package/sun_spec.rb
require 'spec_helper' describe Puppet::Type.type(:package).provider(:sun) do let(:resource) { Puppet::Type.type(:package).new(:name => 'dummy', :ensure => :installed, :provider => :sun) } let(:provider) { resource.provider } describe 'provider features' do it { is_expected.to be_installable } it { is_expected.to be_uninstallable } it { is_expected.to be_upgradeable } it { is_expected.not_to be_versionable } end [:install, :uninstall, :latest, :query, :update].each do |method| it "should have a #{method} method" do expect(provider).to respond_to(method) end end context '#install' do it "should install a package" do resource[:ensure] = :installed resource[:source] = '/cdrom' expect(provider).to receive(:pkgadd).with(['-d', '/cdrom', '-n', 'dummy']) provider.install end it "should install a package if it is not present on update" do expect(provider).to receive(:pkginfo).with('-l', 'dummy').and_return(File.read(my_fixture('dummy.server'))) expect(provider).to receive(:pkgrm).with(['-n', 'dummy']) expect(provider).to receive(:install) provider.update end it "should install a package on global zone if -G specified" do resource[:ensure] = :installed resource[:source] = '/cdrom' resource[:install_options] = '-G' expect(provider).to receive(:pkgadd).with(['-d', '/cdrom', '-G', '-n', 'dummy']) provider.install end end context '#uninstall' do it "should uninstall a package" do expect(provider).to receive(:pkgrm).with(['-n','dummy']) provider.uninstall end end context '#update' do it "should call uninstall if not :absent on info2hash" do allow(provider).to receive(:info2hash).and_return({:name => 'SUNWdummy', :ensure => "11.11.0,REV=2010.10.12.04.23"}) expect(provider).to receive(:uninstall) expect(provider).to receive(:install) provider.update end it "should not call uninstall if :absent on info2hash" do allow(provider).to receive(:info2hash).and_return({:name => 'SUNWdummy', :ensure => :absent}) expect(provider).to receive(:install) provider.update end end context '#query' do it "should find the package on query" do expect(provider).to receive(:pkginfo).with('-l', 'dummy').and_return(File.read(my_fixture('dummy.server'))) expect(provider.query).to eq({ :name => 'SUNWdummy', :category=>"system", :platform=>"i386", :ensure => "11.11.0,REV=2010.10.12.04.23", :root=>"/", :description=>"Dummy server (9.6.1-P3)", :vendor => "Oracle Corporation", }) end it "shouldn't find the package on query if it is not present" do expect(provider).to receive(:pkginfo).with('-l', 'dummy').and_raise(Puppet::ExecutionFailure, "Execution of 'pkginfo -l dummy' returned 3: ERROR: information for \"dummy\" not found.") expect(provider.query).to eq({:ensure => :absent}) end it "unknown message should raise error." do expect(provider).to receive(:pkginfo).with('-l', 'dummy').and_return('RANDOM') expect { provider.query }.to raise_error Puppet::Error end end context '#instance' do it "should list instances when there are packages in the system" do expect(described_class).to receive(:pkginfo).with('-l').and_return(File.read(my_fixture('simple'))) instances = provider.class.instances.map { |p| {:name => p.get(:name), :ensure => p.get(:ensure)} } expect(instances.size).to eq(2) expect(instances[0]).to eq({ :name => 'SUNWdummy', :ensure => "11.11.0,REV=2010.10.12.04.23", }) expect(instances[1]).to eq({ :name => 'SUNWdummyc', :ensure => "11.11.0,REV=2010.10.12.04.24", }) end it "should return empty if there were no packages" do expect(described_class).to receive(:pkginfo).with('-l').and_return('') instances = provider.class.instances expect(instances.size).to eq(0) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/provider/package/dnf_spec.rb
spec/unit/provider/package/dnf_spec.rb
require 'spec_helper' # Note that much of the functionality of the dnf provider is already tested with yum provider tests, # as yum is the parent provider. describe Puppet::Type.type(:package).provider(:dnf) do context 'default' do (19..21).each do |ver| it "should not be the default provider on fedora#{ver}" do allow(Facter).to receive(:value).with('os.family').and_return(:redhat) allow(Facter).to receive(:value).with('os.name').and_return(:fedora) allow(Facter).to receive(:value).with('os.release.major').and_return("#{ver}") expect(described_class).to_not be_default end end (22..26).each do |ver| it "should be the default provider on fedora#{ver}" do allow(Facter).to receive(:value).with('os.family').and_return(:redhat) allow(Facter).to receive(:value).with('os.name').and_return(:fedora) allow(Facter).to receive(:value).with('os.release.major').and_return("#{ver}") expect(described_class).to be_default end end it "should not be the default provider on rhel7" do allow(Facter).to receive(:value).with('os.family').and_return(:redhat) allow(Facter).to receive(:value).with('os.name').and_return(:redhat) allow(Facter).to receive(:value).with('os.release.major').and_return("7") expect(described_class).to_not be_default end it "should be the default provider on some random future fedora" do allow(Facter).to receive(:value).with('os.family').and_return(:redhat) allow(Facter).to receive(:value).with('os.name').and_return(:fedora) allow(Facter).to receive(:value).with('os.release.major').and_return("8675") expect(described_class).to be_default end it "should be the default provider on rhel8" do allow(Facter).to receive(:value).with('os.family').and_return(:redhat) allow(Facter).to receive(:value).with('os.name').and_return(:redhat) allow(Facter).to receive(:value).with('os.release.major').and_return("8") expect(described_class).to be_default end it "should be the default provider on Amazon Linux 2023" do allow(Facter).to receive(:value).with('os.family').and_return(:redhat) allow(Facter).to receive(:value).with('os.name').and_return(:amazon) allow(Facter).to receive(:value).with('os.release.major').and_return("2023") expect(described_class).to be_default end end describe 'provider features' do it { is_expected.to be_versionable } it { is_expected.to be_install_options } it { is_expected.to be_virtual_packages } it { is_expected.to be_install_only } end it_behaves_like 'RHEL package provider', described_class, 'dnf' end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/provider/package/pkgng_spec.rb
spec/unit/provider/package/pkgng_spec.rb
require 'spec_helper' require 'puppet/provider/package/pkgng' describe Puppet::Type.type(:package).provider(:pkgng) do let(:name) { 'bash' } let(:installed_name) { 'zsh' } let(:pkgng) { 'pkgng' } let(:resource) do # When bash is not present Puppet::Type.type(:package).new(:name => name, :provider => pkgng) end let(:installed_resource) do # When zsh is present Puppet::Type.type(:package).new(:name => installed_name, :provider => pkgng) end let(:latest_resource) do # When curl is installed but not the latest Puppet::Type.type(:package).new(:name => 'ftp/curl', :provider => pkgng, :ensure => latest) end let (:provider) { resource.provider } let (:installed_provider) { installed_resource.provider } def run_in_catalog(*resources) catalog = Puppet::Resource::Catalog.new catalog.host_config = false resources.each do |resource| catalog.add_resource(resource) end catalog.apply end before do allow(described_class).to receive(:command).with(:pkg).and_return('/usr/local/sbin/pkg') info = File.read(my_fixture('pkg.query')) allow(described_class).to receive(:get_query).and_return(info) version_list = File.read(my_fixture('pkg.version')) allow(described_class).to receive(:get_version_list).and_return(version_list) end context "#instances" do it "should return the empty set if no packages are listed" do allow(described_class).to receive(:get_query).and_return('') allow(described_class).to receive(:get_version_list).and_return('') expect(described_class.instances).to be_empty end it "should return all packages when invoked" do expect(described_class.instances.map(&:name).sort).to eq( %w{ca_root_nss curl nmap pkg gnupg zsh tac_plus}.sort) end it "should set latest to current version when no upgrade available" do nmap = described_class.instances.find {|i| i.properties[:origin] == 'security/nmap' } expect(nmap.properties[:version]).to eq(nmap.properties[:latest]) end it "should return an empty array when pkg calls raise an exception" do allow(described_class).to receive(:get_query).and_raise(Puppet::ExecutionFailure, 'An error occurred.') expect(described_class.instances).to eq([]) end describe "version" do it "should retrieve the correct version of the current package" do zsh = described_class.instances.find {|i| i.properties[:origin] == 'shells/zsh' } expect(zsh.properties[:version]).to eq('5.0.2_1') end end end context "#install" do it "should call pkg with the specified package version given an origin for package name" do resource = Puppet::Type.type(:package).new( :name => 'ftp/curl', :provider => :pkgng, :ensure => '7.33.1' ) expect(resource.provider).to receive(:pkg) do |arg| expect(arg).to include('curl-7.33.1') end resource.provider.install end it "should call pkg with the specified package version" do resource = Puppet::Type.type(:package).new( :name => 'curl', :provider => :pkgng, :ensure => '7.33.1' ) expect(resource.provider).to receive(:pkg) do |arg| expect(arg).to include('curl-7.33.1') end resource.provider.install end it "should call pkg with the specified package repo" do resource = Puppet::Type.type(:package).new( :name => 'curl', :provider => :pkgng, :source => 'urn:freebsd:repo:FreeBSD' ) expect(resource.provider).to receive(:pkg) do |arg| expect(arg).to include('FreeBSD') end resource.provider.install end it "should call pkg with the specified install options string" do resource = Puppet::Type.type(:package).new( :name => 'curl', :provider => :pkgng, :install_options => ['--foo', '--bar'] ) expect(resource.provider).to receive(:pkg) do |arg| expect(arg).to include('--foo', '--bar') end resource.provider.install end it "should call pkg with the specified install options hash" do resource = Puppet::Type.type(:package).new( :name => 'curl', :provider => :pkgng, :install_options => ['--foo', { '--bar' => 'baz', '--baz' => 'foo' }] ) expect(resource.provider).to receive(:pkg) do |arg| expect(arg).to include('--foo', '--bar=baz', '--baz=foo') end resource.provider.install end end context "#prefetch" do it "should fail gracefully when " do allow(described_class).to receive(:instances).and_return([]) expect{ described_class.prefetch({}) }.to_not raise_error end end context "#query" do it "should return the installed version if present" do pkg_query_zsh = File.read(my_fixture('pkg.query.zsh')) allow(described_class).to receive(:get_resource_info).with('zsh').and_return(pkg_query_zsh) described_class.prefetch({installed_name => installed_resource}) expect(installed_provider.query).to be >= {:version=>'5.0.2_1'} end it "should return nil if not present" do allow(described_class).to receive(:get_resource_info).with('bash').and_raise(Puppet::ExecutionFailure, 'An error occurred') expect(provider.query).to equal(nil) end end describe "latest" do it "should retrieve the correct version of the latest package" do described_class.prefetch( { installed_name => installed_resource }) expect(installed_provider.latest).not_to be_nil end it "should set latest to newer package version when available" do instances = described_class.instances curl = instances.find {|i| i.properties[:origin] == 'ftp/curl' } expect(curl.properties[:latest]).to eq('7.33.0_2') end it "should call update to upgrade the version" do allow(described_class).to receive(:get_resource_info).with('ftp/curl').and_return('curl 7.61.1 ftp/curl') resource = Puppet::Type.type(:package).new( :name => 'ftp/curl', :provider => pkgng, :ensure => :latest ) expect(resource.provider).to receive(:update) resource.property(:ensure).sync end end describe "get_latest_version" do it "should rereturn nil when the current package is the latest" do version_list = File.read(my_fixture('pkg.version')) allow(described_class).to receive(:get_version_list).and_return(version_list) nmap_latest_version = described_class.get_latest_version('security/nmap') expect(nmap_latest_version).to be_nil end it "should match the package name exactly" do version_list = File.read(my_fixture('pkg.version')) allow(described_class).to receive(:get_version_list).and_return(version_list) bash_comp_latest_version = described_class.get_latest_version('shells/bash-completion') expect(bash_comp_latest_version).to eq('2.1_3') end it "should return nil when the package is orphaned" do version_list = File.read(my_fixture('pkg.version')) allow(described_class).to receive(:get_version_list).and_return(version_list) orphan_latest_version = described_class.get_latest_version('sysutils/orphan') expect(orphan_latest_version).to be_nil end it "should return nil when the package is broken" do version_list = File.read(my_fixture('pkg.version')) allow(described_class).to receive(:get_version_list).and_return(version_list) broken_latest_version = described_class.get_latest_version('sysutils/broken') expect(broken_latest_version).to be_nil end end describe "confine" do context "on FreeBSD" do it "should be the default provider" do expect(Facter).to receive(:value).with('os.name').at_least(:once).and_return(:freebsd) expect(described_class).to be_default end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/provider/package/pkgin_spec.rb
spec/unit/provider/package/pkgin_spec.rb
require "spec_helper" describe Puppet::Type.type(:package).provider(:pkgin) do let(:resource) { Puppet::Type.type(:package).new(:name => "vim", :provider => :pkgin) } subject { resource.provider } describe "Puppet provider interface" do it "can return the list of all packages" do expect(described_class).to respond_to(:instances) end end describe "#install" do describe "a package not installed" do before { resource[:ensure] = :absent } it "uses pkgin install to install" do expect(subject).to receive(:pkgin).with("-y", :install, "vim").once() subject.install end end describe "a package with a fixed version" do before { resource[:ensure] = '7.2.446' } it "uses pkgin install to install a fixed version" do expect(subject).to receive(:pkgin).with("-y", :install, "vim-7.2.446").once() subject.install end end end describe "#uninstall" do it "uses pkgin remove to uninstall" do expect(subject).to receive(:pkgin).with("-y", :remove, "vim").once() subject.uninstall end end describe "#instances" do let(:pkgin_ls_output) do "zlib-1.2.3;General purpose data compression library\nzziplib-0.13.59;Library for ZIP archive handling\n" end before do allow(described_class).to receive(:pkgin).with(:list).and_return(pkgin_ls_output) end it "returns an array of providers for each package" do instances = described_class.instances expect(instances.count).to eq 2 instances.each do |instance| expect(instance).to be_a(described_class) end end it "populates each provider with an installed package" do zlib_provider, zziplib_provider = described_class.instances expect(zlib_provider.get(:name)).to eq("zlib") expect(zlib_provider.get(:ensure)).to eq("1.2.3") expect(zziplib_provider.get(:name)).to eq("zziplib") expect(zziplib_provider.get(:ensure)).to eq("0.13.59") end end describe "#latest" do before do allow(described_class).to receive(:pkgin).with(:search, "vim").and_return(pkgin_search_output) end context "when the package is installed" do let(:pkgin_search_output) do "vim-7.2.446;=;Vim editor (vi clone) without GUI\nvim-share-7.2.446;=;Data files for the vim editor (vi clone)\n\n=: package is installed and up-to-date\n<: package is installed but newer version is available\n>: installed package has a greater version than available package\n" end it "returns installed version" do expect(subject).to receive(:properties).and_return({ :ensure => "7.2.446" }) expect(subject.latest).to eq("7.2.446") end end context "when the package is out of date" do let(:pkgin_search_output) do "vim-7.2.447;<;Vim editor (vi clone) without GUI\nvim-share-7.2.447;<;Data files for the vim editor (vi clone)\n\n=: package is installed and up-to-date\n<: package is installed but newer version is available\n>: installed package has a greater version than available package\n" end it "returns the version to be installed" do expect(subject.latest).to eq("7.2.447") end end context "when the package is ahead of date" do let(:pkgin_search_output) do "vim-7.2.446;>;Vim editor (vi clone) without GUI\nvim-share-7.2.446;>;Data files for the vim editor (vi clone)\n\n=: package is installed and up-to-date\n<: package is installed but newer version is available\n>: installed package has a greater version than available package\n" end it "returns current version" do expect(subject).to receive(:properties).and_return({ :ensure => "7.2.446" }) expect(subject.latest).to eq("7.2.446") end end context "when multiple candidates do exists" do let(:pkgin_search_output) do <<-SEARCH vim-7.1;>;Vim editor (vi clone) without GUI vim-share-7.1;>;Data files for the vim editor (vi clone) vim-7.2.446;=;Vim editor (vi clone) without GUI vim-share-7.2.446;=;Data files for the vim editor (vi clone) vim-7.3;<;Vim editor (vi clone) without GUI vim-share-7.3;<;Data files for the vim editor (vi clone) =: package is installed and up-to-date <: package is installed but newer version is available >: installed package has a greater version than available package SEARCH end it "returns the newest available version" do allow(described_class).to receive(:pkgin).with(:search, "vim").and_return(pkgin_search_output) expect(subject.latest).to eq("7.3") end end context "when the package cannot be found" do let(:pkgin_search_output) do "No results found for is-puppet" end it "returns nil" do expect { subject.latest }.to raise_error(Puppet::Error, "No candidate to be installed") end end end describe "#parse_pkgin_line" do context "with an installed package" do let(:package) { "vim-7.2.446;=;Vim editor (vi clone) without GUI" } it "extracts the name and status" do expect(described_class.parse_pkgin_line(package)).to eq({ :name => "vim" , :status => "=" , :ensure => "7.2.446" }) end end context "with an installed package with a hyphen in the name" do let(:package) { "ruby18-puppet-0.25.5nb1;>;Configuration management framework written in Ruby" } it "extracts the name and status" do expect(described_class.parse_pkgin_line(package)).to eq({ :name => "ruby18-puppet", :status => ">" , :ensure => "0.25.5nb1" }) end end context "with an installed package with a hyphen in the name and package description" do let(:package) { "ruby200-facter-2.4.3nb1;=;Cross-platform Ruby library for retrieving facts from OS" } it "extracts the name and status" do expect(described_class.parse_pkgin_line(package)).to eq({ :name => "ruby200-facter", :status => "=" , :ensure => "2.4.3nb1" }) end end context "with a package not yet installed" do let(:package) { "vim-7.2.446;Vim editor (vi clone) without GUI" } it "extracts the name and status" do expect(described_class.parse_pkgin_line(package)).to eq({ :name => "vim" , :status => nil , :ensure => "7.2.446" }) end end context "with an invalid package" do let(:package) { "" } it "returns nil" do expect(described_class.parse_pkgin_line(package)).to be_nil end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/provider/package/dpkg_spec.rb
spec/unit/provider/package/dpkg_spec.rb
require 'spec_helper' require 'stringio' describe Puppet::Type.type(:package).provider(:dpkg), unless: Puppet::Util::Platform.jruby? do let(:bash_version) { '4.2-5ubuntu3' } let(:bash_installed_output) { "install ok installed bash #{bash_version}\n" } let(:bash_installed_io) { StringIO.new(bash_installed_output) } let(:vim_installed_output) { "install ok installed vim 2:7.3.547-6ubuntu5\n" } let(:all_installed_io) { StringIO.new([bash_installed_output, vim_installed_output].join) } let(:args) { ['-W', '--showformat', %Q{'${Status} ${Package} ${Version}\\n'}] } let(:args_with_provides) { ['/bin/dpkg-query','-W', '--showformat', %Q{'${Status} ${Package} ${Version} [${Provides}]\\n'}]} let(:execute_options) do {:failonfail => true, :combine => true, :custom_environment => {}} end let(:resource_name) { 'python' } let(:resource) { double('resource', :[] => resource_name) } let(:dpkg_query_result) { 'install ok installed python 2.7.13' } let(:provider) { described_class.new(resource) } it "has documentation" do expect(described_class.doc).to be_instance_of(String) end context "when listing all instances" do let(:execpipe_args) { args.unshift('myquery') } before do allow(described_class).to receive(:command).with(:dpkgquery).and_return('myquery') end it "creates and return an instance for a single dpkg-query entry" do expect(Puppet::Util::Execution).to receive(:execpipe).with(execpipe_args).and_yield(bash_installed_io) installed = double('bash') expect(described_class).to receive(:new).with({:ensure => "4.2-5ubuntu3", :error => "ok", :desired => "install", :name => "bash", :mark => :none, :status => "installed", :provider => :dpkg}).and_return(installed) expect(described_class.instances).to eq([installed]) end it "parses multiple dpkg-query multi-line entries in the output" do expect(Puppet::Util::Execution).to receive(:execpipe).with(execpipe_args).and_yield(all_installed_io) bash = double('bash') expect(described_class).to receive(:new).with({:ensure => "4.2-5ubuntu3", :error => "ok", :desired => "install", :name => "bash", :mark => :none, :status => "installed", :provider => :dpkg}).and_return(bash) vim = double('vim') expect(described_class).to receive(:new).with({:ensure => "2:7.3.547-6ubuntu5", :error => "ok", :desired => "install", :name => "vim", :mark => :none, :status => "installed", :provider => :dpkg}).and_return(vim) expect(described_class.instances).to eq([bash, vim]) end it "continues without failing if it encounters bad lines between good entries" do expect(Puppet::Util::Execution).to receive(:execpipe).with(execpipe_args).and_yield(StringIO.new([bash_installed_output, "foobar\n", vim_installed_output].join)) bash = double('bash') vim = double('vim') expect(described_class).to receive(:new).twice.and_return(bash, vim) expect(described_class.instances).to eq([bash, vim]) end end context "when querying the current state" do let(:dpkgquery_path) { '/bin/dpkg-query' } let(:query_args) do args.unshift(dpkgquery_path) args.push(resource_name) end def dpkg_query_execution_returns(output) expect(Puppet::Util::Execution).to receive(:execute).with(query_args, execute_options).and_return(Puppet::Util::Execution::ProcessOutput.new(output, 0)) end def dpkg_query_execution_with_multiple_args_returns(output, *args) args.each do |arg| allow(Puppet::Util::Execution).to receive(:execute).with(arg, execute_options).and_return(Puppet::Util::Execution::ProcessOutput.new(output, 0)) end end before do allow(Puppet::Util).to receive(:which).with('/usr/bin/dpkg-query').and_return(dpkgquery_path) end it "considers the package purged if dpkg-query fails" do allow(resource).to receive(:allow_virtual?).and_return(false) allow(Puppet::Util::Execution).to receive(:execute).with(query_args, execute_options).and_raise(Puppet::ExecutionFailure.new("eh")) expect(provider.query[:ensure]).to eq(:purged) end context "allow_virtual true" do before do allow(resource).to receive(:allow_virtual?).and_return(true) end context "virtual_packages" do let(:query_output) { 'install ok installed python 2.7.13 [python-ctypes, python-email, python-importlib, python-profiler, python-wsgiref, python-gold]' } let(:virtual_packages_query_args) do result = args_with_provides.dup result.push(resource_name) end it "considers the package purged if dpkg-query fails" do allow(Puppet::Util::Execution).to receive(:execute).with(args_with_provides, execute_options).and_raise(Puppet::ExecutionFailure.new("eh")) expect(provider.query[:ensure]).to eq(:purged) end it "returns a hash of the found package status for an installed package" do dpkg_query_execution_with_multiple_args_returns(query_output, args_with_provides,virtual_packages_query_args) dpkg_query_execution_with_multiple_args_returns(dpkg_query_result, args, query_args) expect(provider.query).to eq(:ensure => "2.7.13", :error => "ok", :desired => "install", :name => "python", :mark => :none, :status => "installed", :provider => :dpkg) end it "considers the package absent if the dpkg-query result cannot be interpreted" do dpkg_query_execution_with_multiple_args_returns('some-bad-data',args_with_provides,virtual_packages_query_args) dpkg_query_execution_with_multiple_args_returns('some-bad-data', args, query_args) expect(provider.query[:ensure]).to eq(:absent) end it "fails if an error is discovered" do dpkg_query_execution_with_multiple_args_returns(query_output.gsub("ok","error"),args_with_provides,virtual_packages_query_args) dpkg_query_execution_with_multiple_args_returns(dpkg_query_result.gsub("ok","error"), args, query_args) expect { provider.query }.to raise_error(Puppet::Error, /Package python, version 2.7.13 is in error state: error/) end it "considers the package purged if it is marked 'not-installed" do not_installed_query = query_output.gsub("installed", "not-installed").delete!('2.7.13') dpkg_query_execution_with_multiple_args_returns(not_installed_query, args_with_provides,virtual_packages_query_args) dpkg_query_execution_with_multiple_args_returns(dpkg_query_result.gsub("installed", "not-installed").delete!('2.7.13'), args, query_args) expect(provider.query[:ensure]).to eq(:purged) end it "considers the package absent if it is marked 'config-files'" do dpkg_query_execution_with_multiple_args_returns(query_output.gsub("installed","config-files"),args_with_provides,virtual_packages_query_args) dpkg_query_execution_with_multiple_args_returns(dpkg_query_result.gsub("installed","config-files"), args, query_args) expect(provider.query[:ensure]).to eq(:absent) end it "considers the package absent if it is marked 'half-installed'" do dpkg_query_execution_with_multiple_args_returns(query_output.gsub("installed","half-installed"),args_with_provides,virtual_packages_query_args) dpkg_query_execution_with_multiple_args_returns(dpkg_query_result.gsub("installed","half-installed"), args, query_args) expect(provider.query[:ensure]).to eq(:absent) end it "considers the package absent if it is marked 'unpacked'" do dpkg_query_execution_with_multiple_args_returns(query_output.gsub("installed","unpacked"),args_with_provides,virtual_packages_query_args) dpkg_query_execution_with_multiple_args_returns(dpkg_query_result.gsub("installed","unpacked"), args, query_args) expect(provider.query[:ensure]).to eq(:absent) end it "considers the package absent if it is marked 'half-configured'" do dpkg_query_execution_with_multiple_args_returns(query_output.gsub("installed","half-configured"),args_with_provides,virtual_packages_query_args) dpkg_query_execution_with_multiple_args_returns(dpkg_query_result.gsub("installed","half-configured"), args, query_args) expect(provider.query[:ensure]).to eq(:absent) end it "considers the package held if its state is 'hold'" do dpkg_query_execution_with_multiple_args_returns(query_output.gsub("install","hold"),args_with_provides,virtual_packages_query_args) dpkg_query_execution_with_multiple_args_returns(dpkg_query_result.gsub("install","hold"), args, query_args) expect(provider.query[:ensure]).to eq("2.7.13") expect(provider.query[:mark]).to eq(:hold) end it "considers the package held if its state is 'hold'" do dpkg_query_execution_with_multiple_args_returns(query_output.gsub("install","hold"),args_with_provides,virtual_packages_query_args) dpkg_query_execution_with_multiple_args_returns(dpkg_query_result.gsub("install","hold"), args, query_args) expect(provider.query[:ensure]).to eq("2.7.13") expect(provider.query[:mark]).to eq(:hold) end it "considers mark status to be none if package is not held" do dpkg_query_execution_with_multiple_args_returns(query_output.gsub("install","ok"),args_with_provides,virtual_packages_query_args) dpkg_query_execution_with_multiple_args_returns(dpkg_query_result.gsub("install","ok"), args, query_args) expect(provider.query[:ensure]).to eq("2.7.13") expect(provider.query[:mark]).to eq(:none) end context "regex check for query search" do let(:resource_name) { 'python-email' } let(:resource) { instance_double('Puppet::Type::Package') } before do allow(resource).to receive(:[]).with(:name).and_return(resource_name) allow(resource).to receive(:[]=) end it "checks if virtual package regex for query is correct and physical package is installed" do dpkg_query_execution_with_multiple_args_returns(query_output,args_with_provides,virtual_packages_query_args) dpkg_query_execution_with_multiple_args_returns(dpkg_query_result, args, query_args) expect(provider.query).to match({:desired => "install", :ensure => "2.7.13", :error => "ok", :name => "python", :mark => :none, :provider => :dpkg, :status => "installed"}) end context "regex check with no partial matching" do let(:resource_name) { 'python-em' } it "checks if virtual package regex for query is correct and regext dosen't make partial matching" do expect(provider).to receive(:dpkgquery).with('-W', '--showformat', %Q{'${Status} ${Package} ${Version} [${Provides}]\\n'}).and_return(query_output) expect(provider).to receive(:dpkgquery).with('-W', '--showformat', %Q{'${Status} ${Package} ${Version}\\n'}, resource_name).and_return("#{dpkg_query_result} #{resource_name}") provider.query end context "regex check with special characters" do let(:resource_name) { 'g++' } it "checks if virtual package regex for query is correct and regext dosen't make partial matching" do expect(Puppet).to_not receive(:info).with(/is virtual/) expect(provider).to receive(:dpkgquery).with('-W', '--showformat', %Q{'${Status} ${Package} ${Version} [${Provides}]\\n'}).and_return(query_output) expect(provider).to receive(:dpkgquery).with('-W', '--showformat', %Q{'${Status} ${Package} ${Version}\\n'}, resource_name).and_return("#{dpkg_query_result} #{resource_name}") provider.query end end end end end end context "allow_virtual false" do before do allow(resource).to receive(:allow_virtual?).and_return(false) end it "returns a hash of the found package status for an installed package" do dpkg_query_execution_returns(bash_installed_output) expect(provider.query).to eq({:ensure => "4.2-5ubuntu3", :error => "ok", :desired => "install", :name => "bash", :mark => :none, :status => "installed", :provider => :dpkg}) end it "considers the package absent if the dpkg-query result cannot be interpreted" do allow(resource).to receive(:allow_virtual?).and_return(false) dpkg_query_execution_returns('some-bad-data') expect(provider.query[:ensure]).to eq(:absent) end it "fails if an error is discovered" do dpkg_query_execution_returns(bash_installed_output.gsub("ok","error")) expect { provider.query }.to raise_error(Puppet::Error) end it "considers the package purged if it is marked 'not-installed'" do not_installed_bash = bash_installed_output.gsub("installed", "not-installed") not_installed_bash.gsub!(bash_version, "") dpkg_query_execution_returns(not_installed_bash) expect(provider.query[:ensure]).to eq(:purged) end it "considers the package held if its state is 'hold'" do dpkg_query_execution_returns(bash_installed_output.gsub("install","hold")) query=provider.query expect(query[:ensure]).to eq("4.2-5ubuntu3") expect(query[:mark]).to eq(:hold) end it "considers the package absent if it is marked 'config-files'" do dpkg_query_execution_returns(bash_installed_output.gsub("installed","config-files")) expect(provider.query[:ensure]).to eq(:absent) end it "considers the package absent if it is marked 'half-installed'" do dpkg_query_execution_returns(bash_installed_output.gsub("installed","half-installed")) expect(provider.query[:ensure]).to eq(:absent) end it "considers the package absent if it is marked 'unpacked'" do dpkg_query_execution_returns(bash_installed_output.gsub("installed","unpacked")) expect(provider.query[:ensure]).to eq(:absent) end it "considers the package absent if it is marked 'half-configured'" do dpkg_query_execution_returns(bash_installed_output.gsub("installed","half-configured")) expect(provider.query[:ensure]).to eq(:absent) end it "considers the package held if its state is 'hold'" do dpkg_query_execution_returns(bash_installed_output.gsub("install","hold")) query=provider.query expect(query[:ensure]).to eq("4.2-5ubuntu3") expect(query[:mark]).to eq(:hold) end context "parsing tests" do let(:resource_name) { 'name' } let(:package_hash) do { :desired => 'desired', :error => 'ok', :status => 'status', :name => resource_name, :mark => :none, :ensure => 'ensure', :provider => :dpkg, } end let(:package_not_found_hash) do {:ensure => :purged, :status => 'missing', :name => resource_name, :error => 'ok'} end let(:output) {'an unexpected dpkg msg with an exit code of 0'} def parser_test(dpkg_output_string, gold_hash, number_of_debug_logs = 0) dpkg_query_execution_returns(dpkg_output_string) expect(Puppet).not_to receive(:warning) expect(Puppet).to receive(:debug).exactly(number_of_debug_logs).times expect(provider.query).to eq(gold_hash) end it "parses properly even if optional ensure field is missing" do no_ensure = 'desired ok status name ' parser_test(no_ensure, package_hash.merge(:ensure => '')) end it "provides debug logging of unparsable lines with allow_virtual enabled" do allow(resource).to receive(:allow_virtual?).and_return(true) dpkg_query_execution_with_multiple_args_returns(output, args_with_provides, query_args) expect(Puppet).not_to receive(:warning) expect(Puppet).to receive(:debug).exactly(1).times expect(provider.query).to eq(package_not_found_hash.merge(:ensure => :absent)) end it "provides debug logging of unparsable lines" do parser_test('an unexpected dpkg msg with an exit code of 0', package_not_found_hash.merge(:ensure => :absent), 1) end it "does not log if execution returns with non-zero exit code with allow_virtual enabled" do allow(resource).to receive(:allow_virtual?).and_return(true) expect(Puppet::Util::Execution).to receive(:execute).with(args_with_provides, execute_options).and_raise(Puppet::ExecutionFailure.new("failed")) expect(Puppet).not_to receive(:debug) expect(provider.query).to eq(package_not_found_hash) end it "does not log if execution returns with non-zero exit code" do expect(Puppet::Util::Execution).to receive(:execute).with(query_args, execute_options).and_raise(Puppet::ExecutionFailure.new("failed")) expect(Puppet).not_to receive(:debug) expect(provider.query).to eq(package_not_found_hash) end end end end context "when installing" do before do allow(resource).to receive(:[]).with(:source).and_return("mypkg") end it "fails to install if no source is specified in the resource" do expect(resource).to receive(:[]).with(:source).and_return(nil) expect { provider.install }.to raise_error(ArgumentError) end it "uses 'dpkg -i' to install the package" do expect(resource).to receive(:[]).with(:source).and_return("mypackagefile") expect(provider).to receive(:properties).and_return({:mark => :hold}) expect(provider).to receive(:unhold) expect(provider).to receive(:dpkg).with(any_args, "-i", "mypackagefile") provider.install end it "keeps old config files if told to do so" do expect(resource).to receive(:[]).with(:configfiles).and_return(:keep) expect(provider).to receive(:properties).and_return({:mark => :hold}) expect(provider).to receive(:unhold) expect(provider).to receive(:dpkg).with("--force-confold", any_args) provider.install end it "replaces old config files if told to do so" do expect(resource).to receive(:[]).with(:configfiles).and_return(:replace) expect(provider).to receive(:properties).and_return({:mark => :hold}) expect(provider).to receive(:unhold) expect(provider).to receive(:dpkg).with("--force-confnew", any_args) provider.install end it "ensures any hold is removed" do expect(provider).to receive(:properties).and_return({:mark => :hold}) expect(provider).to receive(:unhold).once expect(provider).to receive(:dpkg) provider.install end end context "when holding or unholding" do let(:tempfile) { double('tempfile', :print => nil, :close => nil, :flush => nil, :path => "/other/file") } before do allow(tempfile).to receive(:write) allow(Tempfile).to receive(:open).and_yield(tempfile) end it "executes dpkg --set-selections when holding" do allow(provider).to receive(:install) expect(provider).to receive(:execute).with([:dpkg, '--set-selections'], {:failonfail => false, :combine => false, :stdinfile => tempfile.path}).once provider.hold end it "executes dpkg --set-selections when unholding" do allow(provider).to receive(:install) expect(provider).to receive(:execute).with([:dpkg, '--set-selections'], {:failonfail => false, :combine => false, :stdinfile => tempfile.path}).once provider.hold end end it "uses :install to update" do expect(provider).to receive(:install) provider.update end context "when determining latest available version" do it "returns the version found by dpkg-deb" do expect(resource).to receive(:[]).with(:source).and_return("python") expect(provider).to receive(:dpkg_deb).with('--show', "python").and_return("package\t1.0") expect(provider.latest).to eq("1.0") end it "warns if the package file contains a different package" do expect(provider).to receive(:dpkg_deb).and_return("foo\tversion") expect(provider).to receive(:warning) provider.latest end it "copes with names containing ++" do resource = double('resource', :[] => "package++") provider = described_class.new(resource) expect(provider).to receive(:dpkg_deb).and_return("package++\t1.0") expect(provider.latest).to eq("1.0") end end it "uses 'dpkg -r' to uninstall" do expect(provider).to receive(:dpkg).with("-r", resource_name) provider.uninstall end it "uses 'dpkg --purge' to purge" do expect(provider).to receive(:dpkg).with("--purge", resource_name) provider.purge end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/provider/package/appdmg_spec.rb
spec/unit/provider/package/appdmg_spec.rb
require 'spec_helper' describe Puppet::Type.type(:package).provider(:appdmg) do let(:resource) { Puppet::Type.type(:package).new(:name => 'foo', :provider => :appdmg) } let(:provider) { described_class.new(resource) } describe "when installing an appdmg" do let(:fake_mountpoint) { "/tmp/dmg.foo" } let(:fake_hdiutil_plist) { {"system-entities" => [{"mount-point" => fake_mountpoint}]} } before do fh = double('filehandle', path: '/tmp/foo') resource[:source] = "foo.dmg" allow(File).to receive(:open).and_yield(fh) allow(Dir).to receive(:mktmpdir).and_return("/tmp/testtmp123") allow(FileUtils).to receive(:remove_entry_secure) end describe "from a remote source" do let(:tmpdir) { "/tmp/good123" } before :each do resource[:source] = "http://fake.puppetlabs.com/foo.dmg" end it "should call tmpdir and use the returned directory" do expect(Dir).to receive(:mktmpdir).and_return(tmpdir) allow(Dir).to receive(:entries).and_return(["foo.app"]) expect(described_class).to receive(:curl) do |*args| expect(args[0]).to eq("-o") expect(args[1]).to include(tmpdir) expect(args).not_to include("-k") end allow(described_class).to receive(:hdiutil).and_return('a plist') expect(Puppet::Util::Plist).to receive(:parse_plist).with('a plist').and_return(fake_hdiutil_plist) expect(described_class).to receive(:installapp) provider.install end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/provider/package/openbsd_spec.rb
spec/unit/provider/package/openbsd_spec.rb
require 'spec_helper' require 'stringio' describe Puppet::Type.type(:package).provider(:openbsd) do let(:package) { Puppet::Type.type(:package).new(:name => 'bash', :provider => 'openbsd') } let(:provider) { described_class.new(package) } def expect_read_from_pkgconf(lines) pkgconf = double(:readlines => lines) expect(Puppet::FileSystem).to receive(:exist?).with('/etc/pkg.conf').and_return(true) expect(File).to receive(:open).with('/etc/pkg.conf', 'rb').and_return(pkgconf) end def expect_pkgadd_with_source(source) expect(provider).to receive(:pkgadd).with([source]) do expect(ENV).not_to have_key('PKG_PATH') end end def expect_pkgadd_with_env_and_name(source, &block) expect(ENV).not_to have_key('PKG_PATH') expect(provider).to receive(:pkgadd).with([provider.resource[:name]]) do expect(ENV).to have_key('PKG_PATH') expect(ENV['PKG_PATH']).to eq(source) end expect(provider).to receive(:execpipe).with(['/bin/pkg_info', '-I', provider.resource[:name]]).and_yield('') yield expect(ENV).not_to be_key('PKG_PATH') end context 'provider features' do it { is_expected.to be_installable } it { is_expected.to be_install_options } it { is_expected.to be_uninstallable } it { is_expected.to be_uninstall_options } it { is_expected.to be_upgradeable } it { is_expected.to be_versionable } end before :each do # Stub some provider methods to avoid needing the actual software # installed, so we can test on whatever platform we want. allow(described_class).to receive(:command).with(:pkginfo).and_return('/bin/pkg_info') allow(described_class).to receive(:command).with(:pkgadd).and_return('/bin/pkg_add') allow(described_class).to receive(:command).with(:pkgdelete).and_return('/bin/pkg_delete') allow(Puppet::FileSystem).to receive(:exist?) end context "#instances" do it "should return nil if execution failed" do expect(described_class).to receive(:execpipe).and_raise(Puppet::ExecutionFailure, 'wawawa') expect(described_class.instances).to be_nil end it "should return the empty set if no packages are listed" do expect(described_class).to receive(:execpipe).with(%w{/bin/pkg_info -a}).and_yield(StringIO.new('')) expect(described_class.instances).to be_empty end it "should return all packages when invoked" do fixture = File.read(my_fixture('pkginfo.list')) expect(described_class).to receive(:execpipe).with(%w{/bin/pkg_info -a}).and_yield(fixture) expect(described_class.instances.map(&:name).sort).to eq( %w{bash bzip2 expat gettext libiconv lzo openvpn python vim wget}.sort ) end it "should return all flavors if set" do fixture = File.read(my_fixture('pkginfo_flavors.list')) expect(described_class).to receive(:execpipe).with(%w{/bin/pkg_info -a}).and_yield(fixture) instances = described_class.instances.map {|p| {:name => p.get(:name), :ensure => p.get(:ensure), :flavor => p.get(:flavor)}} expect(instances.size).to eq(2) expect(instances[0]).to eq({:name => 'bash', :ensure => '3.1.17', :flavor => 'static'}) expect(instances[1]).to eq({:name => 'vim', :ensure => '7.0.42', :flavor => 'no_x11'}) end end context "#install" do it "should fail if the resource doesn't have a source" do expect(Puppet::FileSystem).to receive(:exist?).with('/etc/pkg.conf').and_return(false) expect { provider.install }.to raise_error(Puppet::Error, /must specify a package source/) end it "should fail if /etc/pkg.conf exists, but is not readable" do expect(Puppet::FileSystem).to receive(:exist?).with('/etc/pkg.conf').and_return(true) expect(File).to receive(:open).with('/etc/pkg.conf', 'rb').and_raise(Errno::EACCES) expect { provider.install }.to raise_error(Errno::EACCES, /Permission denied/) end it "should fail if /etc/pkg.conf exists, but there is no installpath" do expect_read_from_pkgconf([]) expect { provider.install }.to raise_error(Puppet::Error, /No valid installpath found in \/etc\/pkg\.conf and no source was set/) end it "should install correctly when given a directory-unlike source" do source = '/whatever.tgz' provider.resource[:source] = source expect_pkgadd_with_source(source) provider.install end it "should install correctly when given a directory-like source" do source = '/whatever/' provider.resource[:source] = source expect_pkgadd_with_env_and_name(source) do provider.install end end it "should install correctly when given a CDROM installpath" do dir = '/mnt/cdrom/5.2/packages/amd64/' expect_read_from_pkgconf(["installpath = #{dir}"]) expect_pkgadd_with_env_and_name(dir) do provider.install end end it "should install correctly when given a ftp mirror" do url = 'ftp://your.ftp.mirror/pub/OpenBSD/5.2/packages/amd64/' expect_read_from_pkgconf(["installpath = #{url}"]) expect_pkgadd_with_env_and_name(url) do provider.install end end it "should set the resource's source parameter" do url = 'ftp://your.ftp.mirror/pub/OpenBSD/5.2/packages/amd64/' expect_read_from_pkgconf(["installpath = #{url}"]) expect_pkgadd_with_env_and_name(url) do provider.install end expect(provider.resource[:source]).to eq(url) end it "should strip leading whitespace in installpath" do dir = '/one/' lines = ["# Notice the extra spaces after the ='s\n", "installpath = #{dir}\n", "# And notice how each line ends with a newline\n"] expect_read_from_pkgconf(lines) expect_pkgadd_with_env_and_name(dir) do provider.install end end it "should not require spaces around the equals" do dir = '/one/' lines = ["installpath=#{dir}"] expect_read_from_pkgconf(lines) expect_pkgadd_with_env_and_name(dir) do provider.install end end it "should be case-insensitive" do dir = '/one/' lines = ["INSTALLPATH = #{dir}"] expect_read_from_pkgconf(lines) expect_pkgadd_with_env_and_name(dir) do provider.install end end it "should ignore unknown keywords" do dir = '/one/' lines = ["foo = bar\n", "installpath = #{dir}\n"] expect_read_from_pkgconf(lines) expect_pkgadd_with_env_and_name(dir) do provider.install end end it "should preserve trailing spaces" do dir = '/one/ ' lines = ["installpath = #{dir}"] expect_read_from_pkgconf(lines) expect_pkgadd_with_source(dir) provider.install end it "should append installpath" do urls = ["ftp://your.ftp.mirror/pub/OpenBSD/5.2/packages/amd64/", "http://another.ftp.mirror/pub/OpenBSD/5.2/packages/amd64/"] lines = ["installpath = #{urls[0]}\n", "installpath += #{urls[1]}\n"] expect_read_from_pkgconf(lines) expect_pkgadd_with_env_and_name(urls.join(":")) do provider.install end end it "should handle append on first installpath" do url = "ftp://your.ftp.mirror/pub/OpenBSD/5.2/packages/amd64/" lines = ["installpath += #{url}\n"] expect_read_from_pkgconf(lines) expect_pkgadd_with_env_and_name(url) do provider.install end end %w{ installpath installpath= installpath+=}.each do |line| it "should reject '#{line}'" do expect_read_from_pkgconf([line]) expect { provider.install }.to raise_error(Puppet::Error, /No valid installpath found in \/etc\/pkg\.conf and no source was set/) end end it 'should use install_options as Array' do provider.resource[:source] = '/tma1/' provider.resource[:install_options] = ['-r', '-z'] expect(provider).to receive(:pkgadd).with(['-r', '-z', 'bash']) provider.install end end context "#latest" do before do provider.resource[:source] = '/tmp/tcsh.tgz' provider.resource[:name] = 'tcsh' allow(provider).to receive(:pkginfo).with('tcsh') end it "should return the ensure value if the package is already installed" do allow(provider).to receive(:properties).and_return({:ensure => '4.2.45'}) allow(provider).to receive(:pkginfo).with('-Q', 'tcsh') expect(provider.latest).to eq('4.2.45') end it "should recognize a new version" do pkginfo_query = 'tcsh-6.18.01p1' allow(provider).to receive(:pkginfo).with('-Q', 'tcsh').and_return(pkginfo_query) expect(provider.latest).to eq('6.18.01p1') end it "should recognize a newer version" do allow(provider).to receive(:properties).and_return({:ensure => '1.6.8'}) pkginfo_query = 'tcsh-1.6.10' allow(provider).to receive(:pkginfo).with('-Q', 'tcsh').and_return(pkginfo_query) expect(provider.latest).to eq('1.6.10') end it "should recognize a package that is already the newest" do pkginfo_query = 'tcsh-6.18.01p0 (installed)' allow(provider).to receive(:pkginfo).with('-Q', 'tcsh').and_return(pkginfo_query) expect(provider.latest).to eq('6.18.01p0') end end context "#get_full_name" do it "should return the full unversioned package name when updating with a flavor" do provider.resource[:ensure] = 'latest' provider.resource[:flavor] = 'static' expect(provider.get_full_name).to eq('bash--static') end it "should return the full unversioned package name when updating without a flavor" do provider.resource[:name] = 'puppet' provider.resource[:ensure] = 'latest' expect(provider.get_full_name).to eq('puppet') end it "should use the ensure parameter if it is numeric" do provider.resource[:name] = 'zsh' provider.resource[:ensure] = '1.0' expect(provider.get_full_name).to eq('zsh-1.0') end it "should lookup the correct version" do output = 'bash-3.1.17 GNU Bourne Again Shell' expect(provider).to receive(:execpipe).with(%w{/bin/pkg_info -I bash}).and_yield(output) expect(provider.get_full_name).to eq('bash-3.1.17') end it "should lookup the correction version with flavors" do provider.resource[:name] = 'fossil' provider.resource[:flavor] = 'static' output = 'fossil-1.29v0-static simple distributed software configuration management' expect(provider).to receive(:execpipe).with(%w{/bin/pkg_info -I fossil}).and_yield(output) expect(provider.get_full_name).to eq('fossil-1.29v0-static') end end context "#get_version" do it "should return nil if execution fails" do expect(provider).to receive(:execpipe).and_raise(Puppet::ExecutionFailure, 'wawawa') expect(provider.get_version).to be_nil end it "should return the package version if in the output" do output = 'bash-3.1.17 GNU Bourne Again Shell' expect(provider).to receive(:execpipe).with(%w{/bin/pkg_info -I bash}).and_yield(output) expect(provider.get_version).to eq('3.1.17') end it "should return the empty string if the package is not present" do provider.resource[:name] = 'zsh' expect(provider).to receive(:execpipe).with(%w{/bin/pkg_info -I zsh}).and_yield(StringIO.new('')) expect(provider.get_version).to eq('') end end context "#query" do it "should return the installed version if present" do fixture = File.read(my_fixture('pkginfo.detail')) expect(provider).to receive(:pkginfo).with('bash').and_return(fixture) expect(provider.query).to eq({ :ensure => '3.1.17' }) end it "should return nothing if not present" do provider.resource[:name] = 'zsh' expect(provider).to receive(:pkginfo).with('zsh').and_return('') expect(provider.query).to be_nil end end context "#install_options" do it "should return nill by default" do expect(provider.install_options).to be_nil end it "should return install_options when set" do provider.resource[:install_options] = ['-n'] expect(provider.resource[:install_options]).to eq(['-n']) end it "should return multiple install_options when set" do provider.resource[:install_options] = ['-L', '/opt/puppet'] expect(provider.resource[:install_options]).to eq(['-L', '/opt/puppet']) end it 'should return install_options when set as hash' do provider.resource[:install_options] = { '-Darch' => 'vax' } expect(provider.install_options).to eq(['-Darch=vax']) end end context "#uninstall_options" do it "should return nill by default" do expect(provider.uninstall_options).to be_nil end it "should return uninstall_options when set" do provider.resource[:uninstall_options] = ['-n'] expect(provider.resource[:uninstall_options]).to eq(['-n']) end it "should return multiple uninstall_options when set" do provider.resource[:uninstall_options] = ['-q', '-c'] expect(provider.resource[:uninstall_options]).to eq(['-q', '-c']) end it 'should return uninstall_options when set as hash' do provider.resource[:uninstall_options] = { '-Dbaddepend' => '1' } expect(provider.uninstall_options).to eq(['-Dbaddepend=1']) end end context "#uninstall" do describe 'when uninstalling' do it 'should use erase to purge' do expect(provider).to receive(:pkgdelete).with('-c', '-q', 'bash') provider.purge end end describe 'with uninstall_options' do it 'should use uninstall_options as Array' do provider.resource[:uninstall_options] = ['-q', '-c'] expect(provider).to receive(:pkgdelete).with(['-q', '-c'], 'bash') provider.uninstall end end end context "#flavor" do before do provider.instance_variable_get('@property_hash')[:flavor] = 'no_x11-python' end it 'should return the existing flavor' do expect(provider.flavor).to eq('no_x11-python') end it 'should remove and install the new flavor if different' do provider.resource[:flavor] = 'no_x11-ruby' expect(provider).to receive(:uninstall).ordered expect(provider).to receive(:install).ordered provider.flavor = provider.resource[:flavor] end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/provider/package/aix_spec.rb
spec/unit/provider/package/aix_spec.rb
require 'spec_helper' describe Puppet::Type.type(:package).provider(:aix) do before(:each) do # Create a mock resource @resource = Puppet::Type.type(:package).new(:name => 'mypackage', :ensure => :installed, :source => 'mysource', :provider => :aix) @provider = @resource.provider end [:install, :uninstall, :latest, :query, :update].each do |method| it "should have a #{method} method" do expect(@provider).to respond_to(method) end end it "should uninstall a package" do expect(@provider).to receive(:installp).with('-gu', 'mypackage') expect(@provider.class).to receive(:pkglist).with({:pkgname => 'mypackage'}).and_return(nil) @provider.uninstall end context "when installing" do it "should install a package" do allow(@provider).to receive(:query).and_return({:name => 'mypackage', :ensure => 'present', :status => :committed}) expect(@provider).to receive(:installp).with('-acgwXY', '-d', 'mysource', 'mypackage') @provider.install end it "should install a specific package version" do allow(@resource).to receive(:should).with(:ensure).and_return("1.2.3.4") allow(@provider).to receive(:query).and_return({:name => 'mypackage', :ensure => '1.2.3.4', :status => :committed}) expect(@provider).to receive(:installp).with('-acgwXY', '-d', 'mysource', 'mypackage 1.2.3.4') @provider.install end [:broken, :inconsistent].each do |state| it "should fail if the installation resulted in a '#{state}' state" do allow(@provider).to receive(:query).and_return({:name => 'mypackage', :ensure => 'present', :status => state}) expect(@provider).to receive(:installp).with('-acgwXY', '-d', 'mysource', 'mypackage') expect { @provider.install }.to raise_error(Puppet::Error, "Package 'mypackage' is in a #{state} state and requires manual intervention") end end it "should fail if the specified version is superseded" do @resource[:ensure] = '1.2.3.3' allow(@provider).to receive(:installp).and_return(<<-OUTPUT) +-----------------------------------------------------------------------------+ Pre-installation Verification... +-----------------------------------------------------------------------------+ Verifying selections...done Verifying requisites...done Results... WARNINGS -------- Problems described in this section are not likely to be the source of any immediate or serious failures, but further actions may be necessary or desired. Already Installed ----------------- The number of selected filesets that are either already installed or effectively installed through superseding filesets is 1. See the summaries at the end of this installation for details. NOTE: Base level filesets may be reinstalled using the "Force" option (-F flag), or they may be removed, using the deinstall or "Remove Software Products" facility (-u flag), and then reinstalled. << End of Warning Section >> +-----------------------------------------------------------------------------+ BUILDDATE Verification ... +-----------------------------------------------------------------------------+ Verifying build dates...done FILESET STATISTICS ------------------ 1 Selected to be installed, of which: 1 Already installed (directly or via superseding filesets) ---- 0 Total to be installed Pre-installation Failure/Warning Summary ---------------------------------------- Name Level Pre-installation Failure/Warning ------------------------------------------------------------------------------- mypackage 1.2.3.3 Already superseded by 1.2.3.4 OUTPUT expect { @provider.install }.to raise_error(Puppet::Error, "aix package provider is unable to downgrade packages") end end context "when finding the latest version" do it "should return the current version when no later version is present" do allow(@provider).to receive(:latest_info).and_return(nil) allow(@provider).to receive(:properties).and_return({ :ensure => "1.2.3.4" }) expect(@provider.latest).to eq("1.2.3.4") end it "should return the latest version of a package" do allow(@provider).to receive(:latest_info).and_return({ :version => "1.2.3.5" }) expect(@provider.latest).to eq("1.2.3.5") end it "should prefetch the right values" do allow(Process).to receive(:euid).and_return(0) resource = Puppet::Type.type(:package). new(:name => 'sudo.rte', :ensure => :latest, :source => 'mysource', :provider => :aix) allow(resource).to receive(:should).with(:ensure).and_return(:latest) resource.should(:ensure) allow(resource.provider.class).to receive(:execute).and_return(<<-END.chomp) sudo:sudo.rte:1.7.10.4::I:C:::::N:Configurable super-user privileges runtime::::0:: sudo:sudo.rte:1.8.6.4::I:T:::::N:Configurable super-user privileges runtime::::0:: END resource.provider.class.prefetch('sudo.rte' => resource) expect(resource.provider.latest).to eq('1.8.6.4') end end it "update should install a package" do expect(@provider).to receive(:install).with(false) @provider.update end it "should prefetch when some packages lack sources" do latest = Puppet::Type.type(:package).new(:name => 'mypackage', :ensure => :latest, :source => 'mysource', :provider => :aix) absent = Puppet::Type.type(:package).new(:name => 'otherpackage', :ensure => :absent, :provider => :aix) allow(Process).to receive(:euid).and_return(0) expect(described_class).to receive(:execute).and_return('mypackage:mypackage.rte:1.8.6.4::I:T:::::N:A Super Cool Package::::0::\n') described_class.prefetch({ 'mypackage' => latest, 'otherpackage' => absent }) end context "when querying instances" do before(:each) do allow(described_class).to receive(:execute).and_return(<<-END.chomp) sysmgt.cim.providers:sysmgt.cim.providers.metrics:2.12.1.1: : :B: :Metrics Providers for AIX OS: : : : : : :1:0:/: sysmgt.cim.providers:sysmgt.cim.providers.osbase:2.12.1.1: : :C: :Base Providers for AIX OS: : : : : : :1:0:/: openssl.base:openssl.base:1.0.2.1800: : :?: :Open Secure Socket Layer: : : : : : :0:0:/: END end it "should treat installed packages in broken and inconsistent state as absent" do installed_packages = described_class.instances.map { |package| package.properties } expected_packages = [{:name => 'sysmgt.cim.providers.metrics', :ensure => :absent, :status => :broken, :provider => :aix}, {:name => 'sysmgt.cim.providers.osbase', :ensure => '2.12.1.1', :status => :committed, :provider => :aix}, {:name => 'openssl.base', :ensure => :absent, :status => :inconsistent, :provider => :aix}] expect(installed_packages).to eql(expected_packages) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/provider/package/freebsd_spec.rb
spec/unit/provider/package/freebsd_spec.rb
require 'spec_helper' describe Puppet::Type.type(:package).provider(:freebsd) do before :each do # Create a mock resource @resource = double('resource') # A catch all; no parameters set allow(@resource).to receive(:[]).and_return(nil) # But set name and source allow(@resource).to receive(:[]).with(:name).and_return("mypackage") allow(@resource).to receive(:[]).with(:ensure).and_return(:installed) @provider = subject() @provider.resource = @resource end it "should have an install method" do @provider = subject() expect(@provider).to respond_to(:install) end context "when installing" do before :each do allow(@resource).to receive(:should).with(:ensure).and_return(:installed) end it "should install a package from a path to a directory" do # For better or worse, trailing '/' is needed. --daniel 2011-01-26 path = '/path/to/directory/' allow(@resource).to receive(:[]).with(:source).and_return(path) expect(Puppet::Util).to receive(:withenv).once.with({:PKG_PATH => path}).and_yield expect(@provider).to receive(:pkgadd).once.with("mypackage") expect { @provider.install }.to_not raise_error end %w{http https ftp}.each do |protocol| it "should install a package via #{protocol}" do # For better or worse, trailing '/' is needed. --daniel 2011-01-26 path = "#{protocol}://localhost/" allow(@resource).to receive(:[]).with(:source).and_return(path) expect(Puppet::Util).to receive(:withenv).once.with({:PACKAGESITE => path}).and_yield expect(@provider).to receive(:pkgadd).once.with('-r', "mypackage") expect { @provider.install }.to_not raise_error end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/provider/package/rpm_spec.rb
spec/unit/provider/package/rpm_spec.rb
require 'spec_helper' describe Puppet::Type.type(:package).provider(:rpm) do let (:packages) do <<-RPM_OUTPUT 'cracklib-dicts 0 2.8.9 3.3 x86_64 basesystem 0 8.0 5.1.1.el5.centos noarch chkconfig 0 1.3.30.2 2.el5 x86_64 myresource 0 1.2.3.4 5.el4 noarch mysummaryless 0 1.2.3.4 5.el4 noarch tomcat 1 1.2.3.4 5.el4 x86_64 kernel 1 1.2.3.4 5.el4 x86_64 kernel 1 1.2.3.6 5.el4 x86_64 ' RPM_OUTPUT end let(:resource_name) { 'myresource' } let(:resource) do Puppet::Type.type(:package).new( :name => resource_name, :ensure => :installed, :provider => 'rpm' ) end let(:provider) do provider = subject() provider.resource = resource provider end let(:nevra_format) { %Q{%{NAME} %|EPOCH?{%{EPOCH}}:{0}| %{VERSION} %{RELEASE} %{ARCH}\\n} } let(:execute_options) do {:failonfail => true, :combine => true, :custom_environment => {}} end let(:rpm_version) { "RPM version 5.0.0\n" } before(:each) do allow(Puppet::Util).to receive(:which).with("rpm").and_return("/bin/rpm") allow(described_class).to receive(:which).with("rpm").and_return("/bin/rpm") described_class.instance_variable_set("@current_version", nil) expect(Puppet::Type::Package::ProviderRpm).to receive(:execute) .with(["/bin/rpm", "--version"]) .and_return(rpm_version).at_most(:once) expect(Puppet::Util::Execution).to receive(:execute) .with(["/bin/rpm", "--version"], execute_options) .and_return(Puppet::Util::Execution::ProcessOutput.new(rpm_version, 0)).at_most(:once) end describe 'provider features' do it { is_expected.to be_versionable } it { is_expected.to be_install_options } it { is_expected.to be_uninstall_options } it { is_expected.to be_virtual_packages } end describe "self.instances" do describe "with a modern version of RPM" do it "includes all the modern flags" do expect(Puppet::Util::Execution).to receive(:execpipe) .with("/bin/rpm -qa --nosignature --nodigest --qf '#{nevra_format}' | sort") .and_yield(packages) described_class.instances end end describe "with a version of RPM < 4.1" do let(:rpm_version) { "RPM version 4.0.2\n" } it "excludes the --nosignature flag" do expect(Puppet::Util::Execution).to receive(:execpipe) .with("/bin/rpm -qa --nodigest --qf '#{nevra_format}' | sort") .and_yield(packages) described_class.instances end end describe "with a version of RPM < 4.0.2" do let(:rpm_version) { "RPM version 3.0.5\n" } it "excludes the --nodigest flag" do expect(Puppet::Util::Execution).to receive(:execpipe) .with("/bin/rpm -qa --qf '#{nevra_format}' | sort") .and_yield(packages) described_class.instances end end it "returns an array of packages" do expect(Puppet::Util::Execution).to receive(:execpipe) .with("/bin/rpm -qa --nosignature --nodigest --qf '#{nevra_format}' | sort") .and_yield(packages) installed_packages = described_class.instances expect(installed_packages[0].properties).to eq( { :provider => :rpm, :name => "cracklib-dicts", :epoch => "0", :version => "2.8.9", :release => "3.3", :arch => "x86_64", :ensure => "2.8.9-3.3", } ) expect(installed_packages[1].properties).to eq( { :provider => :rpm, :name => "basesystem", :epoch => "0", :version => "8.0", :release => "5.1.1.el5.centos", :arch => "noarch", :ensure => "8.0-5.1.1.el5.centos", } ) expect(installed_packages[2].properties).to eq( { :provider => :rpm, :name => "chkconfig", :epoch => "0", :version => "1.3.30.2", :release => "2.el5", :arch => "x86_64", :ensure => "1.3.30.2-2.el5", } ) expect(installed_packages[3].properties).to eq( { :provider => :rpm, :name => "myresource", :epoch => "0", :version => "1.2.3.4", :release => "5.el4", :arch => "noarch", :ensure => "1.2.3.4-5.el4", } ) expect(installed_packages[4].properties).to eq( { :provider => :rpm, :name => "mysummaryless", :epoch => "0", :version => "1.2.3.4", :release => "5.el4", :arch => "noarch", :ensure => "1.2.3.4-5.el4", } ) expect(installed_packages[5].properties).to eq( { :provider => :rpm, :name => "tomcat", :epoch => "1", :version => "1.2.3.4", :release => "5.el4", :arch => "x86_64", :ensure => "1:1.2.3.4-5.el4", } ) expect(installed_packages[6].properties).to eq( { :provider => :rpm, :name => "kernel", :epoch => "1", :version => "1.2.3.4", :release => "5.el4", :arch => "x86_64", :ensure => "1:1.2.3.4-5.el4; 1:1.2.3.6-5.el4", } ) end end describe "#install" do let(:resource) do Puppet::Type.type(:package).new( :name => 'myresource', :ensure => :installed, :source => '/path/to/package' ) end describe "when not already installed" do it "only includes the '-i' flag" do expect(Puppet::Util::Execution).to receive(:execute) .with(["/bin/rpm", ["-i"], '/path/to/package'], execute_options) provider.install end end describe "when installed with options" do let(:resource) do Puppet::Type.type(:package).new( :name => resource_name, :ensure => :installed, :provider => 'rpm', :source => '/path/to/package', :install_options => ['-D', {'--test' => 'value'}, '-Q'] ) end it "includes the options" do expect(Puppet::Util::Execution).to receive(:execute) .with(["/bin/rpm", ["-i", "-D", "--test=value", "-Q"], '/path/to/package'], execute_options) provider.install end end describe "when an older version is installed" do before(:each) do # Force the provider to think a version of the package is already installed # This is real hacky. I'm sorry. --jeffweiss 25 Jan 2013 provider.instance_variable_get('@property_hash')[:ensure] = '1.2.3.3' end it "includes the '-U --oldpackage' flags" do expect(Puppet::Util::Execution).to receive(:execute) .with(["/bin/rpm", ["-U", "--oldpackage"], '/path/to/package'], execute_options) provider.install end end end describe "#latest" do it "retrieves version string after querying rpm for version from source file" do expect(resource).to receive(:[]).with(:source).and_return('source-string') expect(Puppet::Util::Execution).to receive(:execute) .with(["/bin/rpm", "-q", "--qf", "#{nevra_format}", "-p", "source-string"]) .and_return(Puppet::Util::Execution::ProcessOutput.new("myresource 0 1.2.3.4 5.el4 noarch\n", 0)) expect(provider.latest).to eq("1.2.3.4-5.el4") end it "raises an error if the rpm command fails" do expect(resource).to receive(:[]).with(:source).and_return('source-string') expect(Puppet::Util::Execution).to receive(:execute) .with(["/bin/rpm", "-q", "--qf", "#{nevra_format}", "-p", "source-string"]) .and_raise(Puppet::ExecutionFailure, 'rpm command failed') expect { provider.latest }.to raise_error(Puppet::Error, 'rpm command failed') end end describe "#uninstall" do let(:resource) do Puppet::Type.type(:package).new( :name => resource_name, :ensure => :installed ) end describe "on an ancient RPM" do let(:rpm_version) { "RPM version 3.0.6\n" } before(:each) do expect(Puppet::Util::Execution).to receive(:execute) .with(["/bin/rpm", "-q", resource_name, '', '', '--qf', "#{nevra_format}"], execute_options) .and_return(Puppet::Util::Execution::ProcessOutput.new("#{resource_name} 0 1.2.3.4 5.el4 noarch\n", 0)) end it "excludes the architecture from the package name" do expect(Puppet::Util::Execution).to receive(:execute) .with(["/bin/rpm", ["-e"], resource_name], execute_options) .and_return(Puppet::Util::Execution::ProcessOutput.new('', 0)).at_most(:once) provider.uninstall end end describe "on a modern RPM" do let(:rpm_version) { "RPM version 4.10.0\n" } before(:each) do expect(Puppet::Util::Execution).to receive(:execute) .with(["/bin/rpm", "-q", resource_name, '--nosignature', '--nodigest', "--qf", "#{nevra_format}"], execute_options) .and_return(Puppet::Util::Execution::ProcessOutput.new("#{resource_name} 0 1.2.3.4 5.el4 noarch\n", 0)) end it "excludes the architecture from the package name" do expect(Puppet::Util::Execution).to receive(:execute) .with(["/bin/rpm", ["-e"], resource_name], execute_options) .and_return(Puppet::Util::Execution::ProcessOutput.new('', 0)).at_most(:once) provider.uninstall end end describe "on a modern RPM when architecture is specified" do let(:rpm_version) { "RPM version 4.10.0\n" } let(:resource) do Puppet::Type.type(:package).new( :name => "#{resource_name}.noarch", :ensure => :absent, ) end before(:each) do expect(Puppet::Util::Execution).to receive(:execute) .with(["/bin/rpm", "-q", "#{resource_name}.noarch", '--nosignature', '--nodigest', "--qf", "#{nevra_format}"], execute_options) .and_return(Puppet::Util::Execution::ProcessOutput.new("#{resource_name} 0 1.2.3.4 5.el4 noarch\n", 0)) end it "includes the architecture in the package name" do expect(Puppet::Util::Execution).to receive(:execute) .with(["/bin/rpm", ["-e"], "#{resource_name}.noarch"], execute_options) .and_return(Puppet::Util::Execution::ProcessOutput.new('', 0)).at_most(:once) provider.uninstall end end describe "when version and release are specified" do let(:resource) do Puppet::Type.type(:package).new( :name => "#{resource_name}-1.2.3.4-5.el4", :ensure => :absent, ) end before(:each) do expect(Puppet::Util::Execution).to receive(:execute) .with(["/bin/rpm", "-q", "#{resource_name}-1.2.3.4-5.el4", '--nosignature', '--nodigest', "--qf", "#{nevra_format}"], execute_options) .and_return(Puppet::Util::Execution::ProcessOutput.new("#{resource_name} 0 1.2.3.4 5.el4 noarch\n", 0)) end it "includes the version and release in the package name" do expect(Puppet::Util::Execution).to receive(:execute) .with(["/bin/rpm", ["-e"], "#{resource_name}-1.2.3.4-5.el4"], execute_options) .and_return(Puppet::Util::Execution::ProcessOutput.new('', 0)).at_most(:once) provider.uninstall end end describe "when only version is specified" do let(:resource) do Puppet::Type.type(:package).new( :name => "#{resource_name}-1.2.3.4", :ensure => :absent, ) end before(:each) do expect(Puppet::Util::Execution).to receive(:execute) .with(["/bin/rpm", "-q", "#{resource_name}-1.2.3.4", '--nosignature', '--nodigest', "--qf", "#{nevra_format}"], execute_options) .and_return(Puppet::Util::Execution::ProcessOutput.new("#{resource_name} 0 1.2.3.4 5.el4 noarch\n", 0)) end it "includes the version in the package name" do expect(Puppet::Util::Execution).to receive(:execute) .with(["/bin/rpm", ["-e"], "#{resource_name}-1.2.3.4"], execute_options) .and_return(Puppet::Util::Execution::ProcessOutput.new('', 0)).at_most(:once) provider.uninstall end end describe "when uninstalled with options" do let(:resource) do Puppet::Type.type(:package).new( :name => resource_name, :ensure => :absent, :provider => 'rpm', :uninstall_options => ['--nodeps'] ) end before(:each) do expect(Puppet::Util::Execution).to receive(:execute) .with(["/bin/rpm", "-q", resource_name, '--nosignature', '--nodigest', "--qf", "#{nevra_format}"], execute_options) .and_return(Puppet::Util::Execution::ProcessOutput.new("#{resource_name} 0 1.2.3.4 5.el4 noarch\n", 0)) end it "includes the options" do expect(Puppet::Util::Execution).to receive(:execute) .with(["/bin/rpm", ["-e", "--nodeps"], resource_name], execute_options) provider.uninstall end end end describe "parsing" do def parser_test(rpm_output_string, gold_hash, number_of_debug_logs = 0) expect(Puppet).to receive(:debug).exactly(number_of_debug_logs).times() expect(Puppet::Util::Execution).to receive(:execute) .with(["/bin/rpm", "-q", resource_name, "--nosignature", "--nodigest", "--qf", "#{nevra_format}"], execute_options) .and_return(Puppet::Util::Execution::ProcessOutput.new(rpm_output_string, 0)) expect(provider.query).to eq(gold_hash) end let(:resource_name) { 'name' } let('delimiter') { ':DESC:' } let(:package_hash) do { :name => 'name', :epoch => 'epoch', :version => 'version', :release => 'release', :arch => 'arch', :provider => :rpm, :ensure => 'epoch:version-release', } end let(:line) { 'name epoch version release arch' } ['name', 'epoch', 'version', 'release', 'arch'].each do |field| it "still parses if #{field} is replaced by delimiter" do parser_test( line.gsub(field, delimiter), package_hash.merge( field.to_sym => delimiter, :ensure => 'epoch:version-release'.gsub(field, delimiter) ) ) end end it "does not fail if line is unparseable, but issues a debug log" do parser_test('bad data', {}, 1) end describe "when the package is not found" do before do expect(Puppet).not_to receive(:debug) expected_args = ["/bin/rpm", "-q", resource_name, "--nosignature", "--nodigest", "--qf", "#{nevra_format}"] expect(Puppet::Util::Execution).to receive(:execute) .with(expected_args, execute_options) .and_raise(Puppet::ExecutionFailure.new("package #{resource_name} is not installed")) end it "does not log or fail if allow_virtual is false" do resource[:allow_virtual] = false expect(provider.query).to be_nil end it "does not log or fail if allow_virtual is true" do resource[:allow_virtual] = true expected_args = ['/bin/rpm', '-q', resource_name, '--nosignature', '--nodigest', '--qf', "#{nevra_format}", '--whatprovides'] expect(Puppet::Util::Execution).to receive(:execute) .with(expected_args, execute_options) .and_raise(Puppet::ExecutionFailure.new("package #{resource_name} is not provided")) expect(provider.query).to be_nil end end it "parses virtual package" do provider.resource[:allow_virtual] = true expected_args = ["/bin/rpm", "-q", resource_name, "--nosignature", "--nodigest", "--qf", "#{nevra_format}"] expect(Puppet::Util::Execution).to receive(:execute) .with(expected_args, execute_options) .and_raise(Puppet::ExecutionFailure.new("package #{resource_name} is not installed")) expect(Puppet::Util::Execution).to receive(:execute) .with(expected_args + ["--whatprovides"], execute_options) .and_return(Puppet::Util::Execution::ProcessOutput.new("myresource 0 1.2.3.4 5.el4 noarch\n", 0)) expect(provider.query).to eq({ :name => "myresource", :epoch => "0", :version => "1.2.3.4", :release => "5.el4", :arch => "noarch", :provider => :rpm, :ensure => "1.2.3.4-5.el4" }) end end describe "#install_options" do it "returns nil by default" do expect(provider.install_options).to eq(nil) end it "returns install_options when set" do provider.resource[:install_options] = ['-n'] expect(provider.install_options).to eq(['-n']) end it "returns multiple install_options when set" do provider.resource[:install_options] = ['-L', '/opt/puppet'] expect(provider.install_options).to eq(['-L', '/opt/puppet']) end it 'returns install_options when set as hash' do provider.resource[:install_options] = [{ '-Darch' => 'vax' }] expect(provider.install_options).to eq(['-Darch=vax']) end it 'returns install_options when an array with hashes' do provider.resource[:install_options] = [ '-L', { '-Darch' => 'vax' }] expect(provider.install_options).to eq(['-L', '-Darch=vax']) end end describe "#uninstall_options" do it "returns nil by default" do expect(provider.uninstall_options).to eq(nil) end it "returns uninstall_options when set" do provider.resource[:uninstall_options] = ['-n'] expect(provider.uninstall_options).to eq(['-n']) end it "returns multiple uninstall_options when set" do provider.resource[:uninstall_options] = ['-L', '/opt/puppet'] expect(provider.uninstall_options).to eq(['-L', '/opt/puppet']) end it 'returns uninstall_options when set as hash' do provider.resource[:uninstall_options] = [{ '-Darch' => 'vax' }] expect(provider.uninstall_options).to eq(['-Darch=vax']) end it 'returns uninstall_options when an array with hashes' do provider.resource[:uninstall_options] = [ '-L', { '-Darch' => 'vax' }] expect(provider.uninstall_options).to eq(['-L', '-Darch=vax']) end end describe ".nodigest" do { '4.0' => nil, '4.0.1' => nil, '4.0.2' => '--nodigest', '4.0.3' => '--nodigest', '4.1' => '--nodigest', '5' => '--nodigest', }.each do |version, expected| describe "when current version is #{version}" do it "returns #{expected.inspect}" do allow(described_class).to receive(:current_version).and_return(version) expect(described_class.nodigest).to eq(expected) end end end end describe ".nosignature" do { '4.0.3' => nil, '4.1' => '--nosignature', '4.1.1' => '--nosignature', '4.2' => '--nosignature', '5' => '--nosignature', }.each do |version, expected| describe "when current version is #{version}" do it "returns #{expected.inspect}" do allow(described_class).to receive(:current_version).and_return(version) expect(described_class.nosignature).to eq(expected) end end end end describe 'insync?' do context 'for multiple versions' do let(:is) { '1:1.2.3.4-5.el4; 1:5.6.7.8-5.el4' } it 'returns true if there is match and feature is enabled' do resource[:install_only] = true resource[:ensure] = '1:1.2.3.4-5.el4' expect(provider).to be_insync(is) end it 'returns false if there is match and feature is not enabled' do resource[:ensure] = '1:1.2.3.4-5.el4' expect(provider).to_not be_insync(is) end it 'returns false if no match and feature is enabled' do resource[:install_only] = true resource[:ensure] = '1:1.2.3.6-5.el4' expect(provider).to_not be_insync(is) end it 'returns false if no match and feature is not enabled' do resource[:ensure] = '1:1.2.3.6-5.el4' expect(provider).to_not be_insync(is) end end context 'for simple versions' do let(:is) { '1:1.2.3.4-5.el4' } it 'returns true if there is match and feature is enabled' do resource[:install_only] = true resource[:ensure] = '1:1.2.3.4-5.el4' expect(provider).to be_insync(is) end it 'returns true if there is match and feature is not enabled' do resource[:ensure] = '1:1.2.3.4-5.el4' expect(provider).to be_insync(is) end it 'returns false if no match and feature is enabled' do resource[:install_only] = true resource[:ensure] = '1:1.2.3.6-5.el4' expect(provider).to_not be_insync(is) end it 'returns false if no match and feature is not enabled' do resource[:ensure] = '1:1.2.3.6-5.el4' expect(provider).to_not be_insync(is) end end end describe 'rpm multiversion to hash' do it 'should return empty hash for empty imput' do package_hash = described_class.nevra_to_multiversion_hash('') expect(package_hash).to eq({}) end it 'should return package hash for one package input' do package_list = <<-RPM_OUTPUT kernel-devel 1 1.2.3.4 5.el4 x86_64 RPM_OUTPUT package_hash = described_class.nevra_to_multiversion_hash(package_list) expect(package_hash).to eq( { :arch => "x86_64", :ensure => "1:1.2.3.4-5.el4", :epoch => "1", :name => "kernel-devel", :provider => :rpm, :release => "5.el4", :version => "1.2.3.4", } ) end it 'should return package hash with versions concatenated in ensure for two package input' do package_list = <<-RPM_OUTPUT kernel-devel 1 1.2.3.4 5.el4 x86_64 kernel-devel 1 5.6.7.8 5.el4 x86_64 RPM_OUTPUT package_hash = described_class.nevra_to_multiversion_hash(package_list) expect(package_hash).to eq( { :arch => "x86_64", :ensure => "1:1.2.3.4-5.el4; 1:5.6.7.8-5.el4", :epoch => "1", :name => "kernel-devel", :provider => :rpm, :release => "5.el4", :version => "1.2.3.4", } ) end it 'should return list of packages for one multiversion and one package input' do package_list = <<-RPM_OUTPUT kernel-devel 1 1.2.3.4 5.el4 x86_64 kernel-devel 1 5.6.7.8 5.el4 x86_64 basesystem 0 8.0 5.1.1.el5.centos noarch RPM_OUTPUT package_hash = described_class.nevra_to_multiversion_hash(package_list) expect(package_hash).to eq( [ { :arch => "x86_64", :ensure => "1:1.2.3.4-5.el4; 1:5.6.7.8-5.el4", :epoch => "1", :name => "kernel-devel", :provider => :rpm, :release => "5.el4", :version => "1.2.3.4", }, { :provider => :rpm, :name => "basesystem", :epoch => "0", :version => "8.0", :release => "5.1.1.el5.centos", :arch => "noarch", :ensure => "8.0-5.1.1.el5.centos", } ] ) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/provider/package/pip3_spec.rb
spec/unit/provider/package/pip3_spec.rb
require 'spec_helper' describe Puppet::Type.type(:package).provider(:pip3) do it { is_expected.to be_installable } it { is_expected.to be_uninstallable } it { is_expected.to be_upgradeable } it { is_expected.to be_versionable } it { is_expected.to be_install_options } it { is_expected.to be_targetable } it "should inherit most things from pip provider" do expect(described_class < Puppet::Type.type(:package).provider(:pip)) end it "should use pip3 command" do expect(described_class.cmd).to eq(["pip3"]) end context 'calculated specificity' do include_context 'provider specificity' context 'when is not defaultfor' do subject { described_class.specificity } it { is_expected.to eql 1 } end context 'when is defaultfor' do let(:os) { Puppet.runtime[:facter].value('os.name') } subject do described_class.defaultfor('os.name': os) described_class.specificity end it { is_expected.to be > 100 } end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/provider/package/pip2_spec.rb
spec/unit/provider/package/pip2_spec.rb
require 'spec_helper' describe Puppet::Type.type(:package).provider(:pip2) do it { is_expected.to be_installable } it { is_expected.to be_uninstallable } it { is_expected.to be_upgradeable } it { is_expected.to be_versionable } it { is_expected.to be_install_options } it { is_expected.to be_targetable } it "should inherit most things from pip provider" do expect(described_class < Puppet::Type.type(:package).provider(:pip)) end it "should use pip2 command" do expect(described_class.cmd).to eq(["pip2"]) end context 'calculated specificity' do include_context 'provider specificity' context 'when is not defaultfor' do subject { described_class.specificity } it { is_expected.to eql 1 } end context 'when is defaultfor' do let(:os) { Puppet.runtime[:facter].value('os.name') } subject do described_class.defaultfor('os.name': os) described_class.specificity end it { is_expected.to be > 100 } end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/provider/package/yum_spec.rb
spec/unit/provider/package/yum_spec.rb
require 'spec_helper' describe Puppet::Type.type(:package).provider(:yum) do include PuppetSpec::Fixtures let(:resource_name) { 'myresource' } let(:resource) do Puppet::Type.type(:package).new( :name => resource_name, :ensure => :installed, :provider => 'yum' ) end let(:provider) { Puppet::Type.type(:package).provider(:yum).new(resource) } it_behaves_like 'RHEL package provider', described_class, 'yum' it "should have lower specificity" do allow(Facter).to receive(:value).with('os.family').and_return(:redhat) allow(Facter).to receive(:value).with('os.name').and_return(:fedora) allow(Facter).to receive(:value).with('os.release.major').and_return("22") expect(described_class.specificity).to be < 200 end describe "should have logical defaults" do [2, 2018].each do |ver| it "should be the default provider on Amazon Linux #{ver}" do allow(Facter).to receive(:value).with('os.name').and_return('amazon') allow(Facter).to receive(:value).with('os.family').and_return('redhat') allow(Facter).to receive(:value).with('os.release.major').and_return(ver) expect(described_class).to be_default end end Array(4..7).each do |ver| it "should be default for redhat #{ver}" do allow(Facter).to receive(:value).with('os.name').and_return('redhat') allow(Facter).to receive(:value).with('os.family').and_return('redhat') allow(Facter).to receive(:value).with('os.release.major').and_return(ver.to_s) expect(described_class).to be_default end end it "should not be default for redhat 8" do allow(Facter).to receive(:value).with('os.name').and_return('redhat') allow(Facter).to receive(:value).with('os.family').and_return('redhat') allow(Facter).to receive(:value).with('os.release.major').and_return('8') expect(described_class).not_to be_default end it "should not be default for Ubuntu 16.04" do allow(Facter).to receive(:value).with('os.name').and_return('ubuntu') allow(Facter).to receive(:value).with('os.family').and_return('ubuntu') allow(Facter).to receive(:value).with('os.release.major').and_return('16.04') expect(described_class).not_to be_default end end describe "when supplied the source param" do let(:name) { 'baz' } let(:resource) do Puppet::Type.type(:package).new( :name => name, :provider => 'yum', ) end let(:provider) do provider = described_class.new provider.resource = resource provider end before { allow(described_class).to receive(:command).with(:cmd).and_return("/usr/bin/yum") } describe 'provider features' do it { is_expected.to be_versionable } it { is_expected.to be_install_options } it { is_expected.to be_virtual_packages } it { is_expected.to be_install_only } end context "when installing" do it "should use the supplied source as the explicit path to a package to install" do resource[:ensure] = :present resource[:source] = "/foo/bar/baz-1.1.0.rpm" expect(provider).to receive(:execute) do |arr| expect(arr[-2..-1]).to eq([:install, "/foo/bar/baz-1.1.0.rpm"]) end provider.install end end context "when ensuring a specific version" do it "should use the suppplied source as the explicit path to the package to update" do # The first query response informs yum provider that package 1.1.0 is # already installed, and the second that it's been upgraded expect(provider).to receive(:query).twice.and_return({:ensure => "1.1.0"}, {:ensure => "1.2.0"}) resource[:ensure] = "1.2.0" resource[:source] = "http://foo.repo.com/baz-1.2.0.rpm" expect(provider).to receive(:execute) do |arr| expect(arr[-2..-1]).to eq(['update', "http://foo.repo.com/baz-1.2.0.rpm"]) end provider.install end end describe 'with install_options' do it 'can parse disable-repo with array of strings' do resource[:install_options] = ['--disable-repo=dev*', '--disable-repo=prod*'] expect(provider).to receive(:execute) do | arr| expect(arr[-3]).to eq(["--disable-repo=dev*", "--disable-repo=prod*"]) end provider.install end it 'can parse disable-repo with array of hashes' do resource[:install_options] = [{'--disable-repo' => 'dev*'}, {'--disable-repo' => 'prod*'}] expect(provider).to receive(:execute) do | arr| expect(arr[-3]).to eq(["--disable-repo=dev*", "--disable-repo=prod*"]) end provider.install end it 'can parse enable-repo with array of strings' do resource[:install_options] = ['--enable-repo=dev*', '--enable-repo=prod*'] expect(provider).to receive(:execute) do | arr| expect(arr[-3]).to eq(["--enable-repo=dev*", "--enable-repo=prod*"]) end provider.install end it 'can parse enable-repo with array of hashes' do resource[:install_options] = [{'--enable-repo' => 'dev*'}, {'--disable-repo' => 'prod*'}] expect(provider).to receive(:execute) do | arr| expect(arr[-3]).to eq(["--enable-repo=dev*", "--disable-repo=prod*"]) end provider.install end it 'can parse enable-repo with single hash' do resource[:install_options] = [{'--enable-repo' => 'dev*','--disable-repo' => 'prod*'}] expect(provider).to receive(:execute) do | arr| expect(arr[-3]).to eq(["--disable-repo=prod*", "--enable-repo=dev*"]) end provider.install end it 'can parse enable-repo with empty array' do resource[:install_options] = [] expect(provider).to receive(:execute) do | arr| expect(arr[-3]).to eq([]) end provider.install end end end context "latest" do let(:name) { 'baz' } let(:resource) do Puppet::Type.type(:package).new( :name => name, :provider => 'yum', ) end let(:provider) do provider = described_class.new provider.resource = resource provider end before { allow(described_class).to receive(:command).with(:cmd).and_return("/usr/bin/yum") Puppet[:log_level] = 'debug' } it "should print a debug message with the current version if newer package is not available" do expect(provider).to receive(:query).and_return({:ensure => "1.2.3"}) expect(described_class).to receive(:latest_package_version).and_return(nil) resource[:ensure] = :present provider.latest expect(@logs).to include(an_object_having_attributes(level: :debug, message: "Yum didn't find updates, current version (1.2.3) is the latest")) end end context "parsing the output of check-update" do context "with no multiline entries" do let(:check_update) { File.read(my_fixture("yum-check-update-simple.txt")) } let(:output) { described_class.parse_updates(check_update) } it 'creates an entry for each package keyed on the package name' do expect(output['curl']).to eq([{:name => 'curl', :epoch => '0', :version => '7.32.0', :release => '10.fc20', :arch => 'i686'}, {:name => 'curl', :epoch => '0', :version => '7.32.0', :release => '10.fc20', :arch => 'x86_64'}]) expect(output['gawk']).to eq([{:name => 'gawk', :epoch => '0', :version => '4.1.0', :release => '3.fc20', :arch => 'i686'}]) expect(output['dhclient']).to eq([{:name => 'dhclient', :epoch => '12', :version => '4.1.1', :release => '38.P1.fc20', :arch => 'i686'}]) expect(output['selinux-policy']).to eq([{:name => 'selinux-policy', :epoch => '0', :version => '3.12.1', :release => '163.fc20', :arch => 'noarch'}]) end it 'creates an entry for each package keyed on the package name and package architecture' do expect(output['curl.i686']).to eq([{:name => 'curl', :epoch => '0', :version => '7.32.0', :release => '10.fc20', :arch => 'i686'}]) expect(output['curl.x86_64']).to eq([{:name => 'curl', :epoch => '0', :version => '7.32.0', :release => '10.fc20', :arch => 'x86_64'}]) expect(output['gawk.i686']).to eq([{:name => 'gawk', :epoch => '0', :version => '4.1.0', :release => '3.fc20', :arch => 'i686'}]) expect(output['dhclient.i686']).to eq([{:name => 'dhclient', :epoch => '12', :version => '4.1.1', :release => '38.P1.fc20', :arch => 'i686'}]) expect(output['selinux-policy.noarch']).to eq([{:name => 'selinux-policy', :epoch => '0', :version => '3.12.1', :release => '163.fc20', :arch => 'noarch'}]) expect(output['java-1.8.0-openjdk.x86_64']).to eq([{:name => 'java-1.8.0-openjdk', :epoch => '1', :version => '1.8.0.131', :release => '2.b11.el7_3', :arch => 'x86_64'}]) end end context "with multiline entries" do let(:check_update) { File.read(my_fixture("yum-check-update-multiline.txt")) } let(:output) { described_class.parse_updates(check_update) } it "parses multi-line values as a single package tuple" do expect(output['libpcap']).to eq([{:name => 'libpcap', :epoch => '14', :version => '1.4.0', :release => '1.20130826git2dbcaa1.el6', :arch => 'x86_64'}]) end end context "with obsoleted packages" do let(:check_update) { File.read(my_fixture("yum-check-update-obsoletes.txt")) } let(:output) { described_class.parse_updates(check_update) } it "ignores all entries including and after 'Obsoleting Packages'" do expect(output).not_to include("Obsoleting") expect(output).not_to include("NetworkManager-bluetooth.x86_64") expect(output).not_to include("1:1.0.0-14.git20150121.b4ea599c.el7") end end context "with security notifications" do let(:check_update) { File.read(my_fixture("yum-check-update-security.txt")) } let(:output) { described_class.parse_updates(check_update) } it "ignores all entries including and after 'Security'" do expect(output).not_to include("Security") end it "includes updates before 'Security'" do expect(output).to include("yum-plugin-fastestmirror.noarch") end end context "with broken update notices" do let(:check_update) { File.read(my_fixture("yum-check-update-broken-notices.txt")) } let(:output) { described_class.parse_updates(check_update) } it "ignores all entries including and after 'Update'" do expect(output).not_to include("Update") end it "includes updates before 'Update'" do expect(output).to include("yum-plugin-fastestmirror.noarch") end end context "with improper package names in output" do it "raises an exception parsing package name" do expect { described_class.update_to_hash('badpackagename', '1') }.to raise_exception(Exception, /Failed to parse/) end end context "with trailing plugin output" do let(:check_update) { File.read(my_fixture("yum-check-update-plugin-output.txt")) } let(:output) { described_class.parse_updates(check_update) } it "parses correctly formatted entries" do expect(output['bash']).to eq([{:name => 'bash', :epoch => '0', :version => '4.2.46', :release => '12.el7', :arch => 'x86_64'}]) end it "ignores all mentions of plugin output" do expect(output).not_to include("Random plugin") end end context "with subscription manager enabled " do let(:check_update) { File.read(my_fixture("yum-check-update-subscription-manager.txt")) } let(:output) { described_class.parse_updates(check_update) } it "parses correctly formatted entries" do expect(output['curl.x86_64']).to eq([{:name => 'curl', :epoch => '0', :version => '7.32.0', :release => '10.fc20', :arch => 'x86_64'}]) end end end describe 'insync?' do context 'when version is not a valid RPM version' do let(:is) { '>===a:123' } before do resource[:ensure] = is end it 'logs a debug message' do expect(Puppet).to receive(:debug).with("Cannot parse #{is} as a RPM version range") provider.insync?(is) end end context 'with valid semantic versions' do let(:is) { '1:1.2.3.4-5.el4' } it 'returns true if the current version matches the given semantic version' do resource[:ensure] = is expect(provider).to be_insync(is) end it 'returns false if the current version does not match the given semantic version' do resource[:ensure] = '999r' expect(provider).not_to be_insync(is) end it 'no debug logs if the current version matches the given semantic version' do resource[:ensure] = is expect(Puppet).not_to receive(:debug) provider.insync?(is) end it 'returns true if current version matches the greater or equal semantic version in ensure' do resource[:ensure] = '<=1:1.2.3.4-5.el4' expect(provider).to be_insync(is) end it 'returns true if current version matches the lesser semantic version in ensure' do resource[:ensure] = '>1:1.0.0' expect(provider).to be_insync(is) end it 'returns true if current version matches two semantic conditions' do resource[:ensure] = '>1:1.1.3.4-5.el4 <1:1.3.3.6-5.el4' expect(provider).to be_insync(is) end it 'returns false if current version does not match matches two semantic conditions' do resource[:ensure] = '<1:1.1.3.4-5.el4 <1:1.3.3.6-5.el4' expect(provider).not_to be_insync(is) end end end describe 'install' do before do resource[:ensure] = ensure_value allow(Facter).to receive(:value).with('os.release.major').and_return('7') allow(described_class).to receive(:command).with(:cmd).and_return('/usr/bin/yum') allow(provider).to receive(:query).twice.and_return(nil, ensure: '18.3.2') allow(provider).to receive(:insync?).with('18.3.2').and_return(true) end context 'with version range' do before do allow(provider).to receive(:available_versions).and_return(available_versions) end context 'without epoch' do let(:ensure_value) { '>18.1 <19' } let(:available_versions) { ['17.5.2', '18.0', 'a:23', '18.3', '18.3.2', '19.0', '3:18.4'] } it 'selects best_version' do expect(provider).to receive(:execute).with( ['/usr/bin/yum', '-d', '0', '-e', '0', '-y', :install, 'myresource-18.3.2'] ) provider.install end context 'when comparing with available packages that do not have epoch' do let(:ensure_value) { '>18' } let(:available_versions) { ['18.3.3', '3:18.3.2'] } it 'treats no epoch as zero' do expect(provider).to receive(:execute).with( ['/usr/bin/yum', '-d', '0', '-e', '0', '-y', :install, 'myresource-18.3.2'] ) provider.install end end end context 'with epoch' do let(:ensure_value) { '>18.1 <3:19' } let(:available_versions) { ['3:17.5.2', '3:18.0', 'a:23', '18.3.3', '3:18.3.2', '3:19.0', '19.1'] } it 'selects best_version and removes epoch' do expect(provider).to receive(:execute).with( ['/usr/bin/yum', '-d', '0', '-e', '0', '-y', :install, 'myresource-18.3.2'] ) provider.install end end context 'when no suitable version in range' do let(:ensure_value) { '>18.1 <19' } let(:available_versions) { ['3:17.5.2', '3:18.0', 'a:23' '18.3', '3:18.3.2', '3:19.0', '19.1'] } it 'uses requested version' do expect(provider).to receive(:execute).with( ['/usr/bin/yum', '-d', '0', '-e', '0', '-y', :install, "myresource->18.1 <19"] ) provider.install end it 'logs a debug message' do allow(provider).to receive(:execute).with( ['/usr/bin/yum', '-d', '0', '-e', '0', '-y', :install, "myresource->18.1 <19"] ) expect(Puppet).to receive(:debug).with( "No available version for package myresource is included in range >18.1 <19" ) provider.install end end end context 'with fix version' do let(:ensure_value) { '1:18.12' } it 'passes the version to yum command' do expect(provider).to receive(:execute).with( ['/usr/bin/yum', '-d', '0', '-e', '0', '-y', :install, "myresource-1:18.12"] ) provider.install end end context 'when upgrading' do let(:ensure_value) { '>18.1 <19' } let(:available_versions) { ['17.5.2', '18.0', 'a:23' '18.3', '18.3.2', '19.0', '3:18.4'] } before do allow(provider).to receive(:available_versions).and_return(available_versions) allow(provider).to receive(:query).twice .and_return({ ensure: '17.0' }, { ensure: '18.3.2' }) end it 'adds update flag to install command' do expect(provider).to receive(:execute).with( ['/usr/bin/yum', '-d', '0', '-e', '0', '-y', 'update', 'myresource-18.3.2'] ) provider.install end end context 'when dowgrading' do let(:ensure_value) { '>18.1 <19' } let(:available_versions) { ['17.5.2', '18.0', 'a:23' '18.3', '18.3.2', '19.0', '3:18.4'] } before do allow(provider).to receive(:available_versions).and_return(available_versions) allow(provider).to receive(:query).twice .and_return({ ensure: '19.0' }, { ensure: '18.3.2' }) end it 'adds downgrade flag to install command' do expect(provider).to receive(:execute).with( ['/usr/bin/yum', '-d', '0', '-e', '0', '-y', :downgrade, 'myresource-18.3.2'] ) provider.install end end context 'on failure' do let(:ensure_value) { '20' } context 'when execute command fails' do before do allow(provider).to receive(:execute).with( ['/usr/bin/yum', '-d', '0', '-e', '0', '-y', :install, "myresource-20"] ).and_return('No package myresource-20 available.') end it 'raises Puppet::Error' do expect { provider.install }.to \ raise_error(Puppet::Error, 'Could not find package myresource-20') end end context 'when package is not found' do before do allow(provider).to receive(:query) allow(provider).to receive(:execute).with( ['/usr/bin/yum', '-d', '0', '-e', '0', '-y', :install, "myresource-20"] ) end it 'raises Puppet::Error' do expect { provider.install }.to \ raise_error(Puppet::Error, 'Could not find package myresource') end end context 'when package is not installed' do before do allow(provider).to receive(:execute).with( ['/usr/bin/yum', '-d', '0', '-e', '0', '-y', :install, "myresource-20"] ) allow(provider).to receive(:insync?).and_return(false) end it 'raises Puppet::Error' do expect { provider.install }.to \ raise_error(Puppet::Error, 'Failed to update to version 20, got version 18.3.2 instead') end end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/provider/package/windows_spec.rb
spec/unit/provider/package/windows_spec.rb
require 'spec_helper' describe Puppet::Type.type(:package).provider(:windows), :if => Puppet.features.microsoft_windows? do let(:name) { 'mysql-5.1.58-win-x64' } let(:source) { 'E:\Rando\Directory\mysql-5.1.58-win-x64.msi' } let(:resource) { Puppet::Type.type(:package).new(:name => name, :provider => :windows, :source => source) } let(:provider) { resource.provider } let(:execute_options) do {:failonfail => false, :combine => true, :suppress_window => true} end before(:each) do # make sure we never try to execute anything @times_execute_called = 0 allow(provider).to receive(:execute) { @times_execute_called += 1} end after(:each) do expect(@times_execute_called).to eq(0) end def expect_execute(command, status) expect(provider).to receive(:execute).with(command, execute_options).and_return(Puppet::Util::Execution::ProcessOutput.new('',status)) end describe 'provider features' do it { is_expected.to be_installable } it { is_expected.to be_uninstallable } it { is_expected.to be_install_options } it { is_expected.to be_uninstall_options } it { is_expected.to be_versionable } end describe 'on Windows', :if => Puppet::Util::Platform.windows? do it 'should be the default provider' do expect(Puppet::Type.type(:package).defaultprovider).to eq(subject.class) end end context '::instances' do it 'should return an array of provider instances' do pkg1 = double('pkg1') pkg2 = double('pkg2') prov1 = double('prov1', :name => 'pkg1', :version => '1.0.0', :package => pkg1) prov2 = double('prov2', :name => 'pkg2', :version => nil, :package => pkg2) expect(Puppet::Provider::Package::Windows::Package).to receive(:map).and_yield(prov1).and_yield(prov2).and_return([prov1, prov2]) providers = provider.class.instances expect(providers.count).to eq(2) expect(providers[0].name).to eq('pkg1') expect(providers[0].version).to eq('1.0.0') expect(providers[0].package).to eq(pkg1) expect(providers[1].name).to eq('pkg2') expect(providers[1].version).to be_nil expect(providers[1].package).to eq(pkg2) end it 'should return an empty array if none found' do expect(Puppet::Provider::Package::Windows::Package).to receive(:map).and_return([]) expect(provider.class.instances).to eq([]) end end context '#query' do it 'should return the hash of the matched packaged' do pkg = double(:name => 'pkg1', :version => nil) expect(pkg).to receive(:match?).and_return(true) expect(Puppet::Provider::Package::Windows::Package).to receive(:find).and_yield(pkg) expect(provider.query).to eq({ :name => 'pkg1', :ensure => :installed, :provider => :windows }) end it 'should include the version string when present' do pkg = double(:name => 'pkg1', :version => '1.0.0') expect(pkg).to receive(:match?).and_return(true) expect(Puppet::Provider::Package::Windows::Package).to receive(:find).and_yield(pkg) expect(provider.query).to eq({ :name => 'pkg1', :ensure => '1.0.0', :provider => :windows }) end it 'should return nil if no package was found' do expect(Puppet::Provider::Package::Windows::Package).to receive(:find) expect(provider.query).to be_nil end end context '#install' do let(:command) { 'blarg.exe /S' } let(:klass) { double('installer', :install_command => ['blarg.exe', '/S'] ) } let(:execute_options) do {:failonfail => false, :combine => true, :cwd => nil, :suppress_window => true} end before :each do expect(Puppet::Provider::Package::Windows::Package).to receive(:installer_class).and_return(klass) end it 'should join the install command and options' do resource[:install_options] = { 'INSTALLDIR' => 'C:\mysql-5.1' } expect_execute("#{command} INSTALLDIR=C:\\mysql-5.1", 0) provider.install end it 'should compact nil install options' do expect_execute(command, 0) provider.install end it 'should not warn if the package install succeeds' do expect_execute(command, 0) expect(provider).not_to receive(:warning) provider.install end it 'should warn if reboot initiated' do expect_execute(command, 1641) expect(provider).to receive(:warning).with('The package installed successfully and the system is rebooting now.') provider.install end it 'should warn if reboot required' do expect_execute(command, 3010) expect(provider).to receive(:warning).with('The package installed successfully, but the system must be rebooted.') provider.install end it 'should fail otherwise', :if => Puppet::Util::Platform.windows? do expect_execute(command, 5) expect do provider.install end.to raise_error do |error| expect(error).to be_a(Puppet::Util::Windows::Error) expect(error.code).to eq(5) # ERROR_ACCESS_DENIED end end context 'With a real working dir' do let(:execute_options) do {:failonfail => false, :combine => true, :cwd => 'E:\Rando\Directory', :suppress_window => true} end it 'should not try to set the working directory' do expect(Puppet::FileSystem).to receive(:exist?).with('E:\Rando\Directory').and_return(true) expect_execute(command, 0) provider.install end end end context '#uninstall' do let(:command) { 'unblarg.exe /Q' } let(:package) { double('package', :uninstall_command => ['unblarg.exe', '/Q'] ) } before :each do resource[:ensure] = :absent provider.package = package end it 'should join the uninstall command and options' do resource[:uninstall_options] = { 'INSTALLDIR' => 'C:\mysql-5.1' } expect_execute("#{command} INSTALLDIR=C:\\mysql-5.1", 0) provider.uninstall end it 'should compact nil install options' do expect_execute(command, 0) provider.uninstall end it 'should not warn if the package install succeeds' do expect_execute(command, 0) expect(provider).not_to receive(:warning) provider.uninstall end it 'should warn if reboot initiated' do expect_execute(command, 1641) expect(provider).to receive(:warning).with('The package uninstalled successfully and the system is rebooting now.') provider.uninstall end it 'should warn if reboot required' do expect_execute(command, 3010) expect(provider).to receive(:warning).with('The package uninstalled successfully, but the system must be rebooted.') provider.uninstall end it 'should fail otherwise', :if => Puppet::Util::Platform.windows? do expect_execute(command, 5) expect do provider.uninstall end.to raise_error do |error| expect(error).to be_a(Puppet::Util::Windows::Error) expect(error.code).to eq(5) # ERROR_ACCESS_DENIED end end end context '#validate_source' do it 'should fail if the source parameter is empty' do expect do resource[:source] = '' end.to raise_error(Puppet::Error, /The source parameter cannot be empty when using the Windows provider/) end it 'should accept a source' do resource[:source] = source end end context '#install_options' do it 'should return nil by default' do expect(provider.install_options).to be_nil end it 'should return the options' do resource[:install_options] = { 'INSTALLDIR' => 'C:\mysql-here' } expect(provider.install_options).to eq(['INSTALLDIR=C:\mysql-here']) end it 'should only quote if needed' do resource[:install_options] = { 'INSTALLDIR' => 'C:\mysql here' } expect(provider.install_options).to eq(['INSTALLDIR="C:\mysql here"']) end it 'should escape embedded quotes in install_options values with spaces' do resource[:install_options] = { 'INSTALLDIR' => 'C:\mysql "here"' } expect(provider.install_options).to eq(['INSTALLDIR="C:\mysql \"here\""']) end end context '#uninstall_options' do it 'should return nil by default' do expect(provider.uninstall_options).to be_nil end it 'should return the options' do resource[:uninstall_options] = { 'INSTALLDIR' => 'C:\mysql-here' } expect(provider.uninstall_options).to eq(['INSTALLDIR=C:\mysql-here']) end end context '#join_options' do it 'should return nil if there are no options' do expect(provider.join_options(nil)).to be_nil end it 'should sort hash keys' do expect(provider.join_options([{'b' => '2', 'a' => '1', 'c' => '3'}])).to eq(['a=1', 'b=2', 'c=3']) end it 'should return strings and hashes' do expect(provider.join_options([{'a' => '1'}, 'b'])).to eq(['a=1', 'b']) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/provider/package/tdnf_spec.rb
spec/unit/provider/package/tdnf_spec.rb
require 'spec_helper' # Note that much of the functionality of the tdnf provider is already tested with yum provider tests, # as yum is the parent provider, via dnf describe Puppet::Type.type(:package).provider(:tdnf) do it_behaves_like 'RHEL package provider', described_class, 'tdnf' context 'default' do it 'should be the default provider on PhotonOS' do allow(Facter).to receive(:value).with('os.family').and_return(:redhat) allow(Facter).to receive(:value).with('os.name').and_return("PhotonOS") expect(described_class).to be_default end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/provider/package/dnfmodule_spec.rb
spec/unit/provider/package/dnfmodule_spec.rb
require 'spec_helper' describe Puppet::Type.type(:package).provider(:dnfmodule) do include PuppetSpec::Fixtures let(:dnf_version) do <<-DNF_OUTPUT 4.0.9 Installed: dnf-0:4.0.9.2-5.el8.noarch at Wed 29 May 2019 07:05:05 AM GMT Built : Red Hat, Inc. <http://bugzilla.redhat.com/bugzilla> at Thu 14 Feb 2019 12:04:07 PM GMT Installed: rpm-0:4.14.2-9.el8.x86_64 at Wed 29 May 2019 07:04:33 AM GMT Built : Red Hat, Inc. <http://bugzilla.redhat.com/bugzilla> at Thu 20 Dec 2018 01:30:03 PM GMT DNF_OUTPUT end let(:execute_options) do {:failonfail => true, :combine => true, :custom_environment => {}} end let(:packages) { File.read(my_fixture("dnf-module-list.txt")) } let(:dnf_path) { '/usr/bin/dnf' } before(:each) { allow(Puppet::Util).to receive(:which).with('/usr/bin/dnf').and_return(dnf_path) } it "should have lower specificity" do allow(Facter).to receive(:value).with('os.family').and_return(:redhat) allow(Facter).to receive(:value).with('os.name').and_return(:redhat) allow(Facter).to receive(:value).with('os.release.major').and_return('8') expect(described_class.specificity).to be < 200 end describe "should be an opt-in provider" do Array(4..8).each do |ver| it "should not be default for redhat #{ver}" do allow(Facter).to receive(:value).with('os.name').and_return('redhat') allow(Facter).to receive(:value).with('os.family').and_return('redhat') allow(Facter).to receive(:value).with('os.release.major').and_return(ver.to_s) expect(described_class).not_to be_default end end end describe "handling dnf versions" do before(:each) do expect(Puppet::Type::Package::ProviderDnfmodule).to receive(:execute) .with(["/usr/bin/dnf", "--version"]) .and_return(Puppet::Util::Execution::ProcessOutput.new(dnf_version, 0)).at_most(:once) expect(Puppet::Util::Execution).to receive(:execute) .with(["/usr/bin/dnf", "--version"], execute_options) .and_return(Puppet::Util::Execution::ProcessOutput.new(dnf_version, 0)) end before(:each) { described_class.instance_variable_set("@current_version", nil) } describe "with a supported dnf version" do it "correctly parses the version" do expect(described_class.current_version).to eq('4.0.9') end end describe "with an unsupported dnf version" do let(:dnf_version) do <<-DNF_OUTPUT 2.7.5 Installed: dnf-0:2.7.5-12.fc28.noarch at Mon 13 Aug 2018 11:05:27 PM GMT Built : Fedora Project at Wed 18 Apr 2018 02:29:51 PM GMT Installed: rpm-0:4.14.1-7.fc28.x86_64 at Mon 13 Aug 2018 11:05:25 PM GMT Built : Fedora Project at Mon 19 Feb 2018 09:29:01 AM GMT DNF_OUTPUT end it "correctly parses the version" do expect(described_class.current_version).to eq('2.7.5') end it "raises an error when attempting prefetch" do expect { described_class.prefetch('anything') }.to raise_error(Puppet::Error, "Modules are not supported on DNF versions lower than 3.0.1") end end end describe "when ensuring a module" do let(:name) { 'baz' } let(:resource) do Puppet::Type.type(:package).new( :name => name, :provider => 'dnfmodule', ) end let(:provider) do provider = described_class.new provider.resource = resource provider end describe 'provider features' do it { is_expected.to be_versionable } it { is_expected.to be_installable } it { is_expected.to be_uninstallable } end context "when installing a new module" do before do provider.instance_variable_get('@property_hash')[:ensure] = :absent end it "should not reset the module stream when package is absent" do resource[:ensure] = :present expect(provider).not_to receive(:uninstall) expect(provider).to receive(:execute) provider.install end it "should not reset the module stream when package is purged" do provider.instance_variable_get('@property_hash')[:ensure] = :purged resource[:ensure] = :present expect(provider).not_to receive(:uninstall) expect(provider).to receive(:execute) provider.install end it "should just enable the module if it has no default profile (missing groups or modules)" do dnf_exception = Puppet::ExecutionFailure.new("Error: Problems in request:\nmissing groups or modules: #{resource[:name]}") allow(provider).to receive(:execute).with(array_including('install')).and_raise(dnf_exception) resource[:ensure] = :present expect(provider).to receive(:execute).with(array_including('install')).ordered expect(provider).to receive(:execute).with(array_including('enable')).ordered provider.install end it "should just enable the module with the right stream if it has no default profile (missing groups or modules)" do stream = '12.3' dnf_exception = Puppet::ExecutionFailure.new("Error: Problems in request:\nmissing groups or modules: #{resource[:name]}:#{stream}") allow(provider).to receive(:execute).with(array_including('install')).and_raise(dnf_exception) resource[:ensure] = stream expect(provider).to receive(:execute).with(array_including('install')).ordered expect(provider).to receive(:execute).with(array_including('enable')).ordered provider.install end it "should just enable the module if it has no default profile (broken groups or modules)" do dnf_exception = Puppet::ExecutionFailure.new("Error: Problems in request:\nbroken groups or modules: #{resource[:name]}") allow(provider).to receive(:execute).with(array_including('install')).and_raise(dnf_exception) resource[:ensure] = :present expect(provider).to receive(:execute).with(array_including('install')).ordered expect(provider).to receive(:execute).with(array_including('enable')).ordered provider.install end it "should just enable the module with the right stream if it has no default profile (broken groups or modules)" do stream = '12.3' dnf_exception = Puppet::ExecutionFailure.new("Error: Problems in request:\nbroken groups or modules: #{resource[:name]}:#{stream}") allow(provider).to receive(:execute).with(array_including('install')).and_raise(dnf_exception) resource[:ensure] = stream expect(provider).to receive(:execute).with(array_including('install')).ordered expect(provider).to receive(:execute).with(array_including('enable')).ordered provider.install end it "should just enable the module if enable_only = true" do resource[:ensure] = :present resource[:enable_only] = true expect(provider).to receive(:execute).with(array_including('enable')) expect(provider).not_to receive(:execute).with(array_including('install')) provider.install end it "should install the default stream and flavor" do resource[:ensure] = :present expect(provider).to receive(:execute).with(array_including('baz')) provider.install end it "should install a specific stream" do resource[:ensure] = '9.6' expect(provider).to receive(:execute).with(array_including('baz:9.6')) provider.install end it "should install a specific flavor" do resource[:ensure] = :present resource[:flavor] = 'minimal' expect(provider).to receive(:execute).with(array_including('baz/minimal')) provider.install end it "should install a specific flavor and stream" do resource[:ensure] = '9.6' resource[:flavor] = 'minimal' expect(provider).to receive(:execute).with(array_including('baz:9.6/minimal')) provider.install end end context "when ensuring a specific version on top of another stream" do before do provider.instance_variable_get('@property_hash')[:ensure] = '9.6' end it "should remove existing packages and reset the module stream before installing" do resource[:ensure] = '10' expect(provider).to receive(:execute).thrice.with(array_including(/remove|reset|install/)) provider.install end end context "with an installed flavor" do before do provider.instance_variable_get('@property_hash')[:flavor] = 'minimal' end it "should remove existing packages and reset the module stream before installing another flavor" do resource[:flavor] = 'common' expect(provider).to receive(:execute).thrice.with(array_including(/remove|reset|install/)) provider.flavor = resource[:flavor] end it "should not do anything if the flavor doesn't change" do resource[:flavor] = 'minimal' expect(provider).not_to receive(:execute) provider.flavor = resource[:flavor] end it "should return the existing flavor" do expect(provider.flavor).to eq('minimal') end end context "when disabling a module" do it "executed the disable command" do resource[:ensure] = :disabled expect(provider).to receive(:execute).with(array_including('disable')) provider.disable end it "does not try to disable if package is already disabled" do allow(described_class).to receive(:command).with(:dnf).and_return(dnf_path) allow(Puppet::Util::Execution).to receive(:execute) .with("/usr/bin/dnf module list -y -d 0 -e 1") .and_return("baz 1.2 [d][x] common [d], complete Package Description") resource[:ensure] = :disabled expect(provider).to be_insync(:disabled) end end end context "parsing the output of module list" do before { allow(described_class).to receive(:command).with(:dnf).and_return(dnf_path) } it "returns an array of enabled modules" do allow(Puppet::Util::Execution).to receive(:execute) .with("/usr/bin/dnf module list -y -d 0 -e 1") .and_return(packages) enabled_packages = described_class.instances.map { |package| package.properties } expected_packages = [{name: "389-ds", ensure: "1.4", flavor: :absent, provider: :dnfmodule}, {name: "gimp", ensure: "2.8", flavor: "devel", provider: :dnfmodule}, {name: "mariadb", ensure: "10.3", flavor: "client", provider: :dnfmodule}, {name: "nodejs", ensure: "10", flavor: "minimal", provider: :dnfmodule}, {name: "perl", ensure: "5.26", flavor: "minimal", provider: :dnfmodule}, {name: "postgresql", ensure: "10", flavor: "server", provider: :dnfmodule}, {name: "ruby", ensure: "2.5", flavor: :absent, provider: :dnfmodule}, {name: "rust-toolset", ensure: "rhel8", flavor: "common", provider: :dnfmodule}, {name: "subversion", ensure: "1.10", flavor: "server", provider: :dnfmodule}, {name: "swig", ensure: :disabled, flavor: :absent, provider: :dnfmodule}, {name: "virt", ensure: :disabled, flavor: :absent, provider: :dnfmodule}] expect(enabled_packages).to eql(expected_packages) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/provider/package/urpmi_spec.rb
spec/unit/provider/package/urpmi_spec.rb
require 'spec_helper' describe Puppet::Type.type(:package).provider(:urpmi) do before do %w[rpm urpmi urpme urpmq].each do |executable| allow(Puppet::Util).to receive(:which).with(executable).and_return(executable) end allow(Puppet::Util::Execution).to receive(:execute) .with(['rpm', '--version'], anything) .and_return(Puppet::Util::Execution::ProcessOutput.new('RPM version 4.9.1.3', 0)) end let(:resource) do Puppet::Type.type(:package).new(:name => 'foopkg', :provider => :urpmi) end before do subject.resource = resource allow(Puppet::Type.type(:package)).to receive(:defaultprovider).and_return(described_class) end describe '#install' do before do allow(subject).to receive(:rpm).with('-q', 'foopkg', any_args).and_return("foopkg 0 1.2.3.4 5 noarch :DESC:\n") end describe 'without a version' do it 'installs the unversioned package' do resource[:ensure] = :present expect(Puppet::Util::Execution).to receive(:execute).with(['urpmi', '--auto', 'foopkg'], anything) subject.install end end describe 'with a version' do it 'installs the versioned package' do resource[:ensure] = '4.5.6' expect(Puppet::Util::Execution).to receive(:execute).with(['urpmi', '--auto', 'foopkg-4.5.6'], anything) subject.install end end describe "and the package install fails" do it "raises an error" do allow(Puppet::Util::Execution).to receive(:execute).with(['urpmi', '--auto', 'foopkg'], anything) allow(subject).to receive(:query) expect { subject.install }.to raise_error Puppet::Error, /Package \S+ was not present after trying to install it/ end end end describe '#latest' do let(:urpmq_output) { 'foopkg : Lorem ipsum dolor sit amet, consectetur adipisicing elit ( 7.8.9-1.mga2 )' } it "uses urpmq to determine the latest package" do expect(Puppet::Util::Execution).to receive(:execute) .with(['urpmq', '-S', 'foopkg'], anything) .and_return(Puppet::Util::Execution::ProcessOutput.new(urpmq_output, 0)) expect(subject.latest).to eq('7.8.9-1.mga2') end it "falls back to the current version" do resource[:ensure] = '5.4.3' expect(Puppet::Util::Execution).to receive(:execute) .with(['urpmq', '-S', 'foopkg'], anything) .and_return(Puppet::Util::Execution::ProcessOutput.new('', 0)) expect(subject.latest).to eq('5.4.3') end end describe '#update' do it 'delegates to #install' do expect(subject).to receive(:install) subject.update end end describe '#purge' do it 'uses urpme to purge packages' do expect(Puppet::Util::Execution).to receive(:execute).with(['urpme', '--auto', 'foopkg'], anything) subject.purge end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/provider/package/puppet_gem_spec.rb
spec/unit/provider/package/puppet_gem_spec.rb
require 'spec_helper' describe Puppet::Type.type(:package).provider(:puppet_gem) do let(:resource) do Puppet::Type.type(:package).new( :name => 'myresource', :ensure => :installed ) end let(:provider) do provider = described_class.new provider.resource = resource provider end if Puppet::Util::Platform.windows? let(:provider_gem_cmd) { 'C:\Program Files\Puppet Labs\Puppet\puppet\bin\gem.bat' } else let(:provider_gem_cmd) { '/opt/puppetlabs/puppet/bin/gem' } end let(:execute_options) do { failonfail: true, combine: true, custom_environment: { 'HOME'=>ENV['HOME'], 'PKG_CONFIG_PATH' => '/opt/puppetlabs/puppet/lib/pkgconfig' } } end before :each do resource.provider = provider if Puppet::Util::Platform.windows? # provider is loaded before we can stub, so stub the class we're testing allow(provider.class).to receive(:command).with(:gemcmd).and_return(provider_gem_cmd) else allow(provider.class).to receive(:which).with(provider_gem_cmd).and_return(provider_gem_cmd) end allow(File).to receive(:file?).with(provider_gem_cmd).and_return(true) end context "when installing" do before :each do allow(provider).to receive(:rubygem_version).and_return('1.9.9') end it "should use the path to the gem command" do expect(described_class).to receive(:execute).with([provider_gem_cmd, be_an(Array)], be_a(Hash)).and_return('') provider.install end it "should not append install_options by default" do expect(described_class).to receive(:execute).with([provider_gem_cmd, %w{install --no-rdoc --no-ri myresource}], anything).and_return('') provider.install end it "should allow setting an install_options parameter" do resource[:install_options] = [ '--force', {'--bindir' => '/usr/bin' } ] expect(described_class).to receive(:execute).with([provider_gem_cmd, %w{install --force --bindir=/usr/bin --no-rdoc --no-ri myresource}], anything).and_return('') provider.install end end context "when uninstalling" do it "should use the path to the gem command" do expect(described_class).to receive(:execute).with([provider_gem_cmd, be_an(Array)], be_a(Hash)).and_return('') provider.uninstall end it "should not append uninstall_options by default" do expect(described_class).to receive(:execute).with([provider_gem_cmd, %w{uninstall --executables --all myresource}], anything).and_return('') provider.uninstall end it "should allow setting an uninstall_options parameter" do resource[:uninstall_options] = [ '--force', {'--bindir' => '/usr/bin' } ] expect(described_class).to receive(:execute).with([provider_gem_cmd, %w{uninstall --executables --all myresource --force --bindir=/usr/bin}], anything).and_return('') provider.uninstall end it 'should invalidate the rubygems cache' do gem_source = double('gem_source') allow(Puppet::Util::Autoload).to receive(:gem_source).and_return(gem_source) expect(described_class).to receive(:execute).with([provider_gem_cmd, %w{uninstall --executables --all myresource}], anything).and_return('') expect(gem_source).to receive(:clear_paths) provider.uninstall end end context 'calculated specificity' do include_context 'provider specificity' context 'when is not defaultfor' do subject { described_class.specificity } it { is_expected.to eql 1 } end context 'when is defaultfor' do let(:os) { Puppet.runtime[:facter].value('os.name') } subject do described_class.defaultfor('os.name': os) described_class.specificity end it { is_expected.to be > 100 } end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/provider/package/base_spec.rb
spec/unit/provider/package/base_spec.rb
require 'spec_helper' require 'puppet/provider/package' Puppet::Type.type(:package).provide(:test_base_provider, parent: Puppet::Provider::Package) do def query; end end describe Puppet::Provider::Package do let(:provider) { Puppet::Type.type(:package).provider(:test_base_provider).new } it 'returns absent for uninstalled packages when not purgeable' do expect(provider.properties[:ensure]).to eq(:absent) end it 'returns purged for uninstalled packages when purgeable' do expect(provider.class).to receive(:feature?).with(:purgeable).and_return(true) expect(provider.properties[:ensure]).to eq(:purged) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/provider/package/pkg_spec.rb
spec/unit/provider/package/pkg_spec.rb
require 'spec_helper' describe Puppet::Type.type(:package).provider(:pkg), unless: Puppet::Util::Platform.jruby? do let (:resource) { Puppet::Resource.new(:package, 'dummy', :parameters => {:name => 'dummy', :ensure => :latest}) } let (:provider) { described_class.new(resource) } before :each do allow(described_class).to receive(:command).with(:pkg).and_return('/bin/pkg') end def self.it_should_respond_to(*actions) actions.each do |action| it "should respond to :#{action}" do expect(provider).to respond_to(action) end end end it_should_respond_to :install, :uninstall, :update, :query, :latest context 'default' do [ 10 ].each do |ver| it "should not be the default provider on Solaris #{ver}" do allow(Facter).to receive(:value).with('os.family').and_return(:Solaris) allow(Facter).to receive(:value).with(:kernelrelease).and_return("5.#{ver}") allow(Facter).to receive(:value).with('os.name').and_return(:Solaris) allow(Facter).to receive(:value).with('os.release.major').and_return("#{ver}") expect(described_class).to_not be_default end end [ 11, 12 ].each do |ver| it "should be the default provider on Solaris #{ver}" do allow(Facter).to receive(:value).with('os.family').and_return(:Solaris) allow(Facter).to receive(:value).with(:kernelrelease).and_return("5.#{ver}") allow(Facter).to receive(:value).with('os.name').and_return(:Solaris) allow(Facter).to receive(:value).with('os.release.major').and_return("#{ver}") expect(described_class).to be_default end end end it "should be versionable" do expect(described_class).to be_versionable end describe "#methods" do context ":pkg_state" do it "should raise error on unknown values" do expect { expect(described_class.pkg_state('extra')).to }.to raise_error(ArgumentError, /Unknown format/) end ['known', 'installed'].each do |k| it "should return known values" do expect(described_class.pkg_state(k)).to eq({:status => k}) end end end context ":ifo_flag" do it "should raise error on unknown values" do expect { expect(described_class.ifo_flag('x--')).to }.to raise_error(ArgumentError, /Unknown format/) end {'i--' => 'installed', '---'=> 'known'}.each do |k, v| it "should return known values" do expect(described_class.ifo_flag(k)).to eq({:status => v}) end end end context ":parse_line" do it "should raise error on unknown values" do expect { expect(described_class.parse_line('pkg (mypkg) 1.2.3.4 i-- zzz')).to }.to raise_error(ArgumentError, /Unknown line format/) end { 'pkg://omnios/SUNWcs@0.5.11,5.11-0.151006:20130506T161045Z i--' => {:name => 'SUNWcs', :ensure => '0.5.11,5.11-0.151006:20130506T161045Z', :status => 'installed', :provider => :pkg, :publisher => 'omnios'}, 'pkg://omnios/incorporation/jeos/illumos-gate@11,5.11-0.151006:20130506T183443Z if-' => {:name => 'incorporation/jeos/illumos-gate', :ensure => "11,5.11-0.151006:20130506T183443Z", :mark => :hold, :status => 'installed', :provider => :pkg, :publisher => 'omnios'}, 'pkg://solaris/SUNWcs@0.5.11,5.11-0.151.0.1:20101105T001108Z installed -----' => {:name => 'SUNWcs', :ensure => '0.5.11,5.11-0.151.0.1:20101105T001108Z', :status => 'installed', :provider => :pkg, :publisher => 'solaris'}, }.each do |k, v| it "[#{k}] should correctly parse" do expect(described_class.parse_line(k)).to eq(v) end end end context ":latest" do before do expect(described_class).to receive(:pkg).with(:refresh) end it "should work correctly for ensure latest on solaris 11 (UFOXI) when there are no further packages to install" do expect(described_class).to receive(:pkg).with(:list,'-Hvn','dummy').and_return(File.read(my_fixture('dummy_solaris11.installed'))) expect(provider.latest).to eq('1.0.6,5.11-0.175.0.0.0.2.537:20131230T130000Z') end it "should work correctly for ensure latest on solaris 11 in the presence of a certificate expiration warning" do expect(described_class).to receive(:pkg).with(:list,'-Hvn','dummy').and_return(File.read(my_fixture('dummy_solaris11.certificate_warning'))) expect(provider.latest).to eq("1.0.6-0.175.0.0.0.2.537") end it "should work correctly for ensure latest on solaris 11(known UFOXI)" do expect(Puppet::Util::Execution).to receive(:execute) .with(['/bin/pkg', 'update', '-n', 'dummy'], {:failonfail => false, :combine => true}) .and_return(Puppet::Util::Execution::ProcessOutput.new('', 0)) expect(described_class).to receive(:pkg).with(:list,'-Hvn','dummy').and_return(File.read(my_fixture('dummy_solaris11.known'))) expect(provider.latest).to eq('1.0.6,5.11-0.175.0.0.0.2.537:20131230T130000Z') end it "should work correctly for ensure latest on solaris 11 (IFO)" do expect(described_class).to receive(:pkg).with(:list,'-Hvn','dummy').and_return(File.read(my_fixture('dummy_solaris11.ifo.installed'))) expect(provider.latest).to eq('1.0.6,5.11-0.175.0.0.0.2.537:20131230T130000Z') end it "should work correctly for ensure latest on solaris 11(known IFO)" do expect(Puppet::Util::Execution).to receive(:execute) .with(['/bin/pkg', 'update', '-n', 'dummy'], {:failonfail => false, :combine => true}) .and_return(Puppet::Util::Execution::ProcessOutput.new('', 0)) expect(described_class).to receive(:pkg).with(:list,'-Hvn','dummy').and_return(File.read(my_fixture('dummy_solaris11.ifo.known'))) expect(provider.latest).to eq('1.0.6,5.11-0.175.0.0.0.2.537:20131230T130000Z') end it "issues a warning when the certificate has expired" do warning = "Certificate '/var/pkg/ssl/871b4ed0ade09926e6adf95f86bf17535f987684' for publisher 'solarisstudio', needed to access 'https://pkg.oracle.com/solarisstudio/release/', will expire in '29' days." expect(Puppet).to receive(:warning).with("pkg warning: #{warning}") expect(described_class).to receive(:pkg).with(:list,'-Hvn','dummy').and_return(File.read(my_fixture('dummy_solaris11.certificate_warning'))) provider.latest end it "doesn't issue a warning when the certificate hasn't expired" do expect(Puppet).not_to receive(:warning).with(/pkg warning/) expect(described_class).to receive(:pkg).with(:list,'-Hvn','dummy').and_return(File.read(my_fixture('dummy_solaris11.installed'))) provider.latest end it "applies install options if available" do resource[:install_options] = ['--foo', {'--bar' => 'baz'}] expect(described_class).to receive(:pkg).with(:list,'-Hvn','dummy').and_return(File.read(my_fixture('dummy_solaris11.known'))) expect(Puppet::Util::Execution).to receive(:execute) .with(['/bin/pkg', 'update', '-n', '--foo', '--bar=baz', 'dummy'], {failonfail: false, combine: true}) .and_return(Puppet::Util::Execution::ProcessOutput.new('', 0)) provider.latest end end context ":instances" do it "should correctly parse lines on solaris 11" do expect(described_class).to receive(:pkg).with(:list, '-Hv').and_return(File.read(my_fixture('solaris11'))) expect(described_class).not_to receive(:warning) instances = described_class.instances.map { |p| {:name => p.get(:name), :ensure => p.get(:ensure) }} expect(instances.size).to eq(2) expect(instances[0]).to eq({:name => 'dummy/dummy', :ensure => '3.0,5.11-0.175.0.0.0.2.537:20131230T130000Z'}) expect(instances[1]).to eq({:name => 'dummy/dummy2', :ensure => '1.8.1.2-0.175.0.0.0.2.537:20131230T130000Z'}) end it "should fail on incorrect lines" do fake_output = File.read(my_fixture('incomplete')) expect(described_class).to receive(:pkg).with(:list,'-Hv').and_return(fake_output) expect { described_class.instances }.to raise_error(ArgumentError, /Unknown line format pkg/) end it "should fail on unknown package status" do expect(described_class).to receive(:pkg).with(:list,'-Hv').and_return(File.read(my_fixture('unknown_status'))) expect { described_class.instances }.to raise_error(ArgumentError, /Unknown format pkg/) end end context ":query" do context "on solaris 10" do it "should find the package" do expect(Puppet::Util::Execution).to receive(:execute) .with(['/bin/pkg', 'list', '-Hv', 'dummy'], {:failonfail => false, :combine => true}) .and_return(Puppet::Util::Execution::ProcessOutput.new(File.read(my_fixture('dummy_solaris10')), 0)) expect(provider.query).to eq({ :name => 'dummy', :ensure => '2.5.5,5.10-0.111:20131230T130000Z', :publisher => 'solaris', :status => 'installed', :provider => :pkg, }) end it "should return :absent when the package is not found" do expect(Puppet::Util::Execution).to receive(:execute) .with(['/bin/pkg', 'list', '-Hv', 'dummy'], {:failonfail => false, :combine => true}) .and_return(Puppet::Util::Execution::ProcessOutput.new('', 1)) expect(provider.query).to eq({:ensure => :absent, :name => "dummy"}) end end context "on solaris 11" do it "should find the package" do expect(Puppet::Util::Execution).to receive(:execute) .with(['/bin/pkg', 'list', '-Hv', 'dummy'], {:failonfail => false, :combine => true}) .and_return(Puppet::Util::Execution::ProcessOutput.new(File.read(my_fixture('dummy_solaris11.installed')), 0)) expect(provider.query).to eq({ :name => 'dummy', :status => 'installed', :ensure => '1.0.6,5.11-0.175.0.0.0.2.537:20131230T130000Z', :publisher => 'solaris', :provider => :pkg, }) end it "should return :absent when the package is not found" do expect(Puppet::Util::Execution).to receive(:execute) .with(['/bin/pkg', 'list', '-Hv', 'dummy'], {:failonfail => false, :combine => true}) .and_return(Puppet::Util::Execution::ProcessOutput.new('', 1)) expect(provider.query).to eq({:ensure => :absent, :name => "dummy"}) end end it "should return fail when the packageline cannot be parsed" do expect(Puppet::Util::Execution).to receive(:execute) .with(['/bin/pkg', 'list', '-Hv', 'dummy'], {:failonfail => false, :combine => true}) .and_return(Puppet::Util::Execution::ProcessOutput.new(File.read(my_fixture('incomplete')), 0)) expect { provider.query }.to raise_error(ArgumentError, /Unknown line format/) end end context ":install" do [ { :osrel => '11.0', :flags => ['--accept'] }, { :osrel => '11.2', :flags => ['--accept', '--sync-actuators-timeout', '900'] }, ].each do |hash| context "with 'os.release.full' #{hash[:osrel]}" do before :each do allow(Facter).to receive(:value).with('os.release.full').and_return(hash[:osrel]) end it "should support install options" do resource[:install_options] = ['--foo', {'--bar' => 'baz'}] expect(provider).to receive(:query).and_return({:ensure => :absent}) expect(provider).to receive(:properties).and_return({:mark => :hold}) expect(provider).to receive(:unhold) expect(Puppet::Util::Execution).to receive(:execute) .with(['/bin/pkg', 'install', *hash[:flags], '--foo', '--bar=baz', 'dummy'], {:failonfail => false, :combine => true}) .and_return(Puppet::Util::Execution::ProcessOutput.new('', 0)) provider.install end it "should accept all licenses" do expect(provider).to receive(:query).with(no_args).and_return({:ensure => :absent}) expect(provider).to receive(:properties).and_return({:mark => :hold}) expect(Puppet::Util::Execution).to receive(:execute) .with(['/bin/pkg', 'install', *hash[:flags], 'dummy'], {:failonfail => false, :combine => true}) .and_return(Puppet::Util::Execution::ProcessOutput.new('', 0)) expect(Puppet::Util::Execution).to receive(:execute) .with(['/bin/pkg', 'unfreeze', 'dummy'], {:failonfail => false, :combine => true}) .and_return(Puppet::Util::Execution::ProcessOutput.new('', 0)) provider.install end it "should install specific version(1)" do # Should install also check if the version installed is the same version we are asked to install? or should we rely on puppet for that? resource[:ensure] = '0.0.7,5.11-0.151006:20131230T130000Z' expect(provider).to receive(:properties).and_return({:mark => :hold}) expect(Puppet::Util::Execution).to receive(:execute) .with(['/bin/pkg', 'unfreeze', 'dummy'], {:failonfail => false, :combine => true}) .and_return(Puppet::Util::Execution::ProcessOutput.new('', 0)) expect(Puppet::Util::Execution).to receive(:execute) .with(['/bin/pkg', 'list', '-Hv', 'dummy'], {:failonfail => false, :combine => true}) .and_return(Puppet::Util::Execution::ProcessOutput.new('pkg://foo/dummy@0.0.6,5.11-0.151006:20131230T130000Z installed -----', 0)) expect(Puppet::Util::Execution).to receive(:execute) .with(['/bin/pkg', 'update', *hash[:flags], 'dummy@0.0.7,5.11-0.151006:20131230T130000Z'], {:failonfail => false, :combine => true}) .and_return(Puppet::Util::Execution::ProcessOutput.new('', 0)) provider.install end it "should install specific version(2)" do resource[:ensure] = '0.0.8' expect(provider).to receive(:properties).and_return({:mark => :hold}) expect(Puppet::Util::Execution).to receive(:execute) .with(['/bin/pkg', 'unfreeze', 'dummy'], {:failonfail => false, :combine => true}) .and_return(Puppet::Util::Execution::ProcessOutput.new('', 0)) expect(Puppet::Util::Execution).to receive(:execute) .with(['/bin/pkg', 'list', '-Hv', 'dummy'], {:failonfail => false, :combine => true}) .and_return(Puppet::Util::Execution::ProcessOutput.new('pkg://foo/dummy@0.0.7,5.11-0.151006:20131230T130000Z installed -----', 0)) expect(Puppet::Util::Execution).to receive(:execute) .with(['/bin/pkg', 'update', *hash[:flags], 'dummy@0.0.8'], {:failonfail => false, :combine => true}) .and_return(Puppet::Util::Execution::ProcessOutput.new('', 0)) provider.install end it "should downgrade to specific version" do resource[:ensure] = '0.0.7' expect(provider).to receive(:properties).and_return({:mark => :hold}) expect(provider).to receive(:query).with(no_args).and_return({:ensure => '0.0.8,5.11-0.151106:20131230T130000Z'}) expect(Puppet::Util::Execution).to receive(:execute) .with(['/bin/pkg', 'unfreeze', 'dummy'], {:failonfail => false, :combine => true}) .and_return(Puppet::Util::Execution::ProcessOutput.new('', 0)) expect(Puppet::Util::Execution).to receive(:execute) .with(['/bin/pkg', 'update', *hash[:flags], 'dummy@0.0.7'], {:failonfail => false, :combine => true}) .and_return(Puppet::Util::Execution::ProcessOutput.new('', 0)) provider.install end it "should install any if version is not specified" do resource[:ensure] = :present expect(provider).to receive(:properties).and_return({:mark => :hold}) expect(provider).to receive(:query).with(no_args).and_return({:ensure => :absent}) expect(Puppet::Util::Execution).to receive(:execute) .with(['/bin/pkg', 'install', *hash[:flags], 'dummy'], {:failonfail => false, :combine => true}) .and_return(Puppet::Util::Execution::ProcessOutput.new('', 0)) expect(Puppet::Util::Execution).to receive(:execute) .with(['/bin/pkg', 'unfreeze', 'dummy'], {:failonfail => false, :combine => true}) .and_return(Puppet::Util::Execution::ProcessOutput.new('', 0)) provider.install end it "should install if no version was previously installed, and a specific version was requested" do resource[:ensure] = '0.0.7' expect(provider).to receive(:properties).and_return({:mark => :hold}) expect(provider).to receive(:query).with(no_args).and_return({:ensure => :absent}) expect(Puppet::Util::Execution).to receive(:execute) .with(['/bin/pkg', 'unfreeze', 'dummy'], {:failonfail => false, :combine => true}) .and_return(Puppet::Util::Execution::ProcessOutput.new('', 0)) expect(Puppet::Util::Execution).to receive(:execute) .with(['/bin/pkg', 'install', *hash[:flags], 'dummy@0.0.7'], {:failonfail => false, :combine => true}) .and_return(Puppet::Util::Execution::ProcessOutput.new('', 0)) provider.install end it "installs the latest matching version when given implicit version, and none are installed" do resource[:ensure] = '1.0-0.151006' is = :absent expect(provider).to receive(:query).with(no_args).and_return({:ensure => is}) expect(provider).to receive(:properties).and_return({:mark => :hold}).exactly(3).times expect(described_class).to receive(:pkg) .with(:freeze, 'dummy') expect(described_class).to receive(:pkg) .with(:list, '-Hvfa', 'dummy@1.0-0.151006') .and_return(Puppet::Util::Execution::ProcessOutput.new(File.read(my_fixture('dummy_implicit_version')), 0)) expect(Puppet::Util::Execution).to receive(:execute) .with(['/bin/pkg', 'install', '-n', 'dummy@1.0,5.11-0.151006:20140220T084443Z'], {:failonfail => false, :combine => true}) .and_return(Puppet::Util::Execution::ProcessOutput.new('', 0)) expect(provider).to receive(:unhold).with(no_args).twice expect(Puppet::Util::Execution).to receive(:execute) .with(['/bin/pkg', 'install', *hash[:flags], 'dummy@1.0,5.11-0.151006:20140220T084443Z'], {:failonfail => false, :combine => true}) .and_return(Puppet::Util::Execution::ProcessOutput.new('', 0)) provider.insync?(is) provider.install end it "updates to the latest matching version when given implicit version" do resource[:ensure] = '1.0-0.151006' is = '1.0,5.11-0.151006:20140219T191204Z' expect(provider).to receive(:query).with(no_args).and_return({:ensure => is}) expect(provider).to receive(:properties).and_return({:mark => :hold}).exactly(3).times expect(described_class).to receive(:pkg) .with(:freeze, 'dummy') expect(described_class).to receive(:pkg) .with(:list, '-Hvfa', 'dummy@1.0-0.151006') .and_return(File.read(my_fixture('dummy_implicit_version'))) expect(Puppet::Util::Execution).to receive(:execute) .with(['/bin/pkg', 'update', '-n', 'dummy@1.0,5.11-0.151006:20140220T084443Z'], {:failonfail => false, :combine => true}) .and_return(Puppet::Util::Execution::ProcessOutput.new('', 0)) expect(provider).to receive(:unhold).with(no_args).twice expect(Puppet::Util::Execution).to receive(:execute) .with(['/bin/pkg', 'update', *hash[:flags], 'dummy@1.0,5.11-0.151006:20140220T084443Z'], {:failonfail => false, :combine => true}) .and_return(Puppet::Util::Execution::ProcessOutput.new('', 0)) provider.insync?(is) provider.install end it "issues a warning when an implicit version number is used, and in sync" do resource[:ensure] = '1.0-0.151006' is = '1.0,5.11-0.151006:20140220T084443Z' expect(provider).to receive(:warning).with("Implicit version 1.0-0.151006 has 3 possible matches") expect(described_class).to receive(:pkg) .with(:list, '-Hvfa', 'dummy@1.0-0.151006') .and_return(Puppet::Util::Execution::ProcessOutput.new(File.read(my_fixture('dummy_implicit_version')), 0)) expect(Puppet::Util::Execution).to receive(:execute) .with(['/bin/pkg', 'list', '-Hv', 'dummy'], {:failonfail => false, :combine => true}) .and_return(Puppet::Util::Execution::ProcessOutput.new(File.read(my_fixture('dummy_implicit_version')), 0)) expect(Puppet::Util::Execution).to receive(:execute) .with(['/bin/pkg', 'update', '-n', 'dummy@1.0,5.11-0.151006:20140220T084443Z'], {:failonfail => false, :combine => true}) .and_return(Puppet::Util::Execution::ProcessOutput.new('', 4)) provider.insync?(is) end it "issues a warning when choosing a version number for an implicit match" do resource[:ensure] = '1.0-0.151006' is = :absent expect(provider).to receive(:warning).with("Implicit version 1.0-0.151006 has 3 possible matches") expect(provider).to receive(:warning).with("Selecting version '1.0,5.11-0.151006:20140220T084443Z' for implicit '1.0-0.151006'") expect(described_class).to receive(:pkg) .with(:list, '-Hvfa', 'dummy@1.0-0.151006') .and_return(Puppet::Util::Execution::ProcessOutput.new(File.read(my_fixture('dummy_implicit_version')), 0)) expect(Puppet::Util::Execution).to receive(:execute) .with(['/bin/pkg', 'list', '-Hv', 'dummy'], {:failonfail => false, :combine => true}) .and_return(Puppet::Util::Execution::ProcessOutput.new(File.read(my_fixture('dummy_implicit_version')), 0)) expect(Puppet::Util::Execution).to receive(:execute) .with(['/bin/pkg', 'install', '-n', 'dummy@1.0,5.11-0.151006:20140220T084443Z'], {:failonfail => false, :combine => true}) .and_return(Puppet::Util::Execution::ProcessOutput.new('', 0)) provider.insync?(is) end it "should try 5 times to install and fail when all tries failed" do allow_any_instance_of(Kernel).to receive(:sleep) expect(provider).to receive(:query).and_return({:ensure => :absent}) expect(provider).to receive(:properties).and_return({:mark => :hold}) expect(provider).to receive(:unhold) expect(Puppet::Util::Execution).to receive(:execute) .with(['/bin/pkg', 'install', *hash[:flags], 'dummy'], {:failonfail => false, :combine => true}) .and_return(Puppet::Util::Execution::ProcessOutput.new('', 7)) .exactly(5).times expect { provider.update }.to raise_error(Puppet::Error, /Pkg could not install dummy after 5 tries. Aborting run/) end end end end context ":update" do it "should not raise error if not necessary" do expect(provider).to receive(:install).with(true).and_return({:exit => 0}) provider.update end it "should not raise error if not necessary (2)" do expect(provider).to receive(:install).with(true).and_return({:exit => 4}) provider.update end it "should raise error if necessary" do expect(provider).to receive(:install).with(true).and_return({:exit => 1}) expect { provider.update }.to raise_error(Puppet::Error, /Unable to update/) end end context ":uninstall" do it "should support current pkg version" do expect(described_class).to receive(:pkg).with(:version).and_return('630e1ffc7a19') expect(described_class).to receive(:pkg).with([:uninstall, resource[:name]]) expect(provider).to receive(:properties).and_return({:hold => false}) provider.uninstall end it "should support original pkg commands" do expect(described_class).to receive(:pkg).with(:version).and_return('052adf36c3f4') expect(described_class).to receive(:pkg).with([:uninstall, '-r', resource[:name]]) expect(provider).to receive(:properties).and_return({:hold => false}) provider.uninstall end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/provider/package/pacman_spec.rb
spec/unit/provider/package/pacman_spec.rb
require 'spec_helper' require 'stringio' describe Puppet::Type.type(:package).provider(:pacman) do let(:no_extra_options) { { :failonfail => true, :combine => true, :custom_environment => {} } } let(:executor) { Puppet::Util::Execution } let(:resolver) { Puppet::Util } let(:resource) { Puppet::Type.type(:package).new(:name => 'package', :provider => 'pacman') } let(:provider) { described_class.new(resource) } before do allow(resolver).to receive(:which).with('/usr/bin/pacman').and_return('/usr/bin/pacman') allow(described_class).to receive(:which).with('/usr/bin/pacman').and_return('/usr/bin/pacman') allow(resolver).to receive(:which).with('/usr/bin/yaourt').and_return('/usr/bin/yaourt') allow(described_class).to receive(:which).with('/usr/bin/yaourt').and_return('/usr/bin/yaourt') allow(described_class).to receive(:group?).and_return(false) allow(described_class).to receive(:yaourt?).and_return(false) end describe "when installing" do before do allow(provider).to receive(:query).and_return({ :ensure => '1.0' }) end it "should call pacman to install the right package quietly when yaourt is not installed" do args = ['--noconfirm', '--needed', '--noprogressbar', '--sync', resource[:name]] expect(provider).to receive(:pacman).at_least(:once).with(*args).and_return('') provider.install end it "should call yaourt to install the right package quietly when yaourt is installed" do without_partial_double_verification do allow(described_class).to receive(:yaourt?).and_return(true) args = ['--noconfirm', '--needed', '--noprogressbar', '--sync', resource[:name]] expect(provider).to receive(:yaourt).at_least(:once).with(*args).and_return('') provider.install end end it "should raise an Puppet::Error if the installation failed" do allow(executor).to receive(:execute).and_return("") expect(provider).to receive(:query).and_return(nil) expect { provider.install }.to raise_exception(Puppet::Error, /Could not find package/) end it "should raise an Puppet::Error when trying to install a group and allow_virtual is false" do allow(described_class).to receive(:group?).and_return(true) resource[:allow_virtual] = false expect { provider.install }.to raise_error(Puppet::Error, /Refusing to install package group/) end it "should not raise an Puppet::Error when trying to install a group and allow_virtual is true" do allow(described_class).to receive(:group?).and_return(true) resource[:allow_virtual] = true allow(executor).to receive(:execute).and_return("") provider.install end describe "and install_options are given" do before do resource[:install_options] = ['-x', {'--arg' => 'value'}] end it "should call pacman to install the right package quietly when yaourt is not installed" do args = ['--noconfirm', '--needed', '--noprogressbar', '-x', '--arg=value', '--sync', resource[:name]] expect(provider).to receive(:pacman).at_least(:once).with(*args).and_return('') provider.install end it "should call yaourt to install the right package quietly when yaourt is installed" do without_partial_double_verification do expect(described_class).to receive(:yaourt?).and_return(true) args = ['--noconfirm', '--needed', '--noprogressbar', '-x', '--arg=value', '--sync', resource[:name]] expect(provider).to receive(:yaourt).at_least(:once).with(*args).and_return('') provider.install end end end context "when :source is specified" do let(:install_seq) { sequence("install") } context "recognizable by pacman" do %w{ /some/package/file http://some.package.in/the/air ftp://some.package.in/the/air }.each do |source| it "should install #{source} directly" do resource[:source] = source expect(executor).to receive(:execute). with(include("--update") & include(source), no_extra_options). ordered. and_return("") provider.install end end end context "as a file:// URL" do let(:actual_file_path) { "/some/package/file" } before do resource[:source] = "file:///some/package/file" end it "should install from the path segment of the URL" do expect(executor).to receive(:execute). with(include("--update") & include(actual_file_path), no_extra_options). ordered. and_return("") provider.install end end context "as a puppet URL" do before do resource[:source] = "puppet://server/whatever" end it "should fail" do expect { provider.install }.to raise_error(Puppet::Error, /puppet:\/\/ URL is not supported/) end end context "as an unsupported URL scheme" do before do resource[:source] = "blah://foo.com" end it "should fail" do expect { provider.install }.to raise_error(Puppet::Error, /Source blah:\/\/foo\.com is not supported/) end end end end describe "when updating" do it "should call install" do expect(provider).to receive(:install).and_return("install return value") expect(provider.update).to eq("install return value") end end describe "when purging" do it "should call pacman to remove the right package and configs quietly" do args = ["/usr/bin/pacman", "--noconfirm", "--noprogressbar", "--remove", "--nosave", resource[:name]] expect(executor).to receive(:execute).with(args, no_extra_options).and_return("") provider.purge end end describe "when uninstalling" do it "should call pacman to remove the right package quietly" do args = ["/usr/bin/pacman", "--noconfirm", "--noprogressbar", "--remove", resource[:name]] expect(executor).to receive(:execute).with(args, no_extra_options).and_return("") provider.uninstall end it "should call yaourt to remove the right package quietly" do without_partial_double_verification do allow(described_class).to receive(:yaourt?).and_return(true) args = ["--noconfirm", "--noprogressbar", "--remove", resource[:name]] expect(provider).to receive(:yaourt).with(*args) provider.uninstall end end it "adds any uninstall_options" do resource[:uninstall_options] = ['-x', {'--arg' => 'value'}] args = ["/usr/bin/pacman", "--noconfirm", "--noprogressbar", "-x", "--arg=value", "--remove", resource[:name]] expect(executor).to receive(:execute).with(args, no_extra_options).and_return("") provider.uninstall end it "should recursively remove packages when given a package group" do allow(described_class).to receive(:group?).and_return(true) args = ["/usr/bin/pacman", "--noconfirm", "--noprogressbar", "--remove", "--recursive", resource[:name]] expect(executor).to receive(:execute).with(args, no_extra_options).and_return("") provider.uninstall end end describe "when querying" do it "should query pacman" do expect(executor).to receive(:execpipe).with(["/usr/bin/pacman", '--query']) expect(executor).to receive(:execpipe).with(["/usr/bin/pacman", '--sync', '-gg', 'package']) provider.query end it "should return the version" do expect(executor).to receive(:execpipe). with(["/usr/bin/pacman", "--query"]).and_yield(<<EOF) otherpackage 1.2.3.4 package 1.01.3-2 yetanotherpackage 1.2.3.4 EOF expect(executor).to receive(:execpipe).with(['/usr/bin/pacman', '--sync', '-gg', 'package']).and_yield('') expect(provider.query).to eq({ :name => 'package', :ensure => '1.01.3-2', :provider => :pacman, }) end it "should return a hash indicating that the package is missing" do expect(executor).to receive(:execpipe).twice.and_yield("") expect(provider.query).to be_nil end it "should raise an error if execpipe fails" do expect(executor).to receive(:execpipe).and_raise(Puppet::ExecutionFailure.new("ERROR!")) expect { provider.query }.to raise_error(RuntimeError) end describe 'when querying a group' do before :each do expect(executor).to receive(:execpipe).with(['/usr/bin/pacman', '--query']).and_yield('foo 1.2.3') expect(executor).to receive(:execpipe).with(['/usr/bin/pacman', '--sync', '-gg', 'package']).and_yield('package foo') end it 'should warn when allow_virtual is false' do resource[:allow_virtual] = false expect(provider).to receive(:warning) provider.query end it 'should not warn allow_virtual is true' do resource[:allow_virtual] = true expect(described_class).not_to receive(:warning) provider.query end end end describe "when determining instances" do it "should retrieve installed packages and groups" do expect(described_class).to receive(:execpipe).with(["/usr/bin/pacman", '--query']) expect(described_class).to receive(:execpipe).with(["/usr/bin/pacman", '--sync', '-gg']) described_class.instances end it "should return installed packages" do expect(described_class).to receive(:execpipe).with(["/usr/bin/pacman", '--query']).and_yield(StringIO.new("package1 1.23-4\npackage2 2.00\n")) expect(described_class).to receive(:execpipe).with(["/usr/bin/pacman", '--sync', '-gg']).and_yield("") instances = described_class.instances expect(instances.length).to eq(2) expect(instances[0].properties).to eq({ :provider => :pacman, :ensure => '1.23-4', :name => 'package1' }) expect(instances[1].properties).to eq({ :provider => :pacman, :ensure => '2.00', :name => 'package2' }) end it "should return completely installed groups with a virtual version together with packages" do expect(described_class).to receive(:execpipe).with(["/usr/bin/pacman", '--query']).and_yield(<<EOF) package1 1.00 package2 1.00 EOF expect(described_class).to receive(:execpipe).with(["/usr/bin/pacman", '--sync', '-gg']).and_yield(<<EOF) group1 package1 group1 package2 EOF instances = described_class.instances expect(instances.length).to eq(3) expect(instances[0].properties).to eq({ :provider => :pacman, :ensure => '1.00', :name => 'package1' }) expect(instances[1].properties).to eq({ :provider => :pacman, :ensure => '1.00', :name => 'package2' }) expect(instances[2].properties).to eq({ :provider => :pacman, :ensure => 'package1 1.00, package2 1.00', :name => 'group1' }) end it "should not return partially installed packages" do expect(described_class).to receive(:execpipe).with(["/usr/bin/pacman", '--query']).and_yield(<<EOF) package1 1.00 EOF expect(described_class).to receive(:execpipe).with(["/usr/bin/pacman", '--sync', '-gg']).and_yield(<<EOF) group1 package1 group1 package2 EOF instances = described_class.instances expect(instances.length).to eq(1) expect(instances[0].properties).to eq({ :provider => :pacman, :ensure => '1.00', :name => 'package1' }) end it 'should sort package names for installed groups' do expect(described_class).to receive(:execpipe).with(['/usr/bin/pacman', '--sync', '-gg', 'group1']).and_yield(<<EOF) group1 aa group1 b group1 a EOF package_versions= { 'a' => '1', 'aa' => '1', 'b' => '1', } virtual_group_version = described_class.get_installed_groups(package_versions, 'group1') expect(virtual_group_version).to eq({ 'group1' => 'a 1, aa 1, b 1' }) end it "should return nil on error" do expect(described_class).to receive(:execpipe).and_raise(Puppet::ExecutionFailure.new("ERROR!")) expect { described_class.instances }.to raise_error(RuntimeError) end it "should warn on invalid input" do expect(described_class).to receive(:execpipe).twice.and_yield(StringIO.new("blah")) expect(described_class).to receive(:warning).with("Failed to match line 'blah'") expect(described_class.instances).to eq([]) end end describe "when determining the latest version" do it "should get query pacman for the latest version" do expect(executor).to receive(:execute). ordered. with(['/usr/bin/pacman', '--sync', '--print', '--print-format', '%v', resource[:name]], no_extra_options). and_return("") provider.latest end it "should return the version number from pacman" do expect(executor).to receive(:execute).at_least(:once).and_return("1.00.2-3\n") expect(provider.latest).to eq("1.00.2-3") end it "should return a virtual group version when resource is a package group" do allow(described_class).to receive(:group?).and_return(true) expect(executor).to receive(:execute).with(['/usr/bin/pacman', '--sync', '--print', '--print-format', '%n %v', resource[:name]], no_extra_options).ordered. and_return(<<EOF) package2 1.0.1 package1 1.0.0 EOF expect(provider.latest).to eq('package1 1.0.0, package2 1.0.1') end end describe 'when determining if a resource is a group' do before do allow(described_class).to receive(:group?).and_call_original end it 'should return false on non-zero pacman exit' do allow(executor).to receive(:execute).with(['/usr/bin/pacman', '--sync', '--groups', 'git'], {:failonfail => true, :combine => true, :custom_environment => {}}).and_raise(Puppet::ExecutionFailure, 'error') expect(described_class.group?('git')).to eq(false) end it 'should return false on empty pacman output' do allow(executor).to receive(:execute).with(['/usr/bin/pacman', '--sync', '--groups', 'git'], {:failonfail => true, :combine => true, :custom_environment => {}}).and_return('') expect(described_class.group?('git')).to eq(false) end it 'should return true on non-empty pacman output' do allow(executor).to receive(:execute).with(['/usr/bin/pacman', '--sync', '--groups', 'vim-plugins'], {:failonfail => true, :combine => true, :custom_environment => {}}).and_return('vim-plugins vim-a') expect(described_class.group?('vim-plugins')).to eq(true) end end describe 'when querying installed groups' do let(:installed_packages) { {'package1' => '1.0', 'package2' => '2.0', 'package3' => '3.0'} } let(:groups) { [['foo package1'], ['foo package2'], ['bar package3'], ['bar package4'], ['baz package5']] } it 'should raise an error on non-zero pacman exit without a filter' do expect(executor).to receive(:open).with('| /usr/bin/pacman --sync -gg 2>&1').and_return('error!') expect(Puppet::Util::Execution).to receive(:exitstatus).and_return(1) expect { described_class.get_installed_groups(installed_packages) }.to raise_error(Puppet::ExecutionFailure, 'error!') end it 'should return empty groups on non-zero pacman exit with a filter' do expect(executor).to receive(:open).with('| /usr/bin/pacman --sync -gg git 2>&1').and_return('') expect(Puppet::Util::Execution).to receive(:exitstatus).and_return(1) expect(described_class.get_installed_groups(installed_packages, 'git')).to eq({}) end it 'should return empty groups on empty pacman output' do pipe = double() expect(pipe).to receive(:each_line) expect(executor).to receive(:open).with('| /usr/bin/pacman --sync -gg 2>&1').and_yield(pipe).and_return('') expect(Puppet::Util::Execution).to receive(:exitstatus).and_return(0) expect(described_class.get_installed_groups(installed_packages)).to eq({}) end it 'should return groups on non-empty pacman output' do pipe = double() pipe_expectation = receive(:each_line) groups.each { |group| pipe_expectation = pipe_expectation.and_yield(*group) } expect(pipe).to pipe_expectation expect(executor).to receive(:open).with('| /usr/bin/pacman --sync -gg 2>&1').and_yield(pipe).and_return('') expect(Puppet::Util::Execution).to receive(:exitstatus).and_return(0) expect(described_class.get_installed_groups(installed_packages)).to eq({'foo' => 'package1 1.0, package2 2.0'}) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/provider/package/nim_spec.rb
spec/unit/provider/package/nim_spec.rb
require 'spec_helper' describe Puppet::Type.type(:package).provider(:nim) do before(:each) do @resource = double('resource') # A catch all; no parameters set allow(@resource).to receive(:[]).and_return(nil) # But set name and source allow(@resource).to receive(:[]).with(:name).and_return("mypackage.foo") allow(@resource).to receive(:[]).with(:source).and_return("mysource") allow(@resource).to receive(:[]).with(:ensure).and_return(:installed) @provider = subject() @provider.resource = @resource end it "should have an install method" do @provider = subject() expect(@provider).to respond_to(:install) end let(:bff_showres_output) { Puppet::Util::Execution::ProcessOutput.new(<<END, 0) mypackage.foo ALL @@I:mypackage.foo _all_filesets @ 1.2.3.1 MyPackage Runtime Environment @@I:mypackage.foo 1.2.3.1 + 1.2.3.4 MyPackage Runtime Environment @@I:mypackage.foo 1.2.3.4 + 1.2.3.8 MyPackage Runtime Environment @@I:mypackage.foo 1.2.3.8 END } let(:rpm_showres_output) { Puppet::Util::Execution::ProcessOutput.new(<<END, 0) mypackage.foo ALL @@R:mypackage.foo _all_filesets @@R:mypackage.foo-1.2.3-1 1.2.3-1 @@R:mypackage.foo-1.2.3-4 1.2.3-4 @@R:mypackage.foo-1.2.3-8 1.2.3-8 END } context "when installing" do it "should install a package" do allow(@resource).to receive(:should).with(:ensure).and_return(:installed) expect(Puppet::Util::Execution).to receive(:execute).with("/usr/sbin/nimclient -o showres -a resource=mysource |/usr/bin/grep -p -E 'mypackage\\.foo'").and_return(bff_showres_output) expect(@provider).to receive(:nimclient).with("-o", "cust", "-a", "installp_flags=acgwXY", "-a", "lpp_source=mysource", "-a", "filesets=mypackage.foo 1.2.3.8") @provider.install end context "when installing versioned packages" do it "should fail if the package is not available on the lpp source" do nimclient_showres_output = "" allow(@resource).to receive(:should).with(:ensure).and_return("1.2.3.4") expect(Puppet::Util::Execution).to receive(:execute).with("/usr/sbin/nimclient -o showres -a resource=mysource |/usr/bin/grep -p -E 'mypackage\\.foo( |-)1\\.2\\.3\\.4'").and_return(nimclient_showres_output) expect { @provider.install }.to raise_error(Puppet::Error, "Unable to find package 'mypackage.foo' with version '1.2.3.4' on lpp_source 'mysource'") end it "should succeed if a BFF/installp package is available on the lpp source" do allow(@resource).to receive(:should).with(:ensure).and_return("1.2.3.4") expect(Puppet::Util::Execution).to receive(:execute).with("/usr/sbin/nimclient -o showres -a resource=mysource |/usr/bin/grep -p -E 'mypackage\\.foo( |-)1\\.2\\.3\\.4'").and_return(bff_showres_output).ordered expect(@provider).to receive(:nimclient).with("-o", "cust", "-a", "installp_flags=acgwXY", "-a", "lpp_source=mysource", "-a", "filesets=mypackage.foo 1.2.3.4").ordered @provider.install end it "should fail if the specified version of a BFF package is superseded" do install_output = <<OUTPUT +-----------------------------------------------------------------------------+ Pre-installation Verification... +-----------------------------------------------------------------------------+ Verifying selections...done Verifying requisites...done Results... WARNINGS -------- Problems described in this section are not likely to be the source of any immediate or serious failures, but further actions may be necessary or desired. Already Installed ----------------- The number of selected filesets that are either already installed or effectively installed through superseding filesets is 1. See the summaries at the end of this installation for details. NOTE: Base level filesets may be reinstalled using the "Force" option (-F flag), or they may be removed, using the deinstall or "Remove Software Products" facility (-u flag), and then reinstalled. << End of Warning Section >> +-----------------------------------------------------------------------------+ BUILDDATE Verification ... +-----------------------------------------------------------------------------+ Verifying build dates...done FILESET STATISTICS ------------------ 1 Selected to be installed, of which: 1 Already installed (directly or via superseding filesets) ---- 0 Total to be installed Pre-installation Failure/Warning Summary ---------------------------------------- Name Level Pre-installation Failure/Warning ------------------------------------------------------------------------------- mypackage.foo 1.2.3.1 Already superseded by 1.2.3.4 OUTPUT allow(@resource).to receive(:should).with(:ensure).and_return("1.2.3.1") expect(Puppet::Util::Execution).to receive(:execute).with("/usr/sbin/nimclient -o showres -a resource=mysource |/usr/bin/grep -p -E 'mypackage\\.foo( |-)1\\.2\\.3\\.1'").and_return(bff_showres_output).ordered expect(@provider).to receive(:nimclient).with("-o", "cust", "-a", "installp_flags=acgwXY", "-a", "lpp_source=mysource", "-a", "filesets=mypackage.foo 1.2.3.1").and_return(install_output).ordered expect { @provider.install }.to raise_error(Puppet::Error, "NIM package provider is unable to downgrade packages") end it "should succeed if an RPM package is available on the lpp source" do allow(@resource).to receive(:should).with(:ensure).and_return("1.2.3-4") expect(Puppet::Util::Execution).to receive(:execute).with("/usr/sbin/nimclient -o showres -a resource=mysource |/usr/bin/grep -p -E 'mypackage\\.foo( |-)1\\.2\\.3\\-4'").and_return(rpm_showres_output).ordered expect(@provider).to receive(:nimclient).with("-o", "cust", "-a", "installp_flags=acgwXY", "-a", "lpp_source=mysource", "-a", "filesets=mypackage.foo-1.2.3-4").ordered @provider.install end end it "should fail if the specified version of a RPM package is superseded" do install_output = <<OUTPUT Validating RPM package selections ... Please wait... +-----------------------------------------------------------------------------+ RPM Error Summary: +-----------------------------------------------------------------------------+ The following RPM packages were requested for installation but they are already installed or superseded by a package installed at a higher level: mypackage.foo-1.2.3-1 is superseded by mypackage.foo-1.2.3-4 OUTPUT allow(@resource).to receive(:should).with(:ensure).and_return("1.2.3-1") expect(Puppet::Util::Execution).to receive(:execute).with("/usr/sbin/nimclient -o showres -a resource=mysource |/usr/bin/grep -p -E 'mypackage\\.foo( |-)1\\.2\\.3\\-1'").and_return(rpm_showres_output) expect(@provider).to receive(:nimclient).with("-o", "cust", "-a", "installp_flags=acgwXY", "-a", "lpp_source=mysource", "-a", "filesets=mypackage.foo-1.2.3-1").and_return(install_output) expect { @provider.install }.to raise_error(Puppet::Error, "NIM package provider is unable to downgrade packages") end end context "when uninstalling" do it "should call installp to uninstall a bff package" do expect(@provider).to receive(:lslpp).with("-qLc", "mypackage.foo").and_return("#bos.atm:bos.atm.atmle:7.1.2.0: : :C: :ATM LAN Emulation Client Support : : : : : : :0:0:/:1241") expect(@provider).to receive(:installp).with("-gu", "mypackage.foo") expect(@provider.class).to receive(:pkglist).with({:pkgname => 'mypackage.foo'}).and_return(nil) @provider.uninstall end it "should call rpm to uninstall an rpm package" do expect(@provider).to receive(:lslpp).with("-qLc", "mypackage.foo").and_return("cdrecord:cdrecord-1.9-6:1.9-6: : :C:R:A command line CD/DVD recording program.: :/bin/rpm -e cdrecord: : : : :0: :/opt/freeware:Wed Jun 29 09:41:32 PDT 2005") expect(@provider).to receive(:rpm).with("-e", "mypackage.foo") expect(@provider.class).to receive(:pkglist).with({:pkgname => 'mypackage.foo'}).and_return(nil) @provider.uninstall end end context "when parsing nimclient showres output" do describe "#parse_showres_output" do it "should be able to parse installp/BFF package listings" do packages = subject.send(:parse_showres_output, bff_showres_output) expect(Set.new(packages.keys)).to eq(Set.new(['mypackage.foo'])) versions = packages['mypackage.foo'] ['1.2.3.1', '1.2.3.4', '1.2.3.8'].each do |version| expect(versions.has_key?(version)).to eq(true) expect(versions[version]).to eq(:installp) end end it "should be able to parse RPM package listings" do packages = subject.send(:parse_showres_output, rpm_showres_output) expect(Set.new(packages.keys)).to eq(Set.new(['mypackage.foo'])) versions = packages['mypackage.foo'] ['1.2.3-1', '1.2.3-4', '1.2.3-8'].each do |version| expect(versions.has_key?(version)).to eq(true) expect(versions[version]).to eq(:rpm) end end it "should be able to parse RPM package listings with letters in version" do showres_output = <<END cairo ALL @@R:cairo _all_filesets @@R:cairo-1.14.6-2waixX11 1.14.6-2waixX11 END packages = subject.send(:parse_showres_output, showres_output) expect(Set.new(packages.keys)).to eq(Set.new(['cairo'])) versions = packages['cairo'] expect(versions.has_key?('1.14.6-2waixX11')).to eq(true) expect(versions['1.14.6-2waixX11']).to eq(:rpm) end it "should raise error when parsing invalid RPM package listings" do showres_output = <<END cairo ALL @@R:cairo _all_filesets @@R:cairo-invalid_version invalid_version END expect{ subject.send(:parse_showres_output, showres_output) }.to raise_error(Puppet::Error, /Unable to parse output from nimclient showres: package string does not match expected rpm package string format/) end end context "#determine_latest_version" do context "when there are multiple versions" do it "should return the latest version" do expect(subject.send(:determine_latest_version, rpm_showres_output, 'mypackage.foo')).to eq([:rpm, '1.2.3-8']) end end context "when there is only one version" do it "should return the type specifier and `nil` for the version number" do nimclient_showres_output = <<END mypackage.foo ALL @@R:mypackage.foo _all_filesets @@R:mypackage.foo-1.2.3-4 1.2.3-4 END expect(subject.send(:determine_latest_version, nimclient_showres_output, 'mypackage.foo')).to eq([:rpm, nil]) end end end context "#determine_package_type" do it "should return :rpm for rpm packages" do expect(subject.send(:determine_package_type, rpm_showres_output, 'mypackage.foo', '1.2.3-4')).to eq(:rpm) end it "should return :installp for installp/bff packages" do expect(subject.send(:determine_package_type, bff_showres_output, 'mypackage.foo', '1.2.3.4')).to eq(:installp) end it "should return :installp for security updates" do nimclient_showres_output = <<END bos.net ALL @@S:bos.net _all_filesets + 7.2.0.1 TCP/IP ntp Applications @@S:bos.net.tcp.ntp 7.2.0.1 + 7.2.0.2 TCP/IP ntp Applications @@S:bos.net.tcp.ntp 7.2.0.2 END expect(subject.send(:determine_package_type, nimclient_showres_output, 'bos.net.tcp.ntp', '7.2.0.2')).to eq(:installp) end it "should raise error when invalid header format is given" do nimclient_showres_output = <<END bos.net ALL @@INVALID_TYPE:bos.net _all_filesets + 7.2.0.1 TCP/IP ntp Applications @@INVALID_TYPE:bos.net.tcp.ntp 7.2.0.1 + 7.2.0.2 TCP/IP ntp Applications @@INVALID_TYPE:bos.net.tcp.ntp 7.2.0.2 END expect{ subject.send(:determine_package_type, nimclient_showres_output, 'bos.net.tcp.ntp', '7.2.0.2') }.to raise_error( Puppet::Error, /Unable to parse output from nimclient showres: line does not match expected package header format/) end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/provider/package/xbps_spec.rb
spec/unit/provider/package/xbps_spec.rb
require "spec_helper" require "stringio" describe Puppet::Type.type(:package).provider(:xbps) do before do @resource = Puppet::Type.type(:package).new(name: "gcc", provider: "xbps") @provider = described_class.new(@resource) @resolver = Puppet::Util allow(described_class).to receive(:which).with("/usr/bin/xbps-install").and_return("/usr/bin/xbps-install") allow(described_class).to receive(:which).with("/usr/bin/xbps-remove").and_return("/usr/bin/xbps-remove") allow(described_class).to receive(:which).with("/usr/bin/xbps-query").and_return("/usr/bin/xbps-query") end it { is_expected.to be_installable } it { is_expected.to be_uninstallable } it { is_expected.to be_install_options } it { is_expected.to be_uninstall_options } it { is_expected.to be_upgradeable } it { is_expected.to be_holdable } it { is_expected.to be_virtual_packages } it "should be the default provider on 'os.name' => Void" do expect(Facter).to receive(:value).with('os.name').and_return("Void") expect(described_class.default?).to be_truthy end describe "when determining instances" do it "should return installed packages" do sample_installed_packages = %{ ii gcc-12.2.0_1 GNU Compiler Collection ii ruby-devel-3.1.3_1 Ruby programming language - development files } expect(described_class).to receive(:execpipe).with(["/usr/bin/xbps-query", "-l"]) .and_yield(StringIO.new(sample_installed_packages)) instances = described_class.instances expect(instances.length).to eq(2) expect(instances[0].properties).to eq({ :name => "gcc", :ensure => "12.2.0_1", :provider => :xbps, }) expect(instances[1].properties).to eq({ :name => "ruby-devel", :ensure => "3.1.3_1", :provider => :xbps, }) end it "should warn on invalid input" do expect(described_class).to receive(:execpipe).and_yield(StringIO.new("blah")) expect(described_class).to receive(:warning).with('Failed to match line \'blah\'') expect(described_class.instances).to eq([]) end end describe "when installing" do it "and install_options are given it should call xbps to install the package quietly with the passed options" do @resource[:install_options] = ["-x", { "--arg" => "value" }] args = ["-S", "-y", "-x", "--arg=value", @resource[:name]] expect(@provider).to receive(:xbps_install).with(*args).and_return("") expect(described_class).to receive(:execpipe).with(["/usr/bin/xbps-query", "-l"]) @provider.install end it "and source is given it should call xbps to install the package from the source as repository" do @resource[:source] = "/path/to/xbps/containing/directory" args = ["-S", "-y", "--repository=#{@resource[:source]}", @resource[:name]] expect(@provider).to receive(:xbps_install).at_least(:once).with(*args).and_return("") expect(described_class).to receive(:execpipe).with(["/usr/bin/xbps-query", "-l"]) @provider.install end end describe "when updating" do it "should call install" do expect(@provider).to receive(:install).and_return("ran install") expect(@provider.update).to eq("ran install") end end describe "when uninstalling" do it "should call xbps to remove the right package quietly" do args = ["-R", "-y", @resource[:name]] expect(@provider).to receive(:xbps_remove).with(*args).and_return("") @provider.uninstall end it "adds any uninstall_options" do @resource[:uninstall_options] = ["-x", { "--arg" => "value" }] args = ["-R", "-y", "-x", "--arg=value", @resource[:name]] expect(@provider).to receive(:xbps_remove).with(*args).and_return("") @provider.uninstall end end describe "when determining the latest version" do it "should return the latest version number of the package" do @resource[:name] = "ruby-devel" expect(described_class).to receive(:execpipe).with(["/usr/bin/xbps-query", "-l"]).and_yield(StringIO.new(%{ ii ruby-devel-3.1.3_1 Ruby programming language - development files })) expect(@provider.latest).to eq("3.1.3_1") end end describe "when querying" do it "should call self.instances and return nil if the package is missing" do expect(described_class).to receive(:instances) .and_return([]) expect(@provider.query).to be_nil end it "should get real-package in case allow_virtual is true" do @resource[:name] = "nodejs-runtime" @resource[:allow_virtual] = true expect(described_class).to receive(:execpipe).with(["/usr/bin/xbps-query", "-l"]) .and_yield(StringIO.new("")) args = ["-Rs", @resource[:name]] expect(@provider).to receive(:xbps_query).with(*args).and_return(%{ [*] nodejs-16.19.0_1 Evented I/O for V8 javascript [-] nodejs-lts-12.22.10_2 Evented I/O for V8 javascript' }) expect(@provider.query).to eq({ :name => "nodejs", :ensure => "16.19.0_1", :provider => :xbps, }) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/provider/package/portage_spec.rb
spec/unit/provider/package/portage_spec.rb
require 'spec_helper' describe Puppet::Type.type(:package).provider(:portage) do before do packagename = "sl" @resource = double('resource', :should => true) allow(@resource).to receive(:[]).with(:name).and_return(packagename) allow(@resource).to receive(:[]).with(:install_options).and_return(['--foo', '--bar']) allow(@resource).to receive(:[]).with(:uninstall_options).and_return(['--foo', { '--bar' => 'baz', '--baz' => 'foo' }]) unslotted_packagename = "dev-lang/ruby" @unslotted_resource = double('resource', :should => true) allow(@unslotted_resource).to receive(:should).with(:ensure).and_return(:latest) allow(@unslotted_resource).to receive(:[]).with(:name).and_return(unslotted_packagename) allow(@unslotted_resource).to receive(:[]).with(:install_options).and_return([]) slotted_packagename = "dev-lang/ruby:2.1" @slotted_resource = double('resource', :should => true) allow(@slotted_resource).to receive(:[]).with(:name).and_return(slotted_packagename) allow(@slotted_resource).to receive(:[]).with(:install_options).and_return(['--foo', { '--bar' => 'baz', '--baz' => 'foo' }]) versioned_packagename = "=dev-lang/ruby-1.9.3" @versioned_resource = double('resource', :should => true) allow(@versioned_resource).to receive(:[]).with(:name).and_return(versioned_packagename) allow(@versioned_resource).to receive(:[]).with(:install_options).and_return([]) allow(@versioned_resource).to receive(:[]).with(:uninstall_options).and_return([]) versioned_slotted_packagename = "=dev-lang/ruby-1.9.3:1.9" @versioned_slotted_resource = double('resource', :should => true) allow(@versioned_slotted_resource).to receive(:[]).with(:name).and_return(versioned_slotted_packagename) allow(@versioned_slotted_resource).to receive(:[]).with(:install_options).and_return([]) allow(@versioned_slotted_resource).to receive(:[]).with(:uninstall_options).and_return([]) set_packagename = "@system" @set_resource = double('resource', :should => true) allow(@set_resource).to receive(:[]).with(:name).and_return(set_packagename) allow(@set_resource).to receive(:[]).with(:install_options).and_return([]) package_sets = "system\nworld\n" @provider = described_class.new(@resource) allow(@provider).to receive(:qatom).and_return({:category=>nil, :pn=>"sl", :pv=>nil, :pr=>nil, :slot=>nil, :pfx=>nil, :sfx=>nil}) allow(@provider.class).to receive(:emerge).with('--list-sets').and_return(package_sets) @unslotted_provider = described_class.new(@unslotted_resource) allow(@unslotted_provider).to receive(:qatom).and_return({:category=>"dev-lang", :pn=>"ruby", :pv=>nil, :pr=>nil, :slot=>nil, :pfx=>nil, :sfx=>nil}) allow(@unslotted_provider.class).to receive(:emerge).with('--list-sets').and_return(package_sets) @slotted_provider = described_class.new(@slotted_resource) allow(@slotted_provider).to receive(:qatom).and_return({:category=>"dev-lang", :pn=>"ruby", :pv=>nil, :pr=>nil, :slot=>"2.1", :pfx=>nil, :sfx=>nil}) allow(@slotted_provider.class).to receive(:emerge).with('--list-sets').and_return(package_sets) @versioned_provider = described_class.new(@versioned_resource) allow(@versioned_provider).to receive(:qatom).and_return({:category=>"dev-lang", :pn=>"ruby", :pv=>"1.9.3", :pr=>nil, :slot=>nil, :pfx=>"=", :sfx=>nil}) allow(@versioned_provider.class).to receive(:emerge).with('--list-sets').and_return(package_sets) @versioned_slotted_provider = described_class.new(@versioned_slotted_resource) allow(@versioned_slotted_provider).to receive(:qatom).and_return({:category=>"dev-lang", :pn=>"ruby", :pv=>"1.9.3", :pr=>nil, :slot=>"1.9", :pfx=>"=", :sfx=>nil}) allow(@versioned_slotted_provider.class).to receive(:emerge).with('--list-sets').and_return(package_sets) @set_provider = described_class.new(@set_resource) allow(@set_provider).to receive(:qatom).and_return({:category=>nil, :pn=>"@system", :pv=>nil, :pr=>nil, :slot=>nil, :pfx=>nil, :sfx=>nil}) allow(@set_provider.class).to receive(:emerge).with('--list-sets').and_return(package_sets) portage = double(:executable => "foo",:execute => true) allow(Puppet::Provider::CommandDefiner).to receive(:define).and_return(portage) @nomatch_result = "" @match_result = "app-misc sl [] [5.02] [] [] [5.02] [5.02:0] http://www.tkl.iis.u-tokyo.ac.jp/~toyoda/index_e.html https://github.com/mtoyoda/sl/ sophisticated graphical program which corrects your miss typing\n" @slot_match_result = "dev-lang ruby [2.1.8] [2.1.9] [2.1.8:2.1] [2.1.8] [2.1.9,,,,,,,] [2.1.9:2.1] http://www.ruby-lang.org/ An object-oriented scripting language\n" end it "is versionable" do expect(described_class).to be_versionable end it "is reinstallable" do expect(described_class).to be_reinstallable end it "should be the default provider on 'os.family' => Gentoo" do expect(Facter).to receive(:value).with('os.family').and_return("Gentoo") expect(described_class.default?).to be_truthy end it 'should support string install options' do expect(@provider).to receive(:emerge).with('--foo', '--bar', @resource[:name]) @provider.install end it 'should support updating' do expect(@unslotted_provider).to receive(:emerge).with('--update', @unslotted_resource[:name]) @unslotted_provider.install end it 'should support hash install options' do expect(@slotted_provider).to receive(:emerge).with('--foo', '--bar=baz', '--baz=foo', @slotted_resource[:name]) @slotted_provider.install end it 'should support hash uninstall options' do expect(@provider).to receive(:emerge).with('--rage-clean', '--foo', '--bar=baz', '--baz=foo', @resource[:name]) @provider.uninstall end it 'should support install of specific version' do expect(@versioned_provider).to receive(:emerge).with(@versioned_resource[:name]) @versioned_provider.install end it 'should support install of specific version and slot' do expect(@versioned_slotted_provider).to receive(:emerge).with(@versioned_slotted_resource[:name]) @versioned_slotted_provider.install end it 'should support uninstall of specific version' do expect(@versioned_provider).to receive(:emerge).with('--rage-clean', @versioned_resource[:name]) @versioned_provider.uninstall end it 'should support uninstall of specific version and slot' do expect(@versioned_slotted_provider).to receive(:emerge).with('--rage-clean', @versioned_slotted_resource[:name]) @versioned_slotted_provider.uninstall end it "uses :emerge to install packages" do expect(@provider).to receive(:emerge) @provider.install end it "uses query to find the latest package" do expect(@provider).to receive(:query).and_return({:versions_available => "myversion"}) @provider.latest end it "uses eix to search the lastest version of a package" do allow(@provider).to receive(:update_eix) expect(@provider).to receive(:eix).and_return(StringIO.new(@match_result)) @provider.query end it "allows to emerge package sets" do expect(@set_provider).to receive(:emerge).with(@set_resource[:name]) @set_provider.install end it "allows to emerge and update package sets" do allow(@set_resource).to receive(:should).with(:ensure).and_return(:latest) expect(@set_provider).to receive(:emerge).with('--update', @set_resource[:name]) @set_provider.install end it "eix arguments must not include --stable" do expect(@provider.class.eix_search_arguments).not_to include("--stable") end it "eix arguments must not include --exact" do expect(@provider.class.eix_search_arguments).not_to include("--exact") end it "query uses default arguments" do allow(@provider).to receive(:update_eix) expect(@provider).to receive(:eix).and_return(StringIO.new(@match_result)) expect(@provider.class).to receive(:eix_search_arguments).and_return([]) @provider.query end it "can handle search output with empty square brackets" do allow(@provider).to receive(:update_eix) expect(@provider).to receive(:eix).and_return(StringIO.new(@match_result)) expect(@provider.query[:name]).to eq("sl") end it "can provide the package name without slot" do expect(@unslotted_provider.qatom[:slot]).to be_nil end it "can extract the slot from the package name" do expect(@slotted_provider.qatom[:slot]).to eq('2.1') end it "returns nil for as the slot when no slot is specified" do expect(@provider.qatom[:slot]).to be_nil end it "provides correct package atoms for unslotted packages" do expect(@versioned_provider.qatom[:pv]).to eq('1.9.3') end it "provides correct package atoms for slotted packages" do expect(@versioned_slotted_provider.qatom[:pfx]).to eq('=') expect(@versioned_slotted_provider.qatom[:category]).to eq('dev-lang') expect(@versioned_slotted_provider.qatom[:pn]).to eq('ruby') expect(@versioned_slotted_provider.qatom[:pv]).to eq('1.9.3') expect(@versioned_slotted_provider.qatom[:slot]).to eq('1.9') end it "can handle search output with slots for unslotted packages" do allow(@unslotted_provider).to receive(:update_eix) expect(@unslotted_provider).to receive(:eix).and_return(StringIO.new(@slot_match_result)) result = @unslotted_provider.query expect(result[:name]).to eq('ruby') expect(result[:ensure]).to eq('2.1.8') expect(result[:version_available]).to eq('2.1.9') end it "can handle search output with slots" do allow(@slotted_provider).to receive(:update_eix) expect(@slotted_provider).to receive(:eix).and_return(StringIO.new(@slot_match_result)) result = @slotted_provider.query expect(result[:name]).to eq('ruby') expect(result[:ensure]).to eq('2.1.8') expect(result[:version_available]).to eq('2.1.9') end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/provider/package/gem_spec.rb
spec/unit/provider/package/gem_spec.rb
require 'spec_helper' context Puppet::Type.type(:package).provider(:gem) do it { is_expected.to be_installable } it { is_expected.to be_uninstallable } it { is_expected.to be_upgradeable } it { is_expected.to be_versionable } it { is_expected.to be_install_options } it { is_expected.to be_targetable } let(:provider_gem_cmd) { '/provider/gem' } let(:execute_options) { {:failonfail => true, :combine => true, :custom_environment => {"HOME"=>ENV["HOME"]}} } before do allow(Puppet::Util::Platform).to receive(:windows?).and_return(false) end context 'installing myresource' do let(:resource) do Puppet::Type.type(:package).new( :name => 'myresource', :ensure => :installed ) end let(:provider) do provider = described_class.new provider.resource = resource provider end before :each do resource.provider = provider allow(described_class).to receive(:command).with(:gemcmd).and_return(provider_gem_cmd) end context "when installing" do before :each do allow(provider).to receive(:rubygem_version).and_return('1.9.9') end context 'on windows' do let(:path) do "C:\\Program Files\\Puppet Labs\\Puppet\\puppet\\bin;C:\\Program Files\\Puppet Labs\\Puppet\\bin;C:\\Ruby26-x64\\bin;C:\\Windows\\system32\\bin" end let(:expected_path) do "C:\\Program Files\\Puppet Labs\\Puppet\\bin;C:\\Ruby26-x64\\bin;C:\\Windows\\system32\\bin" end before do allow(Puppet::Util::Platform).to receive(:windows?).and_return(true) allow(ENV).to receive(:[]).and_call_original allow(ENV).to receive(:[]).with('PATH').and_return(path) allow(described_class).to receive(:validate_command).with(provider_gem_cmd) stub_const('::File::PATH_SEPARATOR', ';') end it 'removes puppet/bin from PATH' do expect(described_class).to receive(:execute) \ .with( anything, hash_including(custom_environment: hash_including(PATH: expected_path)) ) .and_return("") provider.install end end it "should use the path to the gem command" do allow(described_class).to receive(:validate_command).with(provider_gem_cmd) expect(described_class).to receive(:execute).with(be_a(Array), execute_options) { |args| expect(args[0]).to eq(provider_gem_cmd) }.and_return("") provider.install end it "should specify that the gem is being installed" do expect(described_class).to receive(:execute_gem_command).with(provider_gem_cmd, be_a(Array)) { |cmd, args| expect(args[0]).to eq("install") }.and_return("") provider.install end it "should specify that --rdoc should not be included when gem version is < 2.0.0" do expect(described_class).to receive(:execute_gem_command).with(provider_gem_cmd, be_a(Array)) { |cmd, args| expect(args[1]).to eq("--no-rdoc") }.and_return("") provider.install end it "should specify that --ri should not be included when gem version is < 2.0.0" do expect(described_class).to receive(:execute_gem_command).with(provider_gem_cmd, be_a(Array)) { |cmd, args| expect(args[2]).to eq("--no-ri") }.and_return("") provider.install end it "should specify that --document should not be included when gem version is >= 2.0.0" do allow(provider).to receive(:rubygem_version).and_return('2.0.0') expect(described_class).to receive(:execute_gem_command).with(provider_gem_cmd, be_a(Array)) { |cmd, args| expect(args[1]).to eq("--no-document") }.and_return("") provider.install end it "should specify the package name" do expect(described_class).to receive(:execute_gem_command).with(provider_gem_cmd, be_a(Array)) { |cmd, args| expect(args[3]).to eq("myresource") }.and_return("") provider.install end it "should not append install_options by default" do expect(described_class).to receive(:execute_gem_command).with(provider_gem_cmd, be_a(Array)) { |cmd, args| expect(args.length).to eq(4) }.and_return("") provider.install end it "should allow setting an install_options parameter" do resource[:install_options] = [ '--force', {'--bindir' => '/usr/bin' } ] expect(described_class).to receive(:execute_gem_command).with(provider_gem_cmd, be_a(Array)) do |cmd, args| expect(args[1]).to eq('--force') expect(args[2]).to eq('--bindir=/usr/bin') end.and_return("") provider.install end context "when a source is specified" do context "as a normal file" do it "should use the file name instead of the gem name" do resource[:source] = "/my/file" expect(described_class).to receive(:execute_gem_command).with(provider_gem_cmd, array_including("/my/file")).and_return("") provider.install end end context "as a file url" do it "should use the file name instead of the gem name" do resource[:source] = "file:///my/file" expect(described_class).to receive(:execute_gem_command).with(provider_gem_cmd, array_including("/my/file")).and_return("") provider.install end end context "as a puppet url" do it "should fail" do resource[:source] = "puppet://my/file" expect { provider.install }.to raise_error(Puppet::Error) end end context "as a non-file and non-puppet url" do it "should treat the source as a gem repository" do resource[:source] = "http://host/my/file" expect(described_class).to receive(:execute_gem_command).with(provider_gem_cmd, be_a(Array)) { |cmd, args| expect(args[3..5]).to eq(["--source", "http://host/my/file", "myresource"]) }.and_return("") provider.install end end context "as a windows path on windows", :if => Puppet::Util::Platform.windows? do it "should treat the source as a local path" do resource[:source] = "c:/this/is/a/path/to/a/gem.gem" expect(described_class).to receive(:execute_gem_command).with(provider_gem_cmd, array_including("c:/this/is/a/path/to/a/gem.gem")).and_return("") provider.install end end context "with an invalid uri" do it "should fail" do expect(URI).to receive(:parse).and_raise(ArgumentError) resource[:source] = "http:::::uppet:/:/my/file" expect { provider.install }.to raise_error(Puppet::Error) end end end end context "#latest" do it "should return a single value for 'latest'" do #gemlist is used for retrieving both local and remote version numbers, and there are cases # (particularly local) where it makes sense for it to return an array. That doesn't make # sense for '#latest', though. expect(provider.class).to receive(:gemlist).with({:command => provider_gem_cmd, :justme => 'myresource'}).and_return({ :name => 'myresource', :ensure => ["3.0"], :provider => :gem, }) expect(provider.latest).to eq("3.0") end it "should list from the specified source repository" do resource[:source] = "http://foo.bar.baz/gems" expect(provider.class).to receive(:gemlist). with({:command => provider_gem_cmd, :justme => 'myresource', :source => "http://foo.bar.baz/gems"}). and_return({ :name => 'myresource', :ensure => ["3.0"], :provider => :gem, }) expect(provider.latest).to eq("3.0") end end context "#instances" do before do allow(described_class).to receive(:command).with(:gemcmd).and_return(provider_gem_cmd) end it "should return an empty array when no gems installed" do expect(described_class).to receive(:execute_gem_command).with(provider_gem_cmd, %w{list --local}).and_return("\n") expect(described_class.instances).to eq([]) end it "should return ensure values as an array of installed versions" do expect(described_class).to receive(:execute_gem_command).with(provider_gem_cmd, %w{list --local}).and_return(<<-HEREDOC.gsub(/ /, '')) systemu (1.2.0) vagrant (0.8.7, 0.6.9) HEREDOC expect(described_class.instances.map {|p| p.properties}).to eq([ {:name => "systemu", :provider => :gem, :command => provider_gem_cmd, :ensure => ["1.2.0"]}, {:name => "vagrant", :provider => :gem, :command => provider_gem_cmd, :ensure => ["0.8.7", "0.6.9"]} ]) end it "should ignore platform specifications" do expect(described_class).to receive(:execute_gem_command).with(provider_gem_cmd, %w{list --local}).and_return(<<-HEREDOC.gsub(/ /, '')) systemu (1.2.0) nokogiri (1.6.1 ruby java x86-mingw32 x86-mswin32-60, 1.4.4.1 x86-mswin32) HEREDOC expect(described_class.instances.map {|p| p.properties}).to eq([ {:name => "systemu", :provider => :gem, :command => provider_gem_cmd, :ensure => ["1.2.0"]}, {:name => "nokogiri", :provider => :gem, :command => provider_gem_cmd, :ensure => ["1.6.1", "1.4.4.1"]} ]) end it "should not list 'default: ' text from rubygems''" do expect(described_class).to receive(:execute_gem_command).with(provider_gem_cmd, %w{list --local}).and_return(<<-HEREDOC.gsub(/ /, '')) bundler (1.16.1, default: 1.16.0, 1.15.1) HEREDOC expect(described_class.instances.map {|p| p.properties}).to eq([ {:name => "bundler", :provider => :gem, :command => provider_gem_cmd, :ensure => ["1.16.1", "1.16.0", "1.15.1"]} ]) end it "should not fail when an unmatched line is returned" do expect(described_class).to receive(:execute_gem_command).with(provider_gem_cmd, %w{list --local}).and_return(File.read(my_fixture('line-with-1.8.5-warning'))) expect(described_class.instances.map {|p| p.properties}). to eq([{:name=>"columnize", :provider=>:gem, :command => provider_gem_cmd, :ensure=>["0.3.2"]}, {:name=>"diff-lcs", :provider=>:gem, :command => provider_gem_cmd, :ensure=>["1.1.3"]}, {:name=>"metaclass", :provider=>:gem, :command => provider_gem_cmd, :ensure=>["0.0.1"]}, {:name=>"mocha", :provider=>:gem, :command => provider_gem_cmd, :ensure=>["0.10.5"]}, {:name=>"rake", :provider=>:gem, :command => provider_gem_cmd, :ensure=>["0.8.7"]}, {:name=>"rspec-core", :provider=>:gem, :command => provider_gem_cmd, :ensure=>["2.9.0"]}, {:name=>"rspec-expectations", :provider=>:gem, :command => provider_gem_cmd, :ensure=>["2.9.1"]}, {:name=>"rspec-mocks", :provider=>:gem, :command => provider_gem_cmd, :ensure=>["2.9.0"]}, {:name=>"rubygems-bundler", :provider=>:gem, :command => provider_gem_cmd, :ensure=>["0.9.0"]}, {:name=>"rvm", :provider=>:gem, :command => provider_gem_cmd, :ensure=>["1.11.3.3"]}]) end end context "listing gems" do context "searching for a single package" do it "searches for an exact match" do expect(described_class).to receive(:execute_gem_command).with(provider_gem_cmd, array_including('\Abundler\z')).and_return(File.read(my_fixture('gem-list-single-package'))) expected = {:name=>"bundler", :provider=>:gem, :ensure=>["1.6.2"]} expect(described_class.gemlist({:command => provider_gem_cmd, :justme => 'bundler'})).to eq(expected) end end end context 'insync?' do context 'for array of versions' do let(:is) { ['1.3.4', '3.6.1', '5.1.2'] } it 'returns true for ~> 1.3' do resource[:ensure] = '~> 1.3' expect(provider).to be_insync(is) end it 'returns false for ~> 2' do resource[:ensure] = '~> 2' expect(provider).to_not be_insync(is) end it 'returns true for > 4' do resource[:ensure] = '> 4' expect(provider).to be_insync(is) end it 'returns true for 3.6.1' do resource[:ensure] = '3.6.1' expect(provider).to be_insync(is) end it 'returns false for 3.6.2' do resource[:ensure] = '3.6.2' expect(provider).to_not be_insync(is) end it 'returns true for >2, <4' do resource[:ensure] = '>2, <4' expect(provider).to be_insync(is) end it 'returns false for >=4, <5' do resource[:ensure] = '>=4, <5' expect(provider).to_not be_insync(is) end it 'returns true for >2 <4' do resource[:ensure] = '>2 <4' expect(provider).to be_insync(is) end it 'returns false for >=4 <5' do resource[:ensure] = '>=4 <5' expect(provider).to_not be_insync(is) end end context 'for string version' do let(:is) { '1.3.4' } it 'returns true for ~> 1.3' do resource[:ensure] = '~> 1.3' expect(provider).to be_insync(is) end it 'returns false for ~> 2' do resource[:ensure] = '~> 2' expect(provider).to_not be_insync(is) end it 'returns false for > 4' do resource[:ensure] = '> 4' expect(provider).to_not be_insync(is) end it 'returns true for 1.3.4' do resource[:ensure] = '1.3.4' expect(provider).to be_insync(is) end it 'returns false for 3.6.1' do resource[:ensure] = '3.6.1' expect(provider).to_not be_insync(is) end it 'returns true for >=1.3, <2' do resource[:ensure] = '>=1.3, <2' expect(provider).to be_insync(is) end it 'returns false for >1, <=1.3' do resource[:ensure] = '>1, <=1.3' expect(provider).to_not be_insync(is) end it 'returns true for >=1.3 <2' do resource[:ensure] = '>=1.3 <2' expect(provider).to be_insync(is) end it 'returns false for >1 <=1.3' do resource[:ensure] = '>1 <=1.3' expect(provider).to_not be_insync(is) end end it 'should return false for bad version specifiers' do resource[:ensure] = 'not a valid gem specifier' expect(provider).to_not be_insync('1.0') end it 'should return false for :absent' do resource[:ensure] = '~> 1.0' expect(provider).to_not be_insync(:absent) end end end context 'installing myresource with a target command' do let(:resource_gem_cmd) { '/resource/gem' } let(:resource) do Puppet::Type.type(:package).new( :name => "myresource", :ensure => :installed, ) end let(:provider) do provider = described_class.new provider.resource = resource provider end before :each do resource.provider = provider end context "when installing with a target command" do before :each do allow(described_class).to receive(:which).with(resource_gem_cmd).and_return(resource_gem_cmd) end it "should use the path to the other gem" do resource::original_parameters[:command] = resource_gem_cmd expect(described_class).to receive(:execute_gem_command).with(resource_gem_cmd, be_a(Array)).twice.and_return("") provider.install end end end context 'uninstalling myresource' do let(:resource) do Puppet::Type.type(:package).new( :name => 'myresource', :ensure => :absent ) end let(:provider) do provider = described_class.new provider.resource = resource provider end before :each do resource.provider = provider allow(described_class).to receive(:command).with(:gemcmd).and_return(provider_gem_cmd) end context "when uninstalling" do it "should use the path to the gem command" do allow(described_class).to receive(:validate_command).with(provider_gem_cmd) expect(described_class).to receive(:execute).with(be_a(Array), execute_options) { |args| expect(args[0]).to eq(provider_gem_cmd) }.and_return("") provider.uninstall end it "should specify that the gem is being uninstalled" do expect(described_class).to receive(:execute_gem_command).with(provider_gem_cmd, be_a(Array)) { |cmd, args| expect(args[0]).to eq("uninstall") }.and_return("") provider.uninstall end it "should specify that the relevant executables should be removed without confirmation" do expect(described_class).to receive(:execute_gem_command).with(provider_gem_cmd, be_a(Array)) { |cmd, args| expect(args[1]).to eq("--executables") }.and_return("") provider.uninstall end it "should specify that all the matching versions should be removed" do expect(described_class).to receive(:execute_gem_command).with(provider_gem_cmd, be_a(Array)) { |cmd, args| expect(args[2]).to eq("--all") }.and_return("") provider.uninstall end it "should specify the package name" do expect(described_class).to receive(:execute_gem_command).with(provider_gem_cmd, be_a(Array)) { |cmd, args| expect(args[3]).to eq("myresource") }.and_return("") provider.uninstall end it "should not append uninstall_options by default" do expect(described_class).to receive(:execute_gem_command).with(provider_gem_cmd, be_a(Array)) { |cmd, args| expect(args.length).to eq(4) }.and_return("") provider.uninstall end it "should allow setting an uninstall_options parameter" do resource[:uninstall_options] = [ '--ignore-dependencies', {'--version' => '0.1.1' } ] expect(described_class).to receive(:execute_gem_command).with(provider_gem_cmd, be_a(Array)) do |cmd, args| expect(args[4]).to eq('--ignore-dependencies') expect(args[5]).to eq('--version=0.1.1') end.and_return('') provider.uninstall end end end context 'calculated specificity' do include_context 'provider specificity' context 'when is not defaultfor' do subject { described_class.specificity } it { is_expected.to eql 1 } end context 'when is defaultfor' do let(:os) { Puppet.runtime[:facter].value('os.name') } subject do described_class.defaultfor('os.name': os) described_class.specificity end it { is_expected.to be > 100 } end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/provider/package/aptitude_spec.rb
spec/unit/provider/package/aptitude_spec.rb
require 'spec_helper' describe Puppet::Type.type(:package).provider(:aptitude) do let :type do Puppet::Type.type(:package) end let :pkg do type.new(:name => 'faff', :provider => :aptitude, :source => '/tmp/faff.deb') end it { is_expected.to be_versionable } context "when retrieving ensure" do let(:dpkgquery_path) { '/bin/dpkg-query' } before do allow(Puppet::Util).to receive(:which).with('/usr/bin/dpkg-query').and_return(dpkgquery_path) allow(described_class).to receive(:aptmark).with('showmanual', 'faff').and_return("") end { :absent => "deinstall ok config-files faff 1.2.3-1\n", "1.2.3-1" => "install ok installed faff 1.2.3-1\n", }.each do |expect, output| it "detects #{expect} packages" do expect(Puppet::Util::Execution).to receive(:execute).with( [dpkgquery_path, '-W', '--showformat', "'${Status} ${Package} ${Version}\\n'", 'faff'], {:failonfail => true, :combine => true, :custom_environment => {}} ).and_return(Puppet::Util::Execution::ProcessOutput.new(output, 0)) expect(pkg.property(:ensure).retrieve).to eq(expect) end end end it "installs when asked" do expect(pkg.provider).to receive(:aptitude). with('-y', '-o', 'DPkg::Options::=--force-confold', :install, 'faff'). and_return(0) expect(pkg.provider).to receive(:properties).and_return({:mark => :none}) pkg.provider.install end it "purges when asked" do expect(pkg.provider).to receive(:aptitude).with('-y', 'purge', 'faff').and_return(0) pkg.provider.purge end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/provider/package/zypper_spec.rb
spec/unit/provider/package/zypper_spec.rb
require 'spec_helper' describe Puppet::Type.type(:package).provider(:zypper) do before(:each) do # Create a mock resource @resource = double('resource') # A catch all; no parameters set allow(@resource).to receive(:[]).and_return(nil) # But set name and source allow(@resource).to receive(:[]).with(:name).and_return("mypackage") allow(@resource).to receive(:[]).with(:ensure).and_return(:installed) allow(@resource).to receive(:command).with(:zypper).and_return("/usr/bin/zypper") @provider = described_class.new(@resource) end it "should have an install method" do @provider = described_class.new expect(@provider).to respond_to(:install) end it "should have an uninstall method" do @provider = described_class.new expect(@provider).to respond_to(:uninstall) end it "should have an update method" do @provider = described_class.new expect(@provider).to respond_to(:update) end it "should have a latest method" do @provider = described_class.new expect(@provider).to respond_to(:latest) end it "should have a install_options method" do @provider = described_class.new expect(@provider).to respond_to(:install_options) end context "when installing with zypper version >= 1.0" do it "should use a command-line with versioned package'" do allow(@resource).to receive(:should).with(:ensure).and_return("1.2.3-4.5.6") allow(@resource).to receive(:allow_virtual?).and_return(false) allow(@provider).to receive(:zypper_version).and_return("1.2.8") expect(@provider).to receive(:zypper).with('--quiet', :install, '--auto-agree-with-licenses', '--no-confirm', 'mypackage-1.2.3-4.5.6') expect(@provider).to receive(:query).and_return("mypackage 0 1.2.3 4.5.6 x86_64") @provider.install end it "should use a command-line without versioned package" do allow(@resource).to receive(:should).with(:ensure).and_return(:latest) allow(@resource).to receive(:allow_virtual?).and_return(false) allow(@provider).to receive(:zypper_version).and_return("1.2.8") expect(@provider).to receive(:zypper).with('--quiet', :install, '--auto-agree-with-licenses', '--no-confirm', '--name', 'mypackage') expect(@provider).to receive(:query).and_return("mypackage 0 1.2.3 4.5.6 x86_64") @provider.install end end context "when installing with zypper version = 0.6.104" do it "should use a command-line with versioned package'" do allow(@resource).to receive(:should).with(:ensure).and_return("1.2.3-4.5.6") allow(@resource).to receive(:allow_virtual?).and_return(false) allow(@provider).to receive(:zypper_version).and_return("0.6.104") expect(@provider).to receive(:zypper).with('--terse', :install, '--auto-agree-with-licenses', '--no-confirm', 'mypackage-1.2.3-4.5.6') expect(@provider).to receive(:query).and_return("mypackage 0 1.2.3 4.5.6 x86_64") @provider.install end it "should use a command-line without versioned package" do allow(@resource).to receive(:should).with(:ensure).and_return(:latest) allow(@resource).to receive(:allow_virtual?).and_return(false) allow(@provider).to receive(:zypper_version).and_return("0.6.104") expect(@provider).to receive(:zypper).with('--terse', :install, '--auto-agree-with-licenses', '--no-confirm', 'mypackage') expect(@provider).to receive(:query).and_return("mypackage 0 1.2.3 4.5.6 x86_64") @provider.install end end context "when installing with zypper version = 0.6.13" do it "should use a command-line with versioned package'" do allow(@resource).to receive(:should).with(:ensure).and_return("1.2.3-4.5.6") allow(@resource).to receive(:allow_virtual?).and_return(false) allow(@provider).to receive(:zypper_version).and_return("0.6.13") expect(@provider).to receive(:zypper).with('--terse', :install, '--no-confirm', 'mypackage-1.2.3-4.5.6') expect(@provider).to receive(:query).and_return("mypackage 0 1.2.3 4.5.6 x86_64") @provider.install end it "should use a command-line without versioned package" do allow(@resource).to receive(:should).with(:ensure).and_return(:latest) allow(@resource).to receive(:allow_virtual?).and_return(false) allow(@provider).to receive(:zypper_version).and_return("0.6.13") expect(@provider).to receive(:zypper).with('--terse', :install, '--no-confirm', 'mypackage') expect(@provider).to receive(:query).and_return("mypackage 0 1.2.3 4.5.6 x86_64") @provider.install end end context "when updating" do it "should call install method of instance" do expect(@provider).to receive(:install) @provider.update end end context "when getting latest version" do after { described_class.reset! } context "when the package has available update" do it "should return a version string with valid list-updates data from SLES11sp1" do fake_data = File.read(my_fixture('zypper-list-updates-SLES11sp1.out')) allow(@resource).to receive(:[]).with(:name).and_return("at") expect(described_class).to receive(:zypper).with("list-updates").and_return(fake_data) expect(@provider.latest).to eq("3.1.8-1069.18.2") end end context "when the package is in the latest version" do it "should return nil with valid list-updates data from SLES11sp1" do fake_data = File.read(my_fixture('zypper-list-updates-SLES11sp1.out')) allow(@resource).to receive(:[]).with(:name).and_return("zypper-log") expect(described_class).to receive(:zypper).with("list-updates").and_return(fake_data) expect(@provider.latest).to eq(nil) end end context "when there are no updates available" do it "should return nil" do fake_data_empty = File.read(my_fixture('zypper-list-updates-empty.out')) allow(@resource).to receive(:[]).with(:name).and_return("at") expect(described_class).to receive(:zypper).with("list-updates").and_return(fake_data_empty) expect(@provider.latest).to eq(nil) end end end context "should install a virtual package" do it "when zypper version = 0.6.13" do allow(@resource).to receive(:should).with(:ensure).and_return(:installed) allow(@resource).to receive(:allow_virtual?).and_return(true) allow(@provider).to receive(:zypper_version).and_return("0.6.13") expect(@provider).to receive(:zypper).with('--terse', :install, '--no-confirm', 'mypackage') expect(@provider).to receive(:query).and_return("mypackage 0 1.2.3 4.5.6 x86_64") @provider.install end it "when zypper version >= 1.0.0" do allow(@resource).to receive(:should).with(:ensure).and_return(:installed) allow(@resource).to receive(:allow_virtual?).and_return(true) allow(@provider).to receive(:zypper_version).and_return("1.2.8") expect(@provider).to receive(:zypper).with('--quiet', :install, '--auto-agree-with-licenses', '--no-confirm', 'mypackage') expect(@provider).to receive(:query).and_return("mypackage 0 1.2.3 4.5.6 x86_64") @provider.install end end context "when installing with zypper install options" do it "should install the package without checking keys" do allow(@resource).to receive(:[]).with(:name).and_return("php5") allow(@resource).to receive(:[]).with(:install_options).and_return(['--no-gpg-check', {'-p' => '/vagrant/files/localrepo/'}]) allow(@resource).to receive(:should).with(:ensure).and_return("5.4.10-4.5.6") allow(@resource).to receive(:allow_virtual?).and_return(false) allow(@provider).to receive(:zypper_version).and_return("1.2.8") expect(@provider).to receive(:zypper).with('--quiet', '--no-gpg-check', :install, '--auto-agree-with-licenses', '--no-confirm', '-p=/vagrant/files/localrepo/', 'php5-5.4.10-4.5.6') expect(@provider).to receive(:query).and_return("php5 0 5.4.10 4.5.6 x86_64") @provider.install end it "should install the package with --no-gpg-checks" do allow(@resource).to receive(:[]).with(:name).and_return("php5") allow(@resource).to receive(:[]).with(:install_options).and_return(['--no-gpg-checks', {'-p' => '/vagrant/files/localrepo/'}]) allow(@resource).to receive(:should).with(:ensure).and_return("5.4.10-4.5.6") allow(@resource).to receive(:allow_virtual?).and_return(false) allow(@provider).to receive(:zypper_version).and_return("1.2.8") expect(@provider).to receive(:zypper).with('--quiet', '--no-gpg-checks', :install, '--auto-agree-with-licenses', '--no-confirm', '-p=/vagrant/files/localrepo/', 'php5-5.4.10-4.5.6') expect(@provider).to receive(:query).and_return("php5 0 5.4.10 4.5.6 x86_64") @provider.install end it "should install package with hash install options" do allow(@resource).to receive(:[]).with(:name).and_return('vim') allow(@resource).to receive(:[]).with(:install_options).and_return([{ '--a' => 'foo', '--b' => '"quoted bar"' }]) allow(@resource).to receive(:should).with(:ensure).and_return(:present) allow(@resource).to receive(:allow_virtual?).and_return(false) allow(@provider).to receive(:zypper_version).and_return('1.2.8') expect(@provider).to receive(:zypper).with('--quiet', :install, '--auto-agree-with-licenses', '--no-confirm', '--a=foo', '--b="quoted bar"', '--name', 'vim') expect(@provider).to receive(:query).and_return('package vim is not installed') @provider.install end it "should install package with array install options" do allow(@resource).to receive(:[]).with(:name).and_return('vim') allow(@resource).to receive(:[]).with(:install_options).and_return([['--a', '--b', '--c']]) allow(@resource).to receive(:should).with(:ensure).and_return(:present) allow(@resource).to receive(:allow_virtual?).and_return(false) allow(@provider).to receive(:zypper_version).and_return('1.2.8') expect(@provider).to receive(:zypper).with('--quiet', :install, '--auto-agree-with-licenses', '--no-confirm', '--a', '--b', '--c', '--name', 'vim') expect(@provider).to receive(:query).and_return('package vim is not installed') @provider.install end it "should install package with string install options" do allow(@resource).to receive(:[]).with(:name).and_return('vim') allow(@resource).to receive(:[]).with(:install_options).and_return(['--a --b --c']) allow(@resource).to receive(:should).with(:ensure).and_return(:present) allow(@resource).to receive(:allow_virtual?).and_return(false) allow(@provider).to receive(:zypper_version).and_return('1.2.8') expect(@provider).to receive(:zypper).with('--quiet', :install, '--auto-agree-with-licenses', '--no-confirm', '--a --b --c', '--name', 'vim') expect(@provider).to receive(:query).and_return('package vim is not installed') @provider.install end end context 'when uninstalling' do it 'should use remove to uninstall on zypper version 1.6 and above' do allow(@provider).to receive(:zypper_version).and_return('1.6.308') expect(@provider).to receive(:zypper).with(:remove, '--no-confirm', 'mypackage') @provider.uninstall end it 'should use remove --force-solution to uninstall on zypper versions between 1.0 and 1.6' do allow(@provider).to receive(:zypper_version).and_return('1.0.2') expect(@provider).to receive(:zypper).with(:remove, '--no-confirm', '--force-resolution', 'mypackage') @provider.uninstall end end context 'when installing with VersionRange' do let(:search_output) { File.read(my_fixture('zypper-search-uninstalled.out')) } before(:each) do allow(@resource).to receive(:[]).with(:name).and_return('vim') allow(@resource).to receive(:allow_virtual?).and_return(false) allow(@provider).to receive(:zypper_version).and_return('1.0.2') expect(@provider).to receive(:zypper).with('search', '--match-exact', '--type', 'package', '--uninstalled-only', '-s', 'vim') .and_return(search_output) end it 'does install the package if version is available' do expect(@resource).to receive(:should).with(:ensure).and_return('>1.0') expect(@provider).to receive(:zypper).with('--quiet', :install, '--auto-agree-with-licenses', '--no-confirm', 'vim-1.0.20040813-19.9') expect(@provider).to receive(:query).and_return('vim 0 1.0.20040813 19.9 x86_64') @provider.install end it 'does consider range as version if version in range is not available' do allow(@resource).to receive(:should).with(:ensure).and_return('>2.0') expect(@provider).to receive(:zypper).with('--quiet', :install, '--auto-agree-with-licenses', '--no-confirm', 'vim->2.0') .and_raise(Puppet::ExecutionFailure.new('My Error')) expect { @provider.install }.to raise_error(Puppet::ExecutionFailure, 'My Error') end end describe 'insync?' do subject { @provider.insync?('1.19-2') } context 'when versions are matching' do before { allow(@resource).to receive(:[]).with(:ensure).and_return('1.19-2') } it { is_expected.to be true } end context 'when version are not matching' do before { allow(@resource).to receive(:[]).with(:ensure).and_return('1.19-3') } it { is_expected.to be false } end context 'when version is in gt range' do before { allow(@resource).to receive(:[]).with(:ensure).and_return('>1.19-0') } it { is_expected.to be true } end context 'when version is not in gt range' do before { allow(@resource).to receive(:[]).with(:ensure).and_return('>1.19-2') } it { is_expected.to be false } end context 'when version is in min-max range' do before { allow(@resource).to receive(:[]).with(:ensure).and_return('>1.19-0 <1.19-3') } it { is_expected.to be true } end context 'when version is not in min-max range' do before { allow(@resource).to receive(:[]).with(:ensure).and_return('>1.19-0 <1.19-2') } it { is_expected.to be false } end context 'when using eq range' do context 'when ensure without release' do before { allow(@resource).to receive(:[]).with(:ensure).and_return('1.19') } it { is_expected.to be true } end context 'when ensure with release' do before { allow(@resource).to receive(:[]).with(:ensure).and_return('1.19-2') } it { is_expected.to be true } end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/provider/package/windows/msi_package_spec.rb
spec/unit/provider/package/windows/msi_package_spec.rb
require 'spec_helper' require 'puppet/provider/package/windows/msi_package' describe Puppet::Provider::Package::Windows::MsiPackage do let (:name) { 'mysql-5.1.58-win-x64' } let (:version) { '5.1.58' } let (:source) { 'E:\mysql-5.1.58-win-x64.msi' } let (:productcode) { '{E437FFB6-5C49-4DAC-ABAE-33FF065FE7CC}' } let (:packagecode) { '{5A6FD560-763A-4BC1-9E03-B18DFFB7C72C}' } def expect_installer inst = double() expect(inst).to receive(:ProductState).and_return(5) expect(inst).to receive(:ProductInfo).with(productcode, 'PackageCode').and_return(packagecode) expect(described_class).to receive(:installer).and_return(inst) end context '::installer', :if => Puppet::Util::Platform.windows? do it 'should return an instance of the COM interface' do expect(described_class.installer).not_to be_nil end end context '::from_registry' do it 'should return an instance of MsiPackage' do expect(described_class).to receive(:valid?).and_return(true) expect_installer pkg = described_class.from_registry(productcode, {'DisplayName' => name, 'DisplayVersion' => version}) expect(pkg.name).to eq(name) expect(pkg.version).to eq(version) expect(pkg.productcode).to eq(productcode) expect(pkg.packagecode).to eq(packagecode) end it 'should return nil if it is not a valid MSI' do expect(described_class).to receive(:valid?).and_return(false) expect(described_class.from_registry(productcode, {})).to be_nil end end context '::valid?' do let(:values) do { 'DisplayName' => name, 'DisplayVersion' => version, 'WindowsInstaller' => 1 } end { 'DisplayName' => ['My App', ''], 'WindowsInstaller' => [1, nil], }.each_pair do |k, arr| it "should accept '#{k}' with value '#{arr[0]}'" do values[k] = arr[0] expect(described_class.valid?(productcode, values)).to be_truthy end it "should reject '#{k}' with value '#{arr[1]}'" do values[k] = arr[1] expect(described_class.valid?(productcode, values)).to be_falsey end end it 'should reject packages whose name is not a productcode' do expect(described_class.valid?('AddressBook', values)).to be_falsey end it 'should accept packages whose name is a productcode' do expect(described_class.valid?(productcode, values)).to be_truthy end end context '#match?' do it 'should match package codes case-insensitively' do pkg = described_class.new(name, version, productcode, packagecode.upcase) expect(pkg.match?({:name => packagecode.downcase})).to be_truthy end it 'should match product codes case-insensitively' do pkg = described_class.new(name, version, productcode.upcase, packagecode) expect(pkg.match?({:name => productcode.downcase})).to be_truthy end it 'should match product name' do pkg = described_class.new(name, version, productcode, packagecode) expect(pkg.match?({:name => name})).to be_truthy end it 'should return false otherwise' do pkg = described_class.new(name, version, productcode, packagecode) expect(pkg.match?({:name => 'not going to find it'})).to be_falsey end end context '#install_command' do it 'should install using the source' do cmd = described_class.install_command({:source => source}) expect(cmd).to eq(['msiexec.exe', '/qn', '/norestart', '/i', source]) end end context '#uninstall_command' do it 'should uninstall using the productcode' do pkg = described_class.new(name, version, productcode, packagecode) expect(pkg.uninstall_command).to eq(['msiexec.exe', '/qn', '/norestart', '/x', productcode]) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/provider/package/windows/package_spec.rb
spec/unit/provider/package/windows/package_spec.rb
require 'spec_helper' require 'puppet/provider/package/windows/package' describe Puppet::Provider::Package::Windows::Package do let(:hklm) { 'HKEY_LOCAL_MACHINE' } let(:hkcu) { 'HKEY_CURRENT_USER' } let(:path) { 'Software\Microsoft\Windows\CurrentVersion\Uninstall' } let(:key) { double('key', :name => "#{hklm}\\#{path}\\Google") } let(:package) { double('package') } context '::each' do it 'should generate an empty enumeration' do expect(described_class).to receive(:with_key) expect(described_class.to_a).to be_empty end it 'should yield each package it finds' do expect(described_class).to receive(:with_key).and_yield(key, {}) expect(Puppet::Provider::Package::Windows::MsiPackage).to receive(:from_registry).with('Google', {}).and_return(package) yielded = nil described_class.each do |pkg| yielded = pkg end expect(yielded).to eq(package) end end context '::with_key', :if => Puppet::Util::Platform.windows? do it 'should search HKLM (64 & 32) and HKCU (64 & 32)' do expect(described_class).to receive(:open).with(hklm, path, described_class::KEY64 | described_class::KEY_READ).ordered expect(described_class).to receive(:open).with(hklm, path, described_class::KEY32 | described_class::KEY_READ).ordered expect(described_class).to receive(:open).with(hkcu, path, described_class::KEY64 | described_class::KEY_READ).ordered expect(described_class).to receive(:open).with(hkcu, path, described_class::KEY32 | described_class::KEY_READ).ordered described_class.with_key { |key, values| } end it 'should ignore file not found exceptions' do ex = Puppet::Util::Windows::Error.new('Failed to open registry key', Puppet::Util::Windows::Error::ERROR_FILE_NOT_FOUND) # make sure we don't stop after the first exception expect(described_class).to receive(:open).exactly(4).times().and_raise(ex) keys = [] described_class.with_key { |key, values| keys << key } expect(keys).to be_empty end it 'should raise other types of exceptions' do ex = Puppet::Util::Windows::Error.new('Failed to open registry key', Puppet::Util::Windows::Error::ERROR_ACCESS_DENIED) expect(described_class).to receive(:open).and_raise(ex) expect { described_class.with_key{ |key, values| } }.to raise_error do |error| expect(error).to be_a(Puppet::Util::Windows::Error) expect(error.code).to eq(5) # ERROR_ACCESS_DENIED end end end context '::installer_class' do it 'should require the source parameter' do expect { described_class.installer_class({}) }.to raise_error(Puppet::Error, /The source parameter is required when using the Windows provider./) end context 'MSI' do let (:klass) { Puppet::Provider::Package::Windows::MsiPackage } it 'should accept source ending in .msi' do expect(described_class.installer_class({:source => 'foo.msi'})).to eq(klass) end it 'should accept quoted source ending in .msi' do expect(described_class.installer_class({:source => '"foo.msi"'})).to eq(klass) end it 'should accept source case insensitively' do expect(described_class.installer_class({:source => '"foo.MSI"'})).to eq(klass) end it 'should reject source containing msi in the name' do expect { described_class.installer_class({:source => 'mymsi.txt'}) }.to raise_error(Puppet::Error, /Don't know how to install 'mymsi.txt'/) end end context 'Unknown' do it 'should reject packages it does not know about' do expect { described_class.installer_class({:source => 'basram'}) }.to raise_error(Puppet::Error, /Don't know how to install 'basram'/) end end end context '::munge' do it 'should shell quote strings with spaces and fix forward slashes' do expect(described_class.munge('c:/windows/the thing')).to eq('"c:\windows\the thing"') end it 'should leave properly formatted paths alone' do expect(described_class.munge('c:\windows\thething')).to eq('c:\windows\thething') end end context '::replace_forward_slashes' do it 'should replace forward with back slashes' do expect(described_class.replace_forward_slashes('c:/windows/thing/stuff')).to eq('c:\windows\thing\stuff') end end context '::quote' do it 'should shell quote strings with spaces' do expect(described_class.quote('foo bar')).to eq('"foo bar"') end it 'should shell quote strings with spaces and quotes' do expect(described_class.quote('"foo bar" baz')).to eq('"\"foo bar\" baz"') end it 'should not shell quote strings without spaces' do expect(described_class.quote('"foobar"')).to eq('"foobar"') end end context '::get_display_name' do it 'should return nil if values is nil' do expect(described_class.get_display_name(nil)).to be_nil end it 'should return empty if values is empty' do reg_values = {} expect(described_class.get_display_name(reg_values)).to eq('') end it 'should return DisplayName when available' do reg_values = { 'DisplayName' => 'Google' } expect(described_class.get_display_name(reg_values)).to eq('Google') end it 'should return DisplayName when available, even when QuietDisplayName is also available' do reg_values = { 'DisplayName' => 'Google', 'QuietDisplayName' => 'Google Quiet' } expect(described_class.get_display_name(reg_values)).to eq('Google') end it 'should return QuietDisplayName when available if DisplayName is empty' do reg_values = { 'DisplayName' => '', 'QuietDisplayName' =>'Google Quiet' } expect(described_class.get_display_name(reg_values)).to eq('Google Quiet') end it 'should return QuietDisplayName when DisplayName is not available' do reg_values = { 'QuietDisplayName' =>'Google Quiet' } expect(described_class.get_display_name(reg_values)).to eq('Google Quiet') end it 'should return empty when DisplayName is empty and QuietDisplay name is not available' do reg_values = { 'DisplayName' => '' } expect(described_class.get_display_name(reg_values)).to eq('') end it 'should return empty when DisplayName is empty and QuietDisplay name is empty' do reg_values = { 'DisplayName' => '', 'QuietDisplayName' =>'' } expect(described_class.get_display_name(reg_values)).to eq('') end end it 'should implement instance methods' do pkg = described_class.new('orca', '5.0') expect(pkg.name).to eq('orca') expect(pkg.version).to eq('5.0') end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/provider/package/windows/exe_package_spec.rb
spec/unit/provider/package/windows/exe_package_spec.rb
require 'spec_helper' require 'puppet/provider/package/windows/exe_package' require 'puppet/provider/package/windows' describe Puppet::Provider::Package::Windows::ExePackage do let (:name) { 'Git version 1.7.11' } let (:version) { '1.7.11' } let (:source) { 'E:\Git-1.7.11.exe' } let (:uninstall) { '"C:\Program Files (x86)\Git\unins000.exe" /SP-' } context '::from_registry' do it 'should return an instance of ExePackage' do expect(described_class).to receive(:valid?).and_return(true) pkg = described_class.from_registry('', {'DisplayName' => name, 'DisplayVersion' => version, 'UninstallString' => uninstall}) expect(pkg.name).to eq(name) expect(pkg.version).to eq(version) expect(pkg.uninstall_string).to eq(uninstall) end it 'should return nil if it is not a valid executable' do expect(described_class).to receive(:valid?).and_return(false) expect(described_class.from_registry('', {})).to be_nil end end context '::valid?' do let(:name) { 'myproduct' } let(:values) do { 'DisplayName' => name, 'UninstallString' => uninstall } end { 'DisplayName' => ['My App', ''], 'UninstallString' => ['E:\uninstall.exe', ''], 'WindowsInstaller' => [nil, 1], 'ParentKeyName' => [nil, 'Uber Product'], 'Security Update' => [nil, 'KB890830'], 'Update Rollup' => [nil, 'Service Pack 42'], 'Hotfix' => [nil, 'QFE 42'] }.each_pair do |k, arr| it "should accept '#{k}' with value '#{arr[0]}'" do values[k] = arr[0] expect(described_class.valid?(name, values)).to be_truthy end it "should reject '#{k}' with value '#{arr[1]}'" do values[k] = arr[1] expect(described_class.valid?(name, values)).to be_falsey end end it 'should reject packages whose name starts with "KBXXXXXX"' do expect(described_class.valid?('KB890830', values)).to be_falsey end it 'should accept packages whose name does not start with "KBXXXXXX"' do expect(described_class.valid?('My Update (KB890830)', values)).to be_truthy end end context '#match?' do let(:pkg) { described_class.new(name, version, uninstall) } it 'should match product name' do expect(pkg.match?({:name => name})).to be_truthy end it 'should return false otherwise' do expect(pkg.match?({:name => 'not going to find it'})).to be_falsey end end context '#install_command' do it 'should install using the source' do allow(Puppet::FileSystem).to receive(:exist?).with(source).and_return(true) cmd = described_class.install_command({:source => source}) expect(cmd).to eq(source) end it 'should raise error when URI is invalid' do web_source = 'https://www.t e s t.test/test.exe' expect do described_class.install_command({:source => web_source, :name => name}) end.to raise_error(Puppet::Error, /Error when installing #{name}:/) end it 'should download package from source file before installing', if: Puppet::Util::Platform.windows? do web_source = 'https://www.test.test/test.exe' stub_request(:get, web_source).to_return(status: 200, body: 'package binaries') cmd = described_class.install_command({:source => web_source}) expect(File.read(cmd)).to eq('package binaries') end end context '#uninstall_command' do ['C:\uninstall.exe', 'C:\Program Files\uninstall.exe'].each do |exe| it "should quote #{exe}" do expect(described_class.new(name, version, exe).uninstall_command).to eq( "\"#{exe}\"" ) end end ['"C:\Program Files\uninstall.exe"', '"C:\Program Files (x86)\Git\unins000.exe" /SILENT"'].each do |exe| it "should not quote #{exe}" do expect(described_class.new(name, version, exe).uninstall_command).to eq( exe ) end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/file_bucket/file_spec.rb
spec/unit/file_bucket/file_spec.rb
require 'spec_helper' require 'puppet/file_bucket/file' describe Puppet::FileBucket::File, :uses_checksums => true do include PuppetSpec::Files # this is the default from spec_helper, but it keeps getting reset at odd times let(:bucketdir) { Puppet[:bucketdir] = tmpdir('bucket') } it "defaults to serializing to `:binary`" do expect(Puppet::FileBucket::File.default_format).to eq(:binary) end it "only accepts binary" do expect(Puppet::FileBucket::File.supported_formats).to eq([:binary]) end describe "making round trips through network formats" do with_digest_algorithms do it "can make a round trip through `binary`" do file = Puppet::FileBucket::File.new(plaintext) tripped = Puppet::FileBucket::File.convert_from(:binary, file.render) expect(tripped.contents).to eq(plaintext) end end end it "should require contents to be a string" do expect { Puppet::FileBucket::File.new(5) }.to raise_error(ArgumentError, /contents must be a String or Pathname, got a Integer$/) end it "should complain about options other than :bucket_path" do expect { Puppet::FileBucket::File.new('5', :crazy_option => 'should not be passed') }.to raise_error(ArgumentError, /Unknown option\(s\): crazy_option/) end with_digest_algorithms do it "it uses #{metadata[:digest_algorithm]} as the configured digest algorithm" do file = Puppet::FileBucket::File.new(plaintext) expect(file.contents).to eq(plaintext) expect(file.checksum_type).to eq(digest_algorithm) expect(file.checksum).to eq("{#{digest_algorithm}}#{checksum}") expect(file.name).to eq("#{digest_algorithm}/#{checksum}") end end describe "when using back-ends" do it "should redirect using Puppet::Indirector" do expect(Puppet::Indirector::Indirection.instance(:file_bucket_file).model).to equal(Puppet::FileBucket::File) end it "should have a :save instance method" do expect(Puppet::FileBucket::File.indirection).to respond_to(:save) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/file_bucket/dipper_spec.rb
spec/unit/file_bucket/dipper_spec.rb
require 'spec_helper' require 'pathname' require 'puppet/file_bucket/dipper' require 'puppet/indirector/file_bucket_file/rest' require 'puppet/indirector/file_bucket_file/file' require 'puppet/util/checksums' shared_examples_for "a restorable file" do let(:dest) { tmpfile('file_bucket_dest') } describe "restoring the file" do with_digest_algorithms do it "should restore the file" do request = nil # With the *_any_instance_of form of using a block on receive, the # first argument to the block is which instance is currently being # dealt with, and the remaining arguments are the arguments to the # method, instead of the block only getting the arguments to the # method. expect_any_instance_of(klass).to receive(:find) { |_,r| request = r }.and_return(Puppet::FileBucket::File.new(plaintext)) expect(dipper.restore(dest, checksum)).to eq(checksum) expect(digest(Puppet::FileSystem.binread(dest))).to eq(checksum) expect(request.key).to eq("#{digest_algorithm}/#{checksum}") expect(request.server).to eq(server) expect(request.port).to eq(port) end it "should skip restoring if existing file has the same checksum" do File.open(dest, 'wb') {|f| f.print(plaintext) } expect(dipper).not_to receive(:getfile) expect(dipper.restore(dest, checksum)).to be_nil end it "should overwrite existing file if it has different checksum" do expect_any_instance_of(klass).to receive(:find).and_return(Puppet::FileBucket::File.new(plaintext)) File.open(dest, 'wb') {|f| f.print('other contents') } expect(dipper.restore(dest, checksum)).to eq(checksum) end end end end describe Puppet::FileBucket::Dipper, :uses_checksums => true do include PuppetSpec::Files def make_tmp_file(contents) file = tmpfile("file_bucket_file") File.open(file, 'wb') { |f| f.write(contents) } file end it "should fail in an informative way when there are failures checking for the file on the server" do @dipper = Puppet::FileBucket::Dipper.new(:Path => make_absolute("/my/bucket")) file = make_tmp_file('contents') expect(Puppet::FileBucket::File.indirection).to receive(:head).and_raise(ArgumentError) expect { @dipper.backup(file) }.to raise_error(Puppet::Error) end it "should fail in an informative way when there are failures backing up to the server" do @dipper = Puppet::FileBucket::Dipper.new(:Path => make_absolute("/my/bucket")) file = make_tmp_file('contents') expect(Puppet::FileBucket::File.indirection).to receive(:head).and_return(false) expect(Puppet::FileBucket::File.indirection).to receive(:save).and_raise(ArgumentError) expect { @dipper.backup(file) }.to raise_error(Puppet::Error) end describe "when diffing on a local filebucket" do describe "in non-windows environments or JRuby", :unless => Puppet::Util::Platform.windows? || RUBY_PLATFORM == 'java' do with_digest_algorithms do it "should fail in an informative way when one or more checksum doesn't exists" do @dipper = Puppet::FileBucket::Dipper.new(:Path => tmpdir("bucket")) wrong_checksum = "DEADBEEF" # First checksum fails expect { @dipper.diff(wrong_checksum, "WEIRDCKSM", nil, nil) }.to raise_error(RuntimeError, "Invalid checksum #{wrong_checksum.inspect}") file = make_tmp_file(plaintext) @dipper.backup(file) #Diff_with checksum fails expect { @dipper.diff(checksum, wrong_checksum, nil, nil) }.to raise_error(RuntimeError, "could not find diff_with #{wrong_checksum}") end it "should properly diff files on the filebucket" do file1 = make_tmp_file("OriginalContent\n") file2 = make_tmp_file("ModifiedContent\n") @dipper = Puppet::FileBucket::Dipper.new(:Path => tmpdir("bucket")) checksum1 = @dipper.backup(file1) checksum2 = @dipper.backup(file2) # Diff without the context # Lines we need to see match 'Content' instead of trimming diff output filter out # surrounding noise...or hard code the check values if Puppet.runtime[:facter].value('os.family') == 'Solaris' && Puppet::Util::Package.versioncmp(Puppet.runtime[:facter].value('os.release.full'), '11.0') >= 0 # Use gdiff on Solaris diff12 = Puppet::Util::Execution.execute("gdiff -uN #{file1} #{file2}| grep Content") diff21 = Puppet::Util::Execution.execute("gdiff -uN #{file2} #{file1}| grep Content") else diff12 = Puppet::Util::Execution.execute("diff -uN #{file1} #{file2}| grep Content") diff21 = Puppet::Util::Execution.execute("diff -uN #{file2} #{file1}| grep Content") end expect(@dipper.diff(checksum1, checksum2, nil, nil)).to include(diff12) expect(@dipper.diff(checksum1, nil, nil, file2)).to include(diff12) expect(@dipper.diff(nil, checksum2, file1, nil)).to include(diff12) expect(@dipper.diff(nil, nil, file1, file2)).to include(diff12) expect(@dipper.diff(checksum2, checksum1, nil, nil)).to include(diff21) expect(@dipper.diff(checksum2, nil, nil, file1)).to include(diff21) expect(@dipper.diff(nil, checksum1, file2, nil)).to include(diff21) expect(@dipper.diff(nil, nil, file2, file1)).to include(diff21) end end describe "in windows environment", :if => Puppet::Util::Platform.windows? do it "should fail in an informative way when trying to diff" do @dipper = Puppet::FileBucket::Dipper.new(:Path => tmpdir("bucket")) wrong_checksum = "DEADBEEF" # First checksum fails expect { @dipper.diff(wrong_checksum, "WEIRDCKSM", nil, nil) }.to raise_error(RuntimeError, "Diff is not supported on this platform") # Diff_with checksum fails expect { @dipper.diff(checksum, wrong_checksum, nil, nil) }.to raise_error(RuntimeError, "Diff is not supported on this platform") end end end end it "should fail in an informative way when there are failures listing files on the server" do @dipper = Puppet::FileBucket::Dipper.new(:Path => "/unexistent/bucket") expect(Puppet::FileBucket::File.indirection).to receive(:find).and_return(nil) expect { @dipper.list(nil, nil) }.to raise_error(Puppet::Error) end describe "listing files in local filebucket" do with_digest_algorithms do it "should list all files present" do if Puppet::Util::Platform.windows? && digest_algorithm == "sha512" skip "PUP-8257: Skip file bucket test on windows for #{digest_algorithm} due to long path names" end Puppet[:bucketdir] = "/my/bucket" file_bucket = tmpdir("bucket") @dipper = Puppet::FileBucket::Dipper.new(:Path => file_bucket) #First File file1 = make_tmp_file(plaintext) real_path = Pathname.new(file1).realpath expect(digest(plaintext)).to eq(checksum) expect(@dipper.backup(file1)).to eq(checksum) expected_list1_1 = /#{checksum} \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} #{real_path}\n/ File.open(file1, 'w') {|f| f.write("Blahhhh")} new_checksum = digest("Blahhhh") expect(@dipper.backup(file1)).to eq(new_checksum) expected_list1_2 = /#{new_checksum} \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} #{real_path}\n/ #Second File content = "DummyFileWithNonSenseTextInIt" file2 = make_tmp_file(content) real_path = Pathname.new(file2).realpath checksum = digest(content) expect(@dipper.backup(file2)).to eq(checksum) expected_list2 = /#{checksum} \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} #{real_path}\n/ #Third file : Same as the first one with a different path file3 = make_tmp_file(plaintext) real_path = Pathname.new(file3).realpath checksum = digest(plaintext) expect(digest(plaintext)).to eq(checksum) expect(@dipper.backup(file3)).to eq(checksum) expected_list3 = /#{checksum} \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} #{real_path}\n/ result = @dipper.list(nil, nil) expect(result).to match(expected_list1_1) expect(result).to match(expected_list1_2) expect(result).to match(expected_list2) expect(result).to match(expected_list3) end it "should filter with the provided dates" do if Puppet::Util::Platform.windows? && digest_algorithm == "sha512" skip "PUP-8257: Skip file bucket test on windows for #{digest_algorithm} due to long path names" end Puppet[:bucketdir] = "/my/bucket" file_bucket = tmpdir("bucket") twentyminutes=60*20 thirtyminutes=60*30 onehour=60*60 twohours=onehour*2 threehours=onehour*3 # First File created now @dipper = Puppet::FileBucket::Dipper.new(:Path => file_bucket) file1 = make_tmp_file(plaintext) real_path = Pathname.new(file1).realpath expect(digest(plaintext)).to eq(checksum) expect(@dipper.backup(file1)).to eq(checksum) expected_list1 = /#{checksum} \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} #{real_path}\n/ # Second File created an hour ago content = "DummyFileWithNonSenseTextInIt" file2 = make_tmp_file(content) real_path = Pathname.new(file2).realpath checksum = digest(content) expect(@dipper.backup(file2)).to eq(checksum) # Modify mtime of the second file to be an hour ago onehourago = Time.now - onehour bucketed_paths_file = Dir.glob("#{file_bucket}/**/#{checksum}/paths") FileUtils.touch(bucketed_paths_file, mtime: onehourago) expected_list2 = /#{checksum} \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} #{real_path}\n/ now = Time.now #Future expect(@dipper.list((now + threehours).strftime("%F %T"), nil )).to eq("") #Epoch -> Future = Everything (Sorted (desc) by date) expect(@dipper.list(nil, (now + twohours).strftime("%F %T"))).to match(expected_list1) expect(@dipper.list(nil, (now + twohours).strftime("%F %T"))).to match(expected_list2) #Now+1sec -> Future = Nothing expect(@dipper.list((now + 1).strftime("%F %T"), (now + twohours).strftime("%F %T"))).to eq("") #Now-30mins -> Now-20mins = Nothing expect(@dipper.list((now - thirtyminutes).strftime("%F %T"), (now - twentyminutes).strftime("%F %T"))).to eq("") #Now-2hours -> Now-30mins = Second file only expect(@dipper.list((now - twohours).strftime("%F %T"), (now - thirtyminutes).strftime("%F %T"))).to match(expected_list2) expect(@dipper.list((now - twohours).strftime("%F %T"), (now - thirtyminutes).strftime("%F %T"))).not_to match(expected_list1) #Now-30minutes -> Now = First file only expect(@dipper.list((now - thirtyminutes).strftime("%F %T"), now.strftime("%F %T"))).to match(expected_list1) expect(@dipper.list((now - thirtyminutes).strftime("%F %T"), now.strftime("%F %T"))).not_to match(expected_list2) end end end describe "when diffing on a remote filebucket" do describe "in non-windows environments", :unless => Puppet::Util::Platform.windows? do with_digest_algorithms do it "should fail in an informative way when one or more checksum doesn't exists" do @dipper = Puppet::FileBucket::Dipper.new(:Server => "puppetmaster", :Port => "31337") wrong_checksum = "DEADBEEF" expect_any_instance_of(Puppet::FileBucketFile::Rest).to receive(:find).and_return(nil) expect { @dipper.diff(wrong_checksum, "WEIRDCKSM", nil, nil) }.to raise_error(Puppet::Error, "Failed to diff files") end it "should properly diff files on the filebucket" do @dipper = Puppet::FileBucket::Dipper.new(:Server => "puppetmaster", :Port => "31337") expect_any_instance_of(Puppet::FileBucketFile::Rest).to receive(:find).and_return("Probably valid diff") expect(@dipper.diff("checksum1", "checksum2", nil, nil)).to eq("Probably valid diff") end end end describe "in windows environment", :if => Puppet::Util::Platform.windows? do it "should fail in an informative way when trying to diff" do @dipper = Puppet::FileBucket::Dipper.new(:Server => "puppetmaster", :Port => "31337") wrong_checksum = "DEADBEEF" expect { @dipper.diff(wrong_checksum, "WEIRDCKSM", nil, nil) }.to raise_error(RuntimeError, "Diff is not supported on this platform") expect { @dipper.diff(wrong_checksum, nil, nil, nil) }.to raise_error(RuntimeError, "Diff is not supported on this platform") end end end describe "listing files in remote filebucket" do it "is not allowed" do @dipper = Puppet::FileBucket::Dipper.new(:Server => "puppetmaster", :Port=> "31337") expect { @dipper.list(nil, nil) }.to raise_error(Puppet::Error, "Listing remote file buckets is not allowed") end end describe "backing up and retrieving local files" do with_digest_algorithms do it "should backup files to a local bucket" do if Puppet::Util::Platform.windows? && digest_algorithm == "sha512" skip "PUP-8257: Skip file bucket test on windows for #{digest_algorithm} due to long path names" end Puppet[:bucketdir] = "/non/existent/directory" file_bucket = tmpdir("bucket") @dipper = Puppet::FileBucket::Dipper.new(:Path => file_bucket) file = make_tmp_file(plaintext) expect(digest(plaintext)).to eq(checksum) expect(@dipper.backup(file)).to eq(checksum) expect(Puppet::FileSystem.exist?("#{file_bucket}/#{bucket_dir}/contents")).to eq(true) end it "should not backup a file that is already in the bucket" do @dipper = Puppet::FileBucket::Dipper.new(:Path => "/my/bucket") file = make_tmp_file(plaintext) expect(Puppet::FileBucket::File.indirection).to receive(:head).with( %r{#{digest_algorithm}/#{checksum}}, {:bucket_path => "/my/bucket"} ).and_return(true) expect(Puppet::FileBucket::File.indirection).not_to receive(:save) expect(@dipper.backup(file)).to eq(checksum) end it "should retrieve files from a local bucket" do @dipper = Puppet::FileBucket::Dipper.new(:Path => "/my/bucket") request = nil expect_any_instance_of(Puppet::FileBucketFile::File).to receive(:find) { |_,r| request = r }.once.and_return(Puppet::FileBucket::File.new(plaintext)) expect(@dipper.getfile(checksum)).to eq(plaintext) expect(request.key).to eq("#{digest_algorithm}/#{checksum}") end end end describe "backing up and retrieving remote files" do with_digest_algorithms do it "should backup files to a remote server" do @dipper = Puppet::FileBucket::Dipper.new(:Server => "puppetmaster", :Port => "31337") file = make_tmp_file(plaintext) real_path = Pathname.new(file).realpath request1 = nil request2 = nil expect_any_instance_of(Puppet::FileBucketFile::Rest).to receive(:head) { |_,r| request1 = r }.once.and_return(nil) expect_any_instance_of(Puppet::FileBucketFile::Rest).to receive(:save) { |_,r| request2 = r }.once expect(@dipper.backup(file)).to eq(checksum) [request1, request2].each do |r| expect(r.server).to eq('puppetmaster') expect(r.port).to eq(31337) expect(r.key).to eq("#{digest_algorithm}/#{checksum}/#{real_path}") end end it "should retrieve files from a remote server" do @dipper = Puppet::FileBucket::Dipper.new(:Server => "puppetmaster", :Port => "31337") request = nil expect_any_instance_of(Puppet::FileBucketFile::Rest).to receive(:find) { |_,r| request = r }.and_return(Puppet::FileBucket::File.new(plaintext)) expect(@dipper.getfile(checksum)).to eq(plaintext) expect(request.server).to eq('puppetmaster') expect(request.port).to eq(31337) expect(request.key).to eq("#{digest_algorithm}/#{checksum}") end end end describe "#restore" do describe "when restoring from a remote server" do let(:klass) { Puppet::FileBucketFile::Rest } let(:server) { "puppetmaster" } let(:port) { 31337 } it_behaves_like "a restorable file" do let (:dipper) { Puppet::FileBucket::Dipper.new(:Server => server, :Port => port.to_s) } end end describe "when restoring from a local server" do let(:klass) { Puppet::FileBucketFile::File } let(:server) { nil } let(:port) { nil } it_behaves_like "a restorable file" do let (:dipper) { Puppet::FileBucket::Dipper.new(:Path => "/my/bucket") } end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/ssl/certificate_request_attributes_spec.rb
spec/unit/ssl/certificate_request_attributes_spec.rb
require 'spec_helper' require 'puppet/ssl/certificate_request_attributes' describe Puppet::SSL::CertificateRequestAttributes do include PuppetSpec::Files let(:expected) do { "custom_attributes" => { "1.3.6.1.4.1.34380.2.2"=>[3232235521, 3232235777], # system IPs in hex "1.3.6.1.4.1.34380.2.0"=>"hostname.domain.com", "1.3.6.1.4.1.34380.1.1.3"=>:node_image_name, # different UTF-8 widths # 1-byte A # 2-byte ۿ - http://www.fileformat.info/info/unicode/char/06ff/index.htm - 0xDB 0xBF / 219 191 # 3-byte ᚠ - http://www.fileformat.info/info/unicode/char/16A0/index.htm - 0xE1 0x9A 0xA0 / 225 154 160 # 4-byte 𠜎 - http://www.fileformat.info/info/unicode/char/2070E/index.htm - 0xF0 0xA0 0x9C 0x8E / 240 160 156 142 "1.2.840.113549.1.9.7"=>"utf8passwordA\u06FF\u16A0\u{2070E}" } } end let(:csr_attributes_hash) { expected.dup } let(:csr_attributes_path) { tmpfile('csr_attributes.yaml') } let(:csr_attributes) { Puppet::SSL::CertificateRequestAttributes.new(csr_attributes_path) } it "initializes with a path" do expect(csr_attributes.path).to eq(csr_attributes_path) end describe "loading" do it "returns nil when loading from a non-existent file" do nonexistent = Puppet::SSL::CertificateRequestAttributes.new('/does/not/exist.yaml') expect(nonexistent.load).to be_falsey end context "with an available attributes file" do before do Puppet::Util::Yaml.dump(csr_attributes_hash, csr_attributes_path) end it "loads csr attributes from a file when the file is present" do expect(csr_attributes.load).to be_truthy end it "exposes custom_attributes" do csr_attributes.load expect(csr_attributes.custom_attributes).to eq(expected['custom_attributes']) end it "returns an empty hash if custom_attributes points to nil" do Puppet::Util::Yaml.dump({'custom_attributes' => nil }, csr_attributes_path) csr_attributes.load expect(csr_attributes.custom_attributes).to eq({}) end it "returns an empty hash if custom_attributes key is not present" do Puppet::Util::Yaml.dump({}, csr_attributes_path) csr_attributes.load expect(csr_attributes.custom_attributes).to eq({}) end it "raises a Puppet::Error if an unexpected root key is defined" do csr_attributes_hash['unintentional'] = 'data' Puppet::Util::Yaml.dump(csr_attributes_hash, csr_attributes_path) expect { csr_attributes.load }.to raise_error(Puppet::Error, /unexpected attributes.*unintentional/) end it "raises a Puppet::Util::Yaml::YamlLoadError if an unexpected ruby object is present" do csr_attributes_hash['custom_attributes']['whoops'] = Object.new Puppet::Util::Yaml.dump(csr_attributes_hash, csr_attributes_path) expect { csr_attributes.load }.to raise_error(Puppet::Util::Yaml::YamlLoadError, /Tried to load unspecified class: Object/) end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/ssl/certificate_request_spec.rb
spec/unit/ssl/certificate_request_spec.rb
require 'spec_helper' require 'puppet/ssl/certificate_request' describe Puppet::SSL::CertificateRequest do let(:request) { described_class.new("myname") } let(:key) { OpenSSL::PKey::RSA.new(Puppet[:keylength]) } it "should use any provided name as its name" do expect(described_class.new("myname").name).to eq("myname") end it "should only support the text format" do expect(described_class.supported_formats).to eq([:s]) end describe "when converting from a string" do it "should create a CSR instance with its name set to the CSR subject and its content set to the extracted CSR" do csr = double('csr', :subject => OpenSSL::X509::Name.parse("/CN=Foo.madstop.com"), :is_a? => true) expect(OpenSSL::X509::Request).to receive(:new).with("my csr").and_return(csr) mycsr = double('sslcsr') expect(mycsr).to receive(:content=).with(csr) expect(described_class).to receive(:new).with("Foo.madstop.com").and_return(mycsr) described_class.from_s("my csr") end end describe "when managing instances" do it "should have a name attribute" do expect(request.name).to eq("myname") end it "should downcase its name" do expect(described_class.new("MyName").name).to eq("myname") end it "should have a content attribute" do expect(request).to respond_to(:content) end it "should be able to read requests from disk" do path = "/my/path" expect(Puppet::FileSystem).to receive(:read).with(path, {:encoding => Encoding::ASCII}).and_return("my request") my_req = double('request') expect(OpenSSL::X509::Request).to receive(:new).with("my request").and_return(my_req) expect(request.read(path)).to equal(my_req) expect(request.content).to equal(my_req) end it "should return an empty string when converted to a string with no request" do expect(request.to_s).to eq("") end it "should convert the request to pem format when converted to a string", :unless => RUBY_PLATFORM == 'java' do request.generate(key) expect(request.to_s).to eq(request.content.to_pem) end it "should have a :to_text method that it delegates to the actual key" do real_request = double('request') expect(real_request).to receive(:to_text).and_return("requesttext") request.content = real_request expect(request.to_text).to eq("requesttext") end end describe "when generating", :unless => RUBY_PLATFORM == 'java' do it "should verify the CSR using the public key associated with the private key" do request.generate(key) expect(request.content.verify(key.public_key)).to be_truthy end it "should set the version to 0" do request.generate(key) expect(request.content.version).to eq(0) end it "should set the public key to the provided key's public key" do request.generate(key) # The openssl bindings do not define equality on keys so we use to_s expect(request.content.public_key.to_s).to eq(key.public_key.to_s) end context "without subjectAltName / dns_alt_names" do before :each do Puppet[:dns_alt_names] = "" end ["extreq", "msExtReq"].each do |name| it "should not add any #{name} attribute" do request.generate(key) expect(request.content.attributes.find do |attr| attr.oid == name end).not_to be end it "should return no subjectAltNames" do request.generate(key) expect(request.subject_alt_names).to be_empty end end end context "with dns_alt_names" do before :each do Puppet[:dns_alt_names] = "one, two, three" end ["extreq", "msExtReq"].each do |name| it "should not add any #{name} attribute" do request.generate(key) expect(request.content.attributes.find do |attr| attr.oid == name end).not_to be end it "should return no subjectAltNames" do request.generate(key) expect(request.subject_alt_names).to be_empty end end end context "with subjectAltName to generate request" do before :each do Puppet[:dns_alt_names] = "" end it "should add an extreq attribute" do request.generate(key, :dns_alt_names => 'one, two') extReq = request.content.attributes.find do |attr| attr.oid == 'extReq' end expect(extReq).to be extReq.value.value.all? do |x| x.value.all? do |y| expect(y.value[0].value).to eq("subjectAltName") end end end it "should return the subjectAltName values" do request.generate(key, :dns_alt_names => 'one,two') expect(request.subject_alt_names).to match_array(["DNS:myname", "DNS:one", "DNS:two"]) end end context "with DNS and IP SAN specified" do before :each do Puppet[:dns_alt_names] = "" end it "should return the subjectAltName values" do request.generate(key, :dns_alt_names => 'DNS:foo, bar, IP:172.16.254.1') expect(request.subject_alt_names).to match_array(["DNS:bar", "DNS:foo", "DNS:myname", "IP Address:172.16.254.1"]) end end context "with custom CSR attributes" do it "adds attributes with single values" do csr_attributes = { '1.3.6.1.4.1.34380.1.2.1' => 'CSR specific info', '1.3.6.1.4.1.34380.1.2.2' => 'more CSR specific info', } request.generate(key, :csr_attributes => csr_attributes) attrs = request.custom_attributes expect(attrs).to include({'oid' => '1.3.6.1.4.1.34380.1.2.1', 'value' => 'CSR specific info'}) expect(attrs).to include({'oid' => '1.3.6.1.4.1.34380.1.2.2', 'value' => 'more CSR specific info'}) end ['extReq', '1.2.840.113549.1.9.14'].each do |oid| it "doesn't overwrite standard PKCS#9 CSR attribute '#{oid}'" do expect do request.generate(key, :csr_attributes => {oid => 'data'}) end.to raise_error ArgumentError, /Cannot specify.*#{oid}/ end end ['msExtReq', '1.3.6.1.4.1.311.2.1.14'].each do |oid| it "doesn't overwrite Microsoft extension request OID '#{oid}'" do expect do request.generate(key, :csr_attributes => {oid => 'data'}) end.to raise_error ArgumentError, /Cannot specify.*#{oid}/ end end it "raises an error if an attribute cannot be created" do csr_attributes = { "thats.no.moon" => "death star" } expect do request.generate(key, :csr_attributes => csr_attributes) end.to raise_error Puppet::Error, /Cannot create CSR with attribute thats\.no\.moon: / end it "should support old non-DER encoded extensions" do csr = OpenSSL::X509::Request.new(File.read(my_fixture("old-style-cert-request.pem"))) wrapped_csr = Puppet::SSL::CertificateRequest.from_instance csr exts = wrapped_csr.request_extensions() expect(exts.find { |ext| ext['oid'] == 'pp_uuid' }['value']).to eq('I-AM-A-UUID') expect(exts.find { |ext| ext['oid'] == 'pp_instance_id' }['value']).to eq('i_am_an_id') expect(exts.find { |ext| ext['oid'] == 'pp_image_name' }['value']).to eq('i_am_an_image_name') end end context "with extension requests" do let(:extension_data) do { '1.3.6.1.4.1.34380.1.1.31415' => 'pi', '1.3.6.1.4.1.34380.1.1.2718' => 'e', } end it "adds an extreq attribute to the CSR" do request.generate(key, :extension_requests => extension_data) exts = request.content.attributes.select { |attr| attr.oid = 'extReq' } expect(exts.length).to eq(1) end it "adds an extension for each entry in the extension request structure" do request.generate(key, :extension_requests => extension_data) exts = request.request_extensions expect(exts).to include('oid' => '1.3.6.1.4.1.34380.1.1.31415', 'value' => 'pi') expect(exts).to include('oid' => '1.3.6.1.4.1.34380.1.1.2718', 'value' => 'e') end it "defines the extensions as non-critical" do request.generate(key, :extension_requests => extension_data) request.request_extensions.each do |ext| expect(ext['critical']).to be_falsey end end it "rejects the subjectAltNames extension" do san_names = ['subjectAltName', '2.5.29.17'] san_field = 'DNS:first.tld, DNS:second.tld' san_names.each do |name| expect do request.generate(key, :extension_requests => {name => san_field}) end.to raise_error Puppet::Error, /conflicts with internally used extension/ end end it "merges the extReq attribute with the subjectAltNames extension" do request.generate(key, :dns_alt_names => 'first.tld, second.tld', :extension_requests => extension_data) exts = request.request_extensions expect(exts).to include('oid' => '1.3.6.1.4.1.34380.1.1.31415', 'value' => 'pi') expect(exts).to include('oid' => '1.3.6.1.4.1.34380.1.1.2718', 'value' => 'e') expect(exts).to include('oid' => 'subjectAltName', 'value' => 'DNS:first.tld, DNS:myname, DNS:second.tld') expect(request.subject_alt_names).to eq ['DNS:first.tld', 'DNS:myname', 'DNS:second.tld'] end it "raises an error if the OID could not be created" do exts = {"thats.no.moon" => "death star"} expect do request.generate(key, :extension_requests => exts) end.to raise_error Puppet::Error, /Cannot create CSR with extension request thats\.no\.moon.*: / end end it "should sign the csr with the provided key" do request.generate(key) expect(request.content.verify(key.public_key)).to be_truthy end it "should verify the generated request using the public key" do # Stupid keys don't have a competent == method. expect_any_instance_of(OpenSSL::X509::Request).to receive(:verify) do |public_key| public_key.to_s == key.public_key.to_s end.and_return(true) request.generate(key) end it "should fail if verification fails" do expect_any_instance_of(OpenSSL::X509::Request).to receive(:verify) do |public_key| public_key.to_s == key.public_key.to_s end.and_return(false) expect do request.generate(key) end.to raise_error(Puppet::Error, /CSR sign verification failed/) end it "should log the fingerprint" do allow_any_instance_of(Puppet::SSL::Digest).to receive(:to_hex).and_return("FINGERPRINT") allow(Puppet).to receive(:info) expect(Puppet).to receive(:info).with(/FINGERPRINT/) request.generate(key) end it "should return the generated request" do generated = request.generate(key) expect(generated).to be_a(OpenSSL::X509::Request) expect(generated).to be(request.content) end it "should use SHA1 to sign the csr when SHA256 isn't available" do csr = OpenSSL::X509::Request.new csr.public_key = key.public_key expect(OpenSSL::Digest).to receive(:const_defined?).with("SHA256").and_return(false) expect(OpenSSL::Digest).to receive(:const_defined?).with("SHA1").and_return(true) signer = Puppet::SSL::CertificateSigner.new signer.sign(csr, key) expect(csr.verify(key)).to be_truthy end it "should use SHA512 to sign the csr when SHA256 and SHA1 aren't available" do key = OpenSSL::PKey::RSA.new(2048) csr = OpenSSL::X509::Request.new csr.public_key = key.public_key expect(OpenSSL::Digest).to receive(:const_defined?).with("SHA256").and_return(false) expect(OpenSSL::Digest).to receive(:const_defined?).with("SHA1").and_return(false) expect(OpenSSL::Digest).to receive(:const_defined?).with("SHA512").and_return(true) signer = Puppet::SSL::CertificateSigner.new signer.sign(csr, key) expect(csr.verify(key)).to be_truthy end it "should use SHA384 to sign the csr when SHA256/SHA1/SHA512 aren't available" do key = OpenSSL::PKey::RSA.new(2048) csr = OpenSSL::X509::Request.new csr.public_key = key.public_key expect(OpenSSL::Digest).to receive(:const_defined?).with("SHA256").and_return(false) expect(OpenSSL::Digest).to receive(:const_defined?).with("SHA1").and_return(false) expect(OpenSSL::Digest).to receive(:const_defined?).with("SHA512").and_return(false) expect(OpenSSL::Digest).to receive(:const_defined?).with("SHA384").and_return(true) signer = Puppet::SSL::CertificateSigner.new signer.sign(csr, key) expect(csr.verify(key)).to be_truthy end it "should use SHA224 to sign the csr when SHA256/SHA1/SHA512/SHA384 aren't available" do csr = OpenSSL::X509::Request.new csr.public_key = key.public_key expect(OpenSSL::Digest).to receive(:const_defined?).with("SHA256").and_return(false) expect(OpenSSL::Digest).to receive(:const_defined?).with("SHA1").and_return(false) expect(OpenSSL::Digest).to receive(:const_defined?).with("SHA512").and_return(false) expect(OpenSSL::Digest).to receive(:const_defined?).with("SHA384").and_return(false) expect(OpenSSL::Digest).to receive(:const_defined?).with("SHA224").and_return(true) signer = Puppet::SSL::CertificateSigner.new signer.sign(csr, key) expect(csr.verify(key)).to be_truthy end it "should raise an error if neither SHA256/SHA1/SHA512/SHA384/SHA224 are available" do expect(OpenSSL::Digest).to receive(:const_defined?).with("SHA256").and_return(false) expect(OpenSSL::Digest).to receive(:const_defined?).with("SHA1").and_return(false) expect(OpenSSL::Digest).to receive(:const_defined?).with("SHA512").and_return(false) expect(OpenSSL::Digest).to receive(:const_defined?).with("SHA384").and_return(false) expect(OpenSSL::Digest).to receive(:const_defined?).with("SHA224").and_return(false) expect { Puppet::SSL::CertificateSigner.new }.to raise_error(Puppet::Error) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/ssl/state_machine_spec.rb
spec/unit/ssl/state_machine_spec.rb
require 'spec_helper' require 'puppet_spec/files' require 'puppet/ssl' describe Puppet::SSL::StateMachine, unless: Puppet::Util::Platform.jruby? do include PuppetSpec::Files let(:privatekeydir) { tmpdir('privatekeydir') } let(:certdir) { tmpdir('certdir') } let(:requestdir) { tmpdir('requestdir') } let(:machine) { described_class.new } let(:cert_provider) { Puppet::X509::CertProvider.new(privatekeydir: privatekeydir, certdir: certdir, requestdir: requestdir) } let(:ssl_provider) { Puppet::SSL::SSLProvider.new } let(:machine) { described_class.new(cert_provider: cert_provider, ssl_provider: ssl_provider) } let(:cacert_pem) { cacert.to_pem } let(:cacert) { cert_fixture('ca.pem') } let(:cacerts) { [cacert, cert_fixture('intermediate.pem')] } let(:crl_pem) { crl.to_pem } let(:crl) { crl_fixture('crl.pem') } let(:crls) { [crl, crl_fixture('intermediate-crl.pem')] } let(:private_key) { key_fixture('signed-key.pem') } let(:client_cert) { cert_fixture('signed.pem') } let(:refused_message) { %r{Connection refused|No connection could be made because the target machine actively refused it} } before(:each) do Puppet[:daemonize] = false Puppet[:ssl_lockfile] = tmpfile('ssllock') allow(Kernel).to receive(:sleep) future = Time.now + (5 * 60) allow_any_instance_of(Puppet::X509::CertProvider).to receive(:crl_last_update).and_return(future) allow_any_instance_of(Puppet::X509::CertProvider).to receive(:ca_last_update).and_return(future) end def expected_digest(name, content) OpenSSL::Digest.new(name).hexdigest(content) end def to_fingerprint(digest) digest.scan(/../).join(':').upcase end context 'when passing keyword arguments' do it "accepts digest" do expect(described_class.new(digest: 'SHA512').digest).to eq('SHA512') end it "accepts ca_fingerprint" do expect(described_class.new(ca_fingerprint: 'CAFE').ca_fingerprint).to eq('CAFE') end end context 'when ensuring CA certs and CRLs' do it 'returns an SSLContext with the loaded CA certs and CRLs' do allow(cert_provider).to receive(:load_cacerts).and_return(cacerts) allow(cert_provider).to receive(:load_crls).and_return(crls) ssl_context = machine.ensure_ca_certificates expect(ssl_context[:cacerts]).to eq(cacerts) expect(ssl_context[:crls]).to eq(crls) expect(ssl_context[:verify_peer]).to eq(true) end context 'when exceptions occur' do it 'raises in onetime mode' do stub_request(:get, %r{puppet-ca/v1/certificate/ca}) .to_raise(Errno::ECONNREFUSED) machine = described_class.new(cert_provider: cert_provider, ssl_provider: ssl_provider, onetime: true) expect { machine.ensure_ca_certificates }.to raise_error(Puppet::Error, refused_message) end it 'retries CA cert download' do # allow cert to be saved to disk FileUtils.mkdir_p(Puppet[:certdir]) allow(cert_provider).to receive(:load_crls).and_return(crls) req = stub_request(:get, %r{puppet-ca/v1/certificate/ca}) .to_raise(Errno::ECONNREFUSED).then .to_return(status: 200, body: cacert_pem) machine.ensure_ca_certificates expect(req).to have_been_made.twice expect(@logs).to include(an_object_having_attributes(message: refused_message)) end it 'retries CRL download' do # allow crl to be saved to disk FileUtils.mkdir_p(Puppet[:ssldir]) allow(cert_provider).to receive(:load_cacerts).and_return(cacerts) req = stub_request(:get, %r{puppet-ca/v1/certificate_revocation_list/ca}) .to_raise(Errno::ECONNREFUSED).then .to_return(status: 200, body: crl_pem) machine.ensure_ca_certificates expect(req).to have_been_made.twice expect(@logs).to include(an_object_having_attributes(message: refused_message)) end end end context 'when ensuring a client cert' do it 'returns an SSLContext with the loaded CA certs, CRLs, private key and client cert' do allow(cert_provider).to receive(:load_cacerts).and_return(cacerts) allow(cert_provider).to receive(:load_crls).and_return(crls) allow(cert_provider).to receive(:load_private_key).and_return(private_key) allow(cert_provider).to receive(:load_client_cert).and_return(client_cert) ssl_context = machine.ensure_client_certificate expect(ssl_context[:cacerts]).to eq(cacerts) expect(ssl_context[:crls]).to eq(crls) expect(ssl_context[:verify_peer]).to eq(true) expect(ssl_context[:private_key]).to eq(private_key) expect(ssl_context[:client_cert]).to eq(client_cert) end it 'uses the specified digest to log the cert chain fingerprints' do allow(cert_provider).to receive(:load_cacerts).and_return(cacerts) allow(cert_provider).to receive(:load_crls).and_return(crls) allow(cert_provider).to receive(:load_private_key).and_return(private_key) allow(cert_provider).to receive(:load_client_cert).and_return(client_cert) Puppet[:log_level] = :debug machine = described_class.new(cert_provider: cert_provider, digest: 'SHA512') machine.ensure_client_certificate expect(@logs).to include( an_object_having_attributes(message: /Verified CA certificate 'CN=Test CA' fingerprint \(SHA512\)/), an_object_having_attributes(message: /Verified CA certificate 'CN=Test CA Subauthority' fingerprint \(SHA512\)/), an_object_having_attributes(message: /Verified client certificate 'CN=signed' fingerprint \(SHA512\)/) ) end context 'when exceptions occur' do before :each do allow(cert_provider).to receive(:load_cacerts).and_return(cacerts) allow(cert_provider).to receive(:load_crls).and_return(crls) end it 'retries CSR submission' do allow(cert_provider).to receive(:load_private_key).and_return(private_key) allow($stdout).to receive(:puts).with(/Couldn't fetch certificate from CA server; you might still need to sign this agent's certificate/) stub_request(:get, %r{puppet-ca/v1/certificate/#{Puppet[:certname]}}) .to_return(status: 200, body: client_cert.to_pem) # first request raises, second succeeds req = stub_request(:put, %r{puppet-ca/v1/certificate_request/#{Puppet[:certname]}}) .to_raise(Errno::ECONNREFUSED).then .to_return(status: 200) machine.ensure_client_certificate expect(req).to have_been_made.twice expect(@logs).to include(an_object_having_attributes(message: refused_message)) end it 'retries client cert download' do allow(cert_provider).to receive(:load_private_key).and_return(private_key) # first request raises, second succeeds req = stub_request(:get, %r{puppet-ca/v1/certificate/#{Puppet[:certname]}}) .to_raise(Errno::ECONNREFUSED).then .to_return(status: 200, body: client_cert.to_pem) stub_request(:put, %r{puppet-ca/v1/certificate_request/#{Puppet[:certname]}}).to_return(status: 200) machine.ensure_client_certificate expect(req).to have_been_made.twice expect(@logs).to include(an_object_having_attributes(message: refused_message)) end it 'retries when client cert and private key are mismatched' do allow(cert_provider).to receive(:load_private_key).and_return(private_key) # return mismatched cert the first time, correct cert second time req = stub_request(:get, %r{puppet-ca/v1/certificate/#{Puppet[:certname]}}) .to_return(status: 200, body: cert_fixture('pluto.pem').to_pem) .to_return(status: 200, body: client_cert.to_pem) stub_request(:put, %r{puppet-ca/v1/certificate_request/#{Puppet[:certname]}}).to_return(status: 200) machine.ensure_client_certificate expect(req).to have_been_made.twice expect(@logs).to include(an_object_having_attributes(message: %r{The certificate for 'CN=pluto' does not match its private key})) end it 'raises in onetime mode' do stub_request(:get, %r{puppet-ca/v1/certificate/#{Puppet[:certname]}}) .to_raise(Errno::ECONNREFUSED) stub_request(:put, %r{puppet-ca/v1/certificate_request/#{Puppet[:certname]}}) .to_return(status: 200) machine = described_class.new(cert_provider: cert_provider, ssl_provider: ssl_provider, onetime: true) expect { machine.ensure_client_certificate }.to raise_error(Puppet::Error, refused_message) end end end context 'when locking' do let(:lockfile) { Puppet::Util::Pidlock.new(Puppet[:ssl_lockfile]) } let(:machine) { described_class.new(cert_provider: cert_provider, ssl_provider: ssl_provider, lockfile: lockfile) } # lockfile is deleted before `ensure_ca_certificates` returns, so # verify lockfile contents while state machine is running def expect_lockfile_to_contain(pid) allow(cert_provider).to receive(:load_cacerts) do expect(File.read(Puppet[:ssl_lockfile])).to eq(pid.to_s) end.and_return(cacerts) allow(cert_provider).to receive(:load_crls).and_return(crls) end it 'locks the file prior to running the state machine and unlocks when done' do expect(lockfile).to receive(:lock).and_call_original.ordered expect(cert_provider).to receive(:load_cacerts).and_return(cacerts).ordered expect(cert_provider).to receive(:load_crls).and_return(crls).ordered expect(lockfile).to receive(:unlock).ordered machine.ensure_ca_certificates end it 'deletes the lockfile when finished' do allow(cert_provider).to receive(:load_cacerts).and_return(cacerts) allow(cert_provider).to receive(:load_crls).and_return(crls) machine = described_class.new(cert_provider: cert_provider, ssl_provider: ssl_provider) machine.ensure_ca_certificates expect(File).to_not be_exist(Puppet[:ssl_lockfile]) end it 'acquires an empty lockfile' do Puppet::FileSystem.touch(Puppet[:ssl_lockfile]) expect_lockfile_to_contain(Process.pid) machine = described_class.new(cert_provider: cert_provider, ssl_provider: ssl_provider) machine.ensure_ca_certificates end it 'acquires its own lockfile' do File.write(Puppet[:ssl_lockfile], Process.pid.to_s) expect_lockfile_to_contain(Process.pid) machine = described_class.new(cert_provider: cert_provider, ssl_provider: ssl_provider) machine.ensure_ca_certificates end it 'overwrites a stale lockfile' do # 2**31 - 1 chosen to not conflict with existing pid File.write(Puppet[:ssl_lockfile], "2147483647") expect_lockfile_to_contain(Process.pid) machine = described_class.new(cert_provider: cert_provider, ssl_provider: ssl_provider) machine.ensure_ca_certificates end context 'and another puppet process is running' do let(:now) { Time.now } let(:future) { now + (5 * 60)} # 5 mins in the future before :each do allow(lockfile).to receive(:lock).and_return(false) end it 'raises a puppet exception' do expect { machine.ensure_ca_certificates }.to raise_error(Puppet::Error, /Another puppet instance is already running and the waitforlock setting is set to 0; exiting/) end it 'sleeps and retries successfully' do machine = described_class.new(lockfile: lockfile, cert_provider: cert_provider, waitforlock: 1, maxwaitforlock: 10) allow(cert_provider).to receive(:load_cacerts).and_return(cacerts) allow(cert_provider).to receive(:load_crls).and_return(crls) allow(Time).to receive(:now).and_return(now, future) expect(Kernel).to receive(:sleep).with(1) expect(Puppet).to receive(:info).with("Another puppet instance is already running; waiting for it to finish") expect(Puppet).to receive(:info).with("Will try again in 1 seconds.") allow(lockfile).to receive(:lock).and_return(false, true) expect(machine.ensure_ca_certificates).to be_an_instance_of(Puppet::SSL::SSLContext) end it 'sleeps and retries unsuccessfully until the deadline is exceeded' do machine = described_class.new(lockfile: lockfile, waitforlock: 1, maxwaitforlock: 10) allow(Time).to receive(:now).and_return(now, future) expect(Kernel).to receive(:sleep).with(1) expect(Puppet).to receive(:info).with("Another puppet instance is already running; waiting for it to finish") expect(Puppet).to receive(:info).with("Will try again in 1 seconds.") allow(lockfile).to receive(:lock).and_return(false) expect { machine.ensure_ca_certificates }.to raise_error(Puppet::Error, /Another puppet instance is already running and the maxwaitforlock timeout has been exceeded; exiting/) end it 'defaults the waitlock deadline to 60 seconds' do allow(Time).to receive(:now).and_return(now) machine = described_class.new expect(machine.waitlock_deadline).to eq(now.to_i + 60) end end end context 'NeedCACerts' do let(:state) { Puppet::SSL::StateMachine::NeedCACerts.new(machine) } before :each do Puppet[:localcacert] = tmpfile('needcacerts') end it 'transitions to NeedCRLs state' do allow(cert_provider).to receive(:load_cacerts).and_return(cacerts) expect(state.next_state).to be_an_instance_of(Puppet::SSL::StateMachine::NeedCRLs) end it 'loads existing CA certs' do allow(cert_provider).to receive(:load_cacerts).and_return(cacerts) st = state.next_state expect(st.ssl_context[:cacerts]).to eq(cacerts) end it 'fetches and saves CA certs' do allow(cert_provider).to receive(:load_cacerts).and_return(nil) stub_request(:get, %r{puppet-ca/v1/certificate/ca}).to_return(status: 200, body: cacert_pem) st = state.next_state expect(st.ssl_context[:cacerts].map(&:to_pem)).to eq([cacert_pem]) expect(File).to be_exist(Puppet[:localcacert]) end it "does not verify the server's cert if there are no local CA certs" do allow(cert_provider).to receive(:load_cacerts).and_return(nil) stub_request(:get, %r{puppet-ca/v1/certificate/ca}).to_return(status: 200, body: cacert_pem) allow(cert_provider).to receive(:save_cacerts) receive_count = 0 allow_any_instance_of(Net::HTTP).to receive(:verify_mode=).with(OpenSSL::SSL::VERIFY_NONE) { receive_count += 1 } state.next_state expect(receive_count).to eq(2) end it 'returns an Error if the server returns 404' do stub_request(:get, %r{puppet-ca/v1/certificate/ca}).to_return(status: 404) st = state.next_state expect(st).to be_an_instance_of(Puppet::SSL::StateMachine::Error) expect(st.message).to eq("CA certificate is missing from the server") end it 'returns an Error if there is a different exception' do stub_request(:get, %r{puppet-ca/v1/certificate/ca}).to_return(status: [500, 'Internal Server Error']) st = state.next_state expect(st).to be_an_instance_of(Puppet::SSL::StateMachine::Error) expect(st.message).to eq("Could not download CA certificate: Internal Server Error") end it 'returns an Error if CA certs are invalid' do allow(cert_provider).to receive(:load_cacerts).and_return(nil) stub_request(:get, %r{puppet-ca/v1/certificate/ca}).to_return(status: 200, body: '') st = state.next_state expect(st).to be_an_instance_of(Puppet::SSL::StateMachine::Error) expect(st.error).to be_an_instance_of(OpenSSL::X509::CertificateError) end it 'does not save invalid CA certs' do stub_request(:get, %r{puppet-ca/v1/certificate/ca}).to_return(status: 200, body: <<~END) -----BEGIN CERTIFICATE----- MIIBpDCCAQ2gAwIBAgIBAjANBgkqhkiG9w0BAQsFADAfMR0wGwYDVQQDDBRUZXN0 END state.next_state rescue OpenSSL::X509::CertificateError expect(File).to_not exist(Puppet[:localcacert]) end it 'skips CA refresh if it has not expired' do Puppet[:ca_refresh_interval] = '1y' Puppet::FileSystem.touch(Puppet[:localcacert], mtime: Time.now) allow_any_instance_of(Puppet::X509::CertProvider).to receive(:load_cacerts).and_return(cacerts) # we're expecting a net/http request to never be made state.next_state end context 'when verifying CA cert bundle' do before :each do allow(cert_provider).to receive(:load_cacerts).and_return(nil) stub_request(:get, %r{puppet-ca/v1/certificate/ca}).to_return(status: 200, body: cacert_pem) allow(cert_provider).to receive(:save_cacerts) end it 'verifies CA cert bundle if a ca_fingerprint is given case-insensitively' do Puppet[:log_level] = :info digest = expected_digest('SHA256', cacert_pem) fingerprint = to_fingerprint(digest) machine = described_class.new(digest: 'SHA256', ca_fingerprint: digest.downcase) state = Puppet::SSL::StateMachine::NeedCACerts.new(machine) state.next_state expect(@logs).to include(an_object_having_attributes(message: "Verified CA bundle with digest (SHA256) #{fingerprint}")) end it 'verifies CA cert bundle using non-default fingerprint' do Puppet[:log_level] = :info digest = expected_digest('SHA512', cacert_pem) machine = described_class.new(digest: 'SHA512', ca_fingerprint: digest) state = Puppet::SSL::StateMachine::NeedCACerts.new(machine) state.next_state expect(@logs).to include(an_object_having_attributes(message: "Verified CA bundle with digest (SHA512) #{to_fingerprint(digest)}")) end it 'returns an error if verification fails' do machine = described_class.new(digest: 'SHA256', ca_fingerprint: 'wrong!') state = Puppet::SSL::StateMachine::NeedCACerts.new(machine) fingerprint = to_fingerprint(expected_digest('SHA256', cacert_pem)) st = state.next_state expect(st).to be_an_instance_of(Puppet::SSL::StateMachine::Error) expect(st.message).to eq("CA bundle with digest (SHA256) #{fingerprint} did not match expected digest WR:ON:G!") end end context 'when refreshing a CA bundle' do before :each do Puppet[:ca_refresh_interval] = '1s' allow_any_instance_of(Puppet::X509::CertProvider).to receive(:load_cacerts).and_return(cacerts) yesterday = Time.now - (24 * 60 * 60) allow_any_instance_of(Puppet::X509::CertProvider).to receive(:ca_last_update).and_return(yesterday) end let(:new_ca_bundle) do # add 'unknown' cert to the bundle [cacert, cert_fixture('intermediate.pem'), cert_fixture('unknown-ca.pem')].map(&:to_pem) end it 'uses the local CA if it has not been modified' do stub_request(:get, %r{puppet-ca/v1/certificate/ca}).to_return(status: 304) expect(state.next_state.ssl_context.cacerts).to eq(cacerts) end it 'uses the local CA if refreshing fails in HTTP layer' do stub_request(:get, %r{puppet-ca/v1/certificate/ca}).to_return(status: 503) expect(state.next_state.ssl_context.cacerts).to eq(cacerts) end it 'uses the local CA if refreshing fails in TCP layer' do stub_request(:get, %r{puppet-ca/v1/certificate/ca}).to_raise(Errno::ECONNREFUSED) expect(state.next_state.ssl_context.cacerts).to eq(cacerts) end it 'uses the updated crl for the future requests' do stub_request(:get, %r{puppet-ca/v1/certificate/ca}).to_return(status: 200, body: new_ca_bundle.join) expect(state.next_state.ssl_context.cacerts.map(&:to_pem)).to eq(new_ca_bundle) end it 'updates the `last_update` time on successful CA refresh' do stub_request(:get, %r{puppet-ca/v1/certificate/ca}).to_return(status: 200, body: new_ca_bundle.join) expect_any_instance_of(Puppet::X509::CertProvider).to receive(:ca_last_update=).with(be_within(60).of(Time.now)) state.next_state end it "does not update the `last_update` time when CA refresh fails" do stub_request(:get, %r{puppet-ca/v1/certificate/ca}).to_raise(Errno::ECONNREFUSED) expect_any_instance_of(Puppet::X509::CertProvider).to receive(:ca_last_update=).never state.next_state end it 'forces the NeedCRLs to refresh' do stub_request(:get, %r{puppet-ca/v1/certificate/ca}).to_return(status: 200, body: new_ca_bundle.join) st = state.next_state expect(st).to be_an_instance_of(Puppet::SSL::StateMachine::NeedCRLs) expect(st.force_crl_refresh).to eq(true) end end end context 'NeedCRLs' do let(:ssl_context) { Puppet::SSL::SSLContext.new(cacerts: cacerts)} let(:state) { Puppet::SSL::StateMachine::NeedCRLs.new(machine, ssl_context) } before :each do Puppet[:hostcrl] = tmpfile('needcrls') end it 'transitions to NeedKey state' do allow(cert_provider).to receive(:load_crls).and_return(crls) expect(state.next_state).to be_an_instance_of(Puppet::SSL::StateMachine::NeedKey) end it 'loads existing CRLs' do allow(cert_provider).to receive(:load_crls).and_return(crls) st = state.next_state expect(st.ssl_context[:crls]).to eq(crls) end it 'fetches and saves CRLs' do allow(cert_provider).to receive(:load_crls).and_return(nil) stub_request(:get, %r{puppet-ca/v1/certificate_revocation_list/ca}).to_return(status: 200, body: crl_pem) st = state.next_state expect(st.ssl_context[:crls].map(&:to_pem)).to eq([crl_pem]) expect(File).to be_exist(Puppet[:hostcrl]) end it "verifies the server's certificate when fetching the CRL" do allow(cert_provider).to receive(:load_crls).and_return(nil) stub_request(:get, %r{puppet-ca/v1/certificate_revocation_list/ca}).to_return(status: 200, body: crl_pem) allow(cert_provider).to receive(:save_crls) receive_count = 0 allow_any_instance_of(Net::HTTP).to receive(:verify_mode=).with(OpenSSL::SSL::VERIFY_PEER) { receive_count += 1 } state.next_state expect(receive_count).to eq(2) end it 'returns an Error if the server returns 404' do stub_request(:get, %r{puppet-ca/v1/certificate_revocation_list/ca}).to_return(status: 404) st = state.next_state expect(st).to be_an_instance_of(Puppet::SSL::StateMachine::Error) expect(st.message).to eq("CRL is missing from the server") end it 'returns an Error if there is a different exception' do stub_request(:get, %r{puppet-ca/v1/certificate_revocation_list/ca}).to_return(status: [500, 'Internal Server Error']) st = state.next_state expect(st).to be_an_instance_of(Puppet::SSL::StateMachine::Error) expect(st.message).to eq("Could not download CRLs: Internal Server Error") end it 'returns an Error if CRLs are invalid' do allow(cert_provider).to receive(:load_crls).and_return(nil) stub_request(:get, %r{puppet-ca/v1/certificate_revocation_list/ca}).to_return(status: 200, body: '') st = state.next_state expect(st).to be_an_instance_of(Puppet::SSL::StateMachine::Error) expect(st.error).to be_an_instance_of(OpenSSL::X509::CRLError) end it 'does not save invalid CRLs' do stub_request(:get, %r{puppet-ca/v1/certificate_revocation_list/ca}).to_return(status: 200, body: <<~END) -----BEGIN X509 CRL----- MIIBCjB1AgEBMA0GCSqGSIb3DQEBCwUAMBIxEDAOBgNVBAMMB1Rlc3QgQ0EXDTcw END state.next_state rescue OpenSSL::X509::CRLError expect(File).to_not exist(Puppet[:hostcrl]) end it 'skips CRL download when revocation is disabled' do Puppet[:certificate_revocation] = false expect(cert_provider).not_to receive(:load_crls) state.next_state expect(File).to_not exist(Puppet[:hostcrl]) end it 'skips CRL refresh if it has not expired' do Puppet[:crl_refresh_interval] = '1y' Puppet::FileSystem.touch(Puppet[:hostcrl], mtime: Time.now) allow_any_instance_of(Puppet::X509::CertProvider).to receive(:load_crls).and_return(crls) # we're expecting a net/http request to never be made state.next_state end context 'when refreshing a CRL' do before :each do Puppet[:crl_refresh_interval] = '1s' allow_any_instance_of(Puppet::X509::CertProvider).to receive(:load_crls).and_return(crls) yesterday = Time.now - (24 * 60 * 60) allow_any_instance_of(Puppet::X509::CertProvider).to receive(:crl_last_update).and_return(yesterday) end let(:new_crl_bundle) do # add intermediate crl to the bundle int_crl = crl_fixture('intermediate-crl.pem') [crl, int_crl].map(&:to_pem) end it 'uses the local crl if it has not been modified' do stub_request(:get, %r{puppet-ca/v1/certificate_revocation_list/ca}).to_return(status: 304) expect(state.next_state.ssl_context.crls).to eq(crls) end it 'uses the local crl if refreshing fails in HTTP layer' do stub_request(:get, %r{puppet-ca/v1/certificate_revocation_list/ca}).to_return(status: 503) expect(state.next_state.ssl_context.crls).to eq(crls) end it 'uses the local crl if refreshing fails in TCP layer' do stub_request(:get, %r{puppet-ca/v1/certificate_revocation_list/ca}).to_raise(Errno::ECONNREFUSED) expect(state.next_state.ssl_context.crls).to eq(crls) end it 'uses the updated crl for the future requests' do stub_request(:get, %r{puppet-ca/v1/certificate_revocation_list/ca}).to_return(status: 200, body: new_crl_bundle.join) expect(state.next_state.ssl_context.crls.map(&:to_pem)).to eq(new_crl_bundle) end it 'updates the `last_update` time' do stub_request(:get, %r{puppet-ca/v1/certificate_revocation_list/ca}).to_return(status: 200, body: new_crl_bundle.join) expect_any_instance_of(Puppet::X509::CertProvider).to receive(:crl_last_update=).with(be_within(60).of(Time.now)) state.next_state end end end context 'when ensuring a client cert' do context 'in state NeedKey' do let(:ssl_context) { Puppet::SSL::SSLContext.new(cacerts: cacerts, crls: crls)} let(:state) { Puppet::SSL::StateMachine::NeedKey.new(machine, ssl_context) } it 'loads an existing private key and passes it to the next state' do allow(cert_provider).to receive(:load_private_key).and_return(private_key) st = state.next_state expect(st).to be_instance_of(Puppet::SSL::StateMachine::NeedSubmitCSR) expect(st.private_key).to eq(private_key) end it 'loads a matching private key and cert' do allow(cert_provider).to receive(:load_private_key).and_return(private_key) allow(cert_provider).to receive(:load_client_cert).and_return(client_cert) st = state.next_state expect(st).to be_instance_of(Puppet::SSL::StateMachine::Done) end it 'raises if the client cert is mismatched' do allow(cert_provider).to receive(:load_private_key).and_return(private_key) allow(cert_provider).to receive(:load_client_cert).and_return(cert_fixture('tampered-cert.pem')) ssl_context = Puppet::SSL::SSLContext.new(cacerts: [cacert], crls: [crl]) state = Puppet::SSL::StateMachine::NeedKey.new(machine, ssl_context) expect { state.next_state }.to raise_error(Puppet::SSL::SSLError, %r{The certificate for 'CN=signed' does not match its private key}) end it 'generates a new RSA private key, saves it and passes it to the next state' do allow(cert_provider).to receive(:load_private_key).and_return(nil) expect(cert_provider).to receive(:save_private_key) st = state.next_state expect(st).to be_instance_of(Puppet::SSL::StateMachine::NeedSubmitCSR) expect(st.private_key).to be_instance_of(OpenSSL::PKey::RSA) expect(st.private_key).to be_private end it 'generates a new EC private key, saves it and passes it to the next state' do Puppet[:key_type] = 'ec' allow(cert_provider).to receive(:load_private_key).and_return(nil) expect(cert_provider).to receive(:save_private_key) st = state.next_state expect(st).to be_instance_of(Puppet::SSL::StateMachine::NeedSubmitCSR) expect(st.private_key).to be_instance_of(OpenSSL::PKey::EC) expect(st.private_key).to be_private expect(st.private_key.group.curve_name).to eq('prime256v1') end it 'generates a new EC private key with curve `secp384r1`, saves it and passes it to the next state' do Puppet[:key_type] = 'ec' Puppet[:named_curve] = 'secp384r1' allow(cert_provider).to receive(:load_private_key).and_return(nil) expect(cert_provider).to receive(:save_private_key) st = state.next_state expect(st).to be_instance_of(Puppet::SSL::StateMachine::NeedSubmitCSR) expect(st.private_key).to be_instance_of(OpenSSL::PKey::EC) expect(st.private_key).to be_private expect(st.private_key.group.curve_name).to eq('secp384r1') end it 'raises if the named curve is unsupported' do Puppet[:key_type] = 'ec' Puppet[:named_curve] = 'infiniteloop' allow(cert_provider).to receive(:load_private_key).and_return(nil) expect { state.next_state }.to raise_error(OpenSSL::PKey::ECError, /(invalid|unknown) curve name/) end it 'raises an error if it fails to load the key' do allow(cert_provider).to receive(:load_private_key).and_raise(OpenSSL::PKey::RSAError) expect { state.next_state }.to raise_error(OpenSSL::PKey::RSAError) end it "transitions to Done if current time plus renewal interval is less than cert's \"NotAfter\" time" do allow(cert_provider).to receive(:load_private_key).and_return(private_key) allow(cert_provider).to receive(:load_client_cert).and_return(client_cert) st = state.next_state expect(st).to be_instance_of(Puppet::SSL::StateMachine::Done) end it "returns NeedRenewedCert if current time plus renewal interval is greater than cert's \"NotAfter\" time" do client_cert.not_after=(Time.now + 300) allow(cert_provider).to receive(:load_private_key).and_return(private_key) allow(cert_provider).to receive(:load_client_cert).and_return(client_cert) ssl_context = Puppet::SSL::SSLContext.new(cacerts: [cacert], client_cert: client_cert, crls: [crl]) state = Puppet::SSL::StateMachine::NeedKey.new(machine, ssl_context) st = state.next_state expect(st).to be_instance_of(Puppet::SSL::StateMachine::NeedRenewedCert) end end context 'in state NeedSubmitCSR' do let(:ssl_context) { Puppet::SSL::SSLContext.new(cacerts: cacerts, crls: crls)} let(:state) { Puppet::SSL::StateMachine::NeedSubmitCSR.new(machine, ssl_context, private_key) } def write_csr_attributes(data) file_containing('state_machine_csr', YAML.dump(data)) end before :each do allow(cert_provider).to receive(:save_request) end it 'submits the CSR and transitions to NeedCert' do stub_request(:put, %r{puppet-ca/v1/certificate_request/#{Puppet[:certname]}}).to_return(status: 200) expect(state.next_state).to be_an_instance_of(Puppet::SSL::StateMachine::NeedCert) end it 'saves the CSR and transitions to NeedCert' do stub_request(:put, %r{puppet-ca/v1/certificate_request/#{Puppet[:certname]}}).to_return(status: 200) expect(cert_provider).to receive(:save_request).with(Puppet[:certname], instance_of(OpenSSL::X509::Request)) state.next_state end it 'includes DNS alt names' do Puppet[:dns_alt_names] = "one,IP:192.168.0.1,DNS:two.com" stub_request(:put, %r{puppet-ca/v1/certificate_request/#{Puppet[:certname]}}).with do |request| csr = Puppet::SSL::CertificateRequest.from_instance(OpenSSL::X509::Request.new(request.body)) expect( csr.subject_alt_names ).to contain_exactly('DNS:one', 'IP Address:192.168.0.1', 'DNS:two.com', "DNS:#{Puppet[:certname]}")
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
true
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/ssl/oids_spec.rb
spec/unit/ssl/oids_spec.rb
require 'spec_helper' require 'puppet/ssl/oids' describe Puppet::SSL::Oids do describe "defining application OIDs" do { 'puppetlabs' => '1.3.6.1.4.1.34380', 'ppCertExt' => '1.3.6.1.4.1.34380.1', 'ppRegCertExt' => '1.3.6.1.4.1.34380.1.1', 'pp_uuid' => '1.3.6.1.4.1.34380.1.1.1', 'pp_instance_id' => '1.3.6.1.4.1.34380.1.1.2', 'pp_image_name' => '1.3.6.1.4.1.34380.1.1.3', 'pp_preshared_key' => '1.3.6.1.4.1.34380.1.1.4', 'pp_cost_center' => '1.3.6.1.4.1.34380.1.1.5', 'pp_product' => '1.3.6.1.4.1.34380.1.1.6', 'pp_project' => '1.3.6.1.4.1.34380.1.1.7', 'pp_application' => '1.3.6.1.4.1.34380.1.1.8', 'pp_service' => '1.3.6.1.4.1.34380.1.1.9', 'pp_employee' => '1.3.6.1.4.1.34380.1.1.10', 'pp_created_by' => '1.3.6.1.4.1.34380.1.1.11', 'pp_environment' => '1.3.6.1.4.1.34380.1.1.12', 'pp_role' => '1.3.6.1.4.1.34380.1.1.13', 'pp_software_version' => '1.3.6.1.4.1.34380.1.1.14', 'pp_department' => '1.3.6.1.4.1.34380.1.1.15', 'pp_cluster' => '1.3.6.1.4.1.34380.1.1.16', 'pp_provisioner' => '1.3.6.1.4.1.34380.1.1.17', 'pp_region' => '1.3.6.1.4.1.34380.1.1.18', 'pp_datacenter' => '1.3.6.1.4.1.34380.1.1.19', 'pp_zone' => '1.3.6.1.4.1.34380.1.1.20', 'pp_network' => '1.3.6.1.4.1.34380.1.1.21', 'pp_securitypolicy' => '1.3.6.1.4.1.34380.1.1.22', 'pp_cloudplatform' => '1.3.6.1.4.1.34380.1.1.23', 'pp_apptier' => '1.3.6.1.4.1.34380.1.1.24', 'pp_hostname' => '1.3.6.1.4.1.34380.1.1.25', 'pp_owner' => '1.3.6.1.4.1.34380.1.1.26', 'ppPrivCertExt' => '1.3.6.1.4.1.34380.1.2', 'ppAuthCertExt' => '1.3.6.1.4.1.34380.1.3', 'pp_authorization' => '1.3.6.1.4.1.34380.1.3.1', 'pp_auth_role' => '1.3.6.1.4.1.34380.1.3.13', }.each_pair do |sn, oid| it "defines #{sn} as #{oid}" do object_id = OpenSSL::ASN1::ObjectId.new(sn) expect(object_id.oid).to eq oid end end end describe "checking if an OID is a subtree of another OID" do it "can determine if an OID is contained in another OID" do expect(described_class.subtree_of?('1.3.6.1', '1.3.6.1.4.1')).to be_truthy expect(described_class.subtree_of?('1.3.6.1.4.1', '1.3.6.1')).to be_falsey end it "returns true if an OID is compared against itself and exclusive is false" do expect(described_class.subtree_of?('1.3.6.1', '1.3.6.1', false)).to be_truthy end it "returns false if an OID is compared against itself and exclusive is true" do expect(described_class.subtree_of?('1.3.6.1', '1.3.6.1', true)).to be_falsey end it "can compare OIDs defined as short names" do expect(described_class.subtree_of?('IANA', '1.3.6.1.4.1')).to be_truthy expect(described_class.subtree_of?('1.3.6.1', 'enterprises')).to be_truthy end it "returns false when an invalid OID shortname is passed" do expect(described_class.subtree_of?('IANA', 'bananas')).to be_falsey end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/ssl/digest_spec.rb
spec/unit/ssl/digest_spec.rb
require 'spec_helper' require 'puppet/ssl/digest' describe Puppet::SSL::Digest do it "defaults to sha256" do digest = described_class.new(nil, 'blah') expect(digest.name).to eq('SHA256') expect(digest.digest.hexdigest).to eq("8b7df143d91c716ecfa5fc1730022f6b421b05cedee8fd52b1fc65a96030ad52") end describe '#name' do it "prints the hashing algorithm used by the openssl digest" do expect(described_class.new('SHA224', 'blah').name).to eq('SHA224') end it "upcases the hashing algorithm" do expect(described_class.new('sha224', 'blah').name).to eq('SHA224') end end describe '#to_hex' do it "returns ':' separated upper case hex pairs" do described_class.new(nil, 'blah').to_hex =~ /\A([A-Z0-9]:)+[A-Z0-9]\Z/ end end describe '#to_s' do it "formats the digest algorithm and the digest as a string" do digest = described_class.new('sha512', 'some content') expect(digest.to_s).to eq("(#{digest.name}) #{digest.to_hex}") end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/ssl/certificate_spec.rb
spec/unit/ssl/certificate_spec.rb
require 'spec_helper' require 'puppet/certificate_factory' require 'puppet/ssl/certificate' describe Puppet::SSL::Certificate do let :key do OpenSSL::PKey::RSA.new(Puppet[:keylength]) end # Sign the provided cert so that it can be DER-decoded later def sign_wrapped_cert(cert) signer = Puppet::SSL::CertificateSigner.new signer.sign(cert.content, key) end before do @class = Puppet::SSL::Certificate end it "should only support the text format" do expect(@class.supported_formats).to eq([:s]) end describe "when converting from a string" do it "should create a certificate instance with its name set to the certificate subject and its content set to the extracted certificate" do cert = double( 'certificate', :subject => OpenSSL::X509::Name.parse("/CN=Foo.madstop.com"), :is_a? => true ) expect(OpenSSL::X509::Certificate).to receive(:new).with("my certificate").and_return(cert) mycert = double('sslcert') expect(mycert).to receive(:content=).with(cert) expect(@class).to receive(:new).with("Foo.madstop.com").and_return(mycert) @class.from_s("my certificate") end it "should create multiple certificate instances when asked" do cert1 = double('cert1') expect(@class).to receive(:from_s).with("cert1").and_return(cert1) cert2 = double('cert2') expect(@class).to receive(:from_s).with("cert2").and_return(cert2) expect(@class.from_multiple_s("cert1\n---\ncert2")).to eq([cert1, cert2]) end end describe "when converting to a string" do before do @certificate = @class.new("myname") end it "should return an empty string when it has no certificate" do expect(@certificate.to_s).to eq("") end it "should convert the certificate to pem format" do certificate = double('certificate', :to_pem => "pem") @certificate.content = certificate expect(@certificate.to_s).to eq("pem") end it "should be able to convert multiple instances to a string" do cert2 = @class.new("foo") expect(@certificate).to receive(:to_s).and_return("cert1") expect(cert2).to receive(:to_s).and_return("cert2") expect(@class.to_multiple_s([@certificate, cert2])).to eq("cert1\n---\ncert2") end end describe "when managing instances" do def build_cert(opts) key = OpenSSL::PKey::RSA.new(Puppet[:keylength]) csr = Puppet::SSL::CertificateRequest.new('quux') csr.generate(key, opts) raw_cert = Puppet::CertificateFactory.build('client', csr, csr.content, 14) @class.from_instance(raw_cert) end before do @certificate = @class.new("myname") end it "should have a name attribute" do expect(@certificate.name).to eq("myname") end it "should convert its name to a string and downcase it" do expect(@class.new(:MyName).name).to eq("myname") end it "should have a content attribute" do expect(@certificate).to respond_to(:content) end describe "#subject_alt_names", :unless => RUBY_PLATFORM == 'java' do it "should list all alternate names when the extension is present" do certificate = build_cert(:dns_alt_names => 'foo, bar,baz') expect(certificate.subject_alt_names). to match_array(['DNS:foo', 'DNS:bar', 'DNS:baz', 'DNS:quux']) end it "should return an empty list of names if the extension is absent" do certificate = build_cert({}) expect(certificate.subject_alt_names).to be_empty end end describe "custom extensions", :unless => RUBY_PLATFORM == 'java' do it "returns extensions under the ppRegCertExt" do exts = {'pp_uuid' => 'abcdfd'} cert = build_cert(:extension_requests => exts) sign_wrapped_cert(cert) expect(cert.custom_extensions).to include('oid' => 'pp_uuid', 'value' => 'abcdfd') end it "returns extensions under the ppPrivCertExt" do exts = {'1.3.6.1.4.1.34380.1.2.1' => 'x509 :('} cert = build_cert(:extension_requests => exts) sign_wrapped_cert(cert) expect(cert.custom_extensions).to include('oid' => '1.3.6.1.4.1.34380.1.2.1', 'value' => 'x509 :(') end it "returns extensions under the ppAuthCertExt" do exts = {'pp_auth_role' => 'taketwo'} cert = build_cert(:extension_requests => exts) sign_wrapped_cert(cert) expect(cert.custom_extensions).to include('oid' => 'pp_auth_role', 'value' => 'taketwo') end it "doesn't return standard extensions" do cert = build_cert(:dns_alt_names => 'foo') expect(cert.custom_extensions).to be_empty end end it "should return a nil expiration if there is no actual certificate" do allow(@certificate).to receive(:content).and_return(nil) expect(@certificate.expiration).to be_nil end it "should use the expiration of the certificate as its expiration date" do cert = double('cert') allow(@certificate).to receive(:content).and_return(cert) expect(cert).to receive(:not_after).and_return("sometime") expect(@certificate.expiration).to eq("sometime") end it "should be able to read certificates from disk" do path = "/my/path" expect(Puppet::FileSystem).to receive(:read).with(path, {:encoding => Encoding::ASCII}).and_return("my certificate") certificate = double('certificate') expect(OpenSSL::X509::Certificate).to receive(:new).with("my certificate").and_return(certificate) expect(@certificate.read(path)).to equal(certificate) expect(@certificate.content).to equal(certificate) end it "should have a :to_text method that it delegates to the actual key" do real_certificate = double('certificate') expect(real_certificate).to receive(:to_text).and_return("certificatetext") @certificate.content = real_certificate expect(@certificate.to_text).to eq("certificatetext") end it "should parse the old non-DER encoded extension values" do cert = OpenSSL::X509::Certificate.new(File.read(my_fixture("old-style-cert-exts.pem"))) wrapped_cert = Puppet::SSL::Certificate.from_instance cert exts = wrapped_cert.custom_extensions expect(exts.find { |ext| ext['oid'] == 'pp_uuid'}['value']).to eq('I-AM-A-UUID') expect(exts.find { |ext| ext['oid'] == 'pp_instance_id'}['value']).to eq('i_am_an_id') expect(exts.find { |ext| ext['oid'] == 'pp_image_name'}['value']).to eq('i_am_an_image_name') end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/ssl/base_spec.rb
spec/unit/ssl/base_spec.rb
require 'spec_helper' require 'puppet/ssl/certificate' class TestCertificate < Puppet::SSL::Base wraps(Puppet::SSL::Certificate) end describe Puppet::SSL::Certificate do before :each do @base = TestCertificate.new("name") @class = TestCertificate end describe "when creating new instances" do it "should fail if given an object that is not an instance of the wrapped class" do obj = double('obj', :is_a? => false) expect { @class.from_instance(obj) }.to raise_error(ArgumentError) end it "should fail if a name is not supplied and can't be determined from the object" do obj = double('obj', :is_a? => true) expect { @class.from_instance(obj) }.to raise_error(ArgumentError) end it "should determine the name from the object if it has a subject" do obj = double('obj', :is_a? => true, :subject => '/CN=foo') inst = double('base') expect(inst).to receive(:content=).with(obj) expect(@class).to receive(:new).with('foo').and_return(inst) expect(@class).to receive(:name_from_subject).with('/CN=foo').and_return('foo') expect(@class.from_instance(obj)).to eq(inst) end end describe "when determining a name from a certificate subject" do it "should extract only the CN and not any other components" do name = OpenSSL::X509::Name.parse('/CN=host.domain.com/L=Portland/ST=Oregon') expect(@class.name_from_subject(name)).to eq('host.domain.com') end end describe "when initializing wrapped class from a file with #read" do it "should open the file with ASCII encoding" do path = '/foo/bar/cert' expect(Puppet::FileSystem).to receive(:read).with(path, {:encoding => Encoding::ASCII}).and_return("bar") @base.read(path) end end describe "#digest_algorithm" do let(:content) { double('content') } let(:base) { b = Puppet::SSL::Base.new('base') b.content = content b } # Some known signature algorithms taken from RFC 3279, 5758, and browsing # objs_dat.h in openssl { 'md5WithRSAEncryption' => 'md5', 'sha1WithRSAEncryption' => 'sha1', 'md4WithRSAEncryption' => 'md4', 'sha256WithRSAEncryption' => 'sha256', 'ripemd160WithRSA' => 'ripemd160', 'ecdsa-with-SHA1' => 'sha1', 'ecdsa-with-SHA224' => 'sha224', 'ecdsa-with-SHA256' => 'sha256', 'ecdsa-with-SHA384' => 'sha384', 'ecdsa-with-SHA512' => 'sha512', 'dsa_with_SHA224' => 'sha224', 'dsaWithSHA1' => 'sha1', }.each do |signature, digest| it "returns '#{digest}' for signature algorithm '#{signature}'" do allow(content).to receive(:signature_algorithm).and_return(signature) expect(base.digest_algorithm).to eq(digest) end end it "raises an error on an unknown signature algorithm" do allow(content).to receive(:signature_algorithm).and_return("nonsense") expect { base.digest_algorithm }.to raise_error(Puppet::Error, "Unknown signature algorithm 'nonsense'") end end describe "when getting a CN from a subject" do def parse(dn) OpenSSL::X509::Name.parse(dn) end def cn_from(subject) @class.name_from_subject(subject) end it "should correctly parse a subject containing only a CN" do subj = parse('/CN=foo') expect(cn_from(subj)).to eq('foo') end it "should correctly parse a subject containing other components" do subj = parse('/CN=Root CA/OU=Server Operations/O=Example Org') expect(cn_from(subj)).to eq('Root CA') end it "should correctly parse a subject containing other components with CN not first" do subj = parse('/emailAddress=foo@bar.com/CN=foo.bar.com/O=Example Org') expect(cn_from(subj)).to eq('foo.bar.com') end it "should return nil for a subject with no CN" do subj = parse('/OU=Server Operations/O=Example Org') expect(cn_from(subj)).to eq(nil) end it "should return nil for a bare string" do expect(cn_from("/CN=foo")).to eq(nil) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/unit/ssl/ssl_provider_spec.rb
spec/unit/ssl/ssl_provider_spec.rb
require 'spec_helper' describe Puppet::SSL::SSLProvider do include PuppetSpec::Files let(:global_cacerts) { [ cert_fixture('ca.pem'), cert_fixture('intermediate.pem') ] } let(:global_crls) { [ crl_fixture('crl.pem'), crl_fixture('intermediate-crl.pem') ] } let(:wrong_key) { OpenSSL::PKey::RSA.new(512) } context 'when creating an insecure context' do let(:sslctx) { subject.create_insecure_context } it 'has an empty list of trusted certs' do expect(sslctx.cacerts).to eq([]) end it 'has an empty list of crls' do expect(sslctx.crls).to eq([]) end it 'has an empty chain' do expect(sslctx.client_chain).to eq([]) end it 'has a nil private key and cert' do expect(sslctx.private_key).to be_nil expect(sslctx.client_cert).to be_nil end it 'does not authenticate the server' do expect(sslctx.verify_peer).to eq(false) end it 'raises if the frozen context is modified' do expect { sslctx.cacerts = [] }.to raise_error(/can't modify frozen/) end end context 'when creating an root ssl context with CA certs' do let(:config) { { cacerts: [], crls: [], revocation: false } } it 'accepts empty list of certs and crls' do sslctx = subject.create_root_context(**config) expect(sslctx.cacerts).to eq([]) expect(sslctx.crls).to eq([]) end it 'accepts valid root certs' do certs = [cert_fixture('ca.pem')] sslctx = subject.create_root_context(**config.merge(cacerts: certs)) expect(sslctx.cacerts).to eq(certs) end it 'accepts valid intermediate certs' do certs = [cert_fixture('ca.pem'), cert_fixture('intermediate.pem')] sslctx = subject.create_root_context(**config.merge(cacerts: certs)) expect(sslctx.cacerts).to eq(certs) end it 'accepts expired CA certs' do expired = [cert_fixture('ca.pem'), cert_fixture('intermediate.pem')] expired.each { |x509| x509.not_after = Time.at(0) } sslctx = subject.create_root_context(**config.merge(cacerts: expired)) expect(sslctx.cacerts).to eq(expired) end it 'raises if the frozen context is modified' do sslctx = subject.create_root_context(**config) expect { sslctx.verify_peer = false }.to raise_error(/can't modify frozen/) end it 'verifies peer' do sslctx = subject.create_root_context(**config) expect(sslctx.verify_peer).to eq(true) end end context 'when creating a system ssl context' do it 'accepts empty list of CA certs' do sslctx = subject.create_system_context(cacerts: []) expect(sslctx.cacerts).to eq([]) end it 'accepts valid root certs' do certs = [cert_fixture('ca.pem')] sslctx = subject.create_system_context(cacerts: certs) expect(sslctx.cacerts).to eq(certs) end it 'accepts valid intermediate certs' do certs = [cert_fixture('ca.pem'), cert_fixture('intermediate.pem')] sslctx = subject.create_system_context(cacerts: certs) expect(sslctx.cacerts).to eq(certs) end it 'accepts expired CA certs' do expired = [cert_fixture('ca.pem'), cert_fixture('intermediate.pem')] expired.each { |x509| x509.not_after = Time.at(0) } sslctx = subject.create_system_context(cacerts: expired) expect(sslctx.cacerts).to eq(expired) end it 'raises if the frozen context is modified' do sslctx = subject.create_system_context(cacerts: []) expect { sslctx.verify_peer = false }.to raise_error(/can't modify frozen/) end it 'trusts system ca store by default' do expect_any_instance_of(OpenSSL::X509::Store).to receive(:set_default_paths) subject.create_system_context(cacerts: []) end it 'trusts an external ca store' do path = tmpfile('system_cacerts') File.write(path, cert_fixture('ca.pem').to_pem) expect_any_instance_of(OpenSSL::X509::Store).to receive(:add_file).with(path) subject.create_system_context(cacerts: [], path: path) end it 'verifies peer' do sslctx = subject.create_system_context(cacerts: []) expect(sslctx.verify_peer).to eq(true) end it 'disable revocation' do sslctx = subject.create_system_context(cacerts: []) expect(sslctx.revocation).to eq(false) end it 'sets client cert and private key to nil' do sslctx = subject.create_system_context(cacerts: []) expect(sslctx.client_cert).to be_nil expect(sslctx.private_key).to be_nil end it 'includes the client cert and private key when requested' do Puppet[:hostcert] = fixtures('ssl/signed.pem') Puppet[:hostprivkey] = fixtures('ssl/signed-key.pem') sslctx = subject.create_system_context(cacerts: [], include_client_cert: true) expect(sslctx.client_cert).to be_an(OpenSSL::X509::Certificate) expect(sslctx.private_key).to be_an(OpenSSL::PKey::RSA) end it 'ignores non-existent client cert and private key when requested' do Puppet[:certname] = 'doesnotexist' sslctx = subject.create_system_context(cacerts: [], include_client_cert: true) expect(sslctx.client_cert).to be_nil expect(sslctx.private_key).to be_nil end it 'warns if the client cert does not exist' do Puppet[:certname] = 'missingcert' Puppet[:hostprivkey] = fixtures('ssl/signed-key.pem') expect(Puppet).to receive(:warning).with("Client certificate for 'missingcert' does not exist") subject.create_system_context(cacerts: [], include_client_cert: true) end it 'warns if the private key does not exist' do Puppet[:certname] = 'missingkey' Puppet[:hostcert] = fixtures('ssl/signed.pem') expect(Puppet).to receive(:warning).with("Private key for 'missingkey' does not exist") subject.create_system_context(cacerts: [], include_client_cert: true) end it 'raises if client cert and private key are mismatched' do Puppet[:hostcert] = fixtures('ssl/signed.pem') Puppet[:hostprivkey] = fixtures('ssl/127.0.0.1-key.pem') expect { subject.create_system_context(cacerts: [], include_client_cert: true) }.to raise_error(Puppet::SSL::SSLError, "The certificate for 'CN=signed' does not match its private key") end it 'trusts additional system certs' do path = tmpfile('system_cacerts') File.write(path, cert_fixture('ca.pem').to_pem) expect_any_instance_of(OpenSSL::X509::Store).to receive(:add_file).with(path) subject.create_system_context(cacerts: [], path: path) end it 'ignores empty files' do path = tmpfile('system_cacerts') FileUtils.touch(path) subject.create_system_context(cacerts: [], path: path) expect(@logs).to eq([]) end it 'prints an error if it is not a file' do path = tmpdir('system_cacerts') subject.create_system_context(cacerts: [], path: path) expect(@logs).to include(an_object_having_attributes(level: :warning, message: /^The 'ssl_trust_store' setting does not refer to a file and will be ignored/)) end end context 'when creating an ssl context with crls' do let(:config) { { cacerts: global_cacerts, crls: global_crls} } it 'accepts valid CRLs' do certs = [cert_fixture('ca.pem')] crls = [crl_fixture('crl.pem')] sslctx = subject.create_root_context(**config.merge(cacerts: certs, crls: crls)) expect(sslctx.crls).to eq(crls) end it 'accepts valid CRLs for intermediate certs' do certs = [cert_fixture('ca.pem'), cert_fixture('intermediate.pem')] crls = [crl_fixture('crl.pem'), crl_fixture('intermediate-crl.pem')] sslctx = subject.create_root_context(**config.merge(cacerts: certs, crls: crls)) expect(sslctx.crls).to eq(crls) end it 'accepts expired CRLs' do expired = [crl_fixture('crl.pem'), crl_fixture('intermediate-crl.pem')] expired.each { |x509| x509.last_update = Time.at(0) } sslctx = subject.create_root_context(**config.merge(crls: expired)) expect(sslctx.crls).to eq(expired) end it 'verifies peer' do sslctx = subject.create_root_context(**config) expect(sslctx.verify_peer).to eq(true) end end context 'when creating an ssl context with client certs' do let(:client_cert) { cert_fixture('signed.pem') } let(:private_key) { key_fixture('signed-key.pem') } let(:config) { { cacerts: global_cacerts, crls: global_crls, client_cert: client_cert, private_key: private_key } } it 'raises if CA certs are missing' do expect { subject.create_context(**config.merge(cacerts: nil)) }.to raise_error(ArgumentError, /CA certs are missing/) end it 'raises if CRLs are missing' do expect { subject.create_context(**config.merge(crls: nil)) }.to raise_error(ArgumentError, /CRLs are missing/) end it 'raises if private key is missing' do expect { subject.create_context(**config.merge(private_key: nil)) }.to raise_error(ArgumentError, /Private key is missing/) end it 'raises if client cert is missing' do expect { subject.create_context(**config.merge(client_cert: nil)) }.to raise_error(ArgumentError, /Client cert is missing/) end it 'accepts RSA keys' do sslctx = subject.create_context(**config) expect(sslctx.private_key).to eq(private_key) end it 'accepts EC keys' do ec_key = ec_key_fixture('ec-key.pem') ec_cert = cert_fixture('ec.pem') sslctx = subject.create_context(**config.merge(client_cert: ec_cert, private_key: ec_key)) expect(sslctx.private_key).to eq(ec_key) end it 'raises if private key is unsupported' do dsa_key = OpenSSL::PKey::DSA.new expect { subject.create_context(**config.merge(private_key: dsa_key)) }.to raise_error(Puppet::SSL::SSLError, /Unsupported key 'OpenSSL::PKey::DSA'/) end it 'resolves the client chain from leaf to root' do sslctx = subject.create_context(**config) expect( sslctx.client_chain.map(&:subject).map(&:to_utf8) ).to eq(['CN=signed', 'CN=Test CA Subauthority', 'CN=Test CA']) end it 'raises if client cert signature is invalid' do client_cert.public_key = wrong_key.public_key client_cert.sign(wrong_key, OpenSSL::Digest::SHA256.new) expect { subject.create_context(**config.merge(client_cert: client_cert)) }.to raise_error(Puppet::SSL::CertVerifyError, "Invalid signature for certificate 'CN=signed'") end it 'raises if client cert and private key are mismatched' do expect { subject.create_context(**config.merge(private_key: wrong_key)) }.to raise_error(Puppet::SSL::SSLError, "The certificate for 'CN=signed' does not match its private key") end it "raises if client cert's public key has been replaced" do expect { subject.create_context(**config.merge(client_cert: cert_fixture('tampered-cert.pem'))) }.to raise_error(Puppet::SSL::CertVerifyError, "Invalid signature for certificate 'CN=signed'") end # This option is only available in openssl 1.1 # OpenSSL 1.1.1h no longer reports expired root CAs when using "verify". # This regression was fixed in 1.1.1i, so only skip this test if we're on # the affected version. # See: https://github.com/openssl/openssl/pull/13585 if Puppet::Util::Package.versioncmp(OpenSSL::OPENSSL_LIBRARY_VERSION.split[1], '1.1.1h') != 0 it 'raises if root cert signature is invalid', if: defined?(OpenSSL::X509::V_FLAG_CHECK_SS_SIGNATURE) do ca = global_cacerts.first ca.sign(wrong_key, OpenSSL::Digest::SHA256.new) expect { subject.create_context(**config.merge(cacerts: global_cacerts)) }.to raise_error(Puppet::SSL::CertVerifyError, "Invalid signature for certificate 'CN=Test CA'") end end it 'raises if intermediate CA signature is invalid', unless: Puppet::Util::Platform.jruby? && RUBY_VERSION.to_f >= 2.6 do int = global_cacerts.last int.public_key = wrong_key.public_key if Puppet::Util::Platform.jruby? int.sign(wrong_key, OpenSSL::Digest::SHA256.new) expect { subject.create_context(**config.merge(cacerts: global_cacerts)) }.to raise_error(Puppet::SSL::CertVerifyError, "Invalid signature for certificate 'CN=Test CA Subauthority'") end it 'raises if CRL signature for root CA is invalid', unless: Puppet::Util::Platform.jruby? do crl = global_crls.first crl.sign(wrong_key, OpenSSL::Digest::SHA256.new) expect { subject.create_context(**config.merge(crls: global_crls)) }.to raise_error(Puppet::SSL::CertVerifyError, "Invalid signature for CRL issued by 'CN=Test CA'") end it 'raises if CRL signature for intermediate CA is invalid', unless: Puppet::Util::Platform.jruby? do crl = global_crls.last crl.sign(wrong_key, OpenSSL::Digest::SHA256.new) expect { subject.create_context(**config.merge(crls: global_crls)) }.to raise_error(Puppet::SSL::CertVerifyError, "Invalid signature for CRL issued by 'CN=Test CA Subauthority'") end it 'raises if client cert is revoked' do expect { subject.create_context(**config.merge(private_key: key_fixture('revoked-key.pem'), client_cert: cert_fixture('revoked.pem'))) }.to raise_error(Puppet::SSL::CertVerifyError, "Certificate 'CN=revoked' is revoked") end it 'warns if intermediate issuer is missing' do expect(Puppet).to receive(:warning).with("The issuer 'CN=Test CA Subauthority' of certificate 'CN=signed' cannot be found locally") subject.create_context(**config.merge(cacerts: [cert_fixture('ca.pem')])) end it 'raises if root issuer is missing' do expect { subject.create_context(**config.merge(cacerts: [cert_fixture('intermediate.pem')])) }.to raise_error(Puppet::SSL::CertVerifyError, "The issuer 'CN=Test CA' of certificate 'CN=Test CA Subauthority' is missing") end it 'raises if cert is not valid yet', unless: Puppet::Util::Platform.jruby? do client_cert.not_before = Time.now + (5 * 60 * 60) int_key = key_fixture('intermediate-key.pem') client_cert.sign(int_key, OpenSSL::Digest::SHA256.new) expect { subject.create_context(**config.merge(client_cert: client_cert)) }.to raise_error(Puppet::SSL::CertVerifyError, "The certificate 'CN=signed' is not yet valid, verify time is synchronized") end it 'raises if cert is expired', unless: Puppet::Util::Platform.jruby? do client_cert.not_after = Time.at(0) int_key = key_fixture('intermediate-key.pem') client_cert.sign(int_key, OpenSSL::Digest::SHA256.new) expect { subject.create_context(**config.merge(client_cert: client_cert)) }.to raise_error(Puppet::SSL::CertVerifyError, "The certificate 'CN=signed' has expired, verify time is synchronized") end it 'raises if crl is not valid yet', unless: Puppet::Util::Platform.jruby? do future_crls = global_crls # invalidate the CRL issued by the root future_crls.first.last_update = Time.now + (5 * 60 * 60) expect { subject.create_context(**config.merge(crls: future_crls)) }.to raise_error(Puppet::SSL::CertVerifyError, "The CRL issued by 'CN=Test CA' is not yet valid, verify time is synchronized") end it 'raises if crl is expired', unless: Puppet::Util::Platform.jruby? do past_crls = global_crls # invalidate the CRL issued by the root past_crls.first.next_update = Time.at(0) expect { subject.create_context(**config.merge(crls: past_crls)) }.to raise_error(Puppet::SSL::CertVerifyError, "The CRL issued by 'CN=Test CA' has expired, verify time is synchronized") end it 'raises if the root CRL is missing' do crls = [crl_fixture('intermediate-crl.pem')] expect { subject.create_context(**config.merge(crls: crls, revocation: :chain)) }.to raise_error(Puppet::SSL::CertVerifyError, "The CRL issued by 'CN=Test CA' is missing") end it 'raises if the intermediate CRL is missing' do crls = [crl_fixture('crl.pem')] expect { subject.create_context(**config.merge(crls: crls)) }.to raise_error(Puppet::SSL::CertVerifyError, "The CRL issued by 'CN=Test CA Subauthority' is missing") end it "doesn't raise if the root CRL is missing and we're just checking the leaf" do crls = [crl_fixture('intermediate-crl.pem')] subject.create_context(**config.merge(crls: crls, revocation: :leaf)) end it "doesn't raise if the intermediate CRL is missing and revocation checking is disabled" do crls = [crl_fixture('crl.pem')] subject.create_context(**config.merge(crls: crls, revocation: false)) end it "doesn't raise if both CRLs are missing and revocation checking is disabled" do subject.create_context(**config.merge(crls: [], revocation: false)) end # OpenSSL < 1.1 does not verify basicConstraints it "raises if root CA's isCA basic constraint is false", unless: Puppet::Util::Platform.jruby? || OpenSSL::OPENSSL_VERSION_NUMBER < 0x10100000 do certs = [cert_fixture('bad-basic-constraints.pem'), cert_fixture('intermediate.pem')] # openssl 3 returns 79 # define X509_V_ERR_NO_ISSUER_PUBLIC_KEY 24 # define X509_V_ERR_INVALID_CA 79 expect { subject.create_context(**config.merge(cacerts: certs, crls: [], revocation: false)) }.to raise_error(Puppet::SSL::CertVerifyError, /Certificate 'CN=Test CA' failed verification \((24|79)\): invalid CA certificate/) end # OpenSSL < 1.1 does not verify basicConstraints it "raises if intermediate CA's isCA basic constraint is false", unless: Puppet::Util::Platform.jruby? || OpenSSL::OPENSSL_VERSION_NUMBER < 0x10100000 do certs = [cert_fixture('ca.pem'), cert_fixture('bad-int-basic-constraints.pem')] expect { subject.create_context(**config.merge(cacerts: certs, crls: [], revocation: false)) }.to raise_error(Puppet::SSL::CertVerifyError, /Certificate 'CN=Test CA Subauthority' failed verification \((24|79)\): invalid CA certificate/) end it 'accepts CA certs in any order' do sslctx = subject.create_context(**config.merge(cacerts: global_cacerts.reverse)) # certs in ruby+openssl 1.0.x are not comparable, so compare subjects expect(sslctx.client_chain.map(&:subject).map(&:to_utf8)).to contain_exactly('CN=Test CA', 'CN=Test CA Subauthority', 'CN=signed') end it 'accepts CRLs in any order' do sslctx = subject.create_context(**config.merge(crls: global_crls.reverse)) # certs in ruby+openssl 1.0.x are not comparable, so compare subjects expect(sslctx.client_chain.map(&:subject).map(&:to_utf8)).to contain_exactly('CN=Test CA', 'CN=Test CA Subauthority', 'CN=signed') end it 'raises if the frozen context is modified' do sslctx = subject.create_context(**config) expect { sslctx.verify_peer = false }.to raise_error(/can't modify frozen/) end it 'verifies peer' do sslctx = subject.create_context(**config) expect(sslctx.verify_peer).to eq(true) end it 'does not trust the system ca store by default' do expect_any_instance_of(OpenSSL::X509::Store).to receive(:set_default_paths).never subject.create_context(**config) end it 'trusts the system ca store' do expect_any_instance_of(OpenSSL::X509::Store).to receive(:set_default_paths) subject.create_context(**config.merge(include_system_store: true)) end end context 'when loading an ssl context' do let(:client_cert) { cert_fixture('signed.pem') } let(:private_key) { key_fixture('signed-key.pem') } let(:doesnt_exist) { '/does/not/exist' } before :each do Puppet[:localcacert] = file_containing('global_cacerts', global_cacerts.first.to_pem) Puppet[:hostcrl] = file_containing('global_crls', global_crls.first.to_pem) Puppet[:certname] = 'signed' Puppet[:privatekeydir] = tmpdir('privatekeydir') File.write(File.join(Puppet[:privatekeydir], 'signed.pem'), private_key.to_pem) Puppet[:certdir] = tmpdir('privatekeydir') File.write(File.join(Puppet[:certdir], 'signed.pem'), client_cert.to_pem) end it 'raises if CA certs are missing' do Puppet[:localcacert] = doesnt_exist expect { subject.load_context }.to raise_error(Puppet::Error, /The CA certificates are missing from/) end it 'raises if the CRL is missing' do Puppet[:hostcrl] = doesnt_exist expect { subject.load_context }.to raise_error(Puppet::Error, /The CRL is missing from/) end it 'does not raise if the CRL is missing and revocation is disabled' do Puppet[:hostcrl] = doesnt_exist subject.load_context(revocation: false) end it 'raises if the private key is missing' do Puppet[:privatekeydir] = doesnt_exist expect { subject.load_context }.to raise_error(Puppet::Error, /The private key is missing from/) end it 'raises if the client cert is missing' do Puppet[:certdir] = doesnt_exist expect { subject.load_context }.to raise_error(Puppet::Error, /The client certificate is missing from/) end context 'loading private keys', unless: RUBY_PLATFORM == 'java' do it 'loads the private key and client cert' do ssl_context = subject.load_context expect(ssl_context.private_key).to be_an(OpenSSL::PKey::RSA) expect(ssl_context.client_cert).to be_an(OpenSSL::X509::Certificate) end it 'loads a password protected key and client cert' do FileUtils.cp(File.join(PuppetSpec::FIXTURE_DIR, 'ssl', 'encrypted-key.pem'), File.join(Puppet[:privatekeydir], 'signed.pem')) ssl_context = subject.load_context(password: '74695716c8b6') expect(ssl_context.private_key).to be_an(OpenSSL::PKey::RSA) expect(ssl_context.client_cert).to be_an(OpenSSL::X509::Certificate) end it 'raises if the password is incorrect' do FileUtils.cp(File.join(PuppetSpec::FIXTURE_DIR, 'ssl', 'encrypted-key.pem'), File.join(Puppet[:privatekeydir], 'signed.pem')) expect { subject.load_context(password: 'wrongpassword') }.to raise_error(Puppet::SSL::SSLError, /Failed to load private key for host 'signed': Could not parse PKey/) end end it 'does not trust the system ca store by default' do expect_any_instance_of(OpenSSL::X509::Store).to receive(:set_default_paths).never subject.load_context end it 'trusts the system ca store' do expect_any_instance_of(OpenSSL::X509::Store).to receive(:set_default_paths) subject.load_context(include_system_store: true) end end context 'when verifying requests' do let(:csr) { request_fixture('request.pem') } it 'accepts valid requests' do private_key = key_fixture('request-key.pem') expect(subject.verify_request(csr, private_key.public_key)).to eq(csr) end it "raises if the CSR was signed by a private key that doesn't match public key" do expect { subject.verify_request(csr, wrong_key.public_key) }.to raise_error(Puppet::SSL::SSLError, "The CSR for host 'CN=pending' does not match the public key") end it "raises if the CSR was tampered with" do csr = request_fixture('tampered-csr.pem') expect { subject.verify_request(csr, csr.public_key) }.to raise_error(Puppet::SSL::SSLError, "The CSR for host 'CN=signed' does not match the public key") end end context 'printing' do let(:client_cert) { cert_fixture('signed.pem') } let(:private_key) { key_fixture('signed-key.pem') } let(:config) { { cacerts: global_cacerts, crls: global_crls, client_cert: client_cert, private_key: private_key } } it 'prints in debug' do Puppet[:log_level] = 'debug' ctx = subject.create_context(**config) subject.print(ctx) expect(@logs.map(&:message)).to include( /Verified CA certificate 'CN=Test CA' fingerprint/, /Verified CA certificate 'CN=Test CA Subauthority' fingerprint/, /Verified client certificate 'CN=signed' fingerprint/, /Using CRL 'CN=Test CA' authorityKeyIdentifier '(keyid:)?[A-Z0-9:]{59}' crlNumber '0'/, /Using CRL 'CN=Test CA Subauthority' authorityKeyIdentifier '(keyid:)?[A-Z0-9:]{59}' crlNumber '0'/ ) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false