repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/spec_helper.rb
spec/spec_helper.rb
# NOTE: a lot of the stuff in this file is duplicated in the "puppet_spec_helper" in the project # puppetlabs_spec_helper. We should probably eat our own dog food and get rid of most of this from here, # and have the puppet core itself use puppetlabs_spec_helper dir = File.expand_path(File.dirname(__FILE__)) $LOAD_PATH.unshift File.join(dir, 'lib') # Don't want puppet getting the command line arguments for rake ARGV.clear begin require 'rubygems' rescue LoadError end require 'puppet' # Stub out gettext's `_` and `n_()` methods, which attempt to load translations. # Several of our mocks (mostly around file system interaction) are broken by # FastGettext's implementation of these methods. require 'puppet/gettext/stubs' require 'rspec' require 'rspec/its' # So everyone else doesn't have to include this base constant. module PuppetSpec FIXTURE_DIR = File.join(File.expand_path(File.dirname(__FILE__)), "fixtures") unless defined?(FIXTURE_DIR) end require 'pathname' require 'tmpdir' require 'fileutils' require 'puppet_spec/verbose' require 'puppet_spec/files' require 'puppet_spec/settings' require 'puppet_spec/fixtures' require 'puppet_spec/matchers' require 'puppet_spec/unindent' require 'puppet/test/test_helper' Pathname.glob("#{dir}/shared_contexts/*.rb") do |file| require file.relative_path_from(Pathname.new(dir)) end Pathname.glob("#{dir}/shared_behaviours/**/*.rb") do |behaviour| require behaviour.relative_path_from(Pathname.new(dir)) end Pathname.glob("#{dir}/shared_examples/**/*.rb") do |behaviour| require behaviour.relative_path_from(Pathname.new(dir)) end require 'webmock/rspec' require 'vcr' VCR.configure do |vcr| vcr.cassette_library_dir = File.expand_path('vcr/cassettes', PuppetSpec::FIXTURE_DIR) vcr.hook_into :webmock vcr.configure_rspec_metadata! # Uncomment next line to debug vcr # vcr.debug_logger = $stderr end # Disable VCR by default VCR.turn_off! RSpec.configure do |config| include PuppetSpec::Fixtures exclude_filters = {} exclude_filters[:benchmark] = true unless ENV['BENCHMARK'] config.filter_run_excluding exclude_filters config.filter_run_when_matching :focus config.mock_with :rspec do |mocks| mocks.verify_partial_doubles = true end tmpdir = Puppet::FileSystem.expand_path(Dir.mktmpdir("rspecrun")) oldtmpdir = Puppet::FileSystem.expand_path(Dir.tmpdir()) ENV['TMPDIR'] = tmpdir Puppet::Test::TestHelper.initialize config.before :all do Puppet::Test::TestHelper.before_all_tests() if ENV['PROFILE'] == 'all' require 'ruby-prof' RubyProf.start end end config.after :all do if ENV['PROFILE'] == 'all' require 'ruby-prof' result = RubyProf.stop printer = RubyProf::CallTreePrinter.new(result) open(File.join(ENV['PROFILEOUT'],"callgrind.all.#{Time.now.to_i}.trace"), "w") do |f| printer.print(f) end end Puppet::Test::TestHelper.after_all_tests() end config.before :each do |test| # Disabling garbage collection inside each test, and only running it at # the end of each block, gives us an ~ 15 percent speedup, and more on # some platforms *cough* windows *cough* that are a little slower. GC.disable # TODO: in a more sane world, we'd move this logging redirection into our TestHelper class. # Without doing so, external projects will all have to roll their own solution for # redirecting logging, and for validating expected log messages. However, because the # current implementation of this involves creating an instance variable "@logs" on # EVERY SINGLE TEST CLASS, and because there are over 1300 tests that are written to expect # this instance variable to be available--we can't easily solve this problem right now. # # redirecting logging away from console, because otherwise the test output will be # obscured by all of the log output @logs = [] Puppet::Util::Log.close_all if ENV["PUPPET_TEST_LOG_LEVEL"] Puppet::Util::Log.level = ENV["PUPPET_TEST_LOG_LEVEL"].intern end if ENV["PUPPET_TEST_LOG"] Puppet::Util::Log.newdestination(ENV["PUPPET_TEST_LOG"]) m = test.metadata Puppet.notice("*** BEGIN TEST #{m[:file_path]}:#{m[:line_number]}") end Puppet::Util::Log.newdestination(Puppet::Test::LogCollector.new(@logs)) @log_level = Puppet::Util::Log.level base = PuppetSpec::Files.tmpdir('tmp_settings') Puppet[:vardir] = File.join(base, 'var') Puppet[:publicdir] = File.join(base, 'public') Puppet[:confdir] = File.join(base, 'etc') Puppet[:codedir] = File.join(base, 'code') Puppet[:logdir] = "$vardir/log" Puppet[:rundir] = "$vardir/run" Puppet[:hiera_config] = File.join(base, 'hiera') FileUtils.mkdir_p Puppet[:statedir] FileUtils.mkdir_p Puppet[:publicdir] Puppet::Test::TestHelper.before_each_test() end # Facter 2 uses two versions of the GCE API, so match using regex PUPPET_FACTER_2_GCE_URL = %r{^http://metadata/computeMetadata/v1(beta1)?}.freeze PUPPET_FACTER_3_GCE_URL = "http://metadata.google.internal/computeMetadata/v1/?recursive=true&alt=json".freeze # Facter azure metadata endpoint PUPPET_FACTER_AZ_URL = "http://169.254.169.254/metadata/instance?api-version=2020-09-01" # Facter EC2 endpoint PUPPET_FACTER_EC2_METADATA = 'http://169.254.169.254/latest/meta-data/' PUPPET_FACTER_EC2_USERDATA = 'http://169.254.169.254/latest/user-data/' PUPPET_FACTER_EC2_API_TOKEN = 'http://169.254.169.254/latest/api/token' # see https://github.com/puppetlabs/facter/issues/2690 config.around :each do |example| # Ignore requests from Facter to external services stub_request(:get, PUPPET_FACTER_2_GCE_URL) stub_request(:get, PUPPET_FACTER_3_GCE_URL) stub_request(:get, PUPPET_FACTER_AZ_URL) stub_request(:get, PUPPET_FACTER_EC2_METADATA) stub_request(:get, PUPPET_FACTER_EC2_USERDATA) stub_request(:put, PUPPET_FACTER_EC2_API_TOKEN) # Enable VCR if the example is tagged with `:vcr` metadata. if example.metadata[:vcr] VCR.turn_on! begin example.run ensure VCR.turn_off! end else example.run end end config.after :each do Puppet::Test::TestHelper.after_each_test() # TODO: would like to move this into puppetlabs_spec_helper, but there are namespace issues at the moment. allow(Dir).to receive(:entries).and_call_original PuppetSpec::Files.cleanup # TODO: this should be abstracted in the future--see comments above the '@logs' block in the # "before" code above. # # clean up after the logging changes that we made before each test. @logs.clear Puppet::Util::Log.close_all Puppet::Util::Log.level = @log_level # This will perform a GC between tests, but only if actually required. We # experimented with forcing a GC run, and that was less efficient than # just letting it run all the time. GC.enable end config.after :suite do # Log the spec order to a file, but only if the LOG_SPEC_ORDER environment variable is # set. This should be enabled on Jenkins runs, as it can be used with Nick L.'s bisect # script to help identify and debug order-dependent spec failures. if ENV['LOG_SPEC_ORDER'] File.open("./spec_order.txt", "w") do |logfile| config.instance_variable_get(:@files_to_run).each { |f| logfile.puts f } end end # return to original tmpdir ENV['TMPDIR'] = oldtmpdir FileUtils.rm_rf(tmpdir) end if ENV['PROFILE'] require 'ruby-prof' def profile result = RubyProf.profile { yield } name = RSpec.current_example.metadata[:full_description].downcase.gsub(/[^a-z0-9_-]/, "-").gsub(/-+/, "-") printer = RubyProf::CallTreePrinter.new(result) open(File.join(ENV['PROFILEOUT'],"callgrind.#{name}.#{Time.now.to_i}.trace"), "w") do |f| printer.print(f) end end config.around(:each) do |example| if ENV['PROFILE'] == 'each' or (example.metadata[:profile] and ENV['PROFILE']) profile { example.run } else example.run end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/directory_environments_spec.rb
spec/integration/directory_environments_spec.rb
require 'spec_helper' describe "directory environments" do let(:args) { ['--configprint', 'modulepath', '--environment', 'direnv'] } let(:puppet) { Puppet::Application[:apply] } context "with a single directory environmentpath" do before(:each) do environmentdir = PuppetSpec::Files.tmpdir('envpath') Puppet[:environmentpath] = environmentdir FileUtils.mkdir_p(environmentdir + "/direnv/modules") end it "config prints the environments modulepath" do Puppet.settings.initialize_global_settings(args) expect { puppet.run }.to exit_with(0) .and output(%r{/direnv/modules}).to_stdout end it "config prints the cli --modulepath despite environment" do args << '--modulepath' << '/completely/different' Puppet.settings.initialize_global_settings(args) expect { puppet.run }.to exit_with(0) .and output(%r{/completely/different}).to_stdout end it 'given an 8.3 style path on Windows, will config print an expanded path', :if => Puppet::Util::Platform.windows? do # ensure an 8.3 style path is set for environmentpath shortened = Puppet::Util::Windows::File.get_short_pathname(Puppet[:environmentpath]) expanded = Puppet::FileSystem.expand_path(shortened) Puppet[:environmentpath] = shortened expect(Puppet[:environmentpath]).to match(/~/) Puppet.settings.initialize_global_settings(args) expect { puppet.run }.to exit_with(0) .and output(a_string_matching(expanded)).to_stdout end end context "with an environmentpath having multiple directories" do let(:args) { ['--configprint', 'modulepath', '--environment', 'otherdirenv'] } before(:each) do envdir1 = File.join(Puppet[:confdir], 'env1') envdir2 = File.join(Puppet[:confdir], 'env2') Puppet[:environmentpath] = [envdir1, envdir2].join(File::PATH_SEPARATOR) FileUtils.mkdir_p(envdir2 + "/otherdirenv/modules") end it "config prints a directory environment modulepath" do Puppet.settings.initialize_global_settings(args) expect { puppet.run }.to exit_with(0) .and output(%r{otherdirenv/modules}).to_stdout end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/type_spec.rb
spec/integration/type_spec.rb
require 'spec_helper' require 'puppet/type' describe Puppet::Type do it "should not lose its provider list when it is reloaded" do type = Puppet::Type.newtype(:integration_test) do newparam(:name) {} end provider = type.provide(:myprovider) {} # reload it type = Puppet::Type.newtype(:integration_test) do newparam(:name) {} end expect(type.provider(:myprovider)).to equal(provider) end it "should not lose its provider parameter when it is reloaded" do type = Puppet::Type.newtype(:reload_test_type) type.provide(:test_provider) # reload it type = Puppet::Type.newtype(:reload_test_type) expect(type.parameters).to include(:provider) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/configurer_spec.rb
spec/integration/configurer_spec.rb
require 'spec_helper' require 'puppet_spec/network' require 'puppet/configurer' describe Puppet::Configurer do include PuppetSpec::Files include PuppetSpec::Network describe "when running" do before(:each) do @catalog = Puppet::Resource::Catalog.new("testing", Puppet.lookup(:environments).get(Puppet[:environment])) @catalog.add_resource(Puppet::Type.type(:notify).new(:title => "testing")) # Make sure we don't try to persist the local state after the transaction ran, # because it will fail during test (the state file is in a not-existing directory) # and we need the transaction to be successful to be able to produce a summary report @catalog.host_config = false @configurer = Puppet::Configurer.new end it "should send a transaction report with valid data" do allow(@configurer).to receive(:save_last_run_summary) expect(Puppet::Transaction::Report.indirection).to receive(:save) do |report, x| expect(report.time).to be_a(Time) expect(report.logs.length).to be > 0 end.twice Puppet[:report] = true @configurer.run :catalog => @catalog end it "should save a correct last run summary" do report = Puppet::Transaction::Report.new allow(Puppet::Transaction::Report.indirection).to receive(:save) Puppet[:lastrunfile] = tmpfile("lastrunfile") Puppet.settings.setting(:lastrunfile).mode = 0666 Puppet[:report] = true # We only record integer seconds in the timestamp, and truncate # backwards, so don't use a more accurate timestamp in the test. # --daniel 2011-03-07 t1 = Time.now.tv_sec @configurer.run :catalog => @catalog, :report => report t2 = Time.now.tv_sec # sticky bit only applies to directories in windows file_mode = Puppet::Util::Platform.windows? ? '666' : '100666' expect(Puppet::FileSystem.stat(Puppet[:lastrunfile]).mode.to_s(8)).to eq(file_mode) summary = Puppet::Util::Yaml.safe_load_file(Puppet[:lastrunfile]) expect(summary).to be_a(Hash) %w{time changes events resources}.each do |key| expect(summary).to be_key(key) end expect(summary["time"]).to be_key("notify") expect(summary["time"]["last_run"]).to be_between(t1, t2) end it "applies a cached catalog if pluginsync fails when usecacheonfailure is true and environment is valid" do expect(@configurer).to receive(:valid_server_environment?).and_return(true) Puppet[:ignore_plugin_errors] = false Puppet[:use_cached_catalog] = false Puppet[:usecacheonfailure] = true report = Puppet::Transaction::Report.new expect_any_instance_of(Puppet::Configurer::Downloader).to receive(:evaluate).and_raise(Puppet::Error, 'Failed to retrieve: some file') expect(Puppet::Resource::Catalog.indirection).to receive(:find).and_return(@catalog) @configurer.run(pluginsync: true, report: report) expect(report.cached_catalog_status).to eq('on_failure') end it "applies a cached catalog if pluginsync fails when usecacheonfailure is true and environment is invalid" do expect(@configurer).to receive(:valid_server_environment?).and_return(false) Puppet[:ignore_plugin_errors] = false Puppet[:use_cached_catalog] = false Puppet[:usecacheonfailure] = true report = Puppet::Transaction::Report.new expect(Puppet::Resource::Catalog.indirection).to receive(:find).and_raise(Puppet::Error, 'Cannot compile remote catalog') expect(Puppet::Resource::Catalog.indirection).to receive(:find).and_return(@catalog) @configurer.run(pluginsync: true, report: report) expect(report.cached_catalog_status).to eq('on_failure') end describe 'resubmitting facts' do context 'when resubmit_facts is set to false' do it 'should not send data' do expect(@configurer).to receive(:resubmit_facts).never @configurer.run(catalog: @catalog) end end context 'when resubmit_facts is set to true' do let(:test_facts) { Puppet::Node::Facts.new('configurer.test', {test_fact: 'test value'}) } before(:each) do Puppet[:resubmit_facts] = true allow(@configurer).to receive(:find_facts).and_return(test_facts) end it 'uploads facts as application/json' do stub_request(:put, "https://puppet:8140/puppet/v3/facts/configurer.test?environment=production"). with( body: hash_including( { "name" => "configurer.test", "values" => {"test_fact" => 'test value',}, }), headers: { 'Accept'=>acceptable_content_types_string, 'Content-Type'=>'application/json', }) @configurer.run(catalog: @catalog) end it 'logs errors that occur during fact generation' do allow(@configurer).to receive(:find_facts).and_raise('error generating facts') expect(Puppet).to receive(:log_exception).with(instance_of(RuntimeError), /^Failed to submit facts/) @configurer.run(catalog: @catalog) end it 'logs errors that occur during fact submission' do stub_request(:put, "https://puppet:8140/puppet/v3/facts/configurer.test?environment=production").to_return(status: 502) expect(Puppet).to receive(:log_exception).with(Puppet::HTTP::ResponseError, /^Failed to submit facts/) @configurer.run(catalog: @catalog) end it 'records time spent resubmitting facts' do report = Puppet::Transaction::Report.new stub_request(:put, "https://puppet:8140/puppet/v3/facts/configurer.test?environment=production"). with( body: hash_including({ "name" => "configurer.test", "values" => {"test_fact": "test value"}, }), headers: { 'Accept'=>acceptable_content_types_string, 'Content-Type'=>'application/json', }).to_return(status: 200) @configurer.run(catalog: @catalog, report: report) expect(report.metrics['time'].values).to include(["resubmit_facts", anything, Numeric]) end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/util_spec.rb
spec/integration/util_spec.rb
# coding: utf-8 require 'spec_helper' describe Puppet::Util do include PuppetSpec::Files describe "#replace_file on Windows", :if => Puppet::Util::Platform.windows? do it "replace_file should preserve original ACEs from existing replaced file on Windows" do file = tmpfile("somefile") FileUtils.touch(file) admins = 'S-1-5-32-544' dacl = Puppet::Util::Windows::AccessControlList.new dacl.allow(admins, Puppet::Util::Windows::File::FILE_ALL_ACCESS) protect = true expected_sd = Puppet::Util::Windows::SecurityDescriptor.new(admins, admins, dacl, protect) Puppet::Util::Windows::Security.set_security_descriptor(file, expected_sd) ignored_mode = 0644 Puppet::Util.replace_file(file, ignored_mode) do |temp_file| ignored_sd = Puppet::Util::Windows::Security.get_security_descriptor(temp_file.path) users = 'S-1-5-11' ignored_sd.dacl.allow(users, Puppet::Util::Windows::File::FILE_GENERIC_READ) Puppet::Util::Windows::Security.set_security_descriptor(temp_file.path, ignored_sd) end replaced_sd = Puppet::Util::Windows::Security.get_security_descriptor(file) expect(replaced_sd.dacl).to eq(expected_sd.dacl) end it "replace_file should use reasonable default ACEs on a new file on Windows" do dir = tmpdir('DACL_playground') protected_sd = Puppet::Util::Windows::Security.get_security_descriptor(dir) protected_sd.protect = true Puppet::Util::Windows::Security.set_security_descriptor(dir, protected_sd) sibling_path = File.join(dir, 'sibling_file') FileUtils.touch(sibling_path) expected_sd = Puppet::Util::Windows::Security.get_security_descriptor(sibling_path) new_file_path = File.join(dir, 'new_file') ignored_mode = nil Puppet::Util.replace_file(new_file_path, ignored_mode) { |tmp_file| } new_sd = Puppet::Util::Windows::Security.get_security_descriptor(new_file_path) expect(new_sd.dacl).to eq(expected_sd.dacl) end it "replace_file should work with filenames that include - and . (PUP-1389)" do expected_content = 'some content' dir = tmpdir('ReplaceFile_playground') destination_file = File.join(dir, 'some-file.xml') Puppet::Util.replace_file(destination_file, nil) do |temp_file| temp_file.open temp_file.write(expected_content) end actual_content = File.read(destination_file) expect(actual_content).to eq(expected_content) end it "replace_file should work with filenames that include special characters (PUP-1389)" do expected_content = 'some content' dir = tmpdir('ReplaceFile_playground') # http://www.fileformat.info/info/unicode/char/00e8/index.htm # dest_name = "somèfile.xml" dest_name = "som\u00E8file.xml" destination_file = File.join(dir, dest_name) Puppet::Util.replace_file(destination_file, nil) do |temp_file| temp_file.open temp_file.write(expected_content) end actual_content = File.read(destination_file) expect(actual_content).to eq(expected_content) end end describe "#which on Windows", :if => Puppet::Util::Platform.windows? do let (:rune_utf8) { "\u16A0\u16C7\u16BB\u16EB\u16D2\u16E6\u16A6\u16EB\u16A0\u16B1\u16A9\u16A0\u16A2\u16B1\u16EB\u16A0\u16C1\u16B1\u16AA\u16EB\u16B7\u16D6\u16BB\u16B9\u16E6\u16DA\u16B3\u16A2\u16D7" } let (:filename) { 'foo.exe' } it "should be able to use UTF8 characters in the path" do utf8 = tmpdir(rune_utf8) Puppet::FileSystem.mkpath(utf8) filepath = File.join(utf8, filename) Puppet::FileSystem.touch(filepath) path = [utf8, "c:\\windows\\system32", "c:\\windows"].join(File::PATH_SEPARATOR) Puppet::Util.withenv("PATH" => path) do expect(Puppet::Util.which(filename)).to eq(filepath) end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/data_binding_spec.rb
spec/integration/data_binding_spec.rb
require 'spec_helper' require 'puppet/indirector/hiera' require 'puppet_spec/compiler' require 'puppet/indirector/data_binding/hiera' describe "Data binding" do include PuppetSpec::Files include PuppetSpec::Compiler let(:dir) { tmpdir("puppetdir") } let(:data) {{ 'global' => { 'testing::binding::value' => 'the value', 'testing::binding::calling_class' => '%{calling_class}', 'testing::binding::calling_class_path' => '%{calling_class_path}' } }} let(:hash_data) {{ 'global' => { 'testing::hash::options' => { 'key' => 'value', 'port' => '80', 'bind' => 'localhost' } }, 'agent.example.com' => { 'testing::hash::options' => { 'key' => 'new value', 'port' => '443' } } }} let(:hash_data_with_lopts) {{ 'global' => { 'testing::hash::options' => { 'key' => 'value', 'port' => '80', 'bind' => 'localhost' } }, 'agent.example.com' => { 'lookup_options' => { 'testing::hash::options' => { 'merge' => 'deep' } }, 'testing::hash::options' => { 'key' => 'new value', 'port' => '443' } } }} before do # Drop all occurances of cached hiera instances. This will reset @hiera in Puppet::Indirector::Hiera, Testing::DataBinding::Hiera, # and Puppet::DataBinding::Hiera. Different classes are active as indirection depending on configuration ObjectSpace.each_object(Class).select {|klass| klass <= Puppet::Indirector::Hiera }.each { |klass| klass.instance_variable_set(:@hiera, nil) } Puppet[:data_binding_terminus] = 'hiera' Puppet[:modulepath] = dir end context "with testing::binding and global data only" do it "looks up global data from hiera" do configure_hiera_for_one_tier(data) create_manifest_in_module("testing", "binding.pp", <<-MANIFEST) class testing::binding($value, $calling_class, $calling_class_path, $calling_module = $module_name) {} MANIFEST catalog = compile_to_catalog("include testing::binding") resource = catalog.resource('Class[testing::binding]') expect(resource[:value]).to eq("the value") expect(resource[:calling_class]).to eq("testing::binding") expect(resource[:calling_class_path]).to eq("testing/binding") expect(resource[:calling_module]).to eq("testing") end end context "with testing::hash and global data only" do it "looks up global data from hiera" do configure_hiera_for_one_tier(hash_data) create_manifest_in_module("testing", "hash.pp", <<-MANIFEST) class testing::hash($options) {} MANIFEST catalog = compile_to_catalog("include testing::hash") resource = catalog.resource('Class[testing::hash]') expect(resource[:options]).to eq({ 'key' => 'value', 'port' => '80', 'bind' => 'localhost' }) end end context "with custom clientcert" do it "merges global data with agent.example.com data from hiera" do configure_hiera_for_two_tier(hash_data) create_manifest_in_module("testing", "hash.pp", <<-MANIFEST) class testing::hash($options) {} MANIFEST catalog = compile_to_catalog("include testing::hash") resource = catalog.resource('Class[testing::hash]') expect(resource[:options]).to eq({ 'key' => 'new value', 'port' => '443', }) end end context "with custom clientcert and with lookup_options" do it "merges global data with agent.example.com data from hiera" do configure_hiera_for_two_tier(hash_data_with_lopts) create_manifest_in_module("testing", "hash.pp", <<-MANIFEST) class testing::hash($options) {} MANIFEST catalog = compile_to_catalog("include testing::hash") resource = catalog.resource('Class[testing::hash]') expect(resource[:options]).to eq({ 'key' => 'new value', 'port' => '443', 'bind' => 'localhost', }) end end context "with plan_hierarchy key" do context "using Hiera 5" do let(:hiera_config) { <<~CONF } --- version: 5 plan_hierarchy: - path: global name: Common CONF it "ignores plan_hierarchy outside of a Bolt plan" do configure_hiera_for_plan_hierarchy(data, hiera_config) create_manifest_in_module("testing", "binding.pp", <<-MANIFEST) class testing::binding($value) {} MANIFEST expect { compile_to_catalog("include testing::binding") } .to raise_error(/Class\[Testing::Binding\]: expects a value for parameter 'value'/) end end context "with invalid data" do let(:hiera_config) { <<~CONF } --- version: 5 plan_hierarchy: - pop: the question CONF it "raises a validation error" do configure_hiera_for_plan_hierarchy(data, hiera_config) create_manifest_in_module("testing", "binding.pp", <<-MANIFEST) class testing::binding($value) {} MANIFEST expect { compile_to_catalog("include testing::binding") } .to raise_error(/entry 'plan_hierarchy' index 0 unrecognized key 'pop'/) end end context "with Hiera 3" do let(:hiera_config) { <<~CONF } --- plan_hierarchy: ['global'] CONF it "errors with plan_hierarchy key" do configure_hiera_for_plan_hierarchy(data, hiera_config) create_manifest_in_module("testing", "binding.pp", <<-MANIFEST) class testing::binding($value) {} MANIFEST expect { compile_to_catalog("include testing::binding") } .to raise_error(/unrecognized key 'plan_hierarchy'/) end end end def configure_hiera_for_one_tier(data) hiera_config_file = tmpfile("hiera.yaml") File.open(hiera_config_file, 'w:UTF-8') do |f| f.write("--- :yaml: :datadir: #{dir} :hierarchy: ['global'] :logger: 'noop' :backends: ['yaml'] ") end data.each do | file, contents | File.open(File.join(dir, "#{file}.yaml"), 'w:UTF-8') do |f| f.write(YAML.dump(contents)) end end Puppet[:hiera_config] = hiera_config_file end def configure_hiera_for_plan_hierarchy(data, config) hiera_config_file = tmpfile("hiera.yaml") File.open(hiera_config_file, 'w:UTF-8') do |f| f.write(config) end data.each do | file, contents | File.open(File.join(dir, "#{file}.yaml"), 'w:UTF-8') do |f| f.write(YAML.dump(contents)) end end Puppet[:hiera_config] = hiera_config_file end def configure_hiera_for_two_tier(data) hiera_config_file = tmpfile("hiera.yaml") File.open(hiera_config_file, 'w:UTF-8') do |f| f.write("--- :yaml: :datadir: #{dir} :hierarchy: ['agent.example.com', 'global'] :logger: 'noop' :backends: ['yaml'] ") end data.each do | file, contents | File.open(File.join(dir, "#{file}.yaml"), 'w:UTF-8') do |f| f.write(YAML.dump(contents)) end end Puppet[:hiera_config] = hiera_config_file end def create_manifest_in_module(module_name, name, manifest) module_dir = File.join(dir, module_name, 'manifests') FileUtils.mkdir_p(module_dir) File.open(File.join(module_dir, name), 'w:UTF-8') do |f| f.write(manifest) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/transaction_spec.rb
spec/integration/transaction_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'puppet/transaction' Puppet::Type.newtype(:devicetype) do apply_to_device newparam(:name) end describe Puppet::Transaction do include PuppetSpec::Files include PuppetSpec::Compiler before do allow(Puppet::Util::Storage).to receive(:store) end def mk_catalog(*resources) catalog = Puppet::Resource::Catalog.new(Puppet::Node.new("mynode")) resources.each { |res| catalog.add_resource res } catalog end def touch_path Puppet.features.microsoft_windows? ? "#{ENV['windir']}\\system32" : "/usr/bin:/bin" end def usr_bin_touch(path) Puppet.features.microsoft_windows? ? "#{ENV['windir']}\\system32\\cmd.exe /c \"type NUL >> \"#{path}\"\"" : "/usr/bin/touch #{path}" end def touch(path) Puppet.features.microsoft_windows? ? "cmd.exe /c \"type NUL >> \"#{path}\"\"" : "touch #{path}" end it "should not apply generated resources if the parent resource fails" do catalog = Puppet::Resource::Catalog.new resource = Puppet::Type.type(:file).new :path => make_absolute("/foo/bar"), :backup => false catalog.add_resource resource child_resource = Puppet::Type.type(:file).new :path => make_absolute("/foo/bar/baz"), :backup => false expect(resource).to receive(:eval_generate).and_return([child_resource]) transaction = Puppet::Transaction.new(catalog, nil, Puppet::Graph::SequentialPrioritizer.new) expect(resource).to receive(:retrieve).and_raise("this is a failure") allow(resource).to receive(:err) expect(child_resource).not_to receive(:retrieve) transaction.evaluate end it "should not apply virtual resources" do catalog = Puppet::Resource::Catalog.new resource = Puppet::Type.type(:file).new :path => make_absolute("/foo/bar"), :backup => false resource.virtual = true catalog.add_resource resource transaction = Puppet::Transaction.new(catalog, nil, Puppet::Graph::SequentialPrioritizer.new) expect(resource).not_to receive(:retrieve) transaction.evaluate end it "should apply exported resources" do catalog = Puppet::Resource::Catalog.new path = tmpfile("exported_files") resource = Puppet::Type.type(:file).new :path => path, :backup => false, :ensure => :file resource.exported = true catalog.add_resource resource catalog.apply expect(Puppet::FileSystem.exist?(path)).to be_truthy end it "should not apply virtual exported resources" do catalog = Puppet::Resource::Catalog.new resource = Puppet::Type.type(:file).new :path => make_absolute("/foo/bar"), :backup => false resource.exported = true resource.virtual = true catalog.add_resource resource transaction = Puppet::Transaction.new(catalog, nil, Puppet::Graph::SequentialPrioritizer.new) expect(resource).not_to receive(:retrieve) transaction.evaluate end it "should not apply device resources on normal host" do catalog = Puppet::Resource::Catalog.new resource = Puppet::Type.type(:devicetype).new :name => "FastEthernet 0/1" catalog.add_resource resource transaction = Puppet::Transaction.new(catalog, nil, Puppet::Graph::SequentialPrioritizer.new) transaction.for_network_device = false expect(transaction).not_to receive(:apply).with(resource, nil) transaction.evaluate expect(transaction.resource_status(resource)).to be_skipped end it "should not apply host resources on device" do catalog = Puppet::Resource::Catalog.new resource = Puppet::Type.type(:file).new :path => make_absolute("/foo/bar"), :backup => false catalog.add_resource resource transaction = Puppet::Transaction.new(catalog, nil, Puppet::Graph::SequentialPrioritizer.new) transaction.for_network_device = true expect(transaction).not_to receive(:apply).with(resource, nil) transaction.evaluate expect(transaction.resource_status(resource)).to be_skipped end it "should apply device resources on device" do catalog = Puppet::Resource::Catalog.new resource = Puppet::Type.type(:devicetype).new :name => "FastEthernet 0/1" catalog.add_resource resource transaction = Puppet::Transaction.new(catalog, nil, Puppet::Graph::SequentialPrioritizer.new) transaction.for_network_device = true expect(transaction).to receive(:apply).with(resource, nil) transaction.evaluate expect(transaction.resource_status(resource)).not_to be_skipped end it "should apply resources appliable on host and device on a device" do catalog = Puppet::Resource::Catalog.new resource = Puppet::Type.type(:schedule).new :name => "test" catalog.add_resource resource transaction = Puppet::Transaction.new(catalog, nil, Puppet::Graph::SequentialPrioritizer.new) transaction.for_network_device = true expect(transaction).to receive(:apply).with(resource, nil) transaction.evaluate expect(transaction.resource_status(resource)).not_to be_skipped end # Verify that one component requiring another causes the contained # resources in the requiring component to get refreshed. it "should propagate events from a contained resource through its container to its dependent container's contained resources" do file = Puppet::Type.type(:file).new :path => tmpfile("event_propagation"), :ensure => :present execfile = File.join(tmpdir("exec_event"), "exectestingness2") exec = Puppet::Type.type(:exec).new :command => touch(execfile), :path => ENV['PATH'] catalog = mk_catalog(file) fcomp = Puppet::Type.type(:component).new(:name => "Foo[file]") catalog.add_resource fcomp catalog.add_edge(fcomp, file) ecomp = Puppet::Type.type(:component).new(:name => "Foo[exec]") catalog.add_resource ecomp catalog.add_resource exec catalog.add_edge(ecomp, exec) ecomp[:subscribe] = Puppet::Resource.new(:foo, "file") exec[:refreshonly] = true expect(exec).to receive(:refresh) catalog.apply end # Make sure that multiple subscriptions get triggered. it "should propagate events to all dependent resources", :unless => RUBY_PLATFORM == 'java' do path = tmpfile("path") file1 = tmpfile("file1") file2 = tmpfile("file2") file = Puppet::Type.type(:file).new( :path => path, :ensure => "file" ) exec1 = Puppet::Type.type(:exec).new( :path => ENV["PATH"], :command => touch(file1), :refreshonly => true, :subscribe => Puppet::Resource.new(:file, path) ) exec2 = Puppet::Type.type(:exec).new( :path => ENV["PATH"], :command => touch(file2), :refreshonly => true, :subscribe => Puppet::Resource.new(:file, path) ) catalog = mk_catalog(file, exec1, exec2) catalog.apply expect(Puppet::FileSystem.exist?(file1)).to be_truthy expect(Puppet::FileSystem.exist?(file2)).to be_truthy end it "does not refresh resources that have 'noop => true'" do path = tmpfile("path") notify = Puppet::Type.type(:notify).new( :name => "trigger", :notify => Puppet::Resource.new(:exec, "noop exec") ) noop_exec = Puppet::Type.type(:exec).new( :name => "noop exec", :path => ENV["PATH"], :command => touch(path), :noop => true ) catalog = mk_catalog(notify, noop_exec) catalog.apply expect(Puppet::FileSystem.exist?(path)).to be_falsey end it "should apply no resources whatsoever if a pre_run_check fails" do path = tmpfile("path") file = Puppet::Type.type(:file).new( :path => path, :ensure => "file" ) notify = Puppet::Type.type(:notify).new( :title => "foo" ) expect(notify).to receive(:pre_run_check).and_raise(Puppet::Error, "fail for testing") catalog = mk_catalog(file, notify) expect { catalog.apply }.to raise_error(Puppet::Error, /Some pre-run checks failed/) expect(Puppet::FileSystem.exist?(path)).not_to be_truthy end it "one failed refresh should propagate its failure to dependent refreshes", :unless => RUBY_PLATFORM == 'java' do path = tmpfile("path") newfile = tmpfile("file") file = Puppet::Type.type(:file).new( :path => path, :ensure => "file" ) exec1 = Puppet::Type.type(:exec).new( :path => ENV["PATH"], :command => touch(File.expand_path("/this/cannot/possibly/exist")), :logoutput => true, :refreshonly => true, :subscribe => file, :title => "one" ) exec2 = Puppet::Type.type(:exec).new( :path => ENV["PATH"], :command => touch(newfile), :logoutput => true, :refreshonly => true, :subscribe => [file, exec1], :title => "two" ) allow(exec1).to receive(:err) catalog = mk_catalog(file, exec1, exec2) catalog.apply expect(Puppet::FileSystem.exist?(newfile)).to be_falsey end # Ensure when resources have been generated with eval_generate that event # propagation still works when filtering with tags context "when filtering with tags", :unless => RUBY_PLATFORM == 'java' do context "when resources are dependent on dynamically generated resources" do it "should trigger (only) appropriately tagged dependent resources" do source = dir_containing('sourcedir', {'foo' => 'bar'}) target = tmpdir('targetdir') file1 = tmpfile("file1") file2 = tmpfile("file2") file = Puppet::Type.type(:file).new( :path => target, :source => source, :ensure => :present, :recurse => true, :tag => "foo_tag", ) exec1 = Puppet::Type.type(:exec).new( :path => ENV["PATH"], :command => touch(file1), :refreshonly => true, :subscribe => file, :tag => "foo_tag", ) exec2 = Puppet::Type.type(:exec).new( :path => ENV["PATH"], :command => touch(file2), :refreshonly => true, :subscribe => file, ) Puppet[:tags] = "foo_tag" catalog = mk_catalog(file, exec1, exec2) catalog.apply expect(Puppet::FileSystem.exist?(file1)).to be_truthy expect(Puppet::FileSystem.exist?(file2)).to be_falsey end it "should trigger implicitly tagged dependent resources, ie via type name" do file1 = tmpfile("file1") file2 = tmpfile("file2") expect(Puppet::FileSystem).to_not be_exist(file2) exec1 = Puppet::Type.type(:exec).new( :name => "exec1", :path => ENV["PATH"], :command => touch(file1), ) exec2 = Puppet::Type.type(:exec).new( :name => "exec2", :path => ENV["PATH"], :command => touch(file2), :refreshonly => true, :subscribe => exec1, ) Puppet[:tags] = "exec" catalog = mk_catalog(exec1, exec2) catalog.apply expect(Puppet::FileSystem.exist?(file1)).to be_truthy expect(Puppet::FileSystem.exist?(file2)).to be_truthy end end it "should propagate events correctly from a tagged container when running with tags" do file1 = tmpfile("original_tag") file2 = tmpfile("tag_propagation") command1 = usr_bin_touch(file1) command2 = usr_bin_touch(file2) manifest = <<-"MANIFEST" class foo { exec { 'notify test': command => '#{command1}', refreshonly => true, } } class test { include foo exec { 'test': command => '#{command2}', notify => Class['foo'], } } include test MANIFEST Puppet[:tags] = 'test' apply_compiled_manifest(manifest) expect(Puppet::FileSystem.exist?(file1)).to be_truthy expect(Puppet::FileSystem.exist?(file2)).to be_truthy end end describe "skipping resources" do let(:fname) { tmpfile("exec") } let(:file) do Puppet::Type.type(:file).new( :name => tmpfile("file"), :ensure => "file", :backup => false ) end let(:exec) do Puppet::Type.type(:exec).new( :name => touch(fname), :path => touch_path, :subscribe => Puppet::Resource.new("file", file.name) ) end it "does not trigger unscheduled resources", :unless => RUBY_PLATFORM == 'java' do catalog = mk_catalog catalog.add_resource(*Puppet::Type.type(:schedule).mkdefaultschedules) Puppet[:ignoreschedules] = false exec[:schedule] = "monthly" catalog.add_resource(file, exec) # Run it once so further runs don't schedule the resource catalog.apply expect(Puppet::FileSystem.exist?(fname)).to be_truthy # Now remove it, so it can get created again Puppet::FileSystem.unlink(fname) file[:content] = "some content" catalog.apply expect(Puppet::FileSystem.exist?(fname)).to be_falsey end it "does not trigger untagged resources" do catalog = mk_catalog Puppet[:tags] = "runonly" file.tag("runonly") catalog.add_resource(file, exec) catalog.apply expect(Puppet::FileSystem.exist?(fname)).to be_falsey end it "does not trigger skip-tagged resources" do catalog = mk_catalog Puppet[:skip_tags] = "skipme" exec.tag("skipme") catalog.add_resource(file, exec) catalog.apply expect(Puppet::FileSystem.exist?(fname)).to be_falsey end it "does not trigger resources with failed dependencies" do catalog = mk_catalog file[:path] = make_absolute("/foo/bar/baz") catalog.add_resource(file, exec) catalog.apply expect(Puppet::FileSystem.exist?(fname)).to be_falsey end end it "should not attempt to evaluate resources with failed dependencies", :unless => RUBY_PLATFORM == 'java' do exec = Puppet::Type.type(:exec).new( :command => "#{File.expand_path('/bin/mkdir')} /this/path/cannot/possibly/exist", :title => "mkdir" ) file1 = Puppet::Type.type(:file).new( :title => "file1", :path => tmpfile("file1"), :require => exec, :ensure => :file ) file2 = Puppet::Type.type(:file).new( :title => "file2", :path => tmpfile("file2"), :require => file1, :ensure => :file ) catalog = mk_catalog(exec, file1, file2) transaction = catalog.apply expect(Puppet::FileSystem.exist?(file1[:path])).to be_falsey expect(Puppet::FileSystem.exist?(file2[:path])).to be_falsey expect(transaction.resource_status(file1).skipped).to be_truthy expect(transaction.resource_status(file2).skipped).to be_truthy expect(transaction.resource_status(file1).failed_dependencies).to eq([exec]) expect(transaction.resource_status(file2).failed_dependencies).to eq([exec]) end it "on failure, skips dynamically-generated dependents", :unless => RUBY_PLATFORM == 'java' do exec = Puppet::Type.type(:exec).new( :command => "#{File.expand_path('/bin/mkdir')} /this/path/cannot/possibly/exist", :title => "mkdir" ) tmp = tmpfile("dir1") FileUtils.mkdir_p(tmp) FileUtils.mkdir_p(File.join(tmp, "foo")) purge_dir = Puppet::Type.type(:file).new( :title => "dir1", :path => tmp, :require => exec, :ensure => :directory, :recurse => true, :purge => true ) catalog = mk_catalog(exec, purge_dir) txn = catalog.apply expect(txn.resource_status(purge_dir).skipped).to be_truthy children = catalog.relationship_graph.direct_dependents_of(purge_dir) children.each do |child| expect(txn.resource_status(child).skipped).to be_truthy end expect(Puppet::FileSystem.exist?(File.join(tmp, "foo"))).to be_truthy end it "should not trigger subscribing resources on failure", :unless => RUBY_PLATFORM == 'java' do file1 = tmpfile("file1") file2 = tmpfile("file2") create_file1 = Puppet::Type.type(:exec).new( :command => usr_bin_touch(file1) ) exec = Puppet::Type.type(:exec).new( :command => "#{File.expand_path('/bin/mkdir')} /this/path/cannot/possibly/exist", :title => "mkdir", :notify => create_file1 ) create_file2 = Puppet::Type.type(:exec).new( :command => usr_bin_touch(file2), :subscribe => exec ) catalog = mk_catalog(exec, create_file1, create_file2) catalog.apply expect(Puppet::FileSystem.exist?(file1)).to be_falsey expect(Puppet::FileSystem.exist?(file2)).to be_falsey end # #801 -- resources only checked in noop should be rescheduled immediately. it "should immediately reschedule noop resources" do Puppet::Type.type(:schedule).mkdefaultschedules resource = Puppet::Type.type(:notify).new(:name => "mymessage", :noop => true) catalog = Puppet::Resource::Catalog.new catalog.add_resource resource trans = catalog.apply expect(trans.resource_harness).to be_scheduled(resource) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/defaults_spec.rb
spec/integration/defaults_spec.rb
require 'spec_helper' require 'puppet/defaults' describe "Puppet defaults" do describe "when default_manifest is set" do it "returns ./manifests by default" do expect(Puppet[:default_manifest]).to eq('./manifests') end end describe "when disable_per_environment_manifest is set" do it "returns false by default" do expect(Puppet[:disable_per_environment_manifest]).to eq(false) end it "errors when set to true and default_manifest is not an absolute path" do expect { Puppet[:default_manifest] = './some/relative/manifest.pp' Puppet[:disable_per_environment_manifest] = true }.to raise_error Puppet::Settings::ValidationError, /'default_manifest' setting must be.*absolute/ end end describe "when setting the :masterport" do it "should also set :serverport to the same value" do Puppet.settings[:masterport] = 3939 expect(Puppet.settings[:serverport]).to eq(3939) end it "should not overwrite :serverport if explicitly set" do Puppet.settings[:serverport] = 9000 Puppet.settings[:masterport] = 9001 expect(Puppet.settings[:serverport]).to eq(9000) end end describe "when setting the :factpath" do it "should add the :factpath to Facter's search paths" do expect(Facter).to receive(:search).with("/my/fact/path") Puppet.settings[:factpath] = "/my/fact/path" end end describe "when setting the :certname" do it "should fail if the certname is not downcased" do expect { Puppet.settings[:certname] = "Host.Domain.Com" }.to raise_error(ArgumentError) end it 'can set it to a value containing all digits' do Puppet.settings[:certname] = "000000000180" expect(Puppet.settings[:certname]).to eq("000000000180") end end describe "when setting :node_name_value" do it "should default to the value of :certname" do Puppet.settings[:certname] = 'blargle' expect(Puppet.settings[:node_name_value]).to eq('blargle') end end describe "when setting the :node_name_fact" do it "should fail when also setting :node_name_value" do expect do Puppet.settings[:node_name_value] = "some value" Puppet.settings[:node_name_fact] = "some_fact" end.to raise_error("Cannot specify both the node_name_value and node_name_fact settings") end it "should not fail when using the default for :node_name_value" do expect do Puppet.settings[:node_name_fact] = "some_fact" end.not_to raise_error end end it "should have a clientyamldir setting" do expect(Puppet.settings[:clientyamldir]).not_to be_nil end it "should have different values for the yamldir and clientyamldir" do expect(Puppet.settings[:yamldir]).not_to eq(Puppet.settings[:clientyamldir]) end it "should have a client_datadir setting" do expect(Puppet.settings[:client_datadir]).not_to be_nil end it "should have different values for the server_datadir and client_datadir" do expect(Puppet.settings[:server_datadir]).not_to eq(Puppet.settings[:client_datadir]) end # See #1232 it "should not specify a user or group for the clientyamldir" do expect(Puppet.settings.setting(:clientyamldir).owner).to be_nil expect(Puppet.settings.setting(:clientyamldir).group).to be_nil end it "should use the service user and group for the yamldir" do allow(Puppet.settings).to receive(:service_user_available?).and_return(true) allow(Puppet.settings).to receive(:service_group_available?).and_return(true) expect(Puppet.settings.setting(:yamldir).owner).to eq(Puppet.settings[:user]) expect(Puppet.settings.setting(:yamldir).group).to eq(Puppet.settings[:group]) end it "should specify that the host private key should be owned by the service user" do allow(Puppet.settings).to receive(:service_user_available?).and_return(true) expect(Puppet.settings.setting(:hostprivkey).owner).to eq(Puppet.settings[:user]) end it "should specify that the host certificate should be owned by the service user" do allow(Puppet.settings).to receive(:service_user_available?).and_return(true) expect(Puppet.settings.setting(:hostcert).owner).to eq(Puppet.settings[:user]) end [:modulepath, :factpath].each do |setting| it "should configure '#{setting}' not to be a file setting, so multi-directory settings are acceptable" do expect(Puppet.settings.setting(setting)).to be_instance_of(Puppet::Settings::PathSetting) end end describe "on a Unix-like platform it", :if => Puppet.features.posix? do it "should add /usr/sbin and /sbin to the path if they're not there" do Puppet::Util.withenv("PATH" => "/usr/bin#{File::PATH_SEPARATOR}/usr/local/bin") do Puppet.settings[:path] = "none" # this causes it to ignore the setting expect(ENV["PATH"].split(File::PATH_SEPARATOR)).to be_include("/usr/sbin") expect(ENV["PATH"].split(File::PATH_SEPARATOR)).to be_include("/sbin") end end end describe "on a Windows-like platform it", :if => Puppet::Util::Platform.windows? do let (:rune_utf8) { "\u16A0\u16C7\u16BB\u16EB\u16D2\u16E6\u16A6\u16EB\u16A0\u16B1\u16A9\u16A0\u16A2\u16B1\u16EB\u16A0\u16C1\u16B1\u16AA\u16EB\u16B7\u16D6\u16BB\u16B9\u16E6\u16DA\u16B3\u16A2\u16D7" } it "path should not add anything" do path = "c:\\windows\\system32#{File::PATH_SEPARATOR}c:\\windows" Puppet::Util.withenv("PATH" => path) do Puppet.settings[:path] = "none" # this causes it to ignore the setting expect(ENV["PATH"]).to eq(path) end end it "path should support UTF8 characters" do path = "c:\\windows\\system32#{File::PATH_SEPARATOR}c:\\windows#{File::PATH_SEPARATOR}C:\\" + rune_utf8 Puppet::Util.withenv("PATH" => path) do Puppet.settings[:path] = "none" # this causes it to ignore the setting expect(ENV['Path']).to eq(path) end end end it "should default to json for the preferred serialization format" do expect(Puppet.settings.value(:preferred_serialization_format)).to eq("json") end it "should default to true the disable_i18n setting" do expect(Puppet.settings.value(:disable_i18n)).to eq(true) end it "should have a setting for determining the configuration version and should default to an empty string" do expect(Puppet.settings[:config_version]).to eq("") end describe "when enabling reports" do it "should use the default server value when report server is unspecified" do Puppet.settings[:server] = "server" expect(Puppet.settings[:report_server]).to eq("server") end it "should use the default serverport value when report port is unspecified" do Puppet.settings[:serverport] = "1234" expect(Puppet.settings[:report_port]).to eq(1234) end it "should use the default masterport value when report port is unspecified" do Puppet.settings[:masterport] = "1234" expect(Puppet.settings[:report_port]).to eq(1234) end it "should use report_port when set" do Puppet.settings[:serverport] = "1234" Puppet.settings[:report_port] = "5678" expect(Puppet.settings[:report_port]).to eq(5678) end end it "should have a 'prerun_command' that defaults to the empty string" do expect(Puppet.settings[:prerun_command]).to eq("") end it "should have a 'postrun_command' that defaults to the empty string" do expect(Puppet.settings[:postrun_command]).to eq("") end it "should have a 'certificate_revocation' setting that defaults to true" do expect(Puppet.settings[:certificate_revocation]).to be_truthy end describe "reportdir" do subject { Puppet.settings[:reportdir] } it { is_expected.to eq("#{Puppet[:vardir]}/reports") } end describe "reporturl" do subject { Puppet.settings[:reporturl] } it { is_expected.to eq("http://localhost:3000/reports/upload") } end describe "when configuring color" do subject { Puppet.settings[:color] } it { is_expected.to eq("ansi") } end describe "daemonize" do it "should default to true", :unless => Puppet::Util::Platform.windows? do expect(Puppet.settings[:daemonize]).to eq(true) end describe "on Windows", :if => Puppet::Util::Platform.windows? do it "should default to false" do expect(Puppet.settings[:daemonize]).to eq(false) end it "should raise an error if set to true" do expect { Puppet.settings[:daemonize] = true }.to raise_error(/Cannot daemonize on Windows/) end end end describe "diff" do it "should default to 'diff' on POSIX", :unless => Puppet::Util::Platform.windows? do expect(Puppet.settings[:diff]).to eq('diff') end it "should default to '' on Windows", :if => Puppet::Util::Platform.windows? do expect(Puppet.settings[:diff]).to eq('') end end describe "when configuring hiera" do it "should have a hiera_config setting" do expect(Puppet.settings[:hiera_config]).not_to be_nil end end describe "when configuring the data_binding terminus" do it "should have a data_binding_terminus setting" do expect(Puppet.settings[:data_binding_terminus]).not_to be_nil end it "should be set to hiera by default" do expect(Puppet.settings[:data_binding_terminus]).to eq(:hiera) end it "to be neither 'hiera' nor 'none', a deprecation warning is logged" do expect(@logs).to eql([]) Puppet[:data_binding_terminus] = 'magic' expect(@logs[0].to_s).to match(/Setting 'data_binding_terminus' is deprecated/) end it "to not log a warning if set to 'none' or 'hiera'" do expect(@logs).to eql([]) Puppet[:data_binding_terminus] = 'none' Puppet[:data_binding_terminus] = 'hiera' expect(@logs).to eql([]) end end describe "agent_catalog_run_lockfile" do it "(#2888) is not a file setting so it is absent from the Settings catalog" do expect(Puppet.settings.setting(:agent_catalog_run_lockfile)).not_to be_a_kind_of Puppet::Settings::FileSetting expect(Puppet.settings.setting(:agent_catalog_run_lockfile)).to be_a Puppet::Settings::StringSetting end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/node_spec.rb
spec/integration/node_spec.rb
require 'spec_helper' require 'puppet/node' describe Puppet::Node do describe "when delegating indirection calls" do before do Puppet::Node.indirection.reset_terminus_class Puppet::Node.indirection.cache_class = nil @name = "me" @node = Puppet::Node.new(@name) end it "should be able to use the yaml terminus" do allow(Puppet::Node.indirection).to receive(:terminus_class).and_return(:yaml) # Load now, before we stub the exists? method. terminus = Puppet::Node.indirection.terminus(:yaml) expect(terminus).to receive(:path).with(@name).and_return("/my/yaml/file") expect(Puppet::FileSystem).to receive(:exist?).with("/my/yaml/file").and_return(false) expect(Puppet::Node.indirection.find(@name)).to be_nil end it "should be able to use the plain terminus" do allow(Puppet::Node.indirection).to receive(:terminus_class).and_return(:plain) # Load now, before we stub the exists? method. Puppet::Node.indirection.terminus(:plain) expect(Puppet::Node).to receive(:new).with(@name).and_return(@node) expect(Puppet::Node.indirection.find(@name)).to equal(@node) end describe "and using the memory terminus" do before do @name = "me" @terminus = Puppet::Node.indirection.terminus(:memory) allow(Puppet::Node.indirection).to receive(:terminus).and_return(@terminus) @node = Puppet::Node.new(@name) end after do @terminus.instance_variable_set(:@instances, {}) end it "should find no nodes by default" do expect(Puppet::Node.indirection.find(@name)).to be_nil end it "should be able to find nodes that were previously saved" do Puppet::Node.indirection.save(@node) expect(Puppet::Node.indirection.find(@name)).to equal(@node) end it "should replace existing saved nodes when a new node with the same name is saved" do Puppet::Node.indirection.save(@node) two = Puppet::Node.new(@name) Puppet::Node.indirection.save(two) expect(Puppet::Node.indirection.find(@name)).to equal(two) end it "should be able to remove previously saved nodes" do Puppet::Node.indirection.save(@node) Puppet::Node.indirection.destroy(@node.name) expect(Puppet::Node.indirection.find(@name)).to be_nil end it "should fail when asked to destroy a node that does not exist" do expect { Puppet::Node.indirection.destroy(@node) }.to raise_error(ArgumentError) end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/util/autoload_spec.rb
spec/integration/util/autoload_spec.rb
require 'spec_helper' require 'puppet/util/autoload' require 'fileutils' class AutoloadIntegrator @things = [] def self.newthing(name) @things << name end def self.thing?(name) @things.include? name end def self.clear @things.clear end end require 'puppet_spec/files' describe Puppet::Util::Autoload do include PuppetSpec::Files let(:env) { Puppet::Node::Environment.create(:foo, []) } def with_file(name, *path) path = File.join(*path) # Now create a file to load File.open(path, "w") { |f| f.puts "\nAutoloadIntegrator.newthing(:#{name.to_s})\n" } yield File.delete(path) end def with_loader(name, path) dir = tmpfile(name + path) $LOAD_PATH << dir Dir.mkdir(dir) rbdir = File.join(dir, path.to_s) Dir.mkdir(rbdir) loader = Puppet::Util::Autoload.new(name, path) yield rbdir, loader Dir.rmdir(rbdir) Dir.rmdir(dir) $LOAD_PATH.pop AutoloadIntegrator.clear end it "should not fail when asked to load a missing file" do expect(Puppet::Util::Autoload.new("foo", "bar").load(:eh, env)).to be_falsey end it "should load and return true when it successfully loads a file" do with_loader("foo", "bar") { |dir,loader| with_file(:mything, dir, "mything.rb") { expect(loader.load(:mything, env)).to be_truthy expect(loader.class).to be_loaded("bar/mything") expect(AutoloadIntegrator).to be_thing(:mything) } } end it "should consider a file loaded when asked for the name without an extension" do with_loader("foo", "bar") { |dir,loader| with_file(:noext, dir, "noext.rb") { loader.load(:noext, env) expect(loader.class).to be_loaded("bar/noext") } } end it "should consider a file loaded when asked for the name with an extension" do with_loader("foo", "bar") { |dir,loader| with_file(:noext, dir, "withext.rb") { loader.load(:withext, env) expect(loader.class).to be_loaded("bar/withext.rb") } } end it "should be able to load files directly from modules" do ## modulepath can't be used until after app settings are initialized, so we need to simulate that: expect(Puppet.settings).to receive(:app_defaults_initialized?).and_return(true).at_least(:once) modulepath = tmpfile("autoload_module_testing") libdir = File.join(modulepath, "mymod", "lib", "foo") FileUtils.mkdir_p(libdir) file = File.join(libdir, "plugin.rb") env = Puppet::Node::Environment.create(:production, [modulepath]) Puppet.override(:environments => Puppet::Environments::Static.new(env)) do with_loader("foo", "foo") do |dir, loader| with_file(:plugin, file.split("/")) do loader.load(:plugin, env) expect(loader.class).to be_loaded("foo/plugin.rb") end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/util/settings_spec.rb
spec/integration/util/settings_spec.rb
require 'spec_helper' require 'puppet_spec/files' describe Puppet::Settings do include PuppetSpec::Files def minimal_default_settings { :noop => {:default => false, :desc => "noop"} } end def define_settings(section, settings_hash) settings.define_settings(section, minimal_default_settings.update(settings_hash)) end let(:settings) { Puppet::Settings.new } it "should be able to make needed directories" do define_settings(:main, :maindir => { :default => tmpfile("main"), :type => :directory, :desc => "a", } ) settings.use(:main) expect(File.directory?(settings[:maindir])).to be_truthy end it "should make its directories with the correct modes" do Puppet[:manage_internal_file_permissions] = true define_settings(:main, :maindir => { :default => tmpfile("main"), :type => :directory, :desc => "a", :mode => 0750 } ) settings.use(:main) expect(Puppet::FileSystem.stat(settings[:maindir]).mode & 007777).to eq(0750) end it "will properly parse a UTF-8 configuration file" do rune_utf8 = "\u16A0\u16C7\u16BB" # ᚠᛇᚻ config = tmpfile("config") define_settings(:main, :config => { :type => :file, :default => config, :desc => "a" }, :environment => { :default => 'dingos', :desc => 'test', } ) File.open(config, 'w') do |file| file.puts <<-EOF [main] environment=#{rune_utf8} EOF end settings.initialize_global_settings expect(settings[:environment]).to eq(rune_utf8) end it "reparses configuration if configuration file is touched", :if => !Puppet::Util::Platform.windows? do config = tmpfile("config") define_settings(:main, :config => { :type => :file, :default => config, :desc => "a" }, :environment => { :default => 'dingos', :desc => 'test', } ) Puppet[:filetimeout] = '1s' File.open(config, 'w') do |file| file.puts <<-EOF [main] environment=toast EOF end settings.initialize_global_settings expect(settings[:environment]).to eq('toast') # First reparse establishes WatchedFiles settings.reparse_config_files sleep 1 File.open(config, 'w') do |file| file.puts <<-EOF [main] environment=bacon EOF end # Second reparse if later than filetimeout, reparses if changed settings.reparse_config_files expect(settings[:environment]).to eq('bacon') end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/util/execution_spec.rb
spec/integration/util/execution_spec.rb
require 'spec_helper' describe Puppet::Util::Execution, unless: Puppet::Util::Platform.jruby? do include PuppetSpec::Files describe "#execpipe" do it "should set LANG to C avoid localized output", :if => !Puppet::Util::Platform.windows? do out = "" Puppet::Util::Execution.execpipe('echo $LANG'){ |line| out << line.read.chomp } expect(out).to eq("C") end it "should set LC_ALL to C avoid localized output", :if => !Puppet::Util::Platform.windows? do out = "" Puppet::Util::Execution.execpipe('echo $LC_ALL'){ |line| out << line.read.chomp } expect(out).to eq("C") end it "should raise an ExecutionFailure with a missing command and :failonfail set to true" do expect { failonfail = true # NOTE: critical to return l in the block for `output` in method to be #<IO:(closed)> Puppet::Util::Execution.execpipe('conan_the_librarion', failonfail) { |l| l } }.to raise_error(Puppet::ExecutionFailure) end end describe "#execute" do if Puppet::Util::Platform.windows? let(:argv) { ["cmd", "/c", "echo", 123] } else let(:argv) { ["echo", 123] } end it 'stringifies sensitive arguments when given an array containing integers' do result = Puppet::Util::Execution.execute(argv, sensitive: true) expect(result.to_s.strip).to eq("123") expect(result.exitstatus).to eq(0) end it 'redacts sensitive arguments when given an array' do Puppet[:log_level] = :debug Puppet::Util::Execution.execute(argv, sensitive: true) expect(@logs).to include(an_object_having_attributes(level: :debug, message: "Executing: '[redacted]'")) end it 'redacts sensitive arguments when given a string' do Puppet[:log_level] = :debug str = argv.map(&:to_s).join(' ') Puppet::Util::Execution.execute(str, sensitive: true) expect(@logs).to include(an_object_having_attributes(level: :debug, message: "Executing: '[redacted]'")) end it "allows stdout and stderr to share a file" do command = "ruby -e '(1..10).each {|i| (i%2==0) ? $stdout.puts(i) : $stderr.puts(i)}'" expect(Puppet::Util::Execution.execute(command, :combine => true).split).to match_array([*'1'..'10']) end it "returns output and set $CHILD_STATUS" do command = "ruby -e 'puts \"foo\"; exit 42'" output = Puppet::Util::Execution.execute(command, {:failonfail => false}) expect(output).to eq("foo\n") expect($CHILD_STATUS.exitstatus).to eq(42) end it "raises an error if non-zero exit status is returned" do command = "ruby -e 'exit 43'" expect { Puppet::Util::Execution.execute(command) }.to raise_error(Puppet::ExecutionFailure, /Execution of '#{command}' returned 43: /) expect($CHILD_STATUS.exitstatus).to eq(43) end end describe "#execute (non-Windows)", :if => !Puppet::Util::Platform.windows? do it "should execute basic shell command" do result = Puppet::Util::Execution.execute("ls /tmp", :failonfail => true) expect(result.exitstatus).to eq(0) expect(result.to_s).to_not be_nil end end describe "#execute (Windows)", :if => Puppet::Util::Platform.windows? do let(:utf8text) do # Japanese Lorem Ipsum snippet "utf8testfile" + [227, 131, 171, 227, 131, 147, 227, 131, 179, 227, 131, 132, 227, 130, 162, 227, 130, 166, 227, 130, 167, 227, 131, 150, 227, 130, 162, 227, 129, 181, 227, 129, 185, 227, 129, 139, 227, 130, 137, 227, 129, 154, 227, 130, 187, 227, 130, 183, 227, 131, 147, 227, 131, 170, 227, 131, 134].pack('c*').force_encoding(Encoding::UTF_8) end let(:temputf8filename) do script_containing(utf8text, :windows => "@ECHO OFF\r\nECHO #{utf8text}\r\nEXIT 100") end it "should execute with non-english characters in command line" do result = Puppet::Util::Execution.execute("cmd /c \"#{temputf8filename}\"", :failonfail => false) expect(temputf8filename.encoding.name).to eq('UTF-8') expect(result.exitstatus).to eq(100) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/util/rdoc/parser_spec.rb
spec/integration/util/rdoc/parser_spec.rb
require 'spec_helper' require 'puppet/util/rdoc' describe "RDoc::Parser", :unless => Puppet::Util::Platform.windows? do require 'puppet_spec/files' include PuppetSpec::Files let(:document_all) { false } let(:tmp_dir) { tmpdir('rdoc_parser_tmp') } let(:doc_dir) { File.join(tmp_dir, 'doc') } let(:manifests_dir) { File.join(tmp_dir, 'manifests') } let(:modules_dir) { File.join(tmp_dir, 'modules') } let(:modules_and_manifests) do { :site => [ File.join(manifests_dir, 'site.pp'), <<-EOF # The test class comment class test { # The virtual resource comment @notify { virtual: } # The a_notify_resource comment notify { a_notify_resource: message => "a_notify_resource message" } } # The includes_another class comment class includes_another { include another } # The requires_another class comment class requires_another { require another } # node comment node foo { include test $a_var = "var_value" realize Notify[virtual] notify { bar: } } EOF ], :module_readme => [ File.join(modules_dir, 'a_module', 'README'), <<-EOF The a_module README docs. EOF ], :module_init => [ File.join(modules_dir, 'a_module', 'manifests', 'init.pp'), <<-EOF # The a_module class comment class a_module {} class another {} EOF ], :module_type => [ File.join(modules_dir, 'a_module', 'manifests', 'a_type.pp'), <<-EOF # The a_type type comment define a_module::a_type() {} EOF ], :module_plugin => [ File.join(modules_dir, 'a_module', 'lib', 'puppet', 'type', 'a_plugin.rb'), <<-EOF # The a_plugin type comment Puppet::Type.newtype(:a_plugin) do @doc = "Not presented" end EOF ], :module_function => [ File.join(modules_dir, 'a_module', 'lib', 'puppet', 'parser', 'a_function.rb'), <<-EOF # The a_function function comment module Puppet::Parser::Functions newfunction(:a_function, :type => :rvalue) do return end end EOF ], :module_fact => [ File.join(modules_dir, 'a_module', 'lib', 'facter', 'a_fact.rb'), <<-EOF # The a_fact fact comment Puppet.runtime[:facter].add("a_fact") do end EOF ], } end def write_file(file, content) FileUtils.mkdir_p(File.dirname(file)) File.open(file, 'w') do |f| f.puts(content) end end def prepare_manifests_and_modules modules_and_manifests.each do |key,array| write_file(*array) end end def file_exists_and_matches_content(file, *content_patterns) expect(Puppet::FileSystem.exist?(file)).to(be_truthy, "Cannot find #{file}") content_patterns.each do |pattern| content = File.read(file) expect(content).to match(pattern) end end def some_file_exists_with_matching_content(glob, *content_patterns) expect(Dir.glob(glob).select do |f| contents = File.read(f) content_patterns.all? { |p| p.match(contents) } end).not_to(be_empty, "Could not match #{content_patterns} in any of the files found in #{glob}") end around(:each) do |example| env = Puppet::Node::Environment.create(:doc_test_env, [modules_dir], manifests_dir) Puppet.override({:environments => Puppet::Environments::Static.new(env), :current_environment => env}) do example.run end end before :each do prepare_manifests_and_modules Puppet.settings[:document_all] = document_all Puppet.settings[:modulepath] = modules_dir Puppet::Util::RDoc.rdoc(doc_dir, [modules_dir, manifests_dir]) end describe "rdoc2 support" do def module_path(module_name) "#{doc_dir}/#{module_name}.html" end def plugin_path(module_name, type, name) "#{doc_dir}/#{module_name}/__#{type}s__.html" end def has_plugin_rdoc(module_name, type, name) file_exists_and_matches_content( plugin_path(module_name, type, name), /The .*?#{name}.*?\s*#{type} comment/m, /Type.*?#{type}/m ) end it "documents the a_module::a_plugin type" do has_plugin_rdoc("a_module", :type, 'a_plugin') end it "documents the a_module::a_function function" do has_plugin_rdoc("a_module", :function, 'a_function') end it "documents the a_module::a_fact fact" do has_plugin_rdoc("a_module", :fact, 'a_fact') end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/util/windows/security_spec.rb
spec/integration/util/windows/security_spec.rb
require 'spec_helper' if Puppet::Util::Platform.windows? class WindowsSecurityTester require 'puppet/util/windows/security' include Puppet::Util::Windows::Security end end describe "Puppet::Util::Windows::Security", :if => Puppet::Util::Platform.windows? do include PuppetSpec::Files before :all do # necessary for localized name of guests guests_name = Puppet::Util::Windows::SID.sid_to_name('S-1-5-32-546') guests = Puppet::Util::Windows::ADSI::Group.new(guests_name) @sids = { :current_user => Puppet::Util::Windows::SID.name_to_sid(Puppet::Util::Windows::ADSI::User.current_user_name), :system => Puppet::Util::Windows::SID::LocalSystem, :administrators => Puppet::Util::Windows::SID::BuiltinAdministrators, :guest => Puppet::Util::Windows::SID.name_to_sid(guests.members[0]), :users => Puppet::Util::Windows::SID::BuiltinUsers, :power_users => Puppet::Util::Windows::SID::PowerUsers, :none => Puppet::Util::Windows::SID::Nobody, :everyone => Puppet::Util::Windows::SID::Everyone } # The TCP/IP NetBIOS Helper service (aka 'lmhosts') has ended up # disabled on some VMs for reasons we couldn't track down. This # condition causes tests which rely on resolving UNC style paths # (like \\localhost) to fail with unhelpful error messages. # Put a check for this upfront to aid debug should this strike again. service = Puppet::Type.type(:service).new(:name => 'lmhosts') expect(service.provider.status).to eq(:running), 'lmhosts service is not running' end let (:sids) { @sids } let (:winsec) { WindowsSecurityTester.new } let (:klass) { Puppet::Util::Windows::File } def set_group_depending_on_current_user(path) if sids[:current_user] == sids[:system] # if the current user is SYSTEM, by setting the group to # guest, SYSTEM is automagically given full control, so instead # override that behavior with SYSTEM as group and a specific mode winsec.set_group(sids[:system], path) mode = winsec.get_mode(path) winsec.set_mode(mode & ~WindowsSecurityTester::S_IRWXG, path) else winsec.set_group(sids[:guest], path) end end def grant_everyone_full_access(path) sd = winsec.get_security_descriptor(path) everyone = 'S-1-1-0' inherit = Puppet::Util::Windows::AccessControlEntry::OBJECT_INHERIT_ACE | Puppet::Util::Windows::AccessControlEntry::CONTAINER_INHERIT_ACE sd.dacl.allow(everyone, klass::FILE_ALL_ACCESS, inherit) winsec.set_security_descriptor(path, sd) end shared_examples_for "only child owner" do it "should allow child owner" do winsec.set_owner(sids[:guest], parent) winsec.set_group(sids[:current_user], parent) winsec.set_mode(0700, parent) check_delete(path) end it "should deny parent owner" do winsec.set_owner(sids[:guest], path) winsec.set_group(sids[:current_user], path) winsec.set_mode(0700, path) expect { check_delete(path) }.to raise_error(Errno::EACCES) end it "should deny group" do winsec.set_owner(sids[:guest], path) winsec.set_group(sids[:current_user], path) winsec.set_mode(0700, path) expect { check_delete(path) }.to raise_error(Errno::EACCES) end it "should deny other" do winsec.set_owner(sids[:guest], path) winsec.set_group(sids[:current_user], path) winsec.set_mode(0700, path) expect { check_delete(path) }.to raise_error(Errno::EACCES) end end shared_examples_for "a securable object" do describe "on a volume that doesn't support ACLs" do [:owner, :group, :mode].each do |p| it "should return nil #{p}" do allow(winsec).to receive(:supports_acl?).and_return(false) expect(winsec.send("get_#{p}", path)).to be_nil end end end describe "on a volume that supports ACLs" do describe "for a normal user" do before :each do allow(Puppet.features).to receive(:root?).and_return(false) end after :each do winsec.set_mode(WindowsSecurityTester::S_IRWXU, parent) begin winsec.set_mode(WindowsSecurityTester::S_IRWXU, path) rescue nil end end describe "#supports_acl?" do %w[c:/ c:\\ c:/windows/system32 \\\\localhost\\C$ \\\\127.0.0.1\\C$\\foo].each do |path| it "should accept #{path}" do expect(winsec).to be_supports_acl(path) end end it "should raise an exception if it cannot get volume information" do expect { winsec.supports_acl?('foobar') }.to raise_error(Puppet::Error, /Failed to get volume information/) end end describe "#owner=" do it "should allow setting to the current user" do winsec.set_owner(sids[:current_user], path) end it "should raise an exception when setting to a different user" do expect { winsec.set_owner(sids[:guest], path) }.to raise_error do |error| expect(error).to be_a(Puppet::Util::Windows::Error) expect(error.code).to eq(1307) # ERROR_INVALID_OWNER end end end describe "#owner" do it "it should not be empty" do expect(winsec.get_owner(path)).not_to be_empty end it "should raise an exception if an invalid path is provided" do expect { winsec.get_owner("c:\\doesnotexist.txt") }.to raise_error do |error| expect(error).to be_a(Puppet::Util::Windows::Error) expect(error.code).to eq(2) # ERROR_FILE_NOT_FOUND end end end describe "#group=" do it "should allow setting to a group the current owner is a member of" do winsec.set_group(sids[:users], path) end # Unlike unix, if the user has permission to WRITE_OWNER, which the file owner has by default, # then they can set the primary group to a group that the user does not belong to. it "should allow setting to a group the current owner is not a member of" do winsec.set_group(sids[:power_users], path) end it "should consider a mode of 7 for group to be FullControl (F)" do winsec.set_group(sids[:power_users], path) winsec.set_mode(0070, path) group_ace = winsec.get_aces_for_path_by_sid(path, sids[:power_users]) # there should only be a single ace for the given group expect(group_ace.count).to eq(1) expect(group_ace[0].mask).to eq(klass::FILE_ALL_ACCESS) # ensure that mode is still read as 070 (written as 70) expect((winsec.get_mode(path) & 0777).to_s(8).rjust(3, '0')).to eq("070") end end describe "#group" do it "should not be empty" do expect(winsec.get_group(path)).not_to be_empty end it "should raise an exception if an invalid path is provided" do expect { winsec.get_group("c:\\doesnotexist.txt") }.to raise_error do |error| expect(error).to be_a(Puppet::Util::Windows::Error) expect(error.code).to eq(2) # ERROR_FILE_NOT_FOUND end end end it "should preserve inherited full control for SYSTEM when setting owner and group" do # new file has SYSTEM system_aces = winsec.get_aces_for_path_by_sid(path, sids[:system]) expect(system_aces).not_to be_empty # when running under SYSTEM account, multiple ACEs come back # so we only care that we have at least one of these expect(system_aces.any? do |ace| ace.mask == klass::FILE_ALL_ACCESS end).to be_truthy # changing the owner/group will no longer make the SD protected winsec.set_group(sids[:power_users], path) winsec.set_owner(sids[:administrators], path) expect(system_aces.find do |ace| ace.mask == klass::FILE_ALL_ACCESS && ace.inherited? end).not_to be_nil end describe "#mode=" do (0000..0700).step(0100) do |mode| it "should enforce mode #{mode.to_s(8)}" do winsec.set_mode(mode, path) check_access(mode, path) end end it "should round-trip all 128 modes that do not require deny ACEs, where owner and group are different" do # windows defaults set Administrators, None when Administrator # or Administrators, SYSTEM when System # but we can guarantee group is different by explicitly setting to Users winsec.set_group(sids[:users], path) 0.upto(1).each do |s| 0.upto(7).each do |u| 0.upto(u).each do |g| 0.upto(g).each do |o| # if user is superset of group, and group superset of other, then # no deny ace is required, and mode can be converted to win32 # access mask, and back to mode without loss of information # (provided the owner and group are not the same) next if ((u & g) != g) or ((g & o) != o) mode = (s << 9 | u << 6 | g << 3 | o << 0) winsec.set_mode(mode, path) expect(winsec.get_mode(path).to_s(8)).to eq(mode.to_s(8)) end end end end end it "should round-trip all 54 modes that do not require deny ACEs, where owner and group are same" do winsec.set_group(winsec.get_owner(path), path) 0.upto(1).each do |s| 0.upto(7).each do |ug| 0.upto(ug).each do |o| # if user and group superset of other, then # no deny ace is required, and mode can be converted to win32 # access mask, and back to mode without loss of information # (provided the owner and group are the same) next if ((ug & o) != o) mode = (s << 9 | ug << 6 | ug << 3 | o << 0) winsec.set_mode(mode, path) expect(winsec.get_mode(path).to_s(8)).to eq(mode.to_s(8)) end end end end # The SYSTEM user is a special case therefore we need to test that we round trip correctly when set it "should round-trip all 128 modes that do not require deny ACEs, when simulating a SYSTEM service" do # The owner and group for files/dirs created, when running as a service under Local System are # Owner = Administrators # Group = SYSTEM winsec.set_owner(sids[:administrators], path) winsec.set_group(sids[:system], path) 0.upto(1).each do |s| 0.upto(7).each do |u| 0.upto(u).each do |g| 0.upto(g).each do |o| # if user is superset of group, and group superset of other, then # no deny ace is required, and mode can be converted to win32 # access mask, and back to mode without loss of information # (provided the owner and group are not the same) next if ((u & g) != g) or ((g & o) != o) applied_mode = (s << 9 | u << 6 | g << 3 | o << 0) # SYSTEM must always be Full Control (7) expected_mode = (s << 9 | u << 6 | 7 << 3 | o << 0) winsec.set_mode(applied_mode, path) expect(winsec.get_mode(path).to_s(8)).to eq(expected_mode.to_s(8)) end end end end end it "should preserve full control for SYSTEM when setting mode" do # new file has SYSTEM system_aces = winsec.get_aces_for_path_by_sid(path, sids[:system]) expect(system_aces).not_to be_empty # when running under SYSTEM account, multiple ACEs come back # so we only care that we have at least one of these expect(system_aces.any? do |ace| ace.mask == klass::FILE_ALL_ACCESS end).to be_truthy # changing the mode will make the SD protected winsec.set_group(sids[:none], path) winsec.set_mode(0600, path) # and should have a non-inherited SYSTEM ACE(s) system_aces = winsec.get_aces_for_path_by_sid(path, sids[:system]) system_aces.each do |ace| expect(ace.mask).to eq(klass::FILE_ALL_ACCESS) expect(ace).not_to be_inherited end if Puppet::FileSystem.directory?(path) system_aces.each do |ace| expect(ace).to be_object_inherit expect(ace).to be_container_inherit end # it's critically important that this file be default created # and that this file not have it's owner / group / mode set by winsec nested_file = File.join(path, 'nested_file') File.new(nested_file, 'w').close system_aces = winsec.get_aces_for_path_by_sid(nested_file, sids[:system]) # even when SYSTEM is the owner (in CI), there should be an inherited SYSTEM expect(system_aces.any? do |ace| ace.mask == klass::FILE_ALL_ACCESS && ace.inherited? end).to be_truthy end end describe "for modes that require deny aces" do it "should map everyone to group and owner" do winsec.set_mode(0426, path) expect(winsec.get_mode(path).to_s(8)).to eq("666") end it "should combine user and group modes when owner and group sids are equal" do winsec.set_group(winsec.get_owner(path), path) winsec.set_mode(0410, path) expect(winsec.get_mode(path).to_s(8)).to eq("550") end end describe "for read-only objects" do before :each do winsec.set_group(sids[:none], path) winsec.set_mode(0600, path) Puppet::Util::Windows::File.add_attributes(path, klass::FILE_ATTRIBUTE_READONLY) expect(Puppet::Util::Windows::File.get_attributes(path) & klass::FILE_ATTRIBUTE_READONLY).to be_nonzero end it "should make them writable if any sid has write permission" do winsec.set_mode(WindowsSecurityTester::S_IWUSR, path) expect(Puppet::Util::Windows::File.get_attributes(path) & klass::FILE_ATTRIBUTE_READONLY).to eq(0) end it "should leave them read-only if no sid has write permission and should allow full access for SYSTEM" do winsec.set_mode(WindowsSecurityTester::S_IRUSR | WindowsSecurityTester::S_IXGRP, path) expect(Puppet::Util::Windows::File.get_attributes(path) & klass::FILE_ATTRIBUTE_READONLY).to be_nonzero system_aces = winsec.get_aces_for_path_by_sid(path, sids[:system]) # when running under SYSTEM account, and set_group / set_owner hasn't been called # SYSTEM full access will be restored expect(system_aces.any? do |ace| ace.mask == klass::FILE_ALL_ACCESS end).to be_truthy end end it "should raise an exception if an invalid path is provided" do expect { winsec.set_mode(sids[:guest], "c:\\doesnotexist.txt") }.to raise_error do |error| expect(error).to be_a(Puppet::Util::Windows::Error) expect(error.code).to eq(2) # ERROR_FILE_NOT_FOUND end end end describe "#mode" do it "should report when extra aces are encounted" do sd = winsec.get_security_descriptor(path) (544..547).each do |rid| sd.dacl.allow("S-1-5-32-#{rid}", klass::STANDARD_RIGHTS_ALL) end winsec.set_security_descriptor(path, sd) mode = winsec.get_mode(path) expect(mode & WindowsSecurityTester::S_IEXTRA).to eq(WindowsSecurityTester::S_IEXTRA) end it "should return deny aces" do sd = winsec.get_security_descriptor(path) sd.dacl.deny(sids[:guest], klass::FILE_GENERIC_WRITE) winsec.set_security_descriptor(path, sd) guest_aces = winsec.get_aces_for_path_by_sid(path, sids[:guest]) expect(guest_aces.find do |ace| ace.type == Puppet::Util::Windows::AccessControlEntry::ACCESS_DENIED_ACE_TYPE end).not_to be_nil end it "should skip inherit-only ace" do sd = winsec.get_security_descriptor(path) dacl = Puppet::Util::Windows::AccessControlList.new dacl.allow( sids[:current_user], klass::STANDARD_RIGHTS_ALL | klass::SPECIFIC_RIGHTS_ALL ) dacl.allow( sids[:everyone], klass::FILE_GENERIC_READ, Puppet::Util::Windows::AccessControlEntry::INHERIT_ONLY_ACE | Puppet::Util::Windows::AccessControlEntry::OBJECT_INHERIT_ACE ) winsec.set_security_descriptor(path, sd) expect(winsec.get_mode(path) & WindowsSecurityTester::S_IRWXO).to eq(0) end it "should raise an exception if an invalid path is provided" do expect { winsec.get_mode("c:\\doesnotexist.txt") }.to raise_error do |error| expect(error).to be_a(Puppet::Util::Windows::Error) expect(error.code).to eq(2) # ERROR_FILE_NOT_FOUND end end end describe "inherited access control entries" do it "should be absent when the access control list is protected, and should not remove SYSTEM" do winsec.set_mode(WindowsSecurityTester::S_IRWXU, path) mode = winsec.get_mode(path) [ WindowsSecurityTester::S_IEXTRA, WindowsSecurityTester::S_ISYSTEM_MISSING ].each do |flag| expect(mode & flag).not_to eq(flag) end end it "should be present when the access control list is unprotected" do # add a bunch of aces to the parent with permission to add children allow = klass::STANDARD_RIGHTS_ALL | klass::SPECIFIC_RIGHTS_ALL inherit = Puppet::Util::Windows::AccessControlEntry::OBJECT_INHERIT_ACE | Puppet::Util::Windows::AccessControlEntry::CONTAINER_INHERIT_ACE sd = winsec.get_security_descriptor(parent) sd.dacl.allow( "S-1-1-0", #everyone allow, inherit ) (544..547).each do |rid| sd.dacl.allow( "S-1-5-32-#{rid}", klass::STANDARD_RIGHTS_ALL, inherit ) end winsec.set_security_descriptor(parent, sd) # unprotect child, it should inherit from parent winsec.set_mode(WindowsSecurityTester::S_IRWXU, path, false) expect(winsec.get_mode(path) & WindowsSecurityTester::S_IEXTRA).to eq(WindowsSecurityTester::S_IEXTRA) end end end describe "for an administrator", :if => (Puppet.features.root? && Puppet::Util::Platform.windows?) do before :each do is_dir = Puppet::FileSystem.directory?(path) winsec.set_mode(WindowsSecurityTester::S_IRWXU | WindowsSecurityTester::S_IRWXG, path) set_group_depending_on_current_user(path) winsec.set_owner(sids[:guest], path) expected_error = is_dir ? Errno::EISDIR : Errno::EACCES expect { File.open(path, 'r') }.to raise_error(expected_error) end after :each do if Puppet::FileSystem.exist?(path) winsec.set_owner(sids[:current_user], path) winsec.set_mode(WindowsSecurityTester::S_IRWXU, path) end end describe "#owner=" do it "should accept the guest sid" do winsec.set_owner(sids[:guest], path) expect(winsec.get_owner(path)).to eq(sids[:guest]) end it "should accept a user sid" do winsec.set_owner(sids[:current_user], path) expect(winsec.get_owner(path)).to eq(sids[:current_user]) end it "should accept a group sid" do winsec.set_owner(sids[:power_users], path) expect(winsec.get_owner(path)).to eq(sids[:power_users]) end it "should raise an exception if an invalid sid is provided" do expect { winsec.set_owner("foobar", path) }.to raise_error(Puppet::Error, /Failed to convert string SID/) end it "should raise an exception if an invalid path is provided" do expect { winsec.set_owner(sids[:guest], "c:\\doesnotexist.txt") }.to raise_error do |error| expect(error).to be_a(Puppet::Util::Windows::Error) expect(error.code).to eq(2) # ERROR_FILE_NOT_FOUND end end end describe "#group=" do it "should accept the test group" do winsec.set_group(sids[:guest], path) expect(winsec.get_group(path)).to eq(sids[:guest]) end it "should accept a group sid" do winsec.set_group(sids[:power_users], path) expect(winsec.get_group(path)).to eq(sids[:power_users]) end it "should accept a user sid" do winsec.set_group(sids[:current_user], path) expect(winsec.get_group(path)).to eq(sids[:current_user]) end it "should combine owner and group rights when they are the same sid" do winsec.set_owner(sids[:power_users], path) winsec.set_group(sids[:power_users], path) winsec.set_mode(0610, path) expect(winsec.get_owner(path)).to eq(sids[:power_users]) expect(winsec.get_group(path)).to eq(sids[:power_users]) # note group execute permission added to user ace, and then group rwx value # reflected to match # Exclude missing system ace, since that's not relevant expect((winsec.get_mode(path) & 0777).to_s(8)).to eq("770") end it "should raise an exception if an invalid sid is provided" do expect { winsec.set_group("foobar", path) }.to raise_error(Puppet::Error, /Failed to convert string SID/) end it "should raise an exception if an invalid path is provided" do expect { winsec.set_group(sids[:guest], "c:\\doesnotexist.txt") }.to raise_error do |error| expect(error).to be_a(Puppet::Util::Windows::Error) expect(error.code).to eq(2) # ERROR_FILE_NOT_FOUND end end end describe "when the sid is NULL" do it "should retrieve an empty owner sid" it "should retrieve an empty group sid" end describe "when the sid refers to a deleted trustee" do it "should retrieve the user sid" do sid = nil user = Puppet::Util::Windows::ADSI::User.create("puppet#{rand(10000)}") user.password = 'PUPPET_RULeZ_123!' user.commit begin sid = Puppet::Util::Windows::ADSI::User.new(user.name).sid.sid winsec.set_owner(sid, path) winsec.set_mode(WindowsSecurityTester::S_IRWXU, path) ensure Puppet::Util::Windows::ADSI::User.delete(user.name) end expect(winsec.get_owner(path)).to eq(sid) expect(winsec.get_mode(path)).to eq(WindowsSecurityTester::S_IRWXU) end it "should retrieve the group sid" do sid = nil group = Puppet::Util::Windows::ADSI::Group.create("puppet#{rand(10000)}") group.commit begin sid = Puppet::Util::Windows::ADSI::Group.new(group.name).sid.sid winsec.set_group(sid, path) winsec.set_mode(WindowsSecurityTester::S_IRWXG, path) ensure Puppet::Util::Windows::ADSI::Group.delete(group.name) end expect(winsec.get_group(path)).to eq(sid) expect(winsec.get_mode(path)).to eq(WindowsSecurityTester::S_IRWXG) end end describe "#mode" do it "should deny all access when the DACL is empty, including SYSTEM" do sd = winsec.get_security_descriptor(path) # don't allow inherited aces to affect the test protect = true new_sd = Puppet::Util::Windows::SecurityDescriptor.new(sd.owner, sd.group, [], protect) winsec.set_security_descriptor(path, new_sd) expect(winsec.get_mode(path)).to eq(WindowsSecurityTester::S_ISYSTEM_MISSING) end # REMIND: ruby crashes when trying to set a NULL DACL # it "should allow all when it is nil" do # winsec.set_owner(sids[:current_user], path) # winsec.open_file(path, WindowsSecurityTester::READ_CONTROL | WindowsSecurityTester::WRITE_DAC) do |handle| # winsec.set_security_info(handle, WindowsSecurityTester::DACL_SECURITY_INFORMATION | WindowsSecurityTester::PROTECTED_DACL_SECURITY_INFORMATION, nil) # end # winsec.get_mode(path).to_s(8).should == "777" # end end describe "#mode=" do # setting owner to SYSTEM requires root it "should round-trip all 54 modes that do not require deny ACEs, when simulating a SYSTEM scheduled task" do # The owner and group for files/dirs created, when running as a Scheduled Task as Local System are # Owner = SYSTEM # Group = SYSTEM winsec.set_group(sids[:system], path) winsec.set_owner(sids[:system], path) 0.upto(1).each do |s| 0.upto(7).each do |ug| 0.upto(ug).each do |o| # if user and group superset of other, then # no deny ace is required, and mode can be converted to win32 # access mask, and back to mode without loss of information # (provided the owner and group are the same) next if ((ug & o) != o) applied_mode = (s << 9 | ug << 6 | ug << 3 | o << 0) # SYSTEM must always be Full Control (7) expected_mode = (s << 9 | 7 << 6 | 7 << 3 | o << 0) winsec.set_mode(applied_mode, path) expect(winsec.get_mode(path).to_s(8)).to eq(expected_mode.to_s(8)) end end end end end describe "when the parent directory" do before :each do winsec.set_owner(sids[:current_user], parent) winsec.set_owner(sids[:current_user], path) winsec.set_mode(0777, path, false) end describe "is writable and executable" do describe "and sticky bit is set" do it "should allow child owner" do winsec.set_owner(sids[:guest], parent) winsec.set_group(sids[:current_user], parent) winsec.set_mode(01700, parent) check_delete(path) end it "should allow parent owner" do winsec.set_owner(sids[:current_user], parent) winsec.set_group(sids[:guest], parent) winsec.set_mode(01700, parent) winsec.set_owner(sids[:current_user], path) winsec.set_group(sids[:guest], path) winsec.set_mode(0700, path) check_delete(path) end it "should deny group" do winsec.set_owner(sids[:guest], parent) winsec.set_group(sids[:current_user], parent) winsec.set_mode(01770, parent) winsec.set_owner(sids[:guest], path) winsec.set_group(sids[:current_user], path) winsec.set_mode(0700, path) expect { check_delete(path) }.to raise_error(Errno::EACCES) end it "should deny other" do winsec.set_owner(sids[:guest], parent) winsec.set_group(sids[:current_user], parent) winsec.set_mode(01777, parent) winsec.set_owner(sids[:guest], path) winsec.set_group(sids[:current_user], path) winsec.set_mode(0700, path) expect { check_delete(path) }.to raise_error(Errno::EACCES) end end describe "and sticky bit is not set" do it "should allow child owner" do winsec.set_owner(sids[:guest], parent) winsec.set_group(sids[:current_user], parent) winsec.set_mode(0700, parent) check_delete(path) end it "should allow parent owner" do winsec.set_owner(sids[:current_user], parent) winsec.set_group(sids[:guest], parent) winsec.set_mode(0700, parent) winsec.set_owner(sids[:current_user], path) winsec.set_group(sids[:guest], path) winsec.set_mode(0700, path) check_delete(path) end it "should allow group" do winsec.set_owner(sids[:guest], parent) winsec.set_group(sids[:current_user], parent) winsec.set_mode(0770, parent) winsec.set_owner(sids[:guest], path) winsec.set_group(sids[:current_user], path) winsec.set_mode(0700, path) check_delete(path) end it "should allow other" do winsec.set_owner(sids[:guest], parent) winsec.set_group(sids[:current_user], parent) winsec.set_mode(0777, parent) winsec.set_owner(sids[:guest], path) winsec.set_group(sids[:current_user], path) winsec.set_mode(0700, path) check_delete(path) end end end describe "is not writable" do before :each do winsec.set_group(sids[:current_user], parent) winsec.set_mode(0555, parent) end it_behaves_like "only child owner" end describe "is not executable" do before :each do winsec.set_group(sids[:current_user], parent) winsec.set_mode(0666, parent) end it_behaves_like "only child owner" end end end end end describe "file" do let (:parent) do tmpdir('win_sec_test_file') end let (:path) do path = File.join(parent, 'childfile') File.new(path, 'w').close path end after :each do # allow temp files to be cleaned up grant_everyone_full_access(parent) end it_behaves_like "a securable object" do def check_access(mode, path) if (mode & WindowsSecurityTester::S_IRUSR).nonzero? check_read(path) else expect { check_read(path) }.to raise_error(Errno::EACCES) end if (mode & WindowsSecurityTester::S_IWUSR).nonzero? check_write(path) else expect { check_write(path) }.to raise_error(Errno::EACCES) end if (mode & WindowsSecurityTester::S_IXUSR).nonzero? expect { check_execute(path) }.to raise_error(Errno::ENOEXEC) else expect { check_execute(path) }.to raise_error(Errno::EACCES) end end def check_read(path) File.open(path, 'r').close end def check_write(path) File.open(path, 'w').close end def check_execute(path) Kernel.exec(path) end def check_delete(path) File.delete(path) end end describe "locked files" do let (:explorer) { File.join(ENV['SystemRoot'], "explorer.exe") }
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
true
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/util/windows/adsi_spec.rb
spec/integration/util/windows/adsi_spec.rb
require 'spec_helper' require 'puppet/util/windows' describe Puppet::Util::Windows::ADSI::User, :if => Puppet::Util::Platform.windows? do describe ".initialize" do it "cannot reference BUILTIN accounts like SYSTEM due to WinNT moniker limitations" do system = Puppet::Util::Windows::ADSI::User.new('SYSTEM') # trying to retrieve COM object should fail to load with a localized version of: # ADSI connection error: failed to parse display name of moniker `WinNT://./SYSTEM,user' # HRESULT error code:0x800708ad # The user name could not be found. # Matching on error code alone is sufficient expect { system.native_object }.to raise_error(/0x800708ad/) end end describe '.each' do it 'should return a list of users with UTF-8 names' do begin original_codepage = Encoding.default_external Encoding.default_external = Encoding::CP850 # Western Europe Puppet::Util::Windows::ADSI::User.each do |user| expect(user.name.encoding).to be(Encoding::UTF_8) end ensure Encoding.default_external = original_codepage end end end describe '.[]' do it 'should return string attributes as UTF-8' do user = Puppet::Util::Windows::ADSI::User.new('Guest') expect(user['Description'].encoding).to eq(Encoding::UTF_8) end end describe '.groups' do it 'should return a list of groups with UTF-8 names' do begin original_codepage = Encoding.default_external Encoding.default_external = Encoding::CP850 # Western Europe # lookup by English name Administrator is OK on localized Windows administrator = Puppet::Util::Windows::ADSI::User.new('Administrator') administrator.groups.each do |name| expect(name.encoding).to be(Encoding::UTF_8) end ensure Encoding.default_external = original_codepage end end end describe '.current_user_name_with_format' do context 'when desired format is NameSamCompatible' do it 'should get the same user name as the current_user_name method but fully qualified' do user_name = Puppet::Util::Windows::ADSI::User.current_user_name fully_qualified_user_name = Puppet::Util::Windows::ADSI::User.current_sam_compatible_user_name expect(fully_qualified_user_name).to match(/^.+\\#{user_name}$/) end it 'should have the same SID as with the current_user_name method' do user_name = Puppet::Util::Windows::ADSI::User.current_user_name fully_qualified_user_name = Puppet::Util::Windows::ADSI::User.current_sam_compatible_user_name expect(Puppet::Util::Windows::SID.name_to_sid(user_name)).to eq(Puppet::Util::Windows::SID.name_to_sid(fully_qualified_user_name)) end end end end describe Puppet::Util::Windows::ADSI::Group, :if => Puppet::Util::Platform.windows? do let (:administrator_bytes) { [1, 2, 0, 0, 0, 0, 0, 5, 32, 0, 0, 0, 32, 2, 0, 0] } let (:administrators_principal) { Puppet::Util::Windows::SID::Principal.lookup_account_sid(administrator_bytes) } describe '.each' do it 'should return a list of groups with UTF-8 names' do begin original_codepage = Encoding.default_external Encoding.default_external = Encoding::CP850 # Western Europe Puppet::Util::Windows::ADSI::Group.each do |group| expect(group.name.encoding).to be(Encoding::UTF_8) end ensure Encoding.default_external = original_codepage end end end describe '.members' do it 'should return a list of members resolvable with Puppet::Util::Windows::ADSI::Group.name_sid_hash' do temp_groupname = "g#{SecureRandom.uuid}" temp_username = "u#{SecureRandom.uuid}"[0..12] # From https://docs.microsoft.com/en-us/windows/security/threat-protection/security-policy-settings/password-must-meet-complexity-requirements specials = "~!@#$%^&*_-+=`|\(){}[]:;\"'<>,.?/" temp_password = "p#{SecureRandom.uuid[0..7]}-#{SecureRandom.uuid.upcase[0..7]}-#{specials[rand(specials.length)]}" # select a virtual account that requires an authority to be able to resolve to SID # the Dhcp service is chosen for no particular reason aside from it's a service available on all Windows versions dhcp_virtualaccount = Puppet::Util::Windows::SID.name_to_principal('NT SERVICE\Dhcp') # adding :SidTypeGroup as a group member will cause error in IAdsUser::Add # adding :SidTypeDomain (such as S-1-5-80 / NT SERVICE or computer name) won't error # but also won't be returned as a group member # uncertain how to obtain :SidTypeComputer (perhaps AD? the local machine is :SidTypeDomain) users = [ # Use sid_to_name to get localized names of SIDs - BUILTIN, SYSTEM, NT AUTHORITY, Everyone are all localized # :SidTypeWellKnownGroup # SYSTEM is prefixed with the NT Authority authority, resolveable with or without authority { :sid => 'S-1-5-18', :name => Puppet::Util::Windows::SID.sid_to_name('S-1-5-18') }, # Everyone is not prefixed with an authority, resolveable with or without NT AUTHORITY authority { :sid => 'S-1-1-0', :name => Puppet::Util::Windows::SID.sid_to_name('S-1-1-0') }, # Dhcp service account is prefixed with NT SERVICE authority, requires authority to resolve SID # behavior is similar to IIS APPPOOL\DefaultAppPool { :sid => dhcp_virtualaccount.sid, :name => dhcp_virtualaccount.domain_account }, # :SidTypeAlias with authority component # Administrators group is prefixed with BUILTIN authority, can be resolved with or without authority { :sid => 'S-1-5-32-544', :name => Puppet::Util::Windows::SID.sid_to_name('S-1-5-32-544') }, ] begin # :SidTypeUser as user on localhost, can be resolved with or without authority prefix user = Puppet::Util::Windows::ADSI::User.create(temp_username) # appveyor sometimes requires a password user.password = temp_password user.commit() users.push({ :sid => user.sid.sid, :name => Puppet::Util::Windows::ADSI.computer_name + '\\' + temp_username }) # create a test group and add above 5 members by SID group = described_class.create(temp_groupname) group.commit() group.set_members(users.map { |u| u[:sid]} ) # most importantly make sure that all name are convertible to SIDs expect { described_class.name_sid_hash(group.members) }.to_not raise_error # also verify the names returned are as expected expected_usernames = users.map { |u| u[:name] } expect(group.members.map(&:domain_account)).to eq(expected_usernames) ensure described_class.delete(temp_groupname) if described_class.exists?(temp_groupname) Puppet::Util::Windows::ADSI::User.delete(temp_username) if Puppet::Util::Windows::ADSI::User.exists?(temp_username) end end it 'should return a list of Principal objects even with unresolvable SIDs' do members = [ # NULL SID is not localized double('WIN32OLE', { :objectSID => [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], :Name => 'NULL SID', :ole_respond_to? => true, }), # unresolvable SID is a different story altogether double('WIN32OLE', { # completely valid SID, but Name is just a stringified version :objectSID => [1, 5, 0, 0, 0, 0, 0, 5, 21, 0, 0, 0, 5, 113, 65, 218, 15, 127, 9, 57, 219, 4, 84, 126, 88, 4, 0, 0], :Name => 'S-1-5-21-3661721861-956923663-2119435483-1112', :ole_respond_to? => true, }) ] admins_name = Puppet::Util::Windows::SID.sid_to_name('S-1-5-32-544') admins = Puppet::Util::Windows::ADSI::Group.new(admins_name) # touch the native_object member to have it lazily loaded, so COM objects can be stubbed admins.native_object without_partial_double_verification do allow(admins.native_object).to receive(:Members).and_return(members) end # well-known NULL SID expect(admins.members[0].sid).to eq('S-1-0-0') expect(admins.members[0].account_type).to eq(:SidTypeWellKnownGroup) # unresolvable SID expect(admins.members[1].sid).to eq('S-1-5-21-3661721861-956923663-2119435483-1112') expect(admins.members[1].account).to eq('S-1-5-21-3661721861-956923663-2119435483-1112') expect(admins.members[1].account_type).to eq(:SidTypeUnknown) end it 'should return a list of members with UTF-8 names' do begin original_codepage = Encoding.default_external Encoding.default_external = Encoding::CP850 # Western Europe # lookup by English name Administrators is not OK on localized Windows admins = Puppet::Util::Windows::ADSI::Group.new(administrators_principal.account) admins.members.map(&:domain_account).each do |name| expect(name.encoding).to be(Encoding::UTF_8) end ensure Encoding.default_external = original_codepage end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/util/windows/principal_spec.rb
spec/integration/util/windows/principal_spec.rb
require 'spec_helper' require 'puppet/util/windows' describe Puppet::Util::Windows::SID::Principal, :if => Puppet::Util::Platform.windows? do let (:current_user_sid) { Puppet::Util::Windows::ADSI::User.current_user_sid } let (:system_bytes) { [1, 1, 0, 0, 0, 0, 0, 5, 18, 0, 0, 0] } let (:null_sid_bytes) { [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] } let (:administrator_bytes) { [1, 2, 0, 0, 0, 0, 0, 5, 32, 0, 0, 0, 32, 2, 0, 0] } let (:all_application_packages_bytes) { [1, 2, 0, 0, 0, 0, 0, 15, 2, 0, 0, 0, 1, 0, 0, 0] } let (:computer_sid) { Puppet::Util::Windows::SID.name_to_principal(Puppet::Util::Windows::ADSI.computer_name) } # BUILTIN is localized on German Windows, but not French # looking this up like this dilutes the values of the tests as we're comparing two mechanisms # for returning the same values, rather than to a known good let (:builtin_localized) { Puppet::Util::Windows::SID.sid_to_name('S-1-5-32') } describe ".lookup_account_name" do it "should create an instance from a well-known account name" do principal = Puppet::Util::Windows::SID::Principal.lookup_account_name('NULL SID') expect(principal.account).to eq('NULL SID') expect(principal.sid_bytes).to eq(null_sid_bytes) expect(principal.sid).to eq('S-1-0-0') expect(principal.domain).to eq('') expect(principal.domain_account).to eq('NULL SID') expect(principal.account_type).to eq(:SidTypeWellKnownGroup) expect(principal.to_s).to eq('NULL SID') end it "should create an instance from a well-known account prefixed with NT AUTHORITY" do # a special case that can be used to lookup an account on a localized Windows principal = Puppet::Util::Windows::SID::Principal.lookup_account_name('NT AUTHORITY\\SYSTEM') expect(principal.sid_bytes).to eq(system_bytes) expect(principal.sid).to eq('S-1-5-18') # guard these 3 checks on a US Windows with 1033 - primary language id of 9 primary_language_id = 9 # even though lookup in English, returned values may be localized # French Windows returns AUTORITE NT\\Syst\u00E8me, German Windows returns NT-AUTORIT\u00C4T\\SYSTEM if (Puppet::Util::Windows::Process.get_system_default_ui_language & primary_language_id == primary_language_id) expect(principal.account).to eq('SYSTEM') expect(principal.domain).to eq('NT AUTHORITY') expect(principal.domain_account).to eq('NT AUTHORITY\\SYSTEM') expect(principal.to_s).to eq('NT AUTHORITY\\SYSTEM') end # Windows API LookupAccountSid behaves differently if current user is SYSTEM if current_user_sid.sid_bytes != system_bytes account_type = :SidTypeWellKnownGroup else account_type = :SidTypeUser end expect(principal.account_type).to eq(account_type) end it "should create an instance from a local account prefixed with hostname" do running_as_system = (current_user_sid.sid_bytes == system_bytes) username = running_as_system ? # need to return localized name of Administrator account Puppet::Util::Windows::SID.sid_to_name(computer_sid.sid + '-500').split('\\').last : current_user_sid.account user_exists = Puppet::Util::Windows::ADSI::User.exists?(".\\#{username}") # when running as SYSTEM (in Jenkins CI), then Administrator should be used # otherwise running in AppVeyor there is no Administrator and a the current local user can be used skip if (running_as_system && !user_exists) hostname = Puppet::Util::Windows::ADSI.computer_name principal = Puppet::Util::Windows::SID::Principal.lookup_account_name("#{hostname}\\#{username}") expect(principal.account).to match(/^#{Regexp.quote(username)}$/i) # skip SID and bytes in this case since the most interesting thing here is domain_account expect(principal.domain).to match(/^#{Regexp.quote(hostname)}$/i) expect(principal.domain_account).to match(/^#{Regexp.quote(hostname)}\\#{Regexp.quote(username)}$/i) expect(principal.account_type).to eq(:SidTypeUser) end it "should create an instance from a well-known BUILTIN alias" do # by looking up the localized name of the account, the test value is diluted # this localizes Administrators AND BUILTIN qualified_name = Puppet::Util::Windows::SID.sid_to_name('S-1-5-32-544') domain, name = qualified_name.split('\\') principal = Puppet::Util::Windows::SID::Principal.lookup_account_name(name) expect(principal.account).to eq(name) expect(principal.sid_bytes).to eq(administrator_bytes) expect(principal.sid).to eq('S-1-5-32-544') expect(principal.domain).to eq(domain) expect(principal.domain_account).to eq(qualified_name) expect(principal.account_type).to eq(:SidTypeAlias) expect(principal.to_s).to eq(qualified_name) end it "should raise an error when trying to lookup an account that doesn't exist" do principal = Puppet::Util::Windows::SID::Principal expect { principal.lookup_account_name('ConanTheBarbarian') }.to raise_error do |error| expect(error).to be_a(Puppet::Util::Windows::Error) expect(error.code).to eq(1332) # ERROR_NONE_MAPPED end end it "should return a BUILTIN domain principal for empty account names" do principal = Puppet::Util::Windows::SID::Principal.lookup_account_name('') expect(principal.account_type).to eq(:SidTypeDomain) expect(principal.sid).to eq('S-1-5-32') expect(principal.account).to eq(builtin_localized) expect(principal.domain).to eq(builtin_localized) expect(principal.domain_account).to eq(builtin_localized) expect(principal.to_s).to eq(builtin_localized) end it "should return a BUILTIN domain principal for BUILTIN account names" do principal = Puppet::Util::Windows::SID::Principal.lookup_account_name(builtin_localized) expect(principal.account_type).to eq(:SidTypeDomain) expect(principal.sid).to eq('S-1-5-32') expect(principal.account).to eq(builtin_localized) expect(principal.domain).to eq(builtin_localized) expect(principal.domain_account).to eq(builtin_localized) expect(principal.to_s).to eq(builtin_localized) end it "should always sanitize the account name first" do expect(Puppet::Util::Windows::SID::Principal).to receive(:sanitize_account_name).with('NT AUTHORITY\\SYSTEM').and_call_original Puppet::Util::Windows::SID::Principal.lookup_account_name('NT AUTHORITY\\SYSTEM') end it "should be able to create an instance from an account name prefixed by APPLICATION PACKAGE AUTHORITY" do principal = Puppet::Util::Windows::SID::Principal.lookup_account_name('APPLICATION PACKAGE AUTHORITY\\ALL APPLICATION PACKAGES') expect(principal.account).to eq('ALL APPLICATION PACKAGES') expect(principal.sid_bytes).to eq(all_application_packages_bytes) expect(principal.sid).to eq('S-1-15-2-1') expect(principal.domain).to eq('APPLICATION PACKAGE AUTHORITY') expect(principal.domain_account).to eq('APPLICATION PACKAGE AUTHORITY\\ALL APPLICATION PACKAGES') expect(principal.account_type).to eq(:SidTypeWellKnownGroup) expect(principal.to_s).to eq('APPLICATION PACKAGE AUTHORITY\\ALL APPLICATION PACKAGES') end it "should fail without proper account name sanitization when it is prefixed by APPLICATION PACKAGE AUTHORITY" do given_account_name = 'APPLICATION PACKAGE AUTHORITY\\ALL APPLICATION PACKAGES' expect { Puppet::Util::Windows::SID::Principal.lookup_account_name(nil, false, given_account_name) }.to raise_error(Puppet::Util::Windows::Error, /No mapping between account names and security IDs was done./) end end describe ".lookup_account_sid" do it "should create an instance from a user SID" do # take the computer account bytes and append the equivalent of -501 for Guest bytes = (computer_sid.sid_bytes + [245, 1, 0, 0]) # computer SID bytes start with [1, 4, ...] but need to be [1, 5, ...] bytes[1] = 5 principal = Puppet::Util::Windows::SID::Principal.lookup_account_sid(bytes) # use the returned SID to lookup localized Guest account name in Windows guest_name = Puppet::Util::Windows::SID.sid_to_name(principal.sid) expect(principal.sid_bytes).to eq(bytes) expect(principal.sid).to eq(computer_sid.sid + '-501') expect(principal.account).to eq(guest_name.split('\\')[1]) expect(principal.domain).to eq(computer_sid.domain) expect(principal.domain_account).to eq(guest_name) expect(principal.account_type).to eq(:SidTypeUser) expect(principal.to_s).to eq(guest_name) end it "should create an instance from a well-known group SID" do principal = Puppet::Util::Windows::SID::Principal.lookup_account_sid(null_sid_bytes) expect(principal.sid_bytes).to eq(null_sid_bytes) expect(principal.sid).to eq('S-1-0-0') expect(principal.account).to eq('NULL SID') expect(principal.domain).to eq('') expect(principal.domain_account).to eq('NULL SID') expect(principal.account_type).to eq(:SidTypeWellKnownGroup) expect(principal.to_s).to eq('NULL SID') end it "should create an instance from a well-known BUILTIN Alias SID" do principal = Puppet::Util::Windows::SID::Principal.lookup_account_sid(administrator_bytes) # by looking up the localized name of the account, the test value is diluted # this localizes Administrators AND BUILTIN qualified_name = Puppet::Util::Windows::SID.sid_to_name('S-1-5-32-544') domain, name = qualified_name.split('\\') expect(principal.account).to eq(name) expect(principal.sid_bytes).to eq(administrator_bytes) expect(principal.sid).to eq('S-1-5-32-544') expect(principal.domain).to eq(domain) expect(principal.domain_account).to eq(qualified_name) expect(principal.account_type).to eq(:SidTypeAlias) expect(principal.to_s).to eq(qualified_name) end it "should raise an error when trying to lookup nil" do principal = Puppet::Util::Windows::SID::Principal expect { principal.lookup_account_sid(nil) }.to raise_error(Puppet::Util::Windows::Error, /must not be nil/) end it "should raise an error when trying to lookup non-byte array" do principal = Puppet::Util::Windows::SID::Principal expect { principal.lookup_account_sid('ConanTheBarbarian') }.to raise_error(Puppet::Util::Windows::Error, /array/) end it "should raise an error when trying to lookup an empty array" do principal = Puppet::Util::Windows::SID::Principal expect { principal.lookup_account_sid([]) }.to raise_error(Puppet::Util::Windows::Error, /at least 1 byte long/) end # https://technet.microsoft.com/en-us/library/cc962011.aspx # "... The structure used in all SIDs created by Windows NT and Windows 2000 is revision level 1. ..." # Therefore a value of zero for the revision, is not a valid SID it "should raise an error when trying to lookup completely invalid SID bytes" do principal = Puppet::Util::Windows::SID::Principal expect { principal.lookup_account_sid([0]) }.to raise_error do |error| expect(error).to be_a(Puppet::Util::Windows::Error) expect(error.code).to eq(87) # ERROR_INVALID_PARAMETER end end it "should raise an error when trying to lookup a valid SID that doesn't have a matching account" do principal = Puppet::Util::Windows::SID::Principal expect { # S-1-1-1 which is not a valid account principal.lookup_account_sid([1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0]) }.to raise_error do |error| expect(error).to be_a(Puppet::Util::Windows::Error) expect(error.code).to eq(1332) # ERROR_NONE_MAPPED end end it "should return a domain principal for BUILTIN SID S-1-5-32" do principal = Puppet::Util::Windows::SID::Principal.lookup_account_sid([1, 1, 0, 0, 0, 0, 0, 5, 32, 0, 0, 0]) expect(principal.account_type).to eq(:SidTypeDomain) expect(principal.sid).to eq('S-1-5-32') expect(principal.account).to eq(builtin_localized) expect(principal.domain).to eq(builtin_localized) expect(principal.domain_account).to eq(builtin_localized) expect(principal.to_s).to eq(builtin_localized) end end describe "it should create matching Principal objects" do let(:builtin_sid) { [1, 1, 0, 0, 0, 0, 0, 5, 32, 0, 0, 0] } let(:sid_principal) { Puppet::Util::Windows::SID::Principal.lookup_account_sid(builtin_sid) } ['.', ''].each do |name| it "when comparing the one looked up via SID S-1-5-32 to one looked up via non-canonical name #{name} for the BUILTIN domain" do name_principal = Puppet::Util::Windows::SID::Principal.lookup_account_name(name) # compares canonical sid expect(sid_principal).to eq(name_principal) # compare all properties that have public accessors sid_principal.public_methods(false).reject { |m| m == :== }.each do |method| expect(sid_principal.send(method)).to eq(name_principal.send(method)) end end end it "when comparing the one looked up via SID S-1-5-32 to one looked up via non-canonical localized name for the BUILTIN domain" do name_principal = Puppet::Util::Windows::SID::Principal.lookup_account_name(builtin_localized) # compares canonical sid expect(sid_principal).to eq(name_principal) # compare all properties that have public accessors sid_principal.public_methods(false).reject { |m| m == :== }.each do |method| expect(sid_principal.send(method)).to eq(name_principal.send(method)) end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/util/windows/registry_spec.rb
spec/integration/util/windows/registry_spec.rb
require 'spec_helper' require 'puppet/util/windows' if Puppet::Util::Platform.windows? describe Puppet::Util::Windows::Registry do subject do class TestRegistry include Puppet::Util::Windows::Registry extend FFI::Library ffi_lib :advapi32 attach_function :RegSetValueExW, [:handle, :pointer, :dword, :dword, :pointer, :dword], :win32_long def write_corrupt_dword(reg, valuename) # Normally DWORDs contain 4 bytes. This bad data only has 2 bad_data = [0, 0] FFI::Pointer.from_string_to_wide_string(valuename) do |name_ptr| FFI::MemoryPointer.new(:uchar, bad_data.length) do |data_ptr| data_ptr.write_array_of_uchar(bad_data) if RegSetValueExW(reg.hkey, name_ptr, 0, Win32::Registry::REG_DWORD, data_ptr, data_ptr.size) != 0 raise Puppet::Util::Windows::Error.new("Failed to write registry value") end end end end end TestRegistry.new end let(:name) { 'HKEY_LOCAL_MACHINE' } let(:path) { 'Software\Microsoft' } context "#root" do it "should lookup the root hkey" do expect(subject.root(name)).to be_instance_of(Win32::Registry::PredefinedKey) end it "should raise for unknown root keys" do expect { subject.root('HKEY_BOGUS') }.to raise_error(Puppet::Error, /Invalid registry key/) end end context "#open" do let(:hkey) { double('hklm') } let(:subkey) { double('subkey') } before :each do allow(subject).to receive(:root).and_return(hkey) end it "should yield the opened the subkey" do expect(hkey).to receive(:open).with(path, anything).and_yield(subkey) yielded = nil subject.open(name, path) {|reg| yielded = reg} expect(yielded).to eq(subkey) end if Puppet::Util::Platform.windows? [described_class::KEY64, described_class::KEY32].each do |access| it "should open the key for read access 0x#{access.to_s(16)}" do mode = described_class::KEY_READ | access expect(hkey).to receive(:open).with(path, mode) subject.open(name, path, mode) {|reg| } end end end it "should default to KEY64" do expect(hkey).to receive(:open).with(path, described_class::KEY_READ | described_class::KEY64) subject.open(hkey, path) {|hkey| } end it "should raise for a path that doesn't exist" do expect(hkey).to receive(:keyname).and_return('HKEY_LOCAL_MACHINE') expect(hkey).to receive(:open).and_raise(Win32::Registry::Error.new(2)) # file not found expect do subject.open(hkey, 'doesnotexist') {|hkey| } end.to raise_error(Puppet::Error, /Failed to open registry key 'HKEY_LOCAL_MACHINE\\doesnotexist'/) end end context "#values" do let(:key) { double('uninstall') } it "should return each value's name and data" do expect(key).not_to receive(:each_value) expect(subject).to receive(:each_value).with(key).and_yield('string', 1, 'foo').and_yield('dword', 4, 0) expect(subject.values(key)).to eq({ 'string' => 'foo', 'dword' => 0 }) end it "should return an empty hash if there are no values" do expect(key).not_to receive(:each_value) expect(subject).to receive(:each_value).with(key) expect(subject.values(key)).to eq({}) end it "passes REG_DWORD through" do expect(key).not_to receive(:each_value) expect(subject).to receive(:each_value).with(key).and_yield('dword', Win32::Registry::REG_DWORD, '1') value = subject.values(key).first[1] expect(Integer(value)).to eq(1) end context "when reading non-ASCII values" do ENDASH_UTF_8 = [0xE2, 0x80, 0x93] ENDASH_UTF_16 = [0x2013] TM_UTF_8 = [0xE2, 0x84, 0xA2] TM_UTF_16 = [0x2122] let(:hklm) { Win32::Registry::HKEY_LOCAL_MACHINE } let(:puppet_key) { "SOFTWARE\\Puppet Labs"} let(:subkey_name) { "PuppetRegistryTest#{SecureRandom.uuid}" } let(:guid) { SecureRandom.uuid } let(:regsam) { Puppet::Util::Windows::Registry::KEY32 } after(:each) do # Ruby 2.1.5 has bugs with deleting registry keys due to using ANSI # character APIs, but passing wide strings to them (facepalm) # https://github.com/ruby/ruby/blob/v2_1_5/ext/win32/lib/win32/registry.rb#L323-L329 # therefore, use our own built-in registry helper code hklm.open(puppet_key, Win32::Registry::KEY_ALL_ACCESS | regsam) do |reg| subject.delete_key(reg, subkey_name, regsam) end end # proof that local encodings (such as IBM437 are no longer relevant) it "will return a UTF-8 string from a REG_SZ registry value (written as UTF-16LE)", :if => Puppet::Util::Platform.windows? do # create a UTF-16LE byte array representing "–™" utf_16_bytes = ENDASH_UTF_16 + TM_UTF_16 utf_16_str = utf_16_bytes.pack('s*').force_encoding(Encoding::UTF_16LE) # and it's UTF-8 equivalent bytes utf_8_bytes = ENDASH_UTF_8 + TM_UTF_8 utf_8_str = utf_8_bytes.pack('c*').force_encoding(Encoding::UTF_8) hklm.create("#{puppet_key}\\#{subkey_name}", Win32::Registry::KEY_ALL_ACCESS | regsam) do |reg| reg.write("#{guid}", Win32::Registry::REG_SZ, utf_16_str) # trigger Puppet::Util::Windows::Registry FFI calls keys = subject.keys(reg) vals = subject.values(reg) expect(keys).to be_empty expect(vals).to have_key(guid) # The UTF-16LE string written should come back as the equivalent UTF-8 written = vals[guid] expect(written).to eq(utf_8_str) expect(written.encoding).to eq(Encoding::UTF_8) end end end context "when reading values" do let(:hklm) { Win32::Registry::HKEY_LOCAL_MACHINE } let(:puppet_key) { "SOFTWARE\\Puppet Labs"} let(:subkey_name) { "PuppetRegistryTest#{SecureRandom.uuid}" } let(:value_name) { SecureRandom.uuid } after(:each) do hklm.open(puppet_key, Win32::Registry::KEY_ALL_ACCESS) do |reg| subject.delete_key(reg, subkey_name) end end [ {:name => 'REG_SZ', :type => Win32::Registry::REG_SZ, :value => 'reg sz string'}, {:name => 'REG_EXPAND_SZ', :type => Win32::Registry::REG_EXPAND_SZ, :value => 'reg expand string'}, {:name => 'REG_MULTI_SZ', :type => Win32::Registry::REG_MULTI_SZ, :value => ['string1', 'string2']}, {:name => 'REG_BINARY', :type => Win32::Registry::REG_BINARY, :value => 'abinarystring'}, {:name => 'REG_DWORD', :type => Win32::Registry::REG_DWORD, :value => 0xFFFFFFFF}, {:name => 'REG_DWORD_BIG_ENDIAN', :type => Win32::Registry::REG_DWORD_BIG_ENDIAN, :value => 0xFFFF}, {:name => 'REG_QWORD', :type => Win32::Registry::REG_QWORD, :value => 0xFFFFFFFFFFFFFFFF}, ].each do |pair| it "should return #{pair[:name]} values" do hklm.create("#{puppet_key}\\#{subkey_name}", Win32::Registry::KEY_ALL_ACCESS) do |reg| reg.write(value_name, pair[:type], pair[:value]) end hklm.open("#{puppet_key}\\#{subkey_name}", Win32::Registry::KEY_READ) do |reg| vals = subject.values(reg) expect(vals).to have_key(value_name) subject.each_value(reg) do |subkey, type, data| expect(type).to eq(pair[:type]) end written = vals[value_name] expect(written).to eq(pair[:value]) end end end end context "when reading corrupt values" do let(:hklm) { Win32::Registry::HKEY_LOCAL_MACHINE } let(:puppet_key) { "SOFTWARE\\Puppet Labs"} let(:subkey_name) { "PuppetRegistryTest#{SecureRandom.uuid}" } let(:value_name) { SecureRandom.uuid } before(:each) do hklm.create("#{puppet_key}\\#{subkey_name}", Win32::Registry::KEY_ALL_ACCESS) do |reg_key| subject.write_corrupt_dword(reg_key, value_name) end end after(:each) do hklm.open(puppet_key, Win32::Registry::KEY_ALL_ACCESS) do |reg_key| subject.delete_key(reg_key, subkey_name) end end it "should return nil for a corrupt DWORD" do hklm.open("#{puppet_key}\\#{subkey_name}", Win32::Registry::KEY_ALL_ACCESS) do |reg_key| vals = subject.values(reg_key) expect(vals).to have_key(value_name) expect(vals[value_name]).to be_nil end end end context 'whean reading null byte' do let(:hklm) { Win32::Registry::HKEY_LOCAL_MACHINE } let(:puppet_key) { 'SOFTWARE\\Puppet Labs' } let(:subkey_name) { "PuppetRegistryTest#{SecureRandom.uuid}" } let(:value_name) { SecureRandom.uuid } after(:each) do hklm.open(puppet_key, Win32::Registry::KEY_ALL_ACCESS) do |reg| subject.delete_key(reg, subkey_name) end end [ { name: 'REG_SZ', type: Win32::Registry::REG_SZ, value: "reg sz\u0000\u0000 string", expected_value: "reg sz" }, { name: 'REG_SZ_2', type: Win32::Registry::REG_SZ, value: "reg sz 2\x00\x00 string", expected_value: "reg sz 2" }, { name: 'REG_EXPAND_SZ', type: Win32::Registry::REG_EXPAND_SZ, value: "\0\0\0reg expand string", expected_value: "" }, { name: 'REG_EXPAND_SZ_2', type: Win32::Registry::REG_EXPAND_SZ, value: "1\x002\x003\x004\x00\x00\x00\x90\xD8UoY".force_encoding("UTF-16LE"), expected_value: "1234" } ].each do |pair| it 'reads up to the first wide null' do hklm.create("#{puppet_key}\\#{subkey_name}", Win32::Registry::KEY_ALL_ACCESS) do |reg| reg.write(value_name, pair[:type], pair[:value]) end hklm.open("#{puppet_key}\\#{subkey_name}", Win32::Registry::KEY_READ) do |reg| vals = subject.values(reg) expect(vals).to have_key(value_name) subject.each_value(reg) do |_subkey, type, _data| expect(type).to eq(pair[:type]) end written = vals[value_name] expect(written).to eq(pair[:expected_value]) end end end end end context "#values_by_name" do let(:hkey) { double('hklm') } let(:subkey) { double('subkey') } before :each do allow(subject).to receive(:root).and_return(hkey) end context "when reading values" do let(:hklm) { Win32::Registry::HKEY_LOCAL_MACHINE } let(:puppet_key) { "SOFTWARE\\Puppet Labs"} let(:subkey_name) { "PuppetRegistryTest#{SecureRandom.uuid}" } before(:each) do hklm.create("#{puppet_key}\\#{subkey_name}", Win32::Registry::KEY_ALL_ACCESS) do |reg| reg.write('valuename1', Win32::Registry::REG_SZ, 'value1') reg.write('valuename2', Win32::Registry::REG_SZ, 'value2') end end after(:each) do hklm.open(puppet_key, Win32::Registry::KEY_ALL_ACCESS) do |reg| subject.delete_key(reg, subkey_name) end end it "should return only the values for the names specified" do hklm.open("#{puppet_key}\\#{subkey_name}", Win32::Registry::KEY_ALL_ACCESS) do |reg_key| vals = subject.values_by_name(reg_key, ['valuename1', 'missingname']) expect(vals).to have_key('valuename1') expect(vals).to_not have_key('valuename2') expect(vals['valuename1']).to eq('value1') expect(vals['missingname']).to be_nil end end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/util/windows/user_spec.rb
spec/integration/util/windows/user_spec.rb
require 'spec_helper' describe "Puppet::Util::Windows::User", :if => Puppet::Util::Platform.windows? do describe "2003 without UAC" do before :each do allow(Puppet::Util::Windows::Process).to receive(:windows_major_version).and_return(5) allow(Puppet::Util::Windows::Process).to receive(:supports_elevated_security?).and_return(false) end it "should be an admin if user's token contains the Administrators SID" do expect(Puppet::Util::Windows::User).to receive(:check_token_membership).and_return(true) expect(Puppet::Util::Windows::User).to be_admin end it "should not be an admin if user's token doesn't contain the Administrators SID" do expect(Puppet::Util::Windows::User).to receive(:check_token_membership).and_return(false) expect(Puppet::Util::Windows::User).not_to be_admin end it "should raise an exception if we can't check token membership" do expect(Puppet::Util::Windows::User).to receive(:check_token_membership).and_raise(Puppet::Util::Windows::Error, "Access denied.") expect { Puppet::Util::Windows::User.admin? }.to raise_error(Puppet::Util::Windows::Error, /Access denied./) end end context "2008 with UAC" do before :each do allow(Puppet::Util::Windows::Process).to receive(:windows_major_version).and_return(6) allow(Puppet::Util::Windows::Process).to receive(:supports_elevated_security?).and_return(true) end describe "in local administrators group" do before :each do allow(Puppet::Util::Windows::User).to receive(:check_token_membership).and_return(true) end it "should be an admin if user is running with elevated privileges" do allow(Puppet::Util::Windows::Process).to receive(:elevated_security?).and_return(true) expect(Puppet::Util::Windows::User).to be_admin end it "should not be an admin if user is not running with elevated privileges" do allow(Puppet::Util::Windows::Process).to receive(:elevated_security?).and_return(false) expect(Puppet::Util::Windows::User).not_to be_admin end it "should raise an exception if the process fails to open the process token" do allow(Puppet::Util::Windows::Process).to receive(:elevated_security?).and_raise(Puppet::Util::Windows::Error, "Access denied.") expect { Puppet::Util::Windows::User.admin? }.to raise_error(Puppet::Util::Windows::Error, /Access denied./) end end describe "not in local administrators group" do before :each do allow(Puppet::Util::Windows::User).to receive(:check_token_membership).and_return(false) end it "should not be an admin if user is running with elevated privileges" do allow(Puppet::Util::Windows::Process).to receive(:elevated_security?).and_return(true) expect(Puppet::Util::Windows::User).not_to be_admin end it "should not be an admin if user is not running with elevated privileges" do allow(Puppet::Util::Windows::Process).to receive(:elevated_security?).and_return(false) expect(Puppet::Util::Windows::User).not_to be_admin end end end describe "module function" do let(:username) { 'fabio' } let(:bad_password) { 'goldilocks' } let(:logon_fail_msg) { /Failed to logon user "fabio": Logon failure: unknown user name or bad password./ } def expect_logon_failure_error(&block) expect { yield }.to raise_error { |error| expect(error).to be_a(Puppet::Util::Windows::Error) # https://msdn.microsoft.com/en-us/library/windows/desktop/ms681385(v=vs.85).aspx # ERROR_LOGON_FAILURE 1326 expect(error.code).to eq(1326) } end describe "load_profile" do it "should raise an error when provided with an incorrect username and password" do expect_logon_failure_error { Puppet::Util::Windows::User.load_profile(username, bad_password) } end it "should raise an error when provided with an incorrect username and nil password" do expect_logon_failure_error { Puppet::Util::Windows::User.load_profile(username, nil) } end end describe "logon_user" do let(:fLOGON32_PROVIDER_DEFAULT) {0} let(:fLOGON32_LOGON_INTERACTIVE) {2} let(:fLOGON32_LOGON_NETWORK) {3} let(:token) {'test'} let(:user) {'test'} let(:passwd) {'test'} it "should raise an error when provided with an incorrect username and password" do expect_logon_failure_error { Puppet::Util::Windows::User.logon_user(username, bad_password) } end it "should raise an error when provided with an incorrect username and nil password" do expect_logon_failure_error { Puppet::Util::Windows::User.logon_user(username, nil) } end it 'should raise error given that logon returns false' do allow(Puppet::Util::Windows::User).to receive(:logon_user_by_logon_type).with( user, '.', passwd, fLOGON32_LOGON_NETWORK, fLOGON32_PROVIDER_DEFAULT, anything).and_return (0) allow(Puppet::Util::Windows::User).to receive(:logon_user_by_logon_type).with( user, '.', passwd, fLOGON32_LOGON_INTERACTIVE, fLOGON32_PROVIDER_DEFAULT, anything).and_return(0) expect {Puppet::Util::Windows::User.logon_user(user, passwd) {}} .to raise_error(Puppet::Util::Windows::Error, /Failed to logon user/) end end describe "password_is?" do it "should return false given an incorrect username and password" do expect(Puppet::Util::Windows::User.password_is?(username, bad_password)).to be_falsey end it "should return false given a nil username and an incorrect password" do expect(Puppet::Util::Windows::User.password_is?(nil, bad_password)).to be_falsey end context "with a correct password" do it "should return true even if account restrictions are in place " do error = Puppet::Util::Windows::Error.new('', Puppet::Util::Windows::User::ERROR_ACCOUNT_RESTRICTION) allow(Puppet::Util::Windows::User).to receive(:logon_user).and_raise(error) expect(Puppet::Util::Windows::User.password_is?(username, 'p@ssword')).to be(true) end it "should return true even for an account outside of logon hours" do error = Puppet::Util::Windows::Error.new('', Puppet::Util::Windows::User::ERROR_INVALID_LOGON_HOURS) allow(Puppet::Util::Windows::User).to receive(:logon_user).and_raise(error) expect(Puppet::Util::Windows::User.password_is?(username, 'p@ssword')).to be(true) end it "should return true even for an account not allowed to log into this workstation" do error = Puppet::Util::Windows::Error.new('', Puppet::Util::Windows::User::ERROR_INVALID_WORKSTATION) allow(Puppet::Util::Windows::User).to receive(:logon_user).and_raise(error) expect(Puppet::Util::Windows::User.password_is?(username, 'p@ssword')).to be(true) end it "should return true even for a disabled account" do error = Puppet::Util::Windows::Error.new('', Puppet::Util::Windows::User::ERROR_ACCOUNT_DISABLED) allow(Puppet::Util::Windows::User).to receive(:logon_user).and_raise(error) expect(Puppet::Util::Windows::User.password_is?(username, 'p@ssword')).to be(true) end end end describe "check_token_membership" do it "should not raise an error" do # added just to call an FFI code path on all platforms expect { Puppet::Util::Windows::User.check_token_membership }.not_to raise_error end end describe "default_system_account?" do it "should succesfully identify 'SYSTEM' user as a default system account" do allow(Puppet::Util::Windows::SID).to receive(:name_to_sid).with('SYSTEM').and_return(Puppet::Util::Windows::SID::LocalSystem) expect(Puppet::Util::Windows::User.default_system_account?('SYSTEM')).to eq(true) end it "should succesfully identify 'NETWORK SERVICE' user as a default system account" do allow(Puppet::Util::Windows::SID).to receive(:name_to_sid).with('NETWORK SERVICE').and_return(Puppet::Util::Windows::SID::NtNetwork) expect(Puppet::Util::Windows::User.default_system_account?('NETWORK SERVICE')).to eq(true) end it "should succesfully identify 'LOCAL SERVICE' user as a default system account" do allow(Puppet::Util::Windows::SID).to receive(:name_to_sid).with('LOCAL SERVICE').and_return(Puppet::Util::Windows::SID::NtLocal) expect(Puppet::Util::Windows::User.default_system_account?('LOCAL SERVICE')).to eq(true) end it "should not identify user with unknown sid as a default system account" do allow(Puppet::Util::Windows::SID).to receive(:name_to_sid).with('UnknownUser').and_return(Puppet::Util::Windows::SID::Null) expect(Puppet::Util::Windows::User.default_system_account?('UnknownUser')).to eq(false) end end describe "localsystem?" do before do allow(Puppet::Util::Windows::ADSI).to receive(:computer_name).and_return("myPC") end ['LocalSystem', '.\LocalSystem', 'myPC\LocalSystem', 'lOcALsysTem'].each do |input| it "should succesfully identify #{input} as the 'LocalSystem' account" do expect(Puppet::Util::Windows::User.localsystem?(input)).to eq(true) end end it "should not identify any other user as the 'LocalSystem' account" do expect(Puppet::Util::Windows::User.localsystem?('OtherUser')).to eq(false) end end describe "get_rights" do it "should be empty when given user does not exist" do allow(Puppet::Util::Windows::SID).to receive(:name_to_principal).with('NonExistingUser').and_return(nil) expect(Puppet::Util::Windows::User.get_rights('NonExistingUser')).to eq("") end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/util/windows/process_spec.rb
spec/integration/util/windows/process_spec.rb
require 'spec_helper' describe "Puppet::Util::Windows::Process", :if => Puppet::Util::Platform.windows? do describe "as an admin" do it "should have the SeCreateSymbolicLinkPrivilege necessary to create symlinks" do # this is a bit of a lame duck test since it requires running user to be admin # a better integration test would create a new user with the privilege and verify expect(Puppet::Util::Windows::User).to be_admin expect(Puppet::Util::Windows::Process.process_privilege_symlink?).to be_truthy end it "should be able to lookup a standard Windows process privilege" do Puppet::Util::Windows::Process.lookup_privilege_value('SeShutdownPrivilege') do |luid| expect(luid).not_to be_nil expect(luid).to be_instance_of(Puppet::Util::Windows::Process::LUID) end end it "should raise an error for an unknown privilege name" do expect { Puppet::Util::Windows::Process.lookup_privilege_value('foo') }.to raise_error do |error| expect(error).to be_a(Puppet::Util::Windows::Error) expect(error.code).to eq(1313) # ERROR_NO_SUCH_PRIVILEGE end end end describe "when reading environment variables" do it "will ignore only keys or values with corrupt byte sequences" do env_vars = {} # Create a UTF-16LE version of the below null separated environment string # "a=b\x00c=d\x00e=\xDD\xDD\x00f=g\x00\x00" env_var_block = "a=b\x00".encode(Encoding::UTF_16LE) + "c=d\x00".encode(Encoding::UTF_16LE) + 'e='.encode(Encoding::UTF_16LE) + "\xDD\xDD".force_encoding(Encoding::UTF_16LE) + "\x00".encode(Encoding::UTF_16LE) + "f=g\x00\x00".encode(Encoding::UTF_16LE) env_var_block_bytes = env_var_block.bytes.to_a FFI::MemoryPointer.new(:byte, env_var_block_bytes.count) do |ptr| # uchar here is synonymous with byte ptr.put_array_of_uchar(0, env_var_block_bytes) # stub the block of memory that the Win32 API would typically return via pointer allow(Puppet::Util::Windows::Process).to receive(:GetEnvironmentStringsW).and_return(ptr) # stub out the real API call to free memory, else process crashes allow(Puppet::Util::Windows::Process).to receive(:FreeEnvironmentStringsW) env_vars = Puppet::Util::Windows::Process.get_environment_strings end # based on corrupted memory, the e=\xDD\xDD should have been removed from the set expect(env_vars).to eq({'a' => 'b', 'c' => 'd', 'f' => 'g'}) # and Puppet should emit a warning about it expect(@logs.last.level).to eq(:warning) expect(@logs.last.message).to eq("Discarding environment variable e=\uFFFD which contains invalid bytes") end end describe "when setting environment variables" do let(:name) { SecureRandom.uuid } around :each do |example| begin example.run ensure Puppet::Util::Windows::Process.set_environment_variable(name, nil) end end it "sets environment variables containing '='" do value = 'foo=bar' Puppet::Util::Windows::Process.set_environment_variable(name, value) env = Puppet::Util::Windows::Process.get_environment_strings expect(env[name]).to eq(value) end it "sets environment variables contains spaces" do Puppet::Util::Windows::Process.set_environment_variable(name, '') env = Puppet::Util::Windows::Process.get_environment_strings expect(env[name]).to eq('') end it "sets environment variables containing UTF-8" do rune_utf8 = "\u16A0\u16C7\u16BB\u16EB\u16D2\u16E6\u16A6\u16EB\u16A0\u16B1\u16A9\u16A0\u16A2\u16B1\u16EB\u16A0\u16C1\u16B1\u16AA\u16EB\u16B7\u16D6\u16BB\u16B9\u16E6\u16DA\u16B3\u16A2\u16D7" Puppet::Util::Windows::Process.set_environment_variable(name, rune_utf8) env = Puppet::Util::Windows::Process.get_environment_strings expect(env[name]).to eq(rune_utf8) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/util/windows/monkey_patches/process_spec.rb
spec/integration/util/windows/monkey_patches/process_spec.rb
# frozen_string_literal: true require 'spec_helper' describe 'Process', if: Puppet::Util::Platform.windows? do describe '.create' do context 'with common flags' do it do Process.create( app_name: 'cmd.exe /c echo 123', creation_flags: 0x00000008, process_inherit: false, thread_inherit: false, cwd: 'C:\\' ) end context 'when FFI call fails' do before do allow(Process).to receive(:CreateProcessW).and_return(false) end it 'raises SystemCallError' do expect do Process.create( app_name: 'cmd.exe /c echo 123', creation_flags: 0x00000008 ) end.to raise_error(SystemCallError) end end end context 'with logon' do context 'without password' do it 'raises error' do expect do Process.create( app_name: 'cmd.exe /c echo 123', creation_flags: 0x00000008, with_logon: 'test' ) end.to raise_error(ArgumentError, 'password must be specified if with_logon is used') end end context 'with common flags' do before do allow(Process).to receive(:CreateProcessWithLogonW).and_return(true) end it do Process.create( app_name: 'cmd.exe /c echo 123', creation_flags: 0x00000008, process_inherit: false, thread_inherit: false, with_logon: 'test', password: 'password', cwd: 'C:\\' ) end context 'when FFI call fails' do before do allow(Process).to receive(:CreateProcessWithLogonW).and_return(false) end it 'raises SystemCallError' do expect do Process.create( app_name: 'cmd.exe /c echo 123', creation_flags: 0x00000008, with_logon: 'test', password: 'password' ) end.to raise_error(SystemCallError) end end end end describe 'validations' do context 'when args is not a hash' do it 'raises TypeError' do expect do Process.create('test') end.to raise_error(TypeError, 'hash keyword arguments expected') end end context 'when args key is invalid' do it 'raises ArgumentError' do expect do Process.create(invalid_key: 'test') end.to raise_error(ArgumentError, "invalid key 'invalid_key'") end end context 'when startup_info is invalid' do it 'raises ArgumentError' do expect do Process.create(startup_info: { invalid_key: 'test' }) end.to raise_error(ArgumentError, "invalid startup_info key 'invalid_key'") end end context 'when app_name and command_line are missing' do it 'raises ArgumentError' do expect do Process.create(creation_flags: 0) end.to raise_error(ArgumentError, 'command_line or app_name must be specified') end end context 'when executable is not found' do it 'raises Errno::ENOENT' do expect do Process.create(app_name: 'non_existent') end.to raise_error(Errno::ENOENT) end end end context 'when environment is not specified' do it 'passes local environment' do stdout_read, stdout_write = IO.pipe ENV['TEST_ENV'] = 'B' Process.create( app_name: 'cmd.exe /c echo %TEST_ENV%', creation_flags: 0x00000008, startup_info: { stdout: stdout_write } ) stdout_write.close expect(stdout_read.read.chomp).to eql('B') end end context 'when environment is specified' do it 'does not pass local environment' do stdout_read, stdout_write = IO.pipe ENV['TEST_ENV'] = 'B' Process.create( app_name: 'cmd.exe /c echo %TEST_ENV%', creation_flags: 0x00000008, environment: '', startup_info: { stdout: stdout_write } ) stdout_write.close expect(stdout_read.read.chomp).to eql('%TEST_ENV%') end it 'supports :environment as a string' do stdout_read, stdout_write = IO.pipe Process.create( app_name: 'cmd.exe /c echo %A% %B%', creation_flags: 0x00000008, environment: 'A=C;B=D', startup_info: { stdout: stdout_write } ) stdout_write.close expect(stdout_read.read.chomp).to eql('C D') end it 'supports :environment as a string' do stdout_read, stdout_write = IO.pipe Process.create( app_name: 'cmd.exe /c echo %A% %C%', creation_flags: 0x00000008, environment: ['A=B;X;', 'C=;D;Y'], startup_info: { stdout: stdout_write } ) stdout_write.close expect(stdout_read.read.chomp).to eql('B;X; ;D;Y') end end end describe '.setpriority' do let(:priority) { Process::BELOW_NORMAL_PRIORITY_CLASS } context 'when success' do it 'returns 0' do expect(Process.setpriority(0, Process.pid, priority)).to eql(0) end it 'treats an int argument of zero as the current process' do expect(Process.setpriority(0, 0, priority)).to eql(0) end end context 'when invalid arguments are sent' do it 'raises TypeError' do expect { Process.setpriority('test', 0, priority) }.to raise_error(TypeError) end end context 'when process is not found' do before do allow(Process).to receive(:OpenProcess).and_return(0) end it 'raises SystemCallError' do expect { Process.setpriority(0, 0, priority) }.to raise_error(SystemCallError) end end context 'when priority is not set' do before do allow(Process).to receive(:SetPriorityClass).and_return(false) end it 'raises SystemCallError' do expect { Process.setpriority(0, 0, priority) }.to raise_error(SystemCallError) end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/type/file_spec.rb
spec/integration/type/file_spec.rb
# coding: utf-8 require 'spec_helper' require 'puppet_spec/files' if Puppet::Util::Platform.windows? require 'puppet/util/windows' class WindowsSecurity extend Puppet::Util::Windows::Security end end describe Puppet::Type.type(:file), :uses_checksums => true do include PuppetSpec::Files include_context 'with supported checksum types' let(:catalog) { Puppet::Resource::Catalog.new } let(:path) do # we create a directory first so backups of :path that are stored in # the same directory will also be removed after the tests parent = tmpdir('file_spec') File.join(parent, 'file_testing') end let(:path_protected) do # we create a file inside windows protected folders (C:\Windows, C:\Windows\system32, etc) # the file will also be removed after the tests parent = 'C:\Windows' File.join(parent, 'file_testing') end let(:dir) do # we create a directory first so backups of :path that are stored in # the same directory will also be removed after the tests parent = tmpdir('file_spec') File.join(parent, 'dir_testing') end if Puppet.features.posix? def set_mode(mode, file) File.chmod(mode, file) end def get_mode(file) Puppet::FileSystem.lstat(file).mode end def get_owner(file) Puppet::FileSystem.lstat(file).uid end def get_group(file) Puppet::FileSystem.lstat(file).gid end else class SecurityHelper extend Puppet::Util::Windows::Security end def set_mode(mode, file) SecurityHelper.set_mode(mode, file) end def get_mode(file) SecurityHelper.get_mode(file) end def get_owner(file) SecurityHelper.get_owner(file) end def get_group(file) SecurityHelper.get_group(file) end def get_aces_for_path_by_sid(path, sid) SecurityHelper.get_aces_for_path_by_sid(path, sid) end end around :each do |example| Puppet.override(:environments => Puppet::Environments::Static.new) do example.run end end before do # stub this to not try to create state.yaml allow(Puppet::Util::Storage).to receive(:store) allow_any_instance_of(Puppet::Type.type(:file)).to receive(:file).and_return('my/file.pp') allow_any_instance_of(Puppet::Type.type(:file)).to receive(:line).and_return(5) end it "should not attempt to manage files that do not exist if no means of creating the file is specified" do source = tmpfile('source') catalog.add_resource described_class.new :path => source, :mode => '0755' status = catalog.apply.report.resource_statuses["File[#{source}]"] expect(status).not_to be_failed expect(status).not_to be_changed expect(Puppet::FileSystem.exist?(source)).to be_falsey end describe "when ensure is present using an empty file" do before(:each) do catalog.add_resource(described_class.new(:path => path, :ensure => :present, :backup => :false)) end context "file is present" do before(:each) do FileUtils.touch(path) end it "should do nothing" do report = catalog.apply.report expect(report.resource_statuses["File[#{path}]"]).not_to be_failed expect(Puppet::FileSystem.exist?(path)).to be_truthy end it "should log nothing" do logs = catalog.apply.report.logs expect(logs).to be_empty end end context "file is not present" do it "should create the file" do report = catalog.apply.report expect(report.resource_statuses["File[#{path}]"]).not_to be_failed expect(Puppet::FileSystem.exist?(path)).to be_truthy end it "should log that the file was created" do logs = catalog.apply.report.logs expect(logs.first.source).to eq("/File[#{path}]/ensure") expect(logs.first.message).to eq("created") end end end describe "when ensure is absent" do before(:each) do catalog.add_resource(described_class.new(:path => path, :ensure => :absent, :backup => :false)) end context "file is present" do before(:each) do FileUtils.touch(path) end it "should remove the file" do report = catalog.apply.report expect(report.resource_statuses["File[#{path}]"]).not_to be_failed expect(Puppet::FileSystem.exist?(path)).to be_falsey end it "should log that the file was removed" do logs = catalog.apply.report.logs expect(logs.first.source).to eq("/File[#{path}]/ensure") expect(logs.first.message).to eq("removed") end end context "file is not present" do it "should do nothing" do report = catalog.apply.report expect(report.resource_statuses["File[#{path}]"]).not_to be_failed expect(Puppet::FileSystem.exist?(path)).to be_falsey end it "should log nothing" do logs = catalog.apply.report.logs expect(logs).to be_empty end end # issue #14599 it "should not fail if parts of path aren't directories" do FileUtils.touch(path) catalog.add_resource(described_class.new(:path => File.join(path,'no_such_file'), :ensure => :absent, :backup => :false)) report = catalog.apply.report expect(report.resource_statuses["File[#{File.join(path,'no_such_file')}]"]).not_to be_failed end end describe "when setting permissions" do it "should set the owner" do target = tmpfile_with_contents('target', '') owner = get_owner(target) catalog.add_resource described_class.new( :name => target, :owner => owner ) catalog.apply expect(get_owner(target)).to eq(owner) end it "should set the group" do target = tmpfile_with_contents('target', '') group = get_group(target) catalog.add_resource described_class.new( :name => target, :group => group ) catalog.apply expect(get_group(target)).to eq(group) end describe "when setting mode" do describe "for directories" do let(:target) { tmpdir('dir_mode') } it "should set executable bits for newly created directories" do catalog.add_resource described_class.new(:path => target, :ensure => :directory, :mode => '0600') catalog.apply expect(get_mode(target) & 07777).to eq(0700) end it "should set executable bits for existing readable directories" do set_mode(0600, target) catalog.add_resource described_class.new(:path => target, :ensure => :directory, :mode => '0644') catalog.apply expect(get_mode(target) & 07777).to eq(0755) end it "should not set executable bits for unreadable directories" do begin catalog.add_resource described_class.new(:path => target, :ensure => :directory, :mode => '0300') catalog.apply expect(get_mode(target) & 07777).to eq(0300) ensure # so we can cleanup set_mode(0700, target) end end it "should set user, group, and other executable bits" do catalog.add_resource described_class.new(:path => target, :ensure => :directory, :mode => '0664') catalog.apply expect(get_mode(target) & 07777).to eq(0775) end it "should set executable bits when overwriting a non-executable file" do target_path = tmpfile_with_contents('executable', '') set_mode(0444, target_path) catalog.add_resource described_class.new(:path => target_path, :ensure => :directory, :mode => '0666', :backup => false) catalog.apply expect(get_mode(target_path) & 07777).to eq(0777) expect(File).to be_directory(target_path) end end describe "for files" do it "should not set executable bits" do catalog.add_resource described_class.new(:path => path, :ensure => :file, :mode => '0666') catalog.apply expect(get_mode(path) & 07777).to eq(0666) end context "file is in protected windows directory", :if => Puppet.features.microsoft_windows? do after { FileUtils.rm(path_protected) } it "should set and get the correct mode for files inside protected windows folders" do catalog.add_resource described_class.new(:path => path_protected, :ensure => :file, :mode => '0640') catalog.apply expect(get_mode(path_protected) & 07777).to eq(0640) end it "should not change resource's status inside protected windows folders if mode is the same" do FileUtils.touch(path_protected) set_mode(0644, path_protected) catalog.add_resource described_class.new(:path => path_protected, :ensure => :file, :mode => '0644') result = catalog.apply status = result.report.resource_statuses["File[#{path_protected}]"] expect(status).not_to be_failed expect(status).not_to be_changed end end it "should not set executable bits when replacing an executable directory (#10365)" do pending("bug #10365") FileUtils.mkdir(path) set_mode(0777, path) catalog.add_resource described_class.new(:path => path, :ensure => :file, :mode => '0666', :backup => false, :force => true) catalog.apply expect(get_mode(path) & 07777).to eq(0666) end end describe "for links", :if => described_class.defaultprovider.feature?(:manages_symlinks) do let(:link) { tmpfile('link_mode') } describe "when managing links" do let(:link_target) { tmpfile('target') } before :each do FileUtils.touch(link_target) File.chmod(0444, link_target) Puppet::FileSystem.symlink(link_target, link) end it "should not set the executable bit on the link target" do catalog.add_resource described_class.new(:path => link, :ensure => :link, :mode => '0666', :target => link_target, :links => :manage) catalog.apply expected_target_permissions = Puppet::Util::Platform.windows? ? 0700 : 0444 expect(Puppet::FileSystem.stat(link_target).mode & 07777).to eq(expected_target_permissions) end it "should ignore dangling symlinks (#6856)" do File.delete(link_target) catalog.add_resource described_class.new(:path => link, :ensure => :link, :mode => '0666', :target => link_target, :links => :manage) catalog.apply expect(Puppet::FileSystem.exist?(link)).to be_falsey end it "should create a link to the target if ensure is omitted" do FileUtils.touch(link_target) catalog.add_resource described_class.new(:path => link, :target => link_target) catalog.apply expect(Puppet::FileSystem.exist?(link)).to be_truthy expect(Puppet::FileSystem.lstat(link).ftype).to eq('link') expect(Puppet::FileSystem.readlink(link)).to eq(link_target) end end describe "when following links" do it "should ignore dangling symlinks (#6856)" do target = tmpfile('dangling') FileUtils.touch(target) Puppet::FileSystem.symlink(target, link) File.delete(target) catalog.add_resource described_class.new(:path => path, :source => link, :mode => '0600', :links => :follow) catalog.apply end describe "to a directory" do let(:link_target) { tmpdir('dir_target') } before :each do File.chmod(0600, link_target) Puppet::FileSystem.symlink(link_target, link) end after :each do File.chmod(0750, link_target) end describe "that is readable" do it "should set the executable bits when creating the destination (#10315)" do catalog.add_resource described_class.new(:path => path, :source => link, :mode => '0666', :links => :follow) catalog.apply expect(File).to be_directory(path) expect(get_mode(path) & 07777).to eq(0777) end it "should set the executable bits when overwriting the destination (#10315)" do FileUtils.touch(path) catalog.add_resource described_class.new(:path => path, :source => link, :mode => '0666', :links => :follow, :backup => false) catalog.apply expect(File).to be_directory(path) expect(get_mode(path) & 07777).to eq(0777) end end describe "that is not readable" do before :each do set_mode(0300, link_target) end # so we can cleanup after :each do set_mode(0700, link_target) end it "should set executable bits when creating the destination (#10315)" do catalog.add_resource described_class.new(:path => path, :source => link, :mode => '0666', :links => :follow) catalog.apply expect(File).to be_directory(path) expect(get_mode(path) & 07777).to eq(0777) end it "should set executable bits when overwriting the destination" do FileUtils.touch(path) catalog.add_resource described_class.new(:path => path, :source => link, :mode => '0666', :links => :follow, :backup => false) catalog.apply expect(File).to be_directory(path) expect(get_mode(path) & 07777).to eq(0777) end end end describe "to a file" do let(:link_target) { tmpfile('file_target') } before :each do FileUtils.touch(link_target) Puppet::FileSystem.symlink(link_target, link) end it "should create the file, not a symlink (#2817, #10315)" do catalog.add_resource described_class.new(:path => path, :source => link, :mode => '0600', :links => :follow) catalog.apply expect(File).to be_file(path) expect(get_mode(path) & 07777).to eq(0600) end it "should not give a deprecation warning about using a checksum in content when using source to define content" do FileUtils.touch(path) expect(Puppet).not_to receive(:puppet_deprecation_warning) catalog.add_resource described_class.new(:path => path, :source => link, :links => :follow) catalog.apply end context "overwriting a file" do before :each do FileUtils.touch(path) set_mode(0644, path) catalog.add_resource described_class.new(:path => path, :source => link, :mode => '0600', :links => :follow) end it "should overwrite the file" do catalog.apply expect(File).to be_file(path) expect(get_mode(path) & 07777).to eq(0600) end it "should log that the mode changed" do report = catalog.apply.report expect(report.logs.first.message).to eq("mode changed '0644' to '0600'") expect(report.logs.first.source).to eq("/File[#{path}]/mode") end end end describe "to a link to a directory" do let(:real_target) { tmpdir('real_target') } let(:target) { tmpfile('target') } before :each do File.chmod(0666, real_target) # link -> target -> real_target Puppet::FileSystem.symlink(real_target, target) Puppet::FileSystem.symlink(target, link) end after :each do File.chmod(0750, real_target) end describe "when following all links" do it "should create the destination and apply executable bits (#10315)" do catalog.add_resource described_class.new(:path => path, :source => link, :mode => '0600', :links => :follow) catalog.apply expect(File).to be_directory(path) expect(get_mode(path) & 07777).to eq(0700) end it "should overwrite the destination and apply executable bits" do FileUtils.mkdir(path) catalog.add_resource described_class.new(:path => path, :source => link, :mode => '0600', :links => :follow) catalog.apply expect(File).to be_directory(path) expect(get_mode(path) & 0111).to eq(0100) end end end end end end end describe "when writing files" do shared_examples "files are backed up" do |resource_options| it "should backup files to a filebucket when one is configured" do |example| if Puppet::Util::Platform.windows? && ['sha512', 'sha384'].include?(example.metadata[:digest_algorithm]) skip "PUP-8257: Skip file bucket test on windows for #{example.metadata[:digest_algorithm]} due to long path names" end filebucket = Puppet::Type.type(:filebucket).new :path => tmpfile("filebucket"), :name => "mybucket" file = described_class.new({:path => path, :backup => "mybucket", :content => "foo"}.merge(resource_options)) catalog.add_resource file catalog.add_resource filebucket File.open(file[:path], "w") { |f| f.write("bar") } d = filebucket_digest.call(IO.binread(file[:path])) catalog.apply expect(filebucket.bucket.getfile(d)).to eq("bar") end it "should backup files in the local directory when a backup string is provided" do file = described_class.new({:path => path, :backup => ".bak", :content => "foo"}.merge(resource_options)) catalog.add_resource file File.open(file[:path], "w") { |f| f.puts "bar" } catalog.apply backup = file[:path] + ".bak" expect(Puppet::FileSystem.exist?(backup)).to be_truthy expect(File.read(backup)).to eq("bar\n") end it "should fail if no backup can be performed" do dir = tmpdir("backups") file = described_class.new({:path => File.join(dir, "testfile"), :backup => ".bak", :content => "foo"}.merge(resource_options)) catalog.add_resource file File.open(file[:path], 'w') { |f| f.puts "bar" } # Create a directory where the backup should be so that writing to it fails Dir.mkdir(File.join(dir, "testfile.bak")) allow(Puppet::Util::Log).to receive(:newmessage) catalog.apply expect(File.read(file[:path])).to eq("bar\n") end it "should not backup symlinks", :if => described_class.defaultprovider.feature?(:manages_symlinks) do link = tmpfile("link") dest1 = tmpfile("dest1") dest2 = tmpfile("dest2") bucket = Puppet::Type.type(:filebucket).new :path => tmpfile("filebucket"), :name => "mybucket" file = described_class.new({:path => link, :target => dest2, :ensure => :link, :backup => "mybucket"}.merge(resource_options)) catalog.add_resource file catalog.add_resource bucket File.open(dest1, "w") { |f| f.puts "whatever" } Puppet::FileSystem.symlink(dest1, link) catalog.apply expect(Puppet::FileSystem.readlink(link)).to eq(dest2) expect(Puppet::FileSystem.exist?(bucket[:path])).to be_falsey end it "should backup directories to the local filesystem by copying the whole directory" do file = described_class.new({:path => path, :backup => ".bak", :content => "foo", :force => true}.merge(resource_options)) catalog.add_resource file Dir.mkdir(path) otherfile = File.join(path, "foo") File.open(otherfile, "w") { |f| f.print "yay" } catalog.apply backup = "#{path}.bak" expect(FileTest).to be_directory(backup) expect(File.read(File.join(backup, "foo"))).to eq("yay") end it "should backup directories to filebuckets by backing up each file separately" do |example| if Puppet::Util::Platform.windows? && ['sha512', 'sha384'].include?(example.metadata[:digest_algorithm]) skip "PUP-8257: Skip file bucket test on windows for #{example.metadata[:digest_algorithm]} due to long path names" end bucket = Puppet::Type.type(:filebucket).new :path => tmpfile("filebucket"), :name => "mybucket" file = described_class.new({:path => tmpfile("bucket_backs"), :backup => "mybucket", :content => "foo", :force => true}.merge(resource_options)) catalog.add_resource file catalog.add_resource bucket Dir.mkdir(file[:path]) foofile = File.join(file[:path], "foo") barfile = File.join(file[:path], "bar") File.open(foofile, "w") { |f| f.print "fooyay" } File.open(barfile, "w") { |f| f.print "baryay" } food = filebucket_digest.call(File.read(foofile)) bard = filebucket_digest.call(File.read(barfile)) catalog.apply expect(bucket.bucket.getfile(food)).to eq("fooyay") expect(bucket.bucket.getfile(bard)).to eq("baryay") end end it "should not give a checksum deprecation warning when given actual content" do expect(Puppet).not_to receive(:puppet_deprecation_warning) catalog.add_resource described_class.new(:path => path, :content => 'this is content') catalog.apply end with_digest_algorithms do it_should_behave_like "files are backed up", {} do let(:filebucket_digest) { method(:digest) } end it "should give a checksum deprecation warning" do expect(Puppet).to receive(:puppet_deprecation_warning).with('Using a checksum in a file\'s "content" property is deprecated. The ability to use a checksum to retrieve content from the filebucket using the "content" property will be removed in a future release. The literal value of the "content" property will be written to the file. The checksum retrieval functionality is being replaced by the use of static catalogs. See https://puppet.com/docs/puppet/latest/static_catalogs.html for more information.', {:file => 'my/file.pp', :line => 5}) d = digest("this is some content") catalog.add_resource described_class.new(:path => path, :content => "{#{digest_algorithm}}#{d}") catalog.apply end it "should not give a checksum deprecation warning when no content is specified while checksum and checksum value are used" do expect(Puppet).not_to receive(:puppet_deprecation_warning) d = digest("this is some content") catalog.add_resource described_class.new(:path => path, :checksum => digest_algorithm, :checksum_value => d) catalog.apply end end CHECKSUM_TYPES_TO_TRY.each do |checksum_type, checksum| describe "when checksum_type is #{checksum_type}" do # FileBucket uses the globally configured default for lookup by digest, which right now is SHA256. it_should_behave_like "files are backed up", {:checksum => checksum_type} do let(:filebucket_digest) { Proc.new {|x| Puppet::Util::Checksums.sha256(x)} } end end end end describe "when recursing" do def build_path(dir) Dir.mkdir(dir) File.chmod(0750, dir) @dirs = [dir] @files = [] %w{one two}.each do |subdir| fdir = File.join(dir, subdir) Dir.mkdir(fdir) File.chmod(0750, fdir) @dirs << fdir %w{three}.each do |file| ffile = File.join(fdir, file) @files << ffile File.open(ffile, "w") { |f| f.puts "test #{file}" } File.chmod(0640, ffile) end end end it "should be able to recurse over a nonexistent file" do @file = described_class.new( :name => path, :mode => '0644', :recurse => true, :backup => false ) catalog.add_resource @file expect { @file.eval_generate }.not_to raise_error end it "should be able to recursively set properties on existing files" do path = tmpfile("file_integration_tests") build_path(path) file = described_class.new( :name => path, :mode => '0644', :recurse => true, :backup => false ) catalog.add_resource file catalog.apply expect(@dirs).not_to be_empty @dirs.each do |dir| expect(get_mode(dir) & 007777).to eq(0755) end expect(@files).not_to be_empty @files.each do |dir| expect(get_mode(dir) & 007777).to eq(0644) end end it "should be able to recursively make links to other files", :if => described_class.defaultprovider.feature?(:manages_symlinks) do source = tmpfile("file_link_integration_source") build_path(source) dest = tmpfile("file_link_integration_dest") @file = described_class.new(:name => dest, :target => source, :recurse => true, :ensure => :link, :backup => false) catalog.add_resource @file catalog.apply @dirs.each do |path| link_path = path.sub(source, dest) expect(Puppet::FileSystem.lstat(link_path)).to be_directory end @files.each do |path| link_path = path.sub(source, dest) expect(Puppet::FileSystem.lstat(link_path).ftype).to eq("link") end end it "should be able to recursively copy files" do source = tmpfile("file_source_integration_source") build_path(source) dest = tmpfile("file_source_integration_dest") @file = described_class.new(:name => dest, :source => source, :recurse => true, :backup => false) catalog.add_resource @file catalog.apply @dirs.each do |path| newpath = path.sub(source, dest) expect(Puppet::FileSystem.lstat(newpath)).to be_directory end @files.each do |path| newpath = path.sub(source, dest) expect(Puppet::FileSystem.lstat(newpath).ftype).to eq("file") end end it "should not recursively manage files set to be ignored" do srcdir = tmpfile("ignore_vs_recurse_1") dstdir = tmpfile("ignore_vs_recurse_2") FileUtils.mkdir_p(srcdir) FileUtils.mkdir_p(dstdir) srcfile = File.join(srcdir, "file.src") cpyfile = File.join(dstdir, "file.src") ignfile = File.join(srcdir, "file.ign") File.open(srcfile, "w") { |f| f.puts "don't ignore me" } File.open(ignfile, "w") { |f| f.puts "you better ignore me" } catalog.add_resource described_class.new( :name => srcdir, :ensure => 'directory', :mode => '0755',) catalog.add_resource described_class.new( :name => dstdir, :ensure => 'directory', :mode => "755", :source => srcdir, :recurse => true, :ignore => '*.ign',) catalog.apply expect(Puppet::FileSystem.exist?(srcdir)).to be_truthy expect(Puppet::FileSystem.exist?(dstdir)).to be_truthy expect(File.read(srcfile).strip).to eq("don't ignore me") expect(File.read(cpyfile).strip).to eq("don't ignore me") expect(Puppet::FileSystem.exist?("#{dstdir}/file.ign")).to be_falsey end it "should not recursively manage files managed by a more specific explicit file" do dir = tmpfile("recursion_vs_explicit_1") subdir = File.join(dir, "subdir") file = File.join(subdir, "file") FileUtils.mkdir_p(subdir) File.open(file, "w") { |f| f.puts "" } base = described_class.new(:name => dir, :recurse => true, :backup => false, :mode => "755") sub = described_class.new(:name => subdir, :recurse => true, :backup => false, :mode => "644") catalog.add_resource base catalog.add_resource sub catalog.apply expect(get_mode(file) & 007777).to eq(0644) end it "should recursively manage files even if there is an explicit file whose name is a prefix of the managed file" do managed = File.join(path, "file") generated = File.join(path, "file_with_a_name_starting_with_the_word_file") FileUtils.mkdir_p(path) FileUtils.touch(managed) FileUtils.touch(generated) catalog.add_resource described_class.new(:name => path, :recurse => true, :backup => false, :mode => '0700') catalog.add_resource described_class.new(:name => managed, :recurse => true, :backup => false, :mode => "644") catalog.apply expect(get_mode(generated) & 007777).to eq(0700) end describe "when recursing remote directories" do describe "for the 2nd time" do with_checksum_types "one", "x" do let(:target_file) { File.join(path, 'x') } let(:second_catalog) { Puppet::Resource::Catalog.new } before(:each) do @options = { :path => path, :ensure => :directory, :backup => false, :recurse => true, :checksum => checksum_type, :source => env_path } end it "should not update the target directory" do # Ensure the test believes the source file was written in the past. FileUtils.touch checksum_file, :mtime => Time.now - 20 catalog.add_resource Puppet::Type.send(:newfile, @options) catalog.apply expect(File).to be_directory(path) expect(Puppet::FileSystem.exist?(target_file)).to be_truthy # The 2nd time the resource should not change. second_catalog.add_resource Puppet::Type.send(:newfile, @options) result = second_catalog.apply status = result.report.resource_statuses["File[#{target_file}]"] expect(status).not_to be_failed expect(status).not_to be_changed end it "should update the target directory if contents change" do pending "a way to appropriately mock ctime checks for a particular file" if checksum_type == 'ctime' catalog.add_resource Puppet::Type.send(:newfile, @options) catalog.apply expect(File).to be_directory(path) expect(Puppet::FileSystem.exist?(target_file)).to be_truthy # Change the source file. File.open(checksum_file, "wb") { |f| f.write "some content" } FileUtils.touch target_file, mtime: Time.now - 20 # The 2nd time should update the resource. second_catalog.add_resource Puppet::Type.send(:newfile, @options) result = second_catalog.apply status = result.report.resource_statuses["File[#{target_file}]"] expect(status).not_to be_failed expect(status).to be_changed end end end describe "when sourceselect first" do describe "for a directory" do it "should recursively copy the first directory that exists" do one = File.expand_path('thisdoesnotexist') two = tmpdir('two') FileUtils.mkdir_p(File.join(two, 'three')) FileUtils.touch(File.join(two, 'three', 'four')) catalog.add_resource Puppet::Type.newfile( :path => path, :ensure => :directory, :backup => false, :recurse => true, :sourceselect => :first, :source => [one, two] ) catalog.apply expect(File).to be_directory(path) expect(Puppet::FileSystem.exist?(File.join(path, 'one'))).to be_falsey expect(Puppet::FileSystem.exist?(File.join(path, 'three', 'four'))).to be_truthy end it "should recursively copy an empty directory" do
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
true
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/type/notify_spec.rb
spec/integration/type/notify_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' describe Puppet::Type.type(:notify) do include PuppetSpec::Compiler it "logs the title at notice level" do apply_compiled_manifest(<<-MANIFEST) notify { 'hi': } MANIFEST expect(@logs).to include(an_object_having_attributes(level: :notice, message: 'hi')) end it "logs the message property" do apply_compiled_manifest(<<-MANIFEST) notify { 'title': message => 'hello' } MANIFEST expect(@logs).to include(an_object_having_attributes(level: :notice, message: "defined 'message' as 'hello'")) end it "redacts sensitive message properties" do apply_compiled_manifest(<<-MANIFEST) $message = Sensitive('secret') notify { 'notify1': message => $message } MANIFEST expect(@logs).to include(an_object_having_attributes(level: :notice, message: 'changed [redacted] to [redacted]')) end it "redacts sensitive interpolated message properties" do apply_compiled_manifest(<<-MANIFEST) $message = Sensitive('secret') notify { 'notify2': message => "${message}" } MANIFEST expect(@logs).to include(an_object_having_attributes(level: :notice, message: "defined 'message' as 'Sensitive [value redacted]'")) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/type/package_spec.rb
spec/integration/type/package_spec.rb
require 'spec_helper' describe Puppet::Type.type(:package), "when choosing a default package provider" do before do # the default provider is cached. Puppet::Type.type(:package).defaultprovider = nil end def provider_name(os) case os when 'Solaris' if Puppet::Util::Package.versioncmp(Puppet.runtime[:facter].value(:kernelrelease), '5.11') >= 0 :pkg else :sun end when 'Ubuntu' :apt when 'Debian' :apt when 'Darwin' :pkgdmg when 'RedHat' if ['2.1', '3', '4'].include?(Puppet.runtime[:facter].value('os.distro.release.full')) :up2date else :yum end when 'Fedora' if Puppet::Util::Package.versioncmp(Puppet.runtime[:facter].value('os.release.major'), '22') >= 0 :dnf else :yum end when 'Suse' if Puppet::Util::Package.versioncmp(Puppet.runtime[:facter].value('os.release.major'), '10') >= 0 :zypper else :rug end when 'FreeBSD' :pkgng when 'OpenBSD' :openbsd when 'DragonFly' :pkgng when 'OpenWrt' :opkg end end it "should have a default provider" do expect(Puppet::Type.type(:package).defaultprovider).not_to be_nil end it "should choose the correct provider each platform" do unless default_provider = provider_name(Puppet.runtime[:facter].value('os.name')) pending("No default provider specified in this test for #{Puppet.runtime[:facter].value('os.name')}") end expect(Puppet::Type.type(:package).defaultprovider.name).to eq(default_provider) end end describe Puppet::Type.type(:package), "when packages with the same name are sourced" do before :each do allow(Process).to receive(:euid).and_return(0) @provider = double( 'provider', :class => Puppet::Type.type(:package).defaultprovider, :clear => nil, :satisfies? => true, :name => :mock, :validate_source => nil ) allow(Puppet::Type.type(:package).defaultprovider).to receive(:new).and_return(@provider) allow(Puppet::Type.type(:package).defaultprovider).to receive(:instances).and_return([]) @package = Puppet::Type.type(:package).new(:name => "yay", :ensure => :present) @catalog = Puppet::Resource::Catalog.new @catalog.add_resource(@package) end describe "with same title" do before { @alt_package = Puppet::Type.type(:package).new(:name => "yay", :ensure => :present) } it "should give an error" do expect { @catalog.add_resource(@alt_package) }.to raise_error Puppet::Resource::Catalog::DuplicateResourceError, 'Duplicate declaration: Package[yay] is already declared; cannot redeclare' end end describe "with different title" do before :each do @alt_package = Puppet::Type.type(:package).new(:name => "yay", :title => "gem-yay", :ensure => :present) end it "should give an error" do provider_name = Puppet::Type.type(:package).defaultprovider.name expect { @catalog.add_resource(@alt_package) }.to raise_error ArgumentError, "Cannot alias Package[gem-yay] to [nil, \"yay\", :#{provider_name}]; resource [\"Package\", nil, \"yay\", :#{provider_name}] already declared" end end describe "from multiple providers", unless: Puppet::Util::Platform.jruby? do provider_class = Puppet::Type.type(:package).provider(:gem) before :each do @alt_provider = provider_class.new @alt_package = Puppet::Type.type(:package).new(:name => "yay", :title => "gem-yay", :provider => @alt_provider, :ensure => :present) @catalog.add_resource(@alt_package) end describe "when it should be present" do [:present, :latest, "1.0"].each do |state| it "should do nothing if it is #{state.to_s}" do expect(@provider).to receive(:properties).and_return(:ensure => state).at_least(:once) expect(@alt_provider).to receive(:properties).and_return(:ensure => state).at_least(:once) @catalog.apply end end [:purged, :absent].each do |state| it "should install if it is #{state.to_s}" do allow(@provider).to receive(:properties).and_return(:ensure => state) expect(@provider).to receive(:install) allow(@alt_provider).to receive(:properties).and_return(:ensure => state) expect(@alt_provider).to receive(:install) @catalog.apply end end end end end describe Puppet::Type.type(:package), 'logging package state transitions' do let(:catalog) { Puppet::Resource::Catalog.new } let(:provider) { double('provider', :class => Puppet::Type.type(:package).defaultprovider, :clear => nil, :validate_source => nil) } before :each do allow(Process).to receive(:euid).and_return(0) allow(provider).to receive(:satisfies?).with([:purgeable]).and_return(true) allow(provider.class).to receive(:instances).and_return([]) allow(provider).to receive(:install).and_return(nil) allow(provider).to receive(:uninstall).and_return(nil) allow(provider).to receive(:purge).and_return(nil) allow(Puppet::Type.type(:package).defaultprovider).to receive(:new).and_return(provider) end after :each do Puppet::Type.type(:package).defaultprovider = nil end # Map of old state -> {new state -> change} states = { # 'installed' transitions to 'removed' or 'purged' :installed => { :installed => nil, :absent => 'removed', :purged => 'purged' }, # 'absent' transitions to 'created' or 'purged' :absent => { :installed => 'created', :absent => nil, :purged => 'purged' }, # 'purged' transitions to 'created' :purged => { :installed => 'created', :absent => nil, :purged => nil } } states.each do |old, new_states| describe "#{old} package" do before :each do allow(provider).to receive(:properties).and_return(:ensure => old) end new_states.each do |new, status| it "ensure => #{new} should log #{status ? status : 'nothing'}" do catalog.add_resource(described_class.new(:name => 'yay', :ensure => new)) catalog.apply logs = catalog.apply.report.logs if status expect(logs.first.source).to eq("/Package[yay]/ensure") expect(logs.first.message).to eq(status) else expect(logs.first).to be_nil end end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/type/exec_spec.rb
spec/integration/type/exec_spec.rb
require 'spec_helper' require 'puppet_spec/files' describe Puppet::Type.type(:exec), unless: Puppet::Util::Platform.jruby? do include PuppetSpec::Files let(:catalog) { Puppet::Resource::Catalog.new } let(:path) { tmpfile('exec_provider') } before :each do catalog.host_config = false end shared_examples_for 'a valid exec resource' do it "should execute the command" do exec = described_class.new :command => command, :path => ENV['PATH'] catalog.add_resource exec catalog.apply expect(File.read(path)).to eq('foo') end it "should not execute the command if onlyif returns non-zero" do exec = described_class.new( :command => command, :onlyif => "ruby -e 'exit 44'", :path => ENV['PATH'] ) catalog.add_resource exec catalog.apply expect(Puppet::FileSystem.exist?(path)).to be_falsey end it "should execute the command if onlyif returns zero" do exec = described_class.new( :command => command, :onlyif => "ruby -e 'exit 0'", :path => ENV['PATH'] ) catalog.add_resource exec catalog.apply expect(File.read(path)).to eq('foo') end it "should execute the command if unless returns non-zero" do exec = described_class.new( :command => command, :unless => "ruby -e 'exit 45'", :path => ENV['PATH'] ) catalog.add_resource exec catalog.apply expect(File.read(path)).to eq('foo') end it "should not execute the command if unless returns zero" do exec = described_class.new( :command => command, :unless => "ruby -e 'exit 0'", :path => ENV['PATH'] ) catalog.add_resource exec catalog.apply expect(Puppet::FileSystem.exist?(path)).to be_falsey end end context 'when an exec sends an EOF' do let(:command) { ["/bin/bash", "-c", "exec /bin/sleep 1 >/dev/null 2>&1"] } it 'should not take significant user time' do exec = described_class.new :command => command, :path => ENV['PATH'] catalog.add_resource exec timed_apply = Benchmark.measure { catalog.apply } # In testing I found the user time before the patch in 4f35fd262e to be above # 0.3, after the patch it was consistently below 0.1 seconds. expect(timed_apply.utime).to be < 0.3 end end context 'when command is a string' do let(:command) { "ruby -e 'File.open(\"#{path}\", \"w\") { |f| f.print \"foo\" }'" } it_behaves_like 'a valid exec resource' end context 'when command is an array' do let(:command) { ['ruby', '-e', "File.open(\"#{path}\", \"w\") { |f| f.print \"foo\" }"] } it_behaves_like 'a valid exec resource' context 'when is invalid' do let(:command) { [ "ruby -e 'puts 1'" ] } it 'logs error' do exec = described_class.new :command => command, :path => ENV['PATH'] catalog.add_resource exec logs = catalog.apply.report.logs expect(logs[0].message).to eql("Could not find command 'ruby -e 'puts 1''") end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/type/tidy_spec.rb
spec/integration/type/tidy_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'puppet_spec/files' require 'puppet/file_bucket/dipper' describe Puppet::Type.type(:tidy) do include PuppetSpec::Files include PuppetSpec::Compiler before do allow(Puppet::Util::Storage).to receive(:store) end it "should be able to recursively remove directories" do dir = tmpfile("tidy_testing") FileUtils.mkdir_p(File.join(dir, "foo", "bar")) apply_compiled_manifest(<<-MANIFEST) tidy { '#{dir}': recurse => true, rmdirs => true, } MANIFEST expect(Puppet::FileSystem.directory?(dir)).to be_falsey end # Testing #355. it "should be able to remove dead links", :if => Puppet.features.manages_symlinks? do dir = tmpfile("tidy_link_testing") link = File.join(dir, "link") target = tmpfile("no_such_file_tidy_link_testing") Dir.mkdir(dir) Puppet::FileSystem.symlink(target, link) apply_compiled_manifest(<<-MANIFEST) tidy { '#{dir}': recurse => true, } MANIFEST expect(Puppet::FileSystem.symlink?(link)).to be_falsey end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/resource/type_collection_spec.rb
spec/integration/resource/type_collection_spec.rb
require 'spec_helper' require 'puppet_spec/files' require 'puppet/resource/type_collection' describe Puppet::Resource::TypeCollection do describe "when autoloading from modules" do include PuppetSpec::Files before do @dir = tmpfile("autoload_testing") FileUtils.mkdir_p @dir loader = double('loader', load: nil, set_entry: nil) loaders = double('loaders', runtime3_type_loader: loader) expect(Puppet::Pops::Loaders).to receive(:loaders).at_most(:once).and_return(loaders) environment = Puppet::Node::Environment.create(:env, [@dir]) @code = environment.known_resource_types end # Setup a module. def mk_module(name, files = {}) mdir = File.join(@dir, name) mandir = File.join(mdir, "manifests") FileUtils.mkdir_p mandir defs = files.delete(:define) Dir.chdir(mandir) do files.each do |file, classes| File.open("#{file}.pp", "w") do |f| classes.each { |klass| if defs f.puts "define #{klass} {}" else f.puts "class #{klass} {}" end } end end end end it "should return nil when a class can't be found or loaded" do expect(@code.find_hostclass('nosuchclass')).to be_nil end it "should load the module's init file first" do name = "simple" mk_module(name, :init => [name]) expect(@code.find_hostclass(name).name).to eq(name) end it "should be able to load definitions from the module base file" do name = "simpdef" mk_module(name, :define => true, :init => [name]) expect(@code.find_definition(name).name).to eq(name) end it "should be able to load qualified classes from the module base file" do mk_module('both', :init => %w{both both::sub}) expect(@code.find_hostclass("both::sub").name).to eq("both::sub") end it "should be able load classes from a separate file" do mk_module('separate', :init => %w{separate}, :sub => %w{separate::sub}) expect(@code.find_hostclass("separate::sub").name).to eq("separate::sub") end it "should not fail when loading from a separate file if there is no module file" do mk_module('alone', :sub => %w{alone::sub}) expect { @code.find_hostclass("alone::sub") }.not_to raise_error end it "should be able to load definitions from their own file" do name = "mymod" mk_module(name, :define => true, :mydefine => ["mymod::mydefine"]) expect(@code.find_definition("mymod::mydefine").name).to eq("mymod::mydefine") end it 'should be able to load definitions from their own file using uppercased name' do name = 'mymod' mk_module(name, :define => true, :mydefine => ['mymod::mydefine']) expect(@code.find_definition('Mymod::Mydefine')).not_to be_nil end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/resource/catalog_spec.rb
spec/integration/resource/catalog_spec.rb
require 'spec_helper' describe Puppet::Resource::Catalog do describe "when using the indirector" do before do # This is so the tests work w/out networking. allow(Facter).to receive(:to_hash).and_return({"hostname" => "foo.domain.com"}) allow(Facter).to receive(:value).and_return("eh") end it "should be able to delegate to the :yaml terminus" do allow(Puppet::Resource::Catalog.indirection).to receive(:terminus_class).and_return(:yaml) # Load now, before we stub the exists? method. terminus = Puppet::Resource::Catalog.indirection.terminus(:yaml) expect(terminus).to receive(:path).with("me").and_return("/my/yaml/file") expect(Puppet::FileSystem).to receive(:exist?).with("/my/yaml/file").and_return(false) expect(Puppet::Resource::Catalog.indirection.find("me")).to be_nil end it "should be able to delegate to the :compiler terminus" do allow(Puppet::Resource::Catalog.indirection).to receive(:terminus_class).and_return(:compiler) # Load now, before we stub the exists? method. compiler = Puppet::Resource::Catalog.indirection.terminus(:compiler) node = double('node', :add_server_facts => nil, :trusted_data= => nil, :environment => nil) expect(Puppet::Node.indirection).to receive(:find).and_return(node) expect(compiler).to receive(:compile).with(node, anything).and_return(nil) expect(Puppet::Resource::Catalog.indirection.find("me")).to be_nil end it "should pass provided node information directly to the terminus" do node = double('node') terminus = double('terminus') allow(terminus).to receive(:validate) expect(terminus).to receive(:find) { |request| expect(request.options[:use_node]).to eq(node) } allow(Puppet::Resource::Catalog.indirection).to receive(:terminus).and_return(terminus) Puppet::Resource::Catalog.indirection.find("me", :use_node => node) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/node/facts_spec.rb
spec/integration/node/facts_spec.rb
require 'spec_helper' describe Puppet::Node::Facts do describe "when using the indirector" do it "should expire any cached node instances when it is saved" do allow(Puppet::Node::Facts.indirection).to receive(:terminus_class).and_return(:yaml) expect(Puppet::Node::Facts.indirection.terminus(:yaml)).to equal(Puppet::Node::Facts.indirection.terminus(:yaml)) terminus = Puppet::Node::Facts.indirection.terminus(:yaml) allow(terminus).to receive(:save) expect(Puppet::Node.indirection).to receive(:expire).with("me", be_a(Hash).or(be_nil)) facts = Puppet::Node::Facts.new("me") Puppet::Node::Facts.indirection.save(facts) end it "should be able to delegate to the :yaml terminus" do allow(Puppet::Node::Facts.indirection).to receive(:terminus_class).and_return(:yaml) # Load now, before we stub the exists? method. terminus = Puppet::Node::Facts.indirection.terminus(:yaml) expect(terminus).to receive(:path).with("me").and_return("/my/yaml/file") expect(Puppet::FileSystem).to receive(:exist?).with("/my/yaml/file").and_return(false) expect(Puppet::Node::Facts.indirection.find("me")).to be_nil end it "should be able to delegate to the :facter terminus" do allow(Puppet::Node::Facts.indirection).to receive(:terminus_class).and_return(:facter) expect(Facter).to receive(:resolve).and_return({1 => 2}) facts = Puppet::Node::Facts.new("me") expect(Puppet::Node::Facts).to receive(:new).with("me", {1 => 2}).and_return(facts) expect(Puppet::Node::Facts.indirection.find("me")).to equal(facts) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/node/environment_spec.rb
spec/integration/node/environment_spec.rb
require 'spec_helper' require 'puppet_spec/files' require 'puppet_spec/scope' require 'matchers/resource' describe Puppet::Node::Environment do include PuppetSpec::Files include Matchers::Resource def a_module_in(name, dir) Dir.mkdir(dir) moddir = File.join(dir, name) Dir.mkdir(moddir) moddir end it "should be able to return each module from its environment with the environment, name, and path set correctly" do base = tmpfile("env_modules") Dir.mkdir(base) dirs = [] mods = {} %w{1 2}.each do |num| dir = File.join(base, "dir#{num}") dirs << dir mods["mod#{num}"] = a_module_in("mod#{num}", dir) end environment = Puppet::Node::Environment.create(:foo, dirs) environment.modules.each do |mod| expect(mod.environment).to eq(environment) expect(mod.path).to eq(mods[mod.name]) end end it "should expand 8.3 paths on Windows when creating an environment", :if => Puppet::Util::Platform.windows? do # asking for short names only works on paths that exist base = Puppet::Util::Windows::File.get_short_pathname(tmpdir("env_modules")) parent_modules_dir = File.join(base, 'testmoduledir') # make sure the paths have ~ in them, indicating unexpanded 8.3 paths expect(parent_modules_dir).to match(/~/) module_dir = a_module_in('testmodule', parent_modules_dir) # create the environment with unexpanded 8.3 paths environment = Puppet::Node::Environment.create(:foo, [parent_modules_dir]) # and expect fully expanded paths inside the environment # necessary for comparing module paths internally by the parser expect(environment.modulepath).to eq([Puppet::FileSystem.expand_path(parent_modules_dir)]) expect(environment.modules.first.path).to eq(Puppet::FileSystem.expand_path(module_dir)) end it "should not yield the same module from different module paths" do base = tmpfile("env_modules") Dir.mkdir(base) dirs = [] %w{1 2}.each do |num| dir = File.join(base, "dir#{num}") dirs << dir a_module_in("mod", dir) end environment = Puppet::Node::Environment.create(:foo, dirs) mods = environment.modules expect(mods.length).to eq(1) expect(mods[0].path).to eq(File.join(base, "dir1", "mod")) end it "should not yield a module with the same name as a defined Bolt project" do project_path = File.join(tmpfile('project'), 'bolt_project') FileUtils.mkdir_p(project_path) project = Struct.new("Project", :name, :path, :load_as_module?).new('project', project_path, true) Puppet.override(bolt_project: project) do base = tmpfile("base") FileUtils.mkdir_p([File.join(base, 'project'), File.join(base, 'other')]) environment = Puppet::Node::Environment.create(:env, [base]) mods = environment.modules expect(mods.length).to eq(2) expect(mods.map(&:path)).to eq([project_path, File.join(base, 'other')]) end end shared_examples_for "the environment's initial import" do |settings| it "a manifest referring to a directory invokes parsing of all its files in sorted order" do settings.each do |name, value| Puppet[name] = value end # fixture has three files 00_a.pp, 01_b.pp, and 02_c.pp. The 'b' file # depends on 'a' being evaluated first. The 'c' file is empty (to ensure # empty things do not break the directory import). # dirname = my_fixture('sitedir') # Set the manifest to the directory to make it parse and combine them when compiling node = Puppet::Node.new('testnode', :environment => Puppet::Node::Environment.create(:testing, [], dirname)) catalog = Puppet::Parser::Compiler.compile(node) expect(catalog).to have_resource('Class[A]') expect(catalog).to have_resource('Class[B]') expect(catalog).to have_resource('Notify[variables]').with_parameter(:message, "a: 10, b: 10") end end shared_examples_for "the environment's initial import in 4x" do |settings| it "a manifest referring to a directory invokes recursive parsing of all its files in sorted order" do settings.each do |name, value| Puppet[name] = value end # fixture has three files 00_a.pp, 01_b.pp, and 02_c.pp. The 'b' file # depends on 'a' being evaluated first. The 'c' file is empty (to ensure # empty things do not break the directory import). # dirname = my_fixture('sitedir2') # Set the manifest to the directory to make it parse and combine them when compiling node = Puppet::Node.new('testnode', :environment => Puppet::Node::Environment.create(:testing, [], dirname)) catalog = Puppet::Parser::Compiler.compile(node) expect(catalog).to have_resource('Class[A]') expect(catalog).to have_resource('Class[B]') expect(catalog).to have_resource('Notify[variables]').with_parameter(:message, "a: 10, b: 10 c: 20") end end describe 'using 4x parser' do it_behaves_like "the environment's initial import", # fixture uses variables that are set in a particular order (this ensures # that files are parsed and combined in the right order or an error will # be raised if 'b' is evaluated before 'a'). :strict_variables => true end describe 'using 4x parser' do it_behaves_like "the environment's initial import in 4x", # fixture uses variables that are set in a particular order (this ensures # that files are parsed and combined in the right order or an error will # be raised if 'b' is evaluated before 'a'). :strict_variables => true end describe "#extralibs on Windows", :if => Puppet::Util::Platform.windows? do describe "with UTF8 characters in PUPPETLIB" do let(:rune_utf8) { "\u16A0\u16C7\u16BB\u16EB\u16D2\u16E6\u16A6\u16EB\u16A0\u16B1\u16A9\u16A0\u16A2\u16B1\u16EB\u16A0\u16C1\u16B1\u16AA\u16EB\u16B7\u16D6\u16BB\u16B9\u16E6\u16DA\u16B3\u16A2\u16D7" } before { Puppet::Util::Windows::Process.set_environment_variable('PUPPETLIB', rune_utf8) } it "should use UTF8 characters in PUPPETLIB environment variable" do expect(Puppet::Node::Environment.extralibs()).to eq([rune_utf8]) end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/transaction/report_spec.rb
spec/integration/transaction/report_spec.rb
require 'spec_helper' require 'puppet_spec/files' describe Puppet::Transaction::Report do before :each do # Enable persistence during tests allow_any_instance_of(Puppet::Transaction::Persistence).to receive(:enabled?).and_return(true) end describe "when using the indirector" do it "should be able to delegate to the :processor terminus" do allow(Puppet::Transaction::Report.indirection).to receive(:terminus_class).and_return(:processor) terminus = Puppet::Transaction::Report.indirection.terminus(:processor) allow(Facter).to receive(:value).and_return("host.domain.com") report = Puppet::Transaction::Report.new expect(terminus).to receive(:process).with(report) Puppet::Transaction::Report.indirection.save(report) end end describe "when dumping to YAML" do it "should not contain TagSet objects" do resource = Puppet::Resource.new(:notify, "Hello") ral_resource = resource.to_ral status = Puppet::Resource::Status.new(ral_resource) log = Puppet::Util::Log.new(:level => :info, :message => "foo") report = Puppet::Transaction::Report.new report.add_resource_status(status) report << log expect(YAML.dump(report)).to_not match('Puppet::Util::TagSet') end end describe "inference checking" do include PuppetSpec::Files require 'puppet/configurer' def run_catalogs(resources1, resources2, noop1 = false, noop2 = false, &block) last_run_report = nil expect(Puppet::Transaction::Report.indirection).to receive(:save) do |report, x| last_run_report = report true end.exactly(4) Puppet[:report] = true Puppet[:noop] = noop1 configurer = Puppet::Configurer.new configurer.run :catalog => new_catalog(resources1) yield block if block last_report = last_run_report Puppet[:noop] = noop2 configurer = Puppet::Configurer.new configurer.run :catalog => new_catalog(resources2) expect(last_report).not_to eq(last_run_report) return last_run_report end def new_blank_catalog Puppet::Resource::Catalog.new("testing", Puppet.lookup(:environments).get(Puppet[:environment])) end def new_catalog(resources = []) new_cat = new_blank_catalog [resources].flatten.each do |resource| new_cat.add_resource(resource) end new_cat end def get_cc_count(report) report.metrics["resources"].values.each do |v| if v[0] == "corrective_change" return v[2] end end return nil end describe "for agent runs that contain" do it "notifies with catalog change" do report = run_catalogs(Puppet::Type.type(:notify).new(:title => "testing", :message => "foo"), Puppet::Type.type(:notify).new(:title => "testing", :message => "foobar")) expect(report.status).to eq("changed") rs = report.resource_statuses["Notify[testing]"] expect(rs.events.size).to eq(1) expect(rs.events[0].corrective_change).to eq(false) expect(rs.corrective_change).to eq(false) expect(report.corrective_change).to eq(false) expect(get_cc_count(report)).to eq(0) end it "notifies with no catalog change" do report = run_catalogs(Puppet::Type.type(:notify).new(:title => "testing", :message => "foo"), Puppet::Type.type(:notify).new(:title => "testing", :message => "foo")) expect(report.status).to eq("changed") rs = report.resource_statuses["Notify[testing]"] expect(rs.events.size).to eq(1) expect(rs.events[0].corrective_change).to eq(false) expect(rs.corrective_change).to eq(false) expect(report.corrective_change).to eq(false) expect(get_cc_count(report)).to eq(0) end it "new file resource" do file = tmpfile("test_file") report = run_catalogs([], Puppet::Type.type(:file).new(:title => file, :content => "mystuff")) expect(report.status).to eq("changed") rs = report.resource_statuses["File[#{file}]"] expect(rs.events.size).to eq(1) expect(rs.events[0].corrective_change).to eq(false) expect(rs.corrective_change).to eq(false) expect(report.corrective_change).to eq(false) expect(get_cc_count(report)).to eq(0) end it "removal of a file resource" do file = tmpfile("test_file") report = run_catalogs(Puppet::Type.type(:file).new(:title => file, :content => "mystuff"), []) expect(report.status).to eq("unchanged") expect(report.resource_statuses["File[#{file}]"]).to eq(nil) expect(report.corrective_change).to eq(false) expect(get_cc_count(report)).to eq(0) end it "file with a title change" do file1 = tmpfile("test_file") file2 = tmpfile("test_file") report = run_catalogs(Puppet::Type.type(:file).new(:title => file1, :content => "mystuff"), Puppet::Type.type(:file).new(:title => file2, :content => "mystuff")) expect(report.status).to eq("changed") expect(report.resource_statuses["File[#{file1}]"]).to eq(nil) rs = report.resource_statuses["File[#{file2}]"] expect(rs.events.size).to eq(1) expect(rs.events[0].corrective_change).to eq(false) expect(rs.corrective_change).to eq(false) expect(report.corrective_change).to eq(false) expect(get_cc_count(report)).to eq(0) end it "file with no catalog change" do file = tmpfile("test_file") report = run_catalogs(Puppet::Type.type(:file).new(:title => file, :content => "mystuff"), Puppet::Type.type(:file).new(:title => file, :content => "mystuff")) expect(report.status).to eq("unchanged") rs = report.resource_statuses["File[#{file}]"] expect(rs.events.size).to eq(0) expect(rs.corrective_change).to eq(false) expect(report.corrective_change).to eq(false) expect(get_cc_count(report)).to eq(0) end it "file with a new parameter" do file = tmpfile("test_file") report = run_catalogs(Puppet::Type.type(:file).new(:title => file, :content => "mystuff"), Puppet::Type.type(:file).new(:title => file, :content => "mystuff", :loglevel => :debug)) expect(report.status).to eq("unchanged") rs = report.resource_statuses["File[#{file}]"] expect(rs.events.size).to eq(0) expect(rs.corrective_change).to eq(false) expect(report.corrective_change).to eq(false) expect(get_cc_count(report)).to eq(0) end it "file with a removed parameter" do file = tmpfile("test_file") report = run_catalogs(Puppet::Type.type(:file).new(:title => file, :content => "mystuff", :loglevel => :debug), Puppet::Type.type(:file).new(:title => file, :content => "mystuff")) expect(report.status).to eq("unchanged") rs = report.resource_statuses["File[#{file}]"] expect(rs.events.size).to eq(0) expect(rs.corrective_change).to eq(false) expect(report.corrective_change).to eq(false) expect(get_cc_count(report)).to eq(0) end it "file with a property no longer managed" do file = tmpfile("test_file") report = run_catalogs(Puppet::Type.type(:file).new(:title => file, :content => "mystuff"), Puppet::Type.type(:file).new(:title => file)) expect(report.status).to eq("unchanged") rs = report.resource_statuses["File[#{file}]"] expect(rs.events.size).to eq(0) expect(rs.corrective_change).to eq(false) expect(report.corrective_change).to eq(false) expect(get_cc_count(report)).to eq(0) end it "file with no catalog change, but file changed between runs" do file = tmpfile("test_file") report = run_catalogs(Puppet::Type.type(:file).new(:title => file, :content => "mystuff"), Puppet::Type.type(:file).new(:title => file, :content => "mystuff")) do File.open(file, 'w') do |f| f.puts "some content" end end expect(report.status).to eq("changed") rs = report.resource_statuses["File[#{file}]"] expect(rs.events.size).to eq(1) expect(rs.events[0].corrective_change).to eq(true) expect(rs.corrective_change).to eq(true) expect(report.corrective_change).to eq(true) expect(get_cc_count(report)).to eq(1) end it "file with catalog change, but file changed between runs that matched catalog change" do file = tmpfile("test_file") report = run_catalogs(Puppet::Type.type(:file).new(:title => file, :content => "mystuff"), Puppet::Type.type(:file).new(:title => file, :content => "some content")) do File.open(file, 'w') do |f| f.write "some content" end end expect(report.status).to eq("unchanged") rs = report.resource_statuses["File[#{file}]"] expect(rs.events.size).to eq(0) expect(rs.corrective_change).to eq(false) expect(report.corrective_change).to eq(false) expect(get_cc_count(report)).to eq(0) end it "file with catalog change, but file changed between runs that did not match catalog change" do file = tmpfile("test_file") report = run_catalogs(Puppet::Type.type(:file).new(:title => file, :content => "mystuff1"), Puppet::Type.type(:file).new(:title => file, :content => "mystuff2")) do File.open(file, 'w') do |f| f.write "some content" end end expect(report.status).to eq("changed") rs = report.resource_statuses["File[#{file}]"] expect(rs.events.size).to eq(1) expect(rs.events[0].corrective_change).to eq(true) expect(rs.corrective_change).to eq(true) expect(report.corrective_change).to eq(true) expect(get_cc_count(report)).to eq(1) end it "file with catalog change" do file = tmpfile("test_file") report = run_catalogs(Puppet::Type.type(:file).new(:title => file, :content => "mystuff1"), Puppet::Type.type(:file).new(:title => file, :content => "mystuff2")) expect(report.status).to eq("changed") rs = report.resource_statuses["File[#{file}]"] expect(rs.events.size).to eq(1) expect(rs.events[0].corrective_change).to eq(false) expect(rs.corrective_change).to eq(false) expect(report.corrective_change).to eq(false) expect(get_cc_count(report)).to eq(0) end it "file with ensure property set to present" do file = tmpfile("test_file") report = run_catalogs(Puppet::Type.type(:file).new(:title => file, :ensure => :present), Puppet::Type.type(:file).new(:title => file, :ensure => :present)) expect(report.status).to eq("unchanged") rs = report.resource_statuses["File[#{file}]"] expect(rs.events.size).to eq(0) expect(rs.corrective_change).to eq(false) expect(report.corrective_change).to eq(false) expect(get_cc_count(report)).to eq(0) end it "file with ensure property change file => absent" do file = tmpfile("test_file") report = run_catalogs(Puppet::Type.type(:file).new(:title => file, :ensure => :file), Puppet::Type.type(:file).new(:title => file, :ensure => :absent)) expect(report.status).to eq("changed") rs = report.resource_statuses["File[#{file}]"] expect(rs.events.size).to eq(1) expect(rs.events[0].corrective_change).to eq(false) expect(rs.corrective_change).to eq(false) expect(report.corrective_change).to eq(false) expect(get_cc_count(report)).to eq(0) end it "file with ensure property change present => absent" do file = tmpfile("test_file") report = run_catalogs(Puppet::Type.type(:file).new(:title => file, :ensure => :present), Puppet::Type.type(:file).new(:title => file, :ensure => :absent)) expect(report.status).to eq("changed") rs = report.resource_statuses["File[#{file}]"] expect(rs.events.size).to eq(1) expect(rs.events[0].corrective_change).to eq(false) expect(rs.corrective_change).to eq(false) expect(report.corrective_change).to eq(false) expect(get_cc_count(report)).to eq(0) end it "link with ensure property change present => absent", :unless => Puppet::Util::Platform.windows? do file = tmpfile("test_file") FileUtils.symlink(file, tmpfile("test_link")) report = run_catalogs(Puppet::Type.type(:file).new(:title => file, :ensure => :present), Puppet::Type.type(:file).new(:title => file, :ensure => :absent)) expect(report.status).to eq("changed") rs = report.resource_statuses["File[#{file}]"] expect(rs.events.size).to eq(1) expect(rs.events[0].corrective_change).to eq(false) expect(rs.corrective_change).to eq(false) expect(report.corrective_change).to eq(false) expect(get_cc_count(report)).to eq(0) end it "file with ensure property change absent => present" do file = tmpfile("test_file") report = run_catalogs(Puppet::Type.type(:file).new(:title => file, :ensure => :absent), Puppet::Type.type(:file).new(:title => file, :ensure => :present)) expect(report.status).to eq("changed") rs = report.resource_statuses["File[#{file}]"] expect(rs.events.size).to eq(1) expect(rs.events[0].corrective_change).to eq(false) expect(rs.corrective_change).to eq(false) expect(report.corrective_change).to eq(false) expect(get_cc_count(report)).to eq(0) end it "new resource in catalog" do file = tmpfile("test_file") report = run_catalogs([], Puppet::Type.type(:file).new(:title => file, :content => "mystuff asdf")) expect(report.status).to eq("changed") rs = report.resource_statuses["File[#{file}]"] expect(rs.events.size).to eq(1) expect(rs.events[0].corrective_change).to eq(false) expect(rs.corrective_change).to eq(false) expect(report.corrective_change).to eq(false) expect(get_cc_count(report)).to eq(0) end it "exec with idempotence issue", :unless => Puppet::Util::Platform.windows? || RUBY_PLATFORM == 'java' do report = run_catalogs(Puppet::Type.type(:exec).new(:title => "exec1", :command => "/bin/echo foo"), Puppet::Type.type(:exec).new(:title => "exec1", :command => "/bin/echo foo")) expect(report.status).to eq("changed") # Of note here, is that the main idempotence issues lives in 'returns' rs = report.resource_statuses["Exec[exec1]"] expect(rs.events.size).to eq(1) expect(rs.events[0].corrective_change).to eq(true) expect(rs.corrective_change).to eq(true) expect(report.corrective_change).to eq(true) expect(get_cc_count(report)).to eq(1) end it "exec with no idempotence issue", :unless => Puppet::Util::Platform.windows? || RUBY_PLATFORM == 'java' do report = run_catalogs(Puppet::Type.type(:exec).new(:title => "exec1", :command => "echo foo", :path => "/bin", :unless => "ls"), Puppet::Type.type(:exec).new(:title => "exec1", :command => "echo foo", :path => "/bin", :unless => "ls")) expect(report.status).to eq("unchanged") # Of note here, is that the main idempotence issues lives in 'returns' rs = report.resource_statuses["Exec[exec1]"] expect(rs.events.size).to eq(0) expect(rs.corrective_change).to eq(false) expect(report.corrective_change).to eq(false) expect(get_cc_count(report)).to eq(0) end it "noop on second run, file with no catalog change, but file changed between runs" do file = tmpfile("test_file") report = run_catalogs(Puppet::Type.type(:file).new(:title => file, :content => "mystuff"), Puppet::Type.type(:file).new(:title => file, :content => "mystuff"), false, true) do File.open(file, 'w') do |f| f.puts "some content" end end expect(report.status).to eq("unchanged") rs = report.resource_statuses["File[#{file}]"] expect(rs.events[0].corrective_change).to eq(true) expect(rs.events.size).to eq(1) expect(rs.corrective_change).to eq(true) expect(report.corrective_change).to eq(true) expect(get_cc_count(report)).to eq(1) end it "noop on all subsequent runs, file with no catalog change, but file changed between run 1 and 2" do file = tmpfile("test_file") report = run_catalogs(Puppet::Type.type(:file).new(:title => file, :content => "mystuff"), Puppet::Type.type(:file).new(:title => file, :content => "mystuff"), false, true) do File.open(file, 'w') do |f| f.puts "some content" end end expect(report.status).to eq("unchanged") rs = report.resource_statuses["File[#{file}]"] expect(rs.events[0].corrective_change).to eq(true) expect(rs.events.size).to eq(1) expect(rs.corrective_change).to eq(true) expect(report.corrective_change).to eq(true) expect(get_cc_count(report)).to eq(1) # Simply run the catalog twice again, but this time both runs are noop to # test if the corrective field is still set. report = run_catalogs(Puppet::Type.type(:file).new(:title => file, :content => "mystuff"), Puppet::Type.type(:file).new(:title => file, :content => "mystuff"), true, true) expect(report.status).to eq("unchanged") rs = report.resource_statuses["File[#{file}]"] expect(rs.events[0].corrective_change).to eq(true) expect(rs.events.size).to eq(1) expect(rs.corrective_change).to eq(true) expect(report.corrective_change).to eq(true) expect(get_cc_count(report)).to eq(1) end it "noop on first run, file with no catalog change, but file changed between runs" do file = tmpfile("test_file") report = run_catalogs(Puppet::Type.type(:file).new(:title => file, :content => "mystuff"), Puppet::Type.type(:file).new(:title => file, :content => "mystuff"), true, false) do File.open(file, 'w') do |f| f.puts "some content" end end expect(report.status).to eq("changed") rs = report.resource_statuses["File[#{file}]"] expect(rs.events[0].corrective_change).to eq(true) expect(rs.events.size).to eq(1) expect(rs.corrective_change).to eq(true) expect(report.corrective_change).to eq(true) expect(get_cc_count(report)).to eq(1) end it "noop on both runs, file with no catalog change, but file changed between runs" do file = tmpfile("test_file") report = run_catalogs(Puppet::Type.type(:file).new(:title => file, :content => "mystuff"), Puppet::Type.type(:file).new(:title => file, :content => "mystuff"), true, true) do File.open(file, 'w') do |f| f.puts "some content" end end expect(report.status).to eq("unchanged") rs = report.resource_statuses["File[#{file}]"] expect(rs.events.size).to eq(1) expect(rs.events[0].corrective_change).to eq(true) expect(rs.corrective_change).to eq(true) expect(report.corrective_change).to eq(true) expect(get_cc_count(report)).to eq(1) end it "noop on 4 runs, file with no catalog change, but file changed between runs 1 and 2" do file = tmpfile("test_file") report = run_catalogs(Puppet::Type.type(:file).new(:title => file, :content => "mystuff"), Puppet::Type.type(:file).new(:title => file, :content => "mystuff"), true, true) do File.open(file, 'w') do |f| f.puts "some content" end end expect(report.status).to eq("unchanged") rs = report.resource_statuses["File[#{file}]"] expect(rs.events.size).to eq(1) expect(rs.events[0].corrective_change).to eq(true) expect(rs.corrective_change).to eq(true) expect(report.corrective_change).to eq(true) expect(get_cc_count(report)).to eq(1) report = run_catalogs(Puppet::Type.type(:file).new(:title => file, :content => "mystuff"), Puppet::Type.type(:file).new(:title => file, :content => "mystuff"), true, true) expect(report.status).to eq("unchanged") rs = report.resource_statuses["File[#{file}]"] expect(rs.events.size).to eq(1) expect(rs.events[0].corrective_change).to eq(true) expect(rs.corrective_change).to eq(true) expect(report.corrective_change).to eq(true) expect(get_cc_count(report)).to eq(1) end it "noop on both runs, file already exists but with catalog change each time" do file = tmpfile("test_file") File.open(file, 'w') do |f| f.puts "some content" end report = run_catalogs(Puppet::Type.type(:file).new(:title => file, :content => "a"), Puppet::Type.type(:file).new(:title => file, :content => "b"), true, true) expect(report.status).to eq("unchanged") rs = report.resource_statuses["File[#{file}]"] expect(rs.events.size).to eq(1) expect(rs.events[0].corrective_change).to eq(false) expect(rs.corrective_change).to eq(false) expect(report.corrective_change).to eq(false) expect(get_cc_count(report)).to eq(0) end it "file failure should not return corrective_change" do # Making the path a child path (with no parent) forces a failure file = tmpfile("test_file") + "/foo" report = run_catalogs(Puppet::Type.type(:file).new(:title => file, :content => "a"), Puppet::Type.type(:file).new(:title => file, :content => "b"), false, false) expect(report.status).to eq("failed") rs = report.resource_statuses["File[#{file}]"] expect(rs.events.size).to eq(1) expect(rs.events[0].corrective_change).to eq(false) expect(rs.corrective_change).to eq(false) expect(report.corrective_change).to eq(false) expect(get_cc_count(report)).to eq(0) end it "file skipped with file change between runs will not show corrective_change" do # Making the path a child path (with no parent) forces a failure file = tmpfile("test_file") + "/foo" resources1 = [ Puppet::Type.type(:file).new(:title => file, :content => "a", :notify => "Notify['foo']"), Puppet::Type.type(:notify).new(:title => "foo") ] resources2 = [ Puppet::Type.type(:file).new(:title => file, :content => "a", :notify => "Notify[foo]"), Puppet::Type.type(:notify).new(:title => "foo", :message => "foo") ] report = run_catalogs(resources1, resources2, false, false) expect(report.status).to eq("failed") rs = report.resource_statuses["File[#{file}]"] expect(rs.events.size).to eq(1) expect(rs.events[0].corrective_change).to eq(false) expect(rs.corrective_change).to eq(false) rs = report.resource_statuses["Notify[foo]"] expect(rs.events.size).to eq(0) expect(rs.corrective_change).to eq(false) expect(report.corrective_change).to eq(false) expect(get_cc_count(report)).to eq(0) end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/indirector/direct_file_server_spec.rb
spec/integration/indirector/direct_file_server_spec.rb
require 'spec_helper' require 'puppet/indirector/file_content/file' require 'puppet/indirector/file_metadata/file' describe Puppet::Indirector::DirectFileServer, " when interacting with the filesystem and the model" do include PuppetSpec::Files before do # We just test a subclass, since it's close enough. @terminus = Puppet::Indirector::FileContent::File.new end it "should return an instance of the model" do filepath = make_absolute("/path/to/my/file") expect(Puppet::FileSystem).to receive(:exist?).with(filepath).and_return(true) expect(@terminus.find(@terminus.indirection.request(:find, Puppet::Util.path_to_uri(filepath).to_s, nil))).to be_instance_of(Puppet::FileServing::Content) end it "should return an instance capable of returning its content" do filename = file_containing("testfile", "my content") instance = @terminus.find(@terminus.indirection.request(:find, Puppet::Util.path_to_uri(filename).to_s, nil)) expect(instance.content).to eq("my content") end end describe Puppet::Indirector::DirectFileServer, " when interacting with FileServing::Fileset and the model" do include PuppetSpec::Files matcher :file_with_content do |name, content| match do |actual| actual.full_path == name && actual.content == content end end matcher :directory_named do |name| match do |actual| actual.full_path == name end end it "should return an instance for every file in the fileset" do path = tmpdir('direct_file_server_testing') File.open(File.join(path, "one"), "w") { |f| f.print "one content" } File.open(File.join(path, "two"), "w") { |f| f.print "two content" } terminus = Puppet::Indirector::FileContent::File.new request = terminus.indirection.request(:search, Puppet::Util.path_to_uri(path).to_s, nil, :recurse => true) expect(terminus.search(request)).to contain_exactly( file_with_content(File.join(path, "one"), "one content"), file_with_content(File.join(path, "two"), "two content"), directory_named(path)) end end describe Puppet::Indirector::DirectFileServer, " when interacting with filesystem metadata" do include PuppetSpec::Files include_context 'with supported checksum types' before do @terminus = Puppet::Indirector::FileMetadata::File.new end with_checksum_types("file_metadata", "testfile") do it "should return the correct metadata" do request = @terminus.indirection.request(:find, Puppet::Util.path_to_uri(checksum_file).to_s, nil, :checksum_type => checksum_type) result = @terminus.find(request) expect_correct_checksum(result, checksum_type, checksum, Puppet::FileServing::Metadata) end end with_checksum_types("direct_file_server_testing", "testfile") do it "search of FileServing::Fileset should return the correct metadata" do request = @terminus.indirection.request(:search, Puppet::Util.path_to_uri(env_path).to_s, nil, :recurse => true, :checksum_type => checksum_type) result = @terminus.search(request) expect(result).to_not be_nil expect(result.length).to eq(2) file, dir = result.partition {|x| x.relative_path == 'testfile'} expect(file.length).to eq(1) expect(dir.length).to eq(1) expect_correct_checksum(dir[0], 'ctime', "#{CHECKSUM_STAT_TIME}", Puppet::FileServing::Metadata) expect_correct_checksum(file[0], checksum_type, checksum, Puppet::FileServing::Metadata) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/indirector/catalog/compiler_spec.rb
spec/integration/indirector/catalog/compiler_spec.rb
require 'spec_helper' require 'puppet/resource/catalog' Puppet::Resource::Catalog.indirection.terminus(:compiler) describe Puppet::Resource::Catalog::Compiler do before do allow(Facter).to receive(:value).and_return("something") @catalog = Puppet::Resource::Catalog.new("testing", Puppet::Node::Environment::NONE) @catalog.add_resource(@one = Puppet::Resource.new(:file, "/one")) @catalog.add_resource(@two = Puppet::Resource.new(:file, "/two")) end it "should remove virtual resources when filtering" do @one.virtual = true expect(Puppet::Resource::Catalog.indirection.terminus.filter(@catalog).resource_refs).to eq([ @two.ref ]) end it "should not remove exported resources when filtering" do @one.exported = true expect(Puppet::Resource::Catalog.indirection.terminus.filter(@catalog).resource_refs.sort).to eq([ @one.ref, @two.ref ]) end it "should remove virtual exported resources when filtering" do @one.exported = true @one.virtual = true expect(Puppet::Resource::Catalog.indirection.terminus.filter(@catalog).resource_refs).to eq([ @two.ref ]) end it "should filter out virtual resources when finding a catalog" do Puppet[:node_terminus] = :memory Puppet::Node.indirection.save(Puppet::Node.new("mynode")) allow(Puppet::Resource::Catalog.indirection.terminus).to receive(:extract_facts_from_request) allow(Puppet::Resource::Catalog.indirection.terminus).to receive(:compile).and_return(@catalog) @one.virtual = true expect(Puppet::Resource::Catalog.indirection.find("mynode").resource_refs).to eq([ @two.ref ]) end it "should not filter out exported resources when finding a catalog" do Puppet[:node_terminus] = :memory Puppet::Node.indirection.save(Puppet::Node.new("mynode")) allow(Puppet::Resource::Catalog.indirection.terminus).to receive(:extract_facts_from_request) allow(Puppet::Resource::Catalog.indirection.terminus).to receive(:compile).and_return(@catalog) @one.exported = true expect(Puppet::Resource::Catalog.indirection.find("mynode").resource_refs.sort).to eq([ @one.ref, @two.ref ]) end it "should filter out virtual exported resources when finding a catalog" do Puppet[:node_terminus] = :memory Puppet::Node.indirection.save(Puppet::Node.new("mynode")) allow(Puppet::Resource::Catalog.indirection.terminus).to receive(:extract_facts_from_request) allow(Puppet::Resource::Catalog.indirection.terminus).to receive(:compile).and_return(@catalog) @one.exported = true @one.virtual = true expect(Puppet::Resource::Catalog.indirection.find("mynode").resource_refs).to eq([ @two.ref ]) end it "filters out virtual exported resources using the agent's production environment" do Puppet[:node_terminus] = :memory Puppet::Node.indirection.save(Puppet::Node.new("mynode")) catalog_environment = nil expect_any_instance_of(Puppet::Parser::Resource::Catalog).to receive(:to_resource) {catalog_environment = Puppet.lookup(:current_environment).name} Puppet::Resource::Catalog.indirection.find("mynode") expect(catalog_environment).to eq(:production) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/indirector/file_content/file_server_spec.rb
spec/integration/indirector/file_content/file_server_spec.rb
require 'spec_helper' require 'puppet/indirector/file_content/file_server' require 'shared_behaviours/file_server_terminus' require 'puppet_spec/files' describe Puppet::Indirector::FileContent::FileServer, " when finding files" do it_should_behave_like "Puppet::Indirector::FileServerTerminus" include PuppetSpec::Files before do @terminus = Puppet::Indirector::FileContent::FileServer.new @test_class = Puppet::FileServing::Content Puppet::FileServing::Configuration.instance_variable_set(:@configuration, nil) end it "should find plugin file content in the environment specified in the request" do path = tmpfile("file_content_with_env") Dir.mkdir(path) modpath = File.join(path, "mod") FileUtils.mkdir_p(File.join(modpath, "lib")) file = File.join(modpath, "lib", "file.rb") File.open(file, "wb") { |f| f.write "1\r\n" } Puppet.settings[:modulepath] = "/no/such/file" env = Puppet::Node::Environment.create(:foo, [path]) result = Puppet::FileServing::Content.indirection.search("plugins", :environment => env, :recurse => true) expect(result).not_to be_nil expect(result.length).to eq(2) result.map {|x| expect(x).to be_instance_of(Puppet::FileServing::Content) } expect(result.find {|x| x.relative_path == 'file.rb' }.content).to eq("1\r\n") end it "should find file content in modules" do path = tmpfile("file_content") Dir.mkdir(path) modpath = File.join(path, "mymod") FileUtils.mkdir_p(File.join(modpath, "files")) file = File.join(modpath, "files", "myfile") File.open(file, "wb") { |f| f.write "1\r\n" } env = Puppet::Node::Environment.create(:foo, [path]) result = Puppet::FileServing::Content.indirection.find("modules/mymod/myfile", :environment => env) expect(result).not_to be_nil expect(result).to be_instance_of(Puppet::FileServing::Content) expect(result.content).to eq("1\r\n") end it "should find file content of tasks in modules" do path = tmpfile("task_file_content") Dir.mkdir(path) modpath = File.join(path, "myothermod") FileUtils.mkdir_p(File.join(modpath, "tasks")) file = File.join(modpath, "tasks", "mytask") File.open(file, "wb") { |f| f.write "I'm a task" } env = Puppet::Node::Environment.create(:foo, [path]) result = Puppet::FileServing::Content.indirection.find("tasks/myothermod/mytask", :environment => env) expect(result).not_to be_nil expect(result).to be_instance_of(Puppet::FileServing::Content) expect(result.content).to eq("I'm a task") end it "should find file content in files when node name expansions are used" do allow(Puppet::FileSystem).to receive(:exist?).and_return(true) allow(Puppet::FileSystem).to receive(:exist?).with(Puppet[:fileserverconfig]).and_return(true) path = tmpfile("file_server_testing") Dir.mkdir(path) subdir = File.join(path, "mynode") Dir.mkdir(subdir) File.open(File.join(subdir, "myfile"), "wb") { |f| f.write "1\r\n" } # Use a real mount, so the integration is a bit deeper. mount1 = Puppet::FileServing::Configuration::Mount::File.new("one") mount1.path = File.join(path, "%h") parser = double('parser', :changed? => false) allow(parser).to receive(:parse).and_return("one" => mount1) allow(Puppet::FileServing::Configuration::Parser).to receive(:new).and_return(parser) path = File.join(path, "myfile") env = Puppet::Node::Environment.create(:foo, []) result = Puppet::FileServing::Content.indirection.find("one/myfile", :environment => env, :node => "mynode") expect(result).not_to be_nil expect(result).to be_instance_of(Puppet::FileServing::Content) expect(result.content).to eq("1\r\n") end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/indirector/file_metadata/file_server_spec.rb
spec/integration/indirector/file_metadata/file_server_spec.rb
require 'spec_helper' require 'puppet/indirector/file_metadata/file_server' require 'shared_behaviours/file_server_terminus' require 'puppet_spec/files' describe Puppet::Indirector::FileMetadata::FileServer, " when finding files" do it_should_behave_like "Puppet::Indirector::FileServerTerminus" include PuppetSpec::Files include_context 'with supported checksum types' before do @terminus = Puppet::Indirector::FileMetadata::FileServer.new @test_class = Puppet::FileServing::Metadata Puppet::FileServing::Configuration.instance_variable_set(:@configuration, nil) end describe "with a plugin environment specified in the request" do with_checksum_types("file_content_with_env", "mod/lib/file.rb") do it "should return the correct metadata" do Puppet.settings[:modulepath] = "/no/such/file" env = Puppet::Node::Environment.create(:foo, [env_path]) result = Puppet::FileServing::Metadata.indirection.search("plugins", :environment => env, :checksum_type => checksum_type, :recurse => true) expect(result).to_not be_nil expect(result.length).to eq(2) result.map {|x| expect(x).to be_instance_of(Puppet::FileServing::Metadata)} expect_correct_checksum(result.find {|x| x.relative_path == 'file.rb'}, checksum_type, checksum, Puppet::FileServing::Metadata) end end end describe "in modules" do with_checksum_types("file_content", "mymod/files/myfile") do it "should return the correct metadata" do env = Puppet::Node::Environment.create(:foo, [env_path]) result = Puppet::FileServing::Metadata.indirection.find("modules/mymod/myfile", :environment => env, :checksum_type => checksum_type) expect_correct_checksum(result, checksum_type, checksum, Puppet::FileServing::Metadata) end end end describe "that are tasks in modules" do with_checksum_types("task_file_content", "mymod/tasks/mytask") do it "should return the correct metadata" do env = Puppet::Node::Environment.create(:foo, [env_path]) result = Puppet::FileServing::Metadata.indirection.find("tasks/mymod/mytask", :environment => env, :checksum_type => checksum_type) expect_correct_checksum(result, checksum_type, checksum, Puppet::FileServing::Metadata) end end end describe "when node name expansions are used" do with_checksum_types("file_server_testing", "mynode/myfile") do it "should return the correct metadata" do allow(Puppet::FileSystem).to receive(:exist?).with(checksum_file).and_return(true) allow(Puppet::FileSystem).to receive(:exist?).with(Puppet[:fileserverconfig]).and_return(true) # Use a real mount, so the integration is a bit deeper. mount1 = Puppet::FileServing::Configuration::Mount::File.new("one") mount1.path = File.join(env_path, "%h") parser = double('parser', :changed? => false) allow(parser).to receive(:parse).and_return("one" => mount1) allow(Puppet::FileServing::Configuration::Parser).to receive(:new).and_return(parser) env = Puppet::Node::Environment.create(:foo, []) result = Puppet::FileServing::Metadata.indirection.find("one/myfile", :environment => env, :node => "mynode", :checksum_type => checksum_type) expect_correct_checksum(result, checksum_type, checksum, Puppet::FileServing::Metadata) end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/indirector/facts/facter_spec.rb
spec/integration/indirector/facts/facter_spec.rb
require 'spec_helper' require 'puppet_spec/files' require 'puppet_spec/compiler' require 'puppet/indirector/facts/facter' describe Puppet::Node::Facts::Facter do include PuppetSpec::Files include PuppetSpec::Compiler include PuppetSpec::Settings before :each do Puppet::Node::Facts.indirection.terminus_class = :facter end it "preserves case in fact values" do Puppet.runtime[:facter].add(:downcase_test) do setcode do "AaBbCc" end end allow(Facter).to receive(:reset) cat = compile_to_catalog('notify { $downcase_test: }', Puppet::Node.indirection.find('foo')) expect(cat.resource("Notify[AaBbCc]")).to be end context "resolving file based facts" do let(:factdir) { tmpdir('factdir') } it "should resolve custom facts" do test_module = File.join(factdir, 'module', 'lib', 'facter') FileUtils.mkdir_p(test_module) File.open(File.join(test_module, 'custom.rb'), 'wb') { |file| file.write(<<-EOF)} Puppet.runtime[:facter].add(:custom) do setcode do Puppet.runtime[:facter].value('puppetversion') end end EOF Puppet.initialize_settings(['--modulepath', factdir]) apply = Puppet::Application.find(:apply).new(double('command_line', :subcommand_name => :apply, :args => ['--modulepath', factdir, '-e', 'notify { $custom: }'])) expect { apply.run }.to exit_with(0) .and output(/defined 'message' as '#{Puppet.version}'/).to_stdout end it "should resolve external facts" do external_fact = File.join(factdir, 'external.json') File.open(external_fact, 'wb') { |file| file.write(<<-EOF)} {"foo": "bar"} EOF Puppet.initialize_settings(['--pluginfactdest', factdir]) apply = Puppet::Application.find(:apply).new(double('command_line', :subcommand_name => :apply, :args => ['--pluginfactdest', factdir, '-e', 'notify { $foo: }'])) expect { apply.run }.to exit_with(0) .and output(/defined 'message' as 'bar'/).to_stdout end end context "adding facts" do it "adds the puppetversion fact" do allow(Facter).to receive(:reset) cat = compile_to_catalog('notify { $::puppetversion: }', Puppet::Node.indirection.find('foo')) expect(cat.resource("Notify[#{Puppet.version.to_s}]")).to be end context "when adding the agent_specified_environment fact" do it "does not add the fact if the agent environment is not set" do expect do compile_to_catalog('notify { $::agent_specified_environment: }', Puppet::Node.indirection.find('foo')) end.to raise_error(Puppet::PreformattedError) end it "does not add the fact if the agent environment is set in sections other than agent or main" do set_puppet_conf(Puppet[:confdir], <<~CONF) [user] environment=bar CONF Puppet.initialize_settings expect do compile_to_catalog('notify { $::agent_specified_environment: }', Puppet::Node.indirection.find('foo')) end.to raise_error(Puppet::PreformattedError) end it "adds the agent_specified_environment fact when set in the agent section in puppet.conf" do set_puppet_conf(Puppet[:confdir], <<~CONF) [agent] environment=bar CONF Puppet.initialize_settings cat = compile_to_catalog('notify { $::agent_specified_environment: }', Puppet::Node.indirection.find('foo')) expect(cat.resource("Notify[bar]")).to be end it "prefers agent_specified_environment from main if set in section other than agent" do set_puppet_conf(Puppet[:confdir], <<~CONF) [main] environment=baz [user] environment=bar CONF Puppet.initialize_settings cat = compile_to_catalog('notify { $::agent_specified_environment: }', Puppet::Node.indirection.find('foo')) expect(cat.resource("Notify[baz]")).to be end it "prefers agent_specified_environment from agent if set in multiple sections" do set_puppet_conf(Puppet[:confdir], <<~CONF) [main] environment=baz [agent] environment=bar CONF Puppet.initialize_settings cat = compile_to_catalog('notify { $::agent_specified_environment: }', Puppet::Node.indirection.find('foo')) expect(cat.resource("Notify[bar]")).to be end it "adds the agent_specified_environment fact when set in puppet.conf" do set_puppet_conf(Puppet[:confdir], 'environment=bar') Puppet.initialize_settings cat = compile_to_catalog('notify { $::agent_specified_environment: }', Puppet::Node.indirection.find('foo')) expect(cat.resource("Notify[bar]")).to be end it "adds the agent_specified_environment fact when set via command-line" do Puppet.initialize_settings(['--environment', 'bar']) cat = compile_to_catalog('notify { $::agent_specified_environment: }', Puppet::Node.indirection.find('foo')) expect(cat.resource("Notify[bar]")).to be end it "adds the agent_specified_environment fact, preferring cli, when set in puppet.conf and via command-line" do set_puppet_conf(Puppet[:confdir], 'environment=bar') Puppet.initialize_settings(['--environment', 'baz']) cat = compile_to_catalog('notify { $::agent_specified_environment: }', Puppet::Node.indirection.find('foo')) expect(cat.resource("Notify[baz]")).to be end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/application/agent_spec.rb
spec/integration/application/agent_spec.rb
require 'spec_helper' require 'puppet_spec/files' require 'puppet_spec/puppetserver' require 'puppet_spec/compiler' require 'puppet_spec/https' require 'puppet/application/agent' describe "puppet agent", unless: Puppet::Util::Platform.jruby? do include PuppetSpec::Files include PuppetSpec::Compiler include_context "https client" let(:server) { PuppetSpec::Puppetserver.new } let(:agent) { Puppet::Application[:agent] } let(:node) { Puppet::Node.new(Puppet[:certname], environment: 'production')} let(:formatter) { Puppet::Network::FormatHandler.format(:rich_data_json) } # Create temp fixtures since the agent will attempt to refresh the CA/CRL before do Puppet[:localcacert] = ca = tmpfile('ca') Puppet[:hostcrl] = crl = tmpfile('crl') copy_fixtures(%w[ca.pem intermediate.pem], ca) copy_fixtures(%w[crl.pem intermediate-crl.pem], crl) end def copy_fixtures(sources, dest) ssldir = File.join(PuppetSpec::FIXTURE_DIR, 'ssl') File.open(dest, 'w') do |f| sources.each do |s| f.write(File.read(File.join(ssldir, s))) end end end context 'server identification' do it 'emits a notice if the server sends the X-Puppet-Compiler-Name header' do server.start_server do |port| Puppet[:serverport] = port expect { agent.command_line.args << '--test' agent.run }.to exit_with(0) .and output(%r{Notice: Catalog compiled by test-compiler-hostname}).to_stdout end end end context 'server_list' do it "uses the first server in the list" do Puppet[:server_list] = '127.0.0.1' Puppet[:log_level] = 'debug' server.start_server do |port| Puppet[:serverport] = port expect { agent.command_line.args << '--test' agent.run }.to exit_with(0) .and output(%r{HTTP GET https://127.0.0.1:#{port}/status/v1/simple/server returned 200 OK}).to_stdout end end it "falls back, recording the first viable server in the report" do Puppet[:server_list] = "puppet.example.com,#{Puppet[:server]}" server.start_server do |port| Puppet[:serverport] = port expect { agent.command_line.args << '--test' agent.run }.to exit_with(0) .and output(%r{Notice: Applied catalog}).to_stdout .and output(%r{Unable to connect to server from server_list setting: Request to https://puppet.example.com:#{port}/status/v1/simple/server failed}).to_stderr report = Puppet::Transaction::Report.convert_from(:yaml, File.read(Puppet[:lastrunreport])) expect(report.server_used).to eq("127.0.0.1:#{port}") end end it "doesn't write a report if no servers could be contacted" do Puppet[:server_list] = "puppet.example.com" expect { agent.command_line.args << '--test' agent.run }.to exit_with(1) .and output(a_string_matching(%r{Unable to connect to server from server_list setting}) .and matching(/Error: Could not run Puppet configuration client: Could not select a functional puppet server from server_list: 'puppet.example.com'/)).to_stderr # I'd expect puppet to update the last run report even if the server_list was # exhausted, but it doesn't work that way currently, see PUP-6708 expect(File).to_not be_exist(Puppet[:lastrunreport]) end it "omits server_used when not using server_list" do Puppet[:log_level] = 'debug' server.start_server do |port| Puppet[:serverport] = port expect { agent.command_line.args << '--test' agent.run }.to exit_with(0) .and output(%r{Resolved service 'puppet' to https://127.0.0.1:#{port}/puppet/v3}).to_stdout end report = Puppet::Transaction::Report.convert_from(:yaml, File.read(Puppet[:lastrunreport])) expect(report.server_used).to be_nil end it "server_list takes precedence over server" do Puppet[:server] = 'notvalid.example.com' Puppet[:log_level] = 'debug' server.start_server do |port| Puppet[:server_list] = "127.0.0.1:#{port}" expect { agent.command_line.args << '--test' agent.run }.to exit_with(0) .and output(%r{Debug: Resolved service 'puppet' to https://127.0.0.1:#{port}/puppet/v3}).to_stdout report = Puppet::Transaction::Report.convert_from(:yaml, File.read(Puppet[:lastrunreport])) expect(report.server_used).to eq("127.0.0.1:#{port}") end end end context 'rich data' do let(:deferred_file) { tmpfile('deferred') } let(:deferred_manifest) do <<~END file { '#{deferred_file}': ensure => file, content => '123', } -> notify { 'deferred': message => Deferred('binary_file', ['#{deferred_file}']) } END end it "calls a deferred 4x function" do catalog_handler = -> (req, res) { catalog = compile_to_catalog(<<-MANIFEST, node) notify { 'deferred4x': message => Deferred('join', [[1,2,3], ':']) } MANIFEST res.body = formatter.render(catalog) res['Content-Type'] = formatter.mime } server.start_server(mounts: {catalog: catalog_handler}) do |port| Puppet[:serverport] = port expect { agent.command_line.args << '--test' agent.run }.to exit_with(2) .and output(%r{Notice: /Stage\[main\]/Main/Notify\[deferred4x\]/message: defined 'message' as '1:2:3'}).to_stdout end end it "calls a deferred 3x function" do catalog_handler = -> (req, res) { catalog = compile_to_catalog(<<-MANIFEST, node) notify { 'deferred3x': message => Deferred('sprintf', ['%s', 'I am deferred']) } MANIFEST res.body = formatter.render(catalog) res['Content-Type'] = formatter.mime } server.start_server(mounts: {catalog: catalog_handler}) do |port| Puppet[:serverport] = port expect { agent.command_line.args << '--test' agent.run }.to exit_with(2) .and output(%r{Notice: /Stage\[main\]/Main/Notify\[deferred3x\]/message: defined 'message' as 'I am deferred'}).to_stdout end end it "fails to apply a deferred function with an unsatisfied prerequisite" do Puppet[:preprocess_deferred] = true catalog_handler = -> (req, res) { catalog = compile_to_catalog(deferred_manifest, node) res.body = formatter.render(catalog) res['Content-Type'] = formatter.mime } server.start_server(mounts: {catalog: catalog_handler}) do |port| Puppet[:serverport] = port expect { agent.command_line.args << '--test' agent.run }.to exit_with(1) .and output(%r{Using environment}).to_stdout .and output(%r{The given file '#{deferred_file}' does not exist}).to_stderr end end it "applies a deferred function and its prerequisite in the same run" do catalog_handler = -> (req, res) { catalog = compile_to_catalog(deferred_manifest, node) res.body = formatter.render(catalog) res['Content-Type'] = formatter.mime } server.start_server(mounts: {catalog: catalog_handler}) do |port| Puppet[:serverport] = port expect { agent.command_line.args << '--test' agent.run }.to exit_with(2) .and output(%r{defined 'message' as Binary\("MTIz"\)}).to_stdout end end it "re-evaluates a deferred function in a cached catalog" do Puppet[:report] = false Puppet[:use_cached_catalog] = true Puppet[:usecacheonfailure] = false catalog_dir = File.join(Puppet[:client_datadir], 'catalog') Puppet::FileSystem.mkpath(catalog_dir) cached_catalog_path = "#{File.join(catalog_dir, Puppet[:certname])}.json" # our catalog contains a deferred function that calls `binary_file` # to read `source`. The function returns a Binary object, whose # base64 value is printed to stdout source = tmpfile('deferred_source') catalog = File.read(my_fixture('cached_deferred_catalog.json')) catalog.gsub!('__SOURCE_PATH__', source) File.write(cached_catalog_path, catalog) # verify we get a different result each time the deferred function # is evaluated, and reads `source`. { '1234' => 'MTIzNA==', '5678' => 'NTY3OA==' }.each_pair do |content, base64| File.write(source, content) expect { agent.command_line.args << '-t' agent.run }.to exit_with(2) .and output(/Notice: #{base64}/).to_stdout # reset state so we can run again Puppet::Application.clear! end end it "redacts sensitive values" do catalog_handler = -> (req, res) { catalog = compile_to_catalog(<<-MANIFEST, node) notify { 'sensitive': message => Sensitive('supersecret') } MANIFEST res.body = formatter.render(catalog) res['Content-Type'] = formatter.mime } server.start_server(mounts: {catalog: catalog_handler}) do |port| Puppet[:serverport] = port expect { agent.command_line.args << '--test' agent.run }.to exit_with(2) .and output(a_string_matching( /Notice: Sensitive \[value redacted\]/ ).and matching( /Notify\[sensitive\]\/message: changed \[redacted\] to \[redacted\]/ )).to_stdout end end it "applies binary data in a cached catalog" do catalog = compile_to_catalog(<<-MANIFEST, node) notify { 'some title': message => Binary.new('aGk=') } MANIFEST catalog_dir = File.join(Puppet[:client_datadir], 'catalog') Puppet::FileSystem.mkpath(catalog_dir) cached_catalog = "#{File.join(catalog_dir, Puppet[:certname])}.json" File.write(cached_catalog, catalog.render(:rich_data_json)) expect { Puppet[:report] = false Puppet[:use_cached_catalog] = true Puppet[:usecacheonfailure] = false agent.command_line.args << '-t' agent.run }.to exit_with(2) .and output(%r{defined 'message' as 'hi'}).to_stdout end end context 'static catalogs' do let(:path) { tmpfile('file') } let(:metadata) { Puppet::FileServing::Metadata.new(path) } let(:source) { "puppet:///modules/foo/foo.txt" } before :each do Puppet::FileSystem.touch(path) metadata.collect metadata.source = source metadata.content_uri = "puppet:///modules/foo/files/foo.txt" end it 'uses inline file metadata to determine the file is insync' do catalog_handler = -> (req, res) { catalog = compile_to_catalog(<<-MANIFEST, node) file { "#{path}": ensure => file, source => "#{source}" } MANIFEST catalog.metadata = { path => metadata } res.body = formatter.render(catalog) res['Content-Type'] = formatter.mime } server.start_server(mounts: {catalog: catalog_handler}) do |port| Puppet[:serverport] = port expect { expect { agent.command_line.args << '--test' agent.run }.to exit_with(0) }.to_not output(/content changed/).to_stdout end end it 'retrieves file content using the content_uri from the inlined file metadata' do # create file with binary content binary_content = "\xC0\xFF".force_encoding('binary') File.binwrite(path, binary_content) # recollect metadata metadata.collect # overwrite local file so it is no longer in sync File.binwrite(path, "") catalog_handler = -> (req, res) { catalog = compile_to_catalog(<<-MANIFEST, node) file { "#{path}": ensure => file, source => "#{source}", } MANIFEST catalog.metadata = { path => metadata } res.body = formatter.render(catalog) res['Content-Type'] = formatter.mime } static_file_content_handler = -> (req, res) { res.body = binary_content res['Content-Type'] = 'application/octet-stream' } mounts = { catalog: catalog_handler, static_file_content: static_file_content_handler } server.start_server(mounts: mounts) do |port| Puppet[:serverport] = port expect { agent.command_line.args << '--test' agent.run }.to exit_with(2) .and output(/content changed '{sha256}e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855' to '{sha256}3bef83ad320b471d8e3a03c9b9f150749eea610fe266560395d3195cfbd8e6b8'/).to_stdout # verify puppet restored binary content expect(File.binread(path)).to eq(binary_content) end end end context 'https file sources' do let(:path) { tmpfile('https_file_source') } let(:response_body) { "from https server" } let(:digest) { Digest::SHA1.hexdigest(response_body) } it 'rejects HTTPS servers whose root cert is not in the system CA store' do unknown_ca_cert = cert_fixture('unknown-ca.pem') https = PuppetSpec::HTTPSServer.new( ca_cert: unknown_ca_cert, server_cert: cert_fixture('unknown-127.0.0.1.pem'), server_key: key_fixture('unknown-127.0.0.1-key.pem') ) # create a temp cacert bundle ssl_file = tmpfile('systemstore') # add CA cert that is neither the puppet CA nor unknown CA File.write(ssl_file, cert_fixture('netlock-arany-utf8.pem').to_pem) https.start_server do |https_port| catalog_handler = -> (req, res) { catalog = compile_to_catalog(<<-MANIFEST, node) file { "#{path}": ensure => file, backup => false, checksum => sha1, checksum_value => '#{digest}', source => "https://127.0.0.1:#{https_port}/path/to/file" } MANIFEST res.body = formatter.render(catalog) res['Content-Type'] = formatter.mime } server.start_server(mounts: {catalog: catalog_handler}) do |puppetserver_port| Puppet[:serverport] = puppetserver_port # override path to system cacert bundle, this must be done before # the SSLContext is created and the call to X509::Store.set_default_paths Puppet::Util.withenv("SSL_CERT_FILE" => ssl_file) do expect { agent.command_line.args << '--test' agent.run }.to exit_with(4) .and output(/Notice: Applied catalog/).to_stdout .and output(%r{Error: Could not retrieve file metadata for https://127.0.0.1:#{https_port}/path/to/file: certificate verify failed}).to_stderr end expect(File).to_not be_exist(path) end end end it 'accepts HTTPS servers whose cert is in the system CA store' do unknown_ca_cert = cert_fixture('unknown-ca.pem') https = PuppetSpec::HTTPSServer.new( ca_cert: unknown_ca_cert, server_cert: cert_fixture('unknown-127.0.0.1.pem'), server_key: key_fixture('unknown-127.0.0.1-key.pem') ) # create a temp cacert bundle ssl_file = tmpfile('systemstore') File.write(ssl_file, unknown_ca_cert.to_pem) response_proc = -> (req, res) { res.status = 200 res.body = response_body } https.start_server(response_proc: response_proc) do |https_port| catalog_handler = -> (req, res) { catalog = compile_to_catalog(<<-MANIFEST, node) file { "#{path}": ensure => file, backup => false, checksum => sha1, checksum_value => '#{digest}', source => "https://127.0.0.1:#{https_port}/path/to/file" } MANIFEST res.body = formatter.render(catalog) res['Content-Type'] = formatter.mime } server.start_server(mounts: {catalog: catalog_handler}) do |puppetserver_port| Puppet[:serverport] = puppetserver_port # override path to system cacert bundle, this must be done before # the SSLContext is created and the call to X509::Store.set_default_paths Puppet::Util.withenv("SSL_CERT_FILE" => ssl_file) do expect { agent.command_line.args << '--test' agent.run }.to exit_with(2) .and output(%r{https_file_source.*/ensure: created}).to_stdout end expect(File.binread(path)).to eq("from https server") end end end it 'accepts HTTPS servers whose cert is in the external CA store' do unknown_ca_cert = cert_fixture('unknown-ca.pem') https = PuppetSpec::HTTPSServer.new( ca_cert: unknown_ca_cert, server_cert: cert_fixture('unknown-127.0.0.1.pem'), server_key: key_fixture('unknown-127.0.0.1-key.pem') ) # create a temp cacert bundle ssl_file = tmpfile('systemstore') File.write(ssl_file, unknown_ca_cert.to_pem) response_proc = -> (req, res) { res.status = 200 res.body = response_body } https.start_server(response_proc: response_proc) do |https_port| catalog_handler = -> (req, res) { catalog = compile_to_catalog(<<-MANIFEST, node) file { "#{path}": ensure => file, backup => false, checksum => sha1, checksum_value => '#{digest}', source => "https://127.0.0.1:#{https_port}/path/to/file" } MANIFEST res.body = formatter.render(catalog) res['Content-Type'] = formatter.mime } server.start_server(mounts: {catalog: catalog_handler}) do |puppetserver_port| Puppet[:serverport] = puppetserver_port # set path to external cacert bundle, this must be done before # the SSLContext is created Puppet[:ssl_trust_store] = ssl_file expect { agent.command_line.args << '--test' agent.run }.to exit_with(2) .and output(%r{https_file_source.*/ensure: created}).to_stdout end expect(File.binread(path)).to eq("from https server") end end end context 'multiple agents running' do def with_another_agent_running(&block) path = Puppet[:agent_catalog_run_lockfile] th = Thread.new { %x{ruby -e "$0 = 'puppet'; File.write('#{path}', Process.pid); sleep(5)"} } # ensure file is written before yielding until File.exist?(path) && File.size(path) > 0 do sleep 0.1 end begin yield ensure th.kill # kill thread so we don't wait too much end end it "exits if an agent is already running" do with_another_agent_running do expect { agent.command_line.args << '--test' agent.run }.to exit_with(1).and output(/Run of Puppet configuration client already in progress; skipping/).to_stdout end end it "waits for other agent run to finish before starting" do server.start_server do |port| Puppet[:serverport] = port Puppet[:waitforlock] = 1 with_another_agent_running do expect { agent.command_line.args << '--test' agent.run }.to exit_with(0) .and output(a_string_matching( /Info: Will try again in #{Puppet[:waitforlock]} seconds/ ).and matching( /Applied catalog/ )).to_stdout end end end it "exits if maxwaitforlock is exceeded" do Puppet[:waitforlock] = 1 Puppet[:maxwaitforlock] = 0 with_another_agent_running do expect { agent.command_line.args << '--test' agent.run }.to exit_with(1).and output(/Exiting now because the maxwaitforlock timeout has been exceeded./).to_stdout end end end context 'cached catalogs' do it 'falls back to a cached catalog' do catalog_handler = -> (req, res) { catalog = compile_to_catalog(<<-MANIFEST, node) notify { 'a message': } MANIFEST res.body = formatter.render(catalog) res['Content-Type'] = formatter.mime } server.start_server(mounts: {catalog: catalog_handler}) do |port| Puppet[:serverport] = port expect { agent.command_line.args << '--test' agent.run }.to exit_with(2) .and output(%r{Caching catalog for #{Puppet[:certname]}}).to_stdout end # reset state so we can run again Puppet::Application.clear! # --test above turns off `usecacheonfailure` so re-enable here Puppet[:usecacheonfailure] = true # run agent without server expect { agent.command_line.args << '--no-daemonize' << '--onetime' << '--server' << '127.0.0.1' agent.run }.to exit_with(2) .and output(a_string_matching( /Using cached catalog from environment 'production'/ ).and matching( /Notify\[a message\]\/message:/ )).to_stdout .and output(/No more routes to fileserver/).to_stderr end it 'preserves the old cached catalog if validation fails with the old one' do catalog_handler = -> (req, res) { catalog = compile_to_catalog(<<-MANIFEST, node) exec { 'unqualified_command': } MANIFEST res.body = formatter.render(catalog) res['Content-Type'] = formatter.mime } server.start_server(mounts: {catalog: catalog_handler}) do |port| Puppet[:serverport] = port expect { agent.command_line.args << '--test' agent.run }.to exit_with(1) .and output(%r{Retrieving plugin}).to_stdout .and output(%r{Validation of Exec\[unqualified_command\] failed: 'unqualified_command' is not qualified and no path was specified}).to_stderr end # cached catalog should not be updated cached_catalog = "#{File.join(Puppet[:client_datadir], 'catalog', Puppet[:certname])}.json" expect(File).to_not be_exist(cached_catalog) end end context "reporting" do it "stores a finalized report" do catalog_handler = -> (req, res) { catalog = compile_to_catalog(<<-MANIFEST, node) notify { 'foo': require => Notify['bar'] } notify { 'bar': require => Notify['foo'] } MANIFEST res.body = formatter.render(catalog) res['Content-Type'] = formatter.mime } server.start_server(mounts: {catalog: catalog_handler}) do |port| Puppet[:serverport] = port expect { agent.command_line.args << '--test' agent.run }.to exit_with(1) .and output(%r{Applying configuration}).to_stdout .and output(%r{Found 1 dependency cycle}).to_stderr report = Puppet::Transaction::Report.convert_from(:yaml, File.read(Puppet[:lastrunreport])) expect(report.status).to eq("failed") expect(report.metrics).to_not be_empty end end it "caches a report even if the REST request fails" do server.start_server do |port| Puppet[:serverport] = port Puppet[:report_port] = "-1" expect { agent.command_line.args << '--test' agent.run }.to exit_with(0) .and output(%r{Applied catalog}).to_stdout .and output(%r{Could not send report}).to_stderr report = Puppet::Transaction::Report.convert_from(:yaml, File.read(Puppet[:lastrunreport])) expect(report).to be end end end context "environment convergence" do it "falls back to making a node request if the last server-specified environment cannot be loaded" do mounts = {} mounts[:node] = -> (req, res) { node = Puppet::Node.new('test', environment: Puppet::Node::Environment.remote('doesnotexistonagent')) res.body = formatter.render(node) res['Content-Type'] = formatter.mime } server.start_server(mounts: mounts) do |port| Puppet[:serverport] = port Puppet[:log_level] = 'debug' expect { agent.command_line.args << '--test' agent.run }.to exit_with(0) .and output(a_string_matching(%r{Debug: Requesting environment from the server})).to_stdout Puppet::Application.clear! expect { agent.command_line.args << '--test' agent.run }.to exit_with(0) .and output(a_string_matching(%r{Debug: Successfully loaded last environment from the lastrunfile})).to_stdout end end it "switches to 'newenv' environment and retries the run" do first_run = true libdir = File.join(my_fixture_dir, 'lib') # we have to use the :facter terminus to reliably test that pluginsynced # facts are included in the catalog request Puppet::Node::Facts.indirection.terminus_class = :facter mounts = {} # During the first run, only return metadata for the top-level directory. # During the second run, include metadata for all of the 'lib' fixtures # due to the `recurse` option. mounts[:file_metadatas] = -> (req, res) { request = Puppet::FileServing::Metadata.indirection.request( :search, libdir, nil, recurse: !first_run ) data = Puppet::FileServing::Metadata.indirection.terminus(:file).search(request) res.body = formatter.render(data) res['Content-Type'] = formatter.mime } mounts[:file_content] = -> (req, res) { request = Puppet::FileServing::Content.indirection.request( :find, File.join(libdir, 'facter', 'agent_spec_role.rb'), nil ) content = Puppet::FileServing::Content.indirection.terminus(:file).find(request) res.body = content.content res['Content-Length'] = content.content.length res['Content-Type'] = 'application/octet-stream' } # During the first run, return an empty catalog referring to the newenv. # During the second run, compile a catalog that depends on a fact that # only exists in the second environment. If the fact is missing/empty, # then compilation will fail since resources can't have an empty title. mounts[:catalog] = -> (req, res) { node = Puppet::Node.new('test') code = if first_run first_run = false '' else data = CGI.unescape(req.query['facts']) facts = Puppet::Node::Facts.convert_from('json', data) node.fact_merge(facts) 'notify { $facts["agent_spec_role"]: }' end catalog = compile_to_catalog(code, node) catalog.environment = 'newenv' res.body = formatter.render(catalog) res['Content-Type'] = formatter.mime } server.start_server(mounts: mounts) do |port| Puppet[:serverport] = port expect { agent.command_line.args << '--test' agent.run }.to exit_with(2) .and output(a_string_matching(%r{Notice: Local environment: 'production' doesn't match server specified environment 'newenv', restarting agent run with environment 'newenv'}) .and matching(%r{defined 'message' as 'web'})).to_stdout end end end context "ssl" do context "bootstrapping" do before :each do # reconfigure ssl to non-existent dir and files to force bootstrapping dir = tmpdir('ssl') Puppet[:ssldir] = dir Puppet[:localcacert] = File.join(dir, 'ca.pem') Puppet[:hostcrl] = File.join(dir, 'crl.pem') Puppet[:hostprivkey] = File.join(dir, 'cert.pem') Puppet[:hostcert] = File.join(dir, 'key.pem') Puppet[:daemonize] = false Puppet[:logdest] = 'console' Puppet[:log_level] = 'info' end it "exits if the agent is not allowed to wait" do Puppet[:waitforcert] = 0 server.start_server do |port| Puppet[:serverport] = port expect { agent.run }.to exit_with(1) .and output(%r{Exiting now because the waitforcert setting is set to 0}).to_stdout .and output(%r{Failed to submit the CSR, HTTP response was 404}).to_stderr end end it "exits if the maxwaitforcert time is exceeded" do Puppet[:waitforcert] = 1 Puppet[:maxwaitforcert] = 1 server.start_server do |port| Puppet[:serverport] = port expect { agent.run }.to exit_with(1) .and output(%r{Couldn't fetch certificate from CA server; you might still need to sign this agent's certificate \(127.0.0.1\). Exiting now because the maxwaitforcert timeout has been exceeded.}).to_stdout .and output(%r{Failed to submit the CSR, HTTP response was 404}).to_stderr end end end it "reloads the CRL between runs" do Puppet[:hostcert] = cert = tmpfile('cert') Puppet[:hostprivkey] = key = tmpfile('key') copy_fixtures(%w[127.0.0.1.pem], cert) copy_fixtures(%w[127.0.0.1-key.pem], key) revoked = cert_fixture('revoked.pem') revoked_key = key_fixture('revoked-key.pem') mounts = {} mounts[:catalog] = -> (req, res) { catalog = compile_to_catalog(<<~MANIFEST, node) file { '#{cert}': ensure => file, content => '#{revoked}' } file { '#{key}': ensure => file, content => '#{revoked_key}' } MANIFEST res.body = formatter.render(catalog) res['Content-Type'] = formatter.mime } server.start_server(mounts: mounts) do |port| Puppet[:serverport] = port Puppet[:daemonize] = false Puppet[:runinterval] = 1 Puppet[:waitforcert] = 1 Puppet[:maxwaitforcert] = 1 # simulate two runs of the agent, then return so we don't infinite loop allow_any_instance_of(Puppet::Daemon).to receive(:run_event_loop) do |instance| instance.agent.run(splay: false) instance.agent.run(splay: false) end agent.command_line.args << '--verbose' expect { agent.run }.to exit_with(1) .and output(%r{Exiting now because the maxwaitforcert timeout has been exceeded}).to_stdout .and output(%r{Certificate 'CN=revoked' is revoked}).to_stderr end end it "refreshes the CA and CRL" do now = Time.now yesterday = now - (60 * 60 * 24) Puppet::FileSystem.touch(Puppet[:localcacert], mtime: yesterday) Puppet::FileSystem.touch(Puppet[:hostcrl], mtime: yesterday) server.start_server do |port| Puppet[:serverport] = port Puppet[:ca_refresh_interval] = 1 expect { agent.command_line.args << '--test' agent.run }.to exit_with(0) .and output(/Info: Refreshed CA certificate: /).to_stdout end # If the CA is updated, then the CRL must be updated too expect(Puppet::FileSystem.stat(Puppet[:localcacert]).mtime).to be >= now expect(Puppet::FileSystem.stat(Puppet[:hostcrl]).mtime).to be >= now end it "refreshes only the CRL" do now = Time.now tomorrow = now + (60 * 60 * 24) Puppet::FileSystem.touch(Puppet[:localcacert], mtime: tomorrow) yesterday = now - (60 * 60 * 24) Puppet::FileSystem.touch(Puppet[:hostcrl], mtime: yesterday) server.start_server do |port| Puppet[:serverport] = port Puppet[:crl_refresh_interval] = 1 expect { agent.command_line.args << '--test' agent.run }.to exit_with(0) .and output(/Info: Refreshed CRL: /).to_stdout end expect(Puppet::FileSystem.stat(Puppet[:hostcrl]).mtime).to be >= now end end context "legacy facts" do let(:mod_dir) { tmpdir('module_dir') } let(:custom_dir) { File.join(mod_dir, 'lib') } let(:external_dir) { File.join(mod_dir, 'facts.d') } before(:each) do # don't stub facter behavior, since we're relying on
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
true
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/application/apply_spec.rb
spec/integration/application/apply_spec.rb
require 'spec_helper' require 'puppet_spec/files' require 'puppet_spec/compiler' require 'puppet_spec/https' describe "apply", unless: Puppet::Util::Platform.jruby? do include PuppetSpec::Files let(:apply) { Puppet::Application[:apply] } before :each do Puppet[:reports] = "none" # Let exceptions be raised instead of exiting allow_any_instance_of(Puppet::Application).to receive(:exit_on_fail).and_yield end describe "when applying provided catalogs" do it "can apply catalogs provided in a file in json" do file_to_create = tmpfile("json_catalog") catalog = Puppet::Resource::Catalog.new('mine', Puppet.lookup(:environments).get(Puppet[:environment])) resource = Puppet::Resource.new(:file, file_to_create, :parameters => {:content => "my stuff"}) catalog.add_resource resource apply.command_line.args = ['--catalog', file_containing("manifest", catalog.to_json)] expect { apply.run }.to output(/ensure: defined content as/).to_stdout expect(Puppet::FileSystem.exist?(file_to_create)).to be_truthy expect(File.read(file_to_create)).to eq("my stuff") end context 'and pcore types are available' do let(:envdir) { my_fixture('environments') } let(:env_name) { 'spec' } before(:each) do Puppet[:environmentpath] = envdir Puppet[:environment] = env_name end it 'does not load the pcore type' do apply = Puppet::Application[:apply] apply.command_line.args = [ '-e', "Applytest { message => 'the default'} applytest { 'applytest was here': }" ] expect { apply.run }.to exit_with(0) .and output(a_string_matching( /the Puppet::Type says hello/ ).and matching( /applytest was here/ )).to_stdout end end context 'from environment with a pcore defined resource type' do include PuppetSpec::Compiler let(:envdir) { my_fixture('environments') } let(:env_name) { 'spec' } let(:environments) { Puppet::Environments::Directories.new(envdir, []) } let(:env) { Puppet::Node::Environment.create(:'spec', [File.join(envdir, 'spec', 'modules')]) } let(:node) { Puppet::Node.new('test', :environment => env) } around(:each) do |example| Puppet::Type.rmtype(:applytest) Puppet[:environment] = env_name Puppet.override(:environments => environments, :current_environment => env) do example.run end end it 'does not load the pcore type' do catalog = compile_to_catalog('applytest { "applytest was here":}', node) apply.command_line.args = ['--catalog', file_containing('manifest', catalog.to_json)] Puppet[:environmentpath] = envdir expect_any_instance_of(Puppet::Pops::Loader::Runtime3TypeLoader).not_to receive(:find) expect { apply.run }.to output(/the Puppet::Type says hello.*applytest was here/m).to_stdout end # Test just to verify that the Pcore Resource Type and not the Ruby one is produced when the catalog is produced it 'loads pcore resource type instead of ruby resource type during compile' do Puppet[:code] = 'applytest { "applytest was here": }' compiler = Puppet::Parser::Compiler.new(node) tn = Puppet::Pops::Loader::TypedName.new(:resource_type_pp, 'applytest') rt = Puppet::Pops::Resource::ResourceTypeImpl.new('applytest', [Puppet::Pops::Resource::Param.new(String, 'message')], [Puppet::Pops::Resource::Param.new(String, 'name', true)]) expect(compiler.loaders.runtime3_type_loader.instance_variable_get(:@resource_3x_loader)).to receive(:set_entry).once.with(tn, rt, instance_of(String)) .and_return(Puppet::Pops::Loader::Loader::NamedEntry.new(tn, rt, nil)) expect { compiler.compile }.not_to output(/the Puppet::Type says hello/).to_stdout end it "does not fail when pcore type is loaded twice" do Puppet[:code] = 'applytest { xyz: alias => aptest }; Resource[applytest]' compiler = Puppet::Parser::Compiler.new(node) expect { compiler.compile }.not_to raise_error end it "does not load the ruby type when using function 'defined()' on a loaded resource that is missing from the catalog" do # Ensure that the Resource[applytest,foo] is loaded' eval_and_collect_notices('applytest { xyz: }', node) # Ensure that: # a) The catalog contains aliases (using a name for the abc resource ensures this) # b) That Resource[applytest,xyz] is not defined in the catalog (although it's loaded) # c) That this doesn't trigger a load of the Puppet::Type notices = eval_and_collect_notices('applytest { abc: name => some_alias }; notice(defined(Resource[applytest,xyz]))', node) expect(notices).to include('false') expect(notices).not_to include('the Puppet::Type says hello') end it 'does not load the ruby type when when referenced from collector during compile' do notices = eval_and_collect_notices("@applytest { 'applytest was here': }\nApplytest<| title == 'applytest was here' |>", node) expect(notices).not_to include('the Puppet::Type says hello') end it 'does not load the ruby type when when referenced from exported collector during compile' do notices = eval_and_collect_notices("@@applytest { 'applytest was here': }\nApplytest<<| |>>", node) expect(notices).not_to include('the Puppet::Type says hello') end end end context 'from environment with pcore object types' do include PuppetSpec::Compiler let!(:envdir) { Puppet[:environmentpath] } let(:env_name) { 'spec' } let(:dir_structure) { { 'environment.conf' => <<-CONF, rich_data = true CONF 'modules' => { 'mod' => { 'types' => { 'streetaddress.pp' => <<-PUPPET, type Mod::StreetAddress = Object[{ attributes => { 'street' => String, 'zipcode' => String, 'city' => String, } }] PUPPET 'address.pp' => <<-PUPPET, type Mod::Address = Object[{ parent => Mod::StreetAddress, attributes => { 'state' => String } }] PUPPET 'contact.pp' => <<-PUPPET, type Mod::Contact = Object[{ attributes => { 'address' => Mod::Address, 'email' => String } }] PUPPET }, 'manifests' => { 'init.pp' => <<-PUPPET, define mod::person(Mod::Contact $contact) { notify { $title: } notify { $contact.address.street: } notify { $contact.address.zipcode: } notify { $contact.address.city: } notify { $contact.address.state: } } class mod { mod::person { 'Test Person': contact => Mod::Contact( Mod::Address('The Street 23', '12345', 'Some City', 'A State'), 'test@example.com') } } PUPPET } } } } } let(:env) { Puppet::Node::Environment.create(env_name.to_sym, [File.join(envdir, env_name, 'modules')]) } let(:node) { Puppet::Node.new('test', :environment => env) } before(:each) do dir_contained_in(envdir, env_name => dir_structure) PuppetSpec::Files.record_tmp(File.join(envdir, env_name)) end it 'can compile the catalog' do compile_to_catalog('include mod', node) end it 'can apply the catalog with no warning' do logs = [] Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do catalog = compile_to_catalog('include mod', node) Puppet[:environment] = env_name handler = Puppet::Network::FormatHandler.format(:rich_data_json) apply.command_line.args = ['--catalog', file_containing('manifest', handler.render(catalog))] expect { apply.run }.to output(%r{Notify\[The Street 23\]/message: defined 'message' as 'The Street 23'}).to_stdout end # expected to have no warnings expect(logs.select { |log| log.level == :warning }.map { |log| log.message }).to be_empty end end it "raises if the environment directory does not exist" do manifest = file_containing("manifest.pp", "notice('it was applied')") apply.command_line.args = [manifest] special = Puppet::Node::Environment.create(:special, []) Puppet.override(:current_environment => special) do Puppet[:environment] = 'special' expect { apply.run }.to raise_error(Puppet::Environments::EnvironmentNotFound, /Could not find a directory environment named 'special' anywhere in the path/) end end it "adds environment to the $server_facts variable" do manifest = file_containing("manifest.pp", "notice(\"$server_facts\")") apply.command_line.args = [manifest] expect { apply.run }.to exit_with(0) .and output(/{environment => production}/).to_stdout end it "applies a given file even when an ENC is configured", :unless => Puppet::Util::Platform.windows? || Puppet::Util::Platform.jruby? do manifest = file_containing("manifest.pp", "notice('specific manifest applied')") enc = script_containing('enc_script', :windows => '@echo classes: []' + "\n" + '@echo environment: special', :posix => '#!/bin/sh' + "\n" + 'echo "classes: []"' + "\n" + 'echo "environment: special"') Dir.mkdir(File.join(Puppet[:environmentpath], "special"), 0755) special = Puppet::Node::Environment.create(:special, []) Puppet.override(:current_environment => special) do Puppet[:environment] = 'special' Puppet[:node_terminus] = 'exec' Puppet[:external_nodes] = enc apply.command_line.args = [manifest] expect { apply.run }.to exit_with(0) .and output(/Notice: Scope\(Class\[main\]\): specific manifest applied/).to_stdout end end context "handles errors" do it "logs compile errors once" do apply.command_line.args = ['-e', '08'] expect { apply.run }.to exit_with(1) .and output(/Not a valid octal number/).to_stderr end it "logs compile post processing errors once" do path = File.expand_path('/tmp/content_file_test.Q634Dlmtime') apply.command_line.args = ['-e', "file { '#{path}': content => 'This is the test file content', ensure => present, checksum => mtime }"] expect { apply.run }.to exit_with(1) .and output(/Compiled catalog/).to_stdout .and output(/You cannot specify content when using checksum/).to_stderr end end context "with a module in an environment" do let(:envdir) { tmpdir('environments') } let(:modulepath) { File.join(envdir, 'spec', 'modules') } let(:execute) { 'include amod' } before(:each) do dir_contained_in(envdir, { "spec" => { "modules" => { "amod" => { "manifests" => { "init.pp" => "class amod{ notice('amod class included') }" } } } } }) Puppet[:environmentpath] = envdir end context "given a modulepath" do let(:args) { ['-e', execute] } before :each do Puppet[:modulepath] = modulepath apply.command_line.args = args end it "looks in modulepath even when the default directory environment exists" do expect { apply.run }.to exit_with(0) .and output(/amod class included/).to_stdout end it "looks in modulepath even when given a specific directory --environment" do apply.command_line.args = args << '--environment' << 'production' expect { apply.run }.to exit_with(0) .and output(/amod class included/).to_stdout end it "looks in modulepath when given multiple paths in modulepath" do Puppet[:modulepath] = [tmpdir('notmodulepath'), modulepath].join(File::PATH_SEPARATOR) expect { apply.run }.to exit_with(0) .and output(/amod class included/).to_stdout end end context "with an ENC" do let(:enc) do script_containing('enc_script', :windows => '@echo environment: spec', :posix => '#!/bin/sh' + "\n" + 'echo "environment: spec"') end before :each do Puppet[:node_terminus] = 'exec' Puppet[:external_nodes] = enc end it "should use the environment that the ENC mandates" do apply.command_line.args = ['-e', execute] expect { apply.run }.to exit_with(0) .and output(a_string_matching(/amod class included/) .and matching(/Compiled catalog for .* in environment spec/)).to_stdout end it "should prefer the ENC environment over the configured one and emit a warning" do apply.command_line.args = ['-e', execute, '--environment', 'production'] expect { apply.run }.to exit_with(0) .and output(a_string_matching('amod class included') .and matching(/doesn't match server specified environment/)).to_stdout end end end context 'when applying from file' do include PuppetSpec::Compiler let(:env_dir) { tmpdir('environments') } let(:execute) { 'include amod' } let(:rich_data) { false } let(:env_name) { 'spec' } let(:populated_env_dir) do dir_contained_in(env_dir, { env_name => { 'modules' => { 'amod' => { 'manifests' => { 'init.pp' => <<-EOF class amod { notify { rx: message => /[Rr]eg[Ee]xp/ } notify { bin: message => Binary('w5ZzdGVuIG1lZCByw7ZzdGVuCg==') } notify { ver: message => SemVer('2.3.1') } notify { vrange: message => SemVerRange('>=2.3.0') } notify { tspan: message => Timespan(3600) } notify { tstamp: message => Timestamp('2012-03-04T18:15:11.001') } } class amod::bad_type { notify { bogus: message => amod::bogus() } } EOF }, 'lib' => { 'puppet' => { 'functions' => { 'amod' => { 'bogus.rb' => <<-RUBY # Function that leaks an object that is not recognized in the catalog Puppet::Functions.create_function(:'amod::bogus') do def bogus() Time.new(2016, 10, 6, 23, 51, 14, '+02:00') end end RUBY } } } } } } } }) env_dir end let(:env) { Puppet::Node::Environment.create(env_name.to_sym, [File.join(populated_env_dir, 'spec', 'modules')]) } let(:node) { Puppet::Node.new('test', :environment => env) } before(:each) do Puppet[:rich_data] = rich_data Puppet.push_context(:loaders => Puppet::Pops::Loaders.new(env)) end after(:each) do Puppet.pop_context() end context 'and the file is not serialized with rich_data' do # do not want to stub out behavior in tests before :each do Puppet[:strict] = :warning end around :each do |test| Puppet.override(rich_data: false) do test.run end end it 'will notify a string that is the result of Regexp#inspect (from Runtime3xConverter)' do catalog = compile_to_catalog(execute, node) apply.command_line.args = ['--catalog', file_containing('manifest', catalog.to_json)] expect(apply).to receive(:apply_catalog) do |cat| expect(cat.resource(:notify, 'rx')['message']).to be_a(String) expect(cat.resource(:notify, 'bin')['message']).to be_a(String) expect(cat.resource(:notify, 'ver')['message']).to be_a(String) expect(cat.resource(:notify, 'vrange')['message']).to be_a(String) expect(cat.resource(:notify, 'tspan')['message']).to be_a(String) expect(cat.resource(:notify, 'tstamp')['message']).to be_a(String) end apply.run end it 'will notify a string that is the result of to_s on uknown data types' do json = compile_to_catalog('include amod::bad_type', node).to_json apply.command_line.args = ['--catalog', file_containing('manifest', json)] expect(apply).to receive(:apply_catalog) do |catalog| expect(catalog.resource(:notify, 'bogus')['message']).to be_a(String) end apply.run end it 'will log a warning that a value of unknown type is converted into a string' do logs = [] Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do compile_to_catalog('include amod::bad_type', node).to_json end logs = logs.select { |log| log.level == :warning }.map { |log| log.message } expect(logs.empty?).to be_falsey expect(logs[0]).to eql("Notify[bogus]['message'] contains a Time value. It will be converted to the String '2016-10-06 23:51:14 +0200'") end end context 'and the file is serialized with rich_data' do it 'will notify a regexp using Regexp#to_s' do catalog = compile_to_catalog(execute, node) serialized_catalog = Puppet.override(rich_data: true) do catalog.to_json end apply.command_line.args = ['--catalog', file_containing('manifest', serialized_catalog)] expect(apply).to receive(:apply_catalog) do |cat| expect(cat.resource(:notify, 'rx')['message']).to be_a(Regexp) # The resource return in this expect is a String, but since it was a Binary type that # was converted with `resolve_and_replace`, we want to make sure that the encoding # of that string is the expected ASCII-8BIT. expect(cat.resource(:notify, 'bin')['message'].encoding.inspect).to include('ASCII-8BIT') expect(cat.resource(:notify, 'ver')['message']).to be_a(SemanticPuppet::Version) expect(cat.resource(:notify, 'vrange')['message']).to be_a(SemanticPuppet::VersionRange) expect(cat.resource(:notify, 'tspan')['message']).to be_a(Puppet::Pops::Time::Timespan) expect(cat.resource(:notify, 'tstamp')['message']).to be_a(Puppet::Pops::Time::Timestamp) end apply.run end end end context 'puppet file sources' do let(:env_name) { 'dev' } let(:env_dir) { File.join(Puppet[:environmentpath], env_name) } let(:env) { Puppet::Node::Environment.create(env_name.to_sym, [File.join(env_dir, 'modules')]) } let(:node) { Puppet::Node.new(Puppet[:certname], environment: environment) } before :each do Puppet[:environment] = env_name Puppet::FileSystem.mkpath(env_dir) end it "recursively copies a directory from a module" do dir = File.join(env.full_modulepath, 'amod', 'files', 'dir1', 'dir2') Puppet::FileSystem.mkpath(dir) File.write(File.join(dir, 'file'), 'content from the module') base_dir = tmpdir('apply_spec_base') manifest = file_containing("manifest.pp", <<-MANIFEST) file { "#{base_dir}/dir1": ensure => file, source => "puppet:///modules/amod/dir1", recurse => true, } MANIFEST expect { apply.command_line.args << manifest apply.run }.to exit_with(0) .and output(a_string_matching( /dir1\]\/ensure: created/ ).and matching( /dir1\/dir2\]\/ensure: created/ ).and matching( /dir1\/dir2\/file\]\/ensure: defined content as '{sha256}b37c1d77e09471b3139b2cdfee449fd8ba72ebf7634d52023aff0c0cd088cf1b'/ )).to_stdout dest_file = File.join(base_dir, 'dir1', 'dir2', 'file') expect(File.read(dest_file)).to eq("content from the module") end end context 'http file sources' do include_context 'https client' it "requires the caller to URL encode special characters in the request path and query" do Puppet[:server] = '127.0.0.1' request = nil response_proc = -> (req, res) { request = req res['Content-Type'] = 'text/plain' res.body = "from the server" } https = PuppetSpec::HTTPSServer.new https.start_server(response_proc: response_proc) do |https_port| dest = tmpfile('http_file_source') # spaces in path are encoded as %20 and '[' in query is encoded as %5B, # but ':', '=', '-' are not encoded manifest = file_containing("manifest.pp", <<~MANIFEST) file { "#{dest}": ensure => file, source => "https://#{Puppet[:server]}:#{https_port}/path%20to%20file?x=b%5Bc&sv=2019-02-02&st=2020-07-28T20:18:53Z&se=2020-07-28T21:03:00Z&sr=b&sp=r&sig=JaZhcqxT4akJcOwUdUGrQB2m1geUoh89iL8WMag8a8c=", } MANIFEST expect { apply.command_line.args << manifest apply.run }.to exit_with(0) .and output(%r{Main/File\[#{dest}\]/ensure: defined content as}).to_stdout expect(request.path).to eq('/path to file') expect(request.query).to include('x' => 'b[c') expect(request.query).to include('sig' => 'JaZhcqxT4akJcOwUdUGrQB2m1geUoh89iL8WMag8a8c=') end end end context 'http report processor' do include_context 'https client' before :each do Puppet[:reports] = 'http' end let(:unknown_server) do unknown_ca_cert = cert_fixture('unknown-ca.pem') PuppetSpec::HTTPSServer.new( ca_cert: unknown_ca_cert, server_cert: cert_fixture('unknown-127.0.0.1.pem'), server_key: key_fixture('unknown-127.0.0.1-key.pem') ) end it 'submits a report via reporturl' do report = nil response_proc = -> (req, res) { report = Puppet::Transaction::Report.convert_from(:yaml, req.body) } https = PuppetSpec::HTTPSServer.new https.start_server(response_proc: response_proc) do |https_port| Puppet[:reporturl] = "https://127.0.0.1:#{https_port}/reports/upload" expect { apply.command_line.args = ['-e', 'notify { "hi": }'] apply.run }.to exit_with(0) .and output(/Applied catalog/).to_stdout expect(report).to be_a(Puppet::Transaction::Report) expect(report.resource_statuses['Notify[hi]']).to be_a(Puppet::Resource::Status) end end it 'rejects an HTTPS report server whose root cert is not the puppet CA' do unknown_server.start_server do |https_port| Puppet[:reporturl] = "https://127.0.0.1:#{https_port}/reports/upload" # processing the report happens after the transaction is finished, # so we expect exit code 0, with a later failure on stderr expect { apply.command_line.args = ['-e', 'notify { "hi": }'] apply.run }.to exit_with(0) .and output(/Applied catalog/).to_stdout .and output(/Report processor failed: certificate verify failed \[self.signed certificate in certificate chain for CN=Unknown CA\]/).to_stderr end end it 'accepts an HTTPS report servers whose cert is in the system CA store' do Puppet[:report_include_system_store] = true report = nil response_proc = -> (req, res) { report = Puppet::Transaction::Report.convert_from(:yaml, req.body) } # create a temp cacert bundle ssl_file = tmpfile('systemstore') File.write(ssl_file, unknown_server.ca_cert.to_pem) unknown_server.start_server(response_proc: response_proc) do |https_port| Puppet[:reporturl] = "https://127.0.0.1:#{https_port}/reports/upload" # override path to system cacert bundle, this must be done before # the SSLContext is created and the call to X509::Store.set_default_paths Puppet::Util.withenv("SSL_CERT_FILE" => ssl_file) do expect { apply.command_line.args = ['-e', 'notify { "hi": }'] apply.run }.to exit_with(0) .and output(/Applied catalog/).to_stdout end expect(report).to be_a(Puppet::Transaction::Report) expect(report.resource_statuses['Notify[hi]']).to be_a(Puppet::Resource::Status) end end end context 'rich data' do let(:deferred_file) { tmpfile('deferred') } let(:deferred_manifest) do <<~END file { '#{deferred_file}': ensure => file, content => '123', } -> notify { 'deferred': message => Deferred('binary_file', ['#{deferred_file}']) } END end it "calls a deferred 4x function" do apply.command_line.args = ['-e', 'notify { "deferred3x": message => Deferred("join", [[1,2,3], ":"]) }'] expect { apply.run }.to exit_with(0) # for some reason apply returns 0 instead of 2 .and output(%r{Notice: /Stage\[main\]/Main/Notify\[deferred3x\]/message: defined 'message' as '1:2:3'}).to_stdout end it "calls a deferred 3x function" do apply.command_line.args = ['-e', 'notify { "deferred4x": message => Deferred("sprintf", ["%s", "I am deferred"]) }'] expect { apply.run }.to exit_with(0) # for some reason apply returns 0 instead of 2 .and output(%r{Notice: /Stage\[main\]/Main/Notify\[deferred4x\]/message: defined 'message' as 'I am deferred'}).to_stdout end it "fails to apply a deferred function with an unsatisfied prerequisite" do Puppet[:preprocess_deferred] = true apply.command_line.args = ['-e', deferred_manifest] expect { apply.run }.to exit_with(1) # for some reason apply returns 0 instead of 2 .and output(/Compiled catalog/).to_stdout .and output(%r{The given file '#{deferred_file}' does not exist}).to_stderr end it "applies a deferred function and its prerequisite in the same run" do apply.command_line.args = ['-e', deferred_manifest] expect { apply.run }.to exit_with(0) # for some reason apply returns 0 instead of 2 .and output(%r{defined 'message' as Binary\("MTIz"\)}).to_stdout end it "validates the deferred resource before applying any resources" do Puppet[:preprocess_deferred] = true undeferred_file = tmpfile('undeferred') manifest = <<~END file { '#{undeferred_file}': ensure => file, } file { '#{deferred_file}': ensure => file, content => Deferred('inline_epp', ['<%= 42 %>']), source => 'http://example.com/content', } END apply.command_line.args = ['-e', manifest] expect { apply.run }.to exit_with(1) .and output(/Compiled catalog/).to_stdout .and output(/Validation of File.* failed: You cannot specify more than one of content, source, target/).to_stderr # validation happens before all resources are applied, so this shouldn't exist expect(File).to_not be_exist(undeferred_file) end it "evaluates resources before validating the deferred resource" do manifest = <<~END notify { 'runs before file': } -> file { '#{deferred_file}': ensure => file, content => Deferred('inline_epp', ['<%= 42 %>']), source => 'http://example.com/content', } END apply.command_line.args = ['-e', manifest] expect { apply.run }.to exit_with(1) .and output(/Notify\[runs before file\]/).to_stdout .and output(/Validation of File.* failed: You cannot specify more than one of content, source, target/).to_stderr end it "applies deferred sensitive file content" do manifest = <<~END file { '#{deferred_file}': ensure => file, content => Deferred('new', [Sensitive, "hello\n"]) } END apply.command_line.args = ['-e', manifest] expect { apply.run }.to exit_with(0) .and output(/ensure: changed \[redacted\] to \[redacted\]/).to_stdout end it "applies nested deferred sensitive file content" do manifest = <<~END $vars = {'token' => Deferred('new', [Sensitive, "hello"])} file { '#{deferred_file}': ensure => file, content => Deferred('inline_epp', ['<%= $token %>', $vars]) } END apply.command_line.args = ['-e', manifest] expect { apply.run }.to exit_with(0) .and output(/ensure: changed \[redacted\] to \[redacted\]/).to_stdout end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/application/filebucket_spec.rb
spec/integration/application/filebucket_spec.rb
require 'spec_helper' require 'puppet/face' require 'puppet_spec/puppetserver' require 'puppet_spec/files' describe "puppet filebucket", unless: Puppet::Util::Platform.jruby? do include PuppetSpec::Files include_context "https client" let(:server) { PuppetSpec::Puppetserver.new } let(:filebucket) { Puppet::Application[:filebucket] } let(:backup_file) { tmpfile('backup_file') } let(:text) { 'some random text' } let(:sha256) { Digest::SHA256.file(backup_file).to_s } before :each do Puppet[:log_level] = 'debug' File.binwrite(backup_file, text) end after :each do # mute debug messages generated during `after :each` blocks Puppet::Util::Log.close_all end it "backs up to and restores from the local filebucket" do filebucket.command_line.args = ['backup', backup_file, '--local'] expect { filebucket.run }.to output(/: #{sha256}/).to_stdout dest = tmpfile('file_bucket_restore') filebucket.command_line.args = ['restore', dest, sha256, '--local'] expect { filebucket.run }.to output(/FileBucket read #{sha256}/).to_stdout expect(FileUtils.compare_file(backup_file, dest)).to eq(true) end it "backs up text files to the filebucket server" do server.start_server do |port| Puppet[:serverport] = port expect { filebucket.command_line.args = ['backup', backup_file] filebucket.run }.to output(a_string_matching( %r{Debug: HTTP HEAD https:\/\/127.0.0.1:#{port}\/puppet\/v3\/file_bucket_file\/sha256\/#{sha256}\/#{File.realpath(backup_file)}\?environment\=production returned 404 Not Found} ).and matching( %r{Debug: HTTP PUT https:\/\/127.0.0.1:#{port}\/puppet\/v3\/file_bucket_file\/sha256\/#{sha256}\/#{File.realpath(backup_file)}\?environment\=production returned 200 OK} ).and matching( %r{#{backup_file}: #{sha256}} )).to_stdout expect(File.binread(File.join(server.upload_directory, 'filebucket'))).to eq(text) end end it "backs up binary files to the filebucket server" do binary = "\xD1\xF2\r\n\x81NuSc\x00".force_encoding(Encoding::ASCII_8BIT) File.binwrite(backup_file, binary) server.start_server do |port| Puppet[:serverport] = port expect { filebucket.command_line.args = ['backup', backup_file] filebucket.run }.to output(a_string_matching( %r{Debug: HTTP HEAD https:\/\/127.0.0.1:#{port}\/puppet\/v3\/file_bucket_file/sha256/f3aee54d781e413862eb068d89661f930385cc81bbafffc68477ff82eb9bea43/} ).and matching( %r{Debug: HTTP PUT https:\/\/127.0.0.1:#{port}\/puppet\/v3\/file_bucket_file/sha256/f3aee54d781e413862eb068d89661f930385cc81bbafffc68477ff82eb9bea43/} )).to_stdout expect(File.binread(File.join(server.upload_directory, 'filebucket'))).to eq(binary) end end it "backs up utf-8 encoded files to the filebucket server" do utf8 = "\u2603".force_encoding(Encoding::UTF_8) File.binwrite(backup_file, utf8) server.start_server do |port| Puppet[:serverport] = port expect { filebucket.command_line.args = ['backup', backup_file] filebucket.run }.to output(a_string_matching( %r{Debug: HTTP HEAD https:\/\/127.0.0.1:#{port}\/puppet\/v3\/file_bucket_file/sha256/51643361c79ecaef25a8de802de24f570ba25d9c2df1d22d94fade11b4f466cc/} ).and matching( %r{Debug: HTTP PUT https:\/\/127.0.0.1:#{port}\/puppet\/v3\/file_bucket_file/sha256/51643361c79ecaef25a8de802de24f570ba25d9c2df1d22d94fade11b4f466cc/} )).to_stdout expect(File.read(File.join(server.upload_directory, 'filebucket'), encoding: 'utf-8')).to eq(utf8) end end it "doesn't attempt to back up file that already exists on the filebucket server" do file_exists_handler = -> (req, res) { res.status = 200 } server.start_server(mounts: {filebucket: file_exists_handler}) do |port| Puppet[:serverport] = port expect { filebucket.command_line.args = ['backup', backup_file] filebucket.run }.to output(a_string_matching( %r{Debug: HTTP HEAD https:\/\/127.0.0.1:#{port}\/puppet\/v3\/file_bucket_file\/sha256\/#{sha256}\/#{File.realpath(backup_file)}\?environment\=production returned 200 OK} ).and matching( %r{#{backup_file}: #{sha256}} )).to_stdout end end it "downloads files from the filebucket server" do get_handler = -> (req, res) { res['Content-Type'] = 'application/octet-stream' res.body = 'something to store' } server.start_server(mounts: {filebucket: get_handler}) do |port| Puppet[:serverport] = port expect { filebucket.command_line.args = ['get', 'fac251367c9e083c6b1f0f3181'] filebucket.run }.to output(a_string_matching( %r{Debug: HTTP GET https:\/\/127.0.0.1:#{port}\/puppet\/v3\/file_bucket_file\/sha256\/fac251367c9e083c6b1f0f3181\?environment\=production returned 200 OK} ).and matching( %r{something to store} )).to_stdout end end it "lists the local filebucket even if the environment doesn't exist locally" do Puppet[:environment] = 'doesnotexist' Puppet::FileSystem.mkpath(Puppet[:clientbucketdir]) filebucket.command_line.args = ['backup', '--local', backup_file] expect { result = filebucket.run expect(result).to eq([backup_file]) }.to output(/Computing checksum on file/).to_stdout end context 'diff', unless: Puppet::Util::Platform.windows? || Puppet::Util::Platform.jruby? do context 'using a remote bucket' do it 'outputs a diff between a local and remote file' do File.binwrite(backup_file, "bar\nbaz") get_handler = -> (req, res) { res['Content-Type'] = 'application/octet-stream' res.body = 'foo' } server.start_server(mounts: {filebucket: get_handler}) do |port| Puppet[:serverport] = port expect { filebucket.command_line.args = ['diff', 'fac251367c9e083c6b1f0f3181', backup_file, '--remote'] filebucket.run }.to output(a_string_matching( /[-<] ?foo/ ).and matching( /[+>] ?bar/ ).and matching( /[+>] ?baz/ )).to_stdout end end it 'outputs a diff between two remote files' do get_handler = -> (req, res) { res['Content-Type'] = 'application/octet-stream' res.body = <<~END --- /opt/puppetlabs/server/data/puppetserver/bucket/d/3/b/0/7/3/8/4/d3b07384d113edec49eaa6238ad5ff00/contents\t2020-04-06 21:25:24.892367570 +0000 +++ /opt/puppetlabs/server/data/puppetserver/bucket/9/9/b/9/9/9/2/0/99b999207e287afffc86c053e5693247/contents\t2020-04-06 21:26:13.603398063 +0000 @@ -1 +1,2 @@ -foo +bar +baz END } server.start_server(mounts: {filebucket: get_handler}) do |port| Puppet[:serverport] = port expect { filebucket.command_line.args = ['diff', 'd3b07384d113edec49eaa6238ad5ff00', "99b999207e287afffc86c053e5693247", '--remote'] filebucket.run }.to output(a_string_matching( /[-<] ?foo/ ).and matching( /[+>] ?bar/ ).and matching( /[+>] ?baz/ )).to_stdout end end end context 'using a local bucket' do let(:filea) { f = tmpfile('filea') File.binwrite(f, 'foo') f } let(:fileb) { f = tmpfile('fileb') File.binwrite(f, "bar\nbaz") f } let(:checksuma) { Digest::SHA256.file(filea).to_s } let(:checksumb) { Digest::SHA256.file(fileb).to_s } it 'compares to files stored in a local bucket' do expect { filebucket.command_line.args = ['backup', filea, '--local'] filebucket.run }.to output(/#{filea}: #{checksuma}/).to_stdout expect{ filebucket.command_line.args = ['backup', fileb, '--local'] filebucket.run }.to output(/#{fileb}: #{checksumb}\n/).to_stdout expect { filebucket.command_line.args = ['diff', checksuma, checksumb, '--local'] filebucket.run }.to output(a_string_matching( /[-<] ?foo/ ).and matching( /[+>] ?bar/ ).and matching( /[+>] ?baz/ )).to_stdout end it 'compares a file on the filesystem and a file stored in a local bucket' do expect { filebucket.command_line.args = ['backup', filea, '--local'] filebucket.run }.to output(/#{filea}: #{checksuma}/).to_stdout expect { filebucket.command_line.args = ['diff', checksuma, fileb, '--local'] filebucket.run }.to output(a_string_matching( /[-<] ?foo/ ).and matching( /[+>] ?bar/ ).and matching( /[+>] ?baz/ )).to_stdout end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/application/module_spec.rb
spec/integration/application/module_spec.rb
# coding: utf-8 require 'spec_helper' require 'puppet/forge' require 'puppet_spec/https' describe 'puppet module', unless: Puppet::Util::Platform.jruby? do include PuppetSpec::Files include_context "https client" let(:app) { Puppet::Application[:module] } let(:wrong_hostname) { 'localhost' } let(:server) { PuppetSpec::HTTPSServer.new } let(:ssl_provider) { Puppet::SSL::SSLProvider.new } let(:release_response) { File.read(fixtures('unit/forge/bacula-releases.json')) } let(:release_tarball) { File.binread(fixtures('unit/forge/bacula.tar.gz')) } let(:target_dir) { tmpdir('bacula') } before :each do SemanticPuppet::Dependency.clear_sources end it 'installs a module' do # create a temp cacert bundle ssl_file = tmpfile('systemstore') File.write(ssl_file, server.ca_cert) response_proc = -> (req, res) { if req.path == '/v3/releases' res['Content-Type'] = 'application/json' res.body = release_response else res['Content-Type'] = 'application/octet-stream' res.body = release_tarball end res.status = 200 } # override path to system cacert bundle, this must be done before # the SSLContext is created and the call to X509::Store.set_default_paths Puppet::Util.withenv("SSL_CERT_FILE" => ssl_file) do server.start_server(response_proc: response_proc) do |port| Puppet[:module_repository] = "https://127.0.0.1:#{port}" # On Windows, CP437 encoded output can't be matched against UTF-8 regexp, # so encode the regexp to the external encoding and match against that. app.command_line.args = ['install', 'puppetlabs-bacula', '--target-dir', target_dir] expect { app.run }.to exit_with(0) .and output(Regexp.new("└── puppetlabs-bacula".encode(Encoding.default_external))).to_stdout end end end it 'returns a valid exception when there is an SSL verification problem' do server.start_server do |port| Puppet[:module_repository] = "https://#{wrong_hostname}:#{port}" expect { app.command_line.args = ['install', 'puppetlabs-bacula', '--target-dir', target_dir] app.run }.to exit_with(1) .and output(%r{Notice: Downloading from https://#{wrong_hostname}:#{port}}).to_stdout .and output(%r{Unable to verify the SSL certificate}).to_stderr end end it 'prints the complete URL it tried to connect to' do response_proc = -> (req, res) { res.status = 404 } # create a temp cacert bundle ssl_file = tmpfile('systemstore') File.write(ssl_file, server.ca_cert) Puppet::Util.withenv("SSL_CERT_FILE" => ssl_file) do server.start_server(response_proc: response_proc) do |port| Puppet[:module_repository] = "https://127.0.0.1:#{port}/bogus_test/puppet" expect { app.command_line.args = ['install', 'puppetlabs-bacula'] app.run }.to exit_with(1) .and output(%r{Notice: Downloading from https://127.0.0.1:#{port}}).to_stdout .and output(%r{https://127.0.0.1:#{port}/bogus_test/puppet/v3/releases}).to_stderr end end end context 'install' do it 'lists a module in a non-default directory environment' do Puppet.initialize_settings(['-E', 'direnv']) Puppet[:color] = false Puppet[:environmentpath] = File.join(my_fixture_dir, 'environments') expect { app.command_line.args = ['list'] app.run }.to exit_with(0) .and output(Regexp.new("└── pmtacceptance-nginx".encode(Encoding.default_external), Regexp::MULTILINE)).to_stdout end end context 'changes' do let(:tmp) { tmpdir('module_changes') } before :each do Puppet.initialize_settings(['-E', 'direnv']) Puppet[:color] = false end def use_local_fixture Puppet[:environmentpath] = File.join(my_fixture_dir, 'environments') end def create_working_copy Puppet[:environmentpath] = File.join(tmp, 'environments') FileUtils.cp_r(File.join(my_fixture_dir, 'environments'), tmp) end it 'reports an error when the install path is invalid' do use_local_fixture pattern = Regexp.new([ %Q{.*Error: Could not find a valid module at "#{tmp}/nginx".*}, %Q{.*Error: Try 'puppet help module changes' for usage.*}, ].join("\n"), Regexp::MULTILINE) expect { app.command_line.args = ['changes', File.join(tmp, 'nginx')] app.run }.to exit_with(1) .and output(pattern).to_stderr end it 'reports when checksums are missing from metadata.json' do create_working_copy # overwrite checksums in metadata.json nginx_dir = File.join(tmp, 'environments', 'direnv', 'modules', 'nginx') File.write(File.join(nginx_dir, 'metadata.json'), <<~END) { "name": "pmtacceptance/nginx", "version": "0.0.1" } END pattern = Regexp.new([ %Q{.*Error: No file containing checksums found.*}, %Q{.*Error: Try 'puppet help module changes' for usage.*}, ].join("\n"), Regexp::MULTILINE) expect { app.command_line.args = ['changes', nginx_dir] app.run }.to exit_with(1) .and output(pattern).to_stderr end it 'reports module not found when metadata.json is missing' do create_working_copy # overwrite checksums in metadata.json nginx_dir = File.join(tmp, 'environments', 'direnv', 'modules', 'nginx') File.unlink(File.join(nginx_dir, 'metadata.json')) pattern = Regexp.new([ %Q{.*Error: Could not find a valid module at.*}, %Q{.*Error: Try 'puppet help module changes' for usage.*}, ].join("\n"), Regexp::MULTILINE) expect { app.command_line.args = ['changes', nginx_dir] app.run }.to exit_with(1) .and output(pattern).to_stderr end it 'reports when a file is modified' do create_working_copy # overwrite README so checksum doesn't match nginx_dir = File.join(tmp, 'environments', 'direnv', 'modules', 'nginx') File.write(File.join(nginx_dir, 'README'), '') pattern = Regexp.new([ %Q{.*Warning: 1 files modified.*}, ].join("\n"), Regexp::MULTILINE) expect { app.command_line.args = ['changes', nginx_dir] app.run }.to exit_with(0) .and output(%r{README}).to_stdout .and output(pattern).to_stderr end it 'reports when a file is missing' do create_working_copy # delete README so checksum doesn't match nginx_dir = File.join(tmp, 'environments', 'direnv', 'modules', 'nginx') File.unlink(File.join(nginx_dir, 'README')) # odd that it says modified pattern = Regexp.new([ %Q{.*Warning: 1 files modified.*}, ].join("\n"), Regexp::MULTILINE) expect { app.command_line.args = ['changes', nginx_dir] app.run }.to exit_with(0) .and output(%r{README}).to_stdout .and output(pattern).to_stderr end it 'reports when there are no changes' do use_local_fixture nginx_dir = File.join(Puppet[:environmentpath], 'direnv', 'modules', 'nginx') expect { app.command_line.args = ['changes', nginx_dir] app.run }.to exit_with(0) .and output(/No modified files/).to_stdout end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/application/plugin_spec.rb
spec/integration/application/plugin_spec.rb
require 'spec_helper' require 'puppet/face' require 'puppet_spec/puppetserver' describe "puppet plugin", unless: Puppet::Util::Platform.jruby? do include_context "https client" let(:server) { PuppetSpec::Puppetserver.new } let(:plugin) { Puppet::Application[:plugin] } let(:response_body) { "[{\"path\":\"/etc/puppetlabs/code/environments/production/modules\",\"relative_path\":\".\",\"links\":\"follow\",\"owner\":0,\"group\":0,\"mode\":493,\"checksum\":{\"type\":\"ctime\",\"value\":\"{ctime}2020-03-06 20:14:25 UTC\"},\"type\":\"directory\",\"destination\":null}]" } it "downloads from plugins, pluginsfacts and locales mounts when i18n is enabled" do Puppet[:disable_i18n] = false current_version_handler = -> (req, res) { res['X-Puppet-Version'] = Puppet.version res['Content-Type'] = 'application/json' res.body = response_body } server.start_server(mounts: {file_metadatas: current_version_handler}) do |port| Puppet[:serverport] = port expect { plugin.command_line.args << 'download' plugin.run }.to exit_with(0) .and output(matching( "Downloaded these plugins: #{Regexp.escape(Puppet[:pluginfactdest])}, #{Regexp.escape(Puppet[:plugindest])}, #{Regexp.escape(Puppet[:localedest])}" )).to_stdout end end it "downloads from plugins, pluginsfacts but no locales mounts when i18n is disabled" do Puppet[:disable_i18n] = true current_version_handler = -> (req, res) { res['X-Puppet-Version'] = Puppet.version res['Content-Type'] = 'application/json' res.body = response_body } server.start_server(mounts: {file_metadatas: current_version_handler}) do |port| Puppet[:serverport] = port expect { plugin.command_line.args << 'download' plugin.run }.to exit_with(0) .and output(matching( "Downloaded these plugins: #{Regexp.escape(Puppet[:pluginfactdest])}, #{Regexp.escape(Puppet[:plugindest])}" )).to_stdout end end it "downloads from plugins and pluginsfacts from older puppetservers" do no_locales_handler = -> (req, res) { res['X-Puppet-Version'] = '5.3.3' # locales mount was added in 5.3.4 res['Content-Type'] = 'application/json' res.body = response_body } server.start_server(mounts: {file_metadatas: no_locales_handler}) do |port| Puppet[:serverport] = port expect { plugin.command_line.args << 'download' plugin.run }.to exit_with(0) .and output(matching( "Downloaded these plugins: #{Regexp.escape(Puppet[:pluginfactdest])}, #{Regexp.escape(Puppet[:plugindest])}" )).to_stdout end end it "downloads from an environment that doesn't exist locally" do requested_environment = nil current_version_handler = -> (req, res) { res['X-Puppet-Version'] = Puppet.version res['Content-Type'] = 'application/json' res.body = response_body requested_environment = req.query['environment'] } server.start_server(mounts: {file_metadatas: current_version_handler}) do |port| Puppet[:environment] = 'doesnotexistontheagent' Puppet[:serverport] = port expect { plugin.command_line.args << 'download' plugin.run }.to exit_with(0) .and output(matching("Downloaded these plugins")).to_stdout expect(requested_environment).to eq('doesnotexistontheagent') end end context "pluginsync for external facts uses source permissions to preserve fact executable-ness" do before :all do WebMock.enable! end after :all do WebMock.disable! end before :each do metadata = "[{\"path\":\"/etc/puppetlabs/code\",\"relative_path\":\".\",\"links\":\"follow\",\"owner\":0,\"group\":0,\"mode\":420,\"checksum\":{\"type\":\"ctime\",\"value\":\"{ctime}2020-07-10 14:00:00 -0700\"},\"type\":\"directory\",\"destination\":null}]" stub_request(:get, %r{/puppet/v3/file_metadatas/(plugins|locales)}).to_return(status: 200, body: metadata, headers: {'Content-Type' => 'application/json'}) # response retains owner/group/mode due to source_permissions => use facts_metadata = "[{\"path\":\"/etc/puppetlabs/code\",\"relative_path\":\".\",\"links\":\"follow\",\"owner\":500,\"group\":500,\"mode\":493,\"checksum\":{\"type\":\"ctime\",\"value\":\"{ctime}2020-07-10 14:00:00 -0700\"},\"type\":\"directory\",\"destination\":null}]" stub_request(:get, %r{/puppet/v3/file_metadatas/pluginfacts}).to_return(status: 200, body: facts_metadata, headers: {'Content-Type' => 'application/json'}) end it "processes a download request resulting in no changes" do # Create these so there are no changes Puppet::FileSystem.mkpath(Puppet[:plugindest]) Puppet::FileSystem.mkpath(Puppet[:localedest]) # /opt/puppetlabs/puppet/cache/facts.d will be created based on our umask. # If the mode on disk is not 0755, then the mode from the metadata response # (493 => 0755) will be applied, resulting in "plugins were downloaded" # message. Enforce a umask so the results are consistent. Puppet::FileSystem.mkpath(Puppet[:pluginfactdest]) Puppet::FileSystem.chmod(0755, Puppet[:pluginfactdest]) app = Puppet::Application[:plugin] app.command_line.args << 'download' expect { app.run }.to exit_with(0) .and output(/No plugins downloaded/).to_stdout end it "updates the facts.d mode", unless: Puppet::Util::Platform.windows? do Puppet::FileSystem.mkpath(Puppet[:pluginfactdest]) Puppet::FileSystem.chmod(0775, Puppet[:pluginfactdest]) app = Puppet::Application[:plugin] app.command_line.args << 'download' expect { app.run }.to exit_with(0) .and output(/Downloaded these plugins: .*facts\.d/).to_stdout end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/application/ssl_spec.rb
spec/integration/application/ssl_spec.rb
require 'spec_helper' describe "puppet ssl", unless: Puppet::Util::Platform.jruby? do context "print" do it 'translates custom oids to their long name' do basedir = File.expand_path("#{__FILE__}/../../../fixtures/ssl") # registering custom oids changes global state, so shell out output = %x{puppet ssl show \ --certname oid \ --localcacert #{basedir}/ca.pem \ --hostcrl #{basedir}/crl.pem \ --hostprivkey #{basedir}/oid-key.pem \ --hostcert #{basedir}/oid.pem \ --trusted_oid_mapping_file #{basedir}/trusted_oid_mapping.yaml 2>&1 } expect(output).to match(/Long name:/) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/application/help_spec.rb
spec/integration/application/help_spec.rb
require 'spec_helper' require 'puppet/application/help' describe "puppet help" do let(:app) { Puppet::Application[:help] } it "generates global help" do expect { app.run }.to exit_with(0) .and output(Regexp.new(Regexp.escape(<<~END), Regexp::MULTILINE)).to_stdout Usage: puppet <subcommand> [options] <action> [options] Available subcommands: END end Puppet::Face.faces.sort.each do |face_name| next if face_name == :key context "for #{face_name}" do it "generates help" do app.command_line.args = ['help', face_name] expect { app.run }.to exit_with(0) .and output(/USAGE: puppet #{face_name} <action>/).to_stdout end Puppet::Face[face_name, :current].actions.sort.each do |action_name| it "for action #{action_name}" do app.command_line.args = ['help', face_name, action_name] expect { app.run }.to exit_with(0) .and output(/USAGE: puppet #{face_name}/).to_stdout end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/application/lookup_spec.rb
spec/integration/application/lookup_spec.rb
require 'spec_helper' require 'puppet_spec/files' require 'puppet_spec/compiler' require 'deep_merge/core' describe 'lookup' do include PuppetSpec::Files context 'with an environment' do let(:fqdn) { Puppet[:certname] } let(:env_name) { 'spec' } let(:env_dir) { tmpdir('environments') } let(:environment_files) do { env_name => { 'modules' => {}, 'hiera.yaml' => <<-YAML.unindent, --- version: 5 hierarchy: - name: "Common" data_hash: yaml_data path: "common.yaml" YAML 'data' => { 'common.yaml' => <<-YAML.unindent --- a: value a mod_a::a: value mod_a::a (from environment) mod_a::hash_a: a: value mod_a::hash_a.a (from environment) mod_a::hash_b: a: value mod_a::hash_b.a (from environment) lookup_options: mod_a::hash_b: merge: hash YAML } }, 'someother' => { } } end let(:app) { Puppet::Application[:lookup] } let(:facts) { Puppet::Node::Facts.new("facts", {'my_fact' => 'my_fact_value'}) } let(:cert) { pem_content('oid.pem') } let(:node) { Puppet::Node.new('testnode', :facts => facts) } let(:populated_env_dir) do dir_contained_in(env_dir, environment_files) env_dir end before do stub_request(:get, "https://puppet:8140/puppet-ca/v1/certificate/#{fqdn}").to_return(body: cert) allow(Puppet::Node::Facts.indirection).to receive(:find).and_return(facts) Puppet[:environment] = env_name Puppet[:environmentpath] = populated_env_dir http = Puppet::HTTP::Client.new(ssl_context: Puppet::SSL::SSLProvider.new.create_insecure_context) Puppet.runtime[:http] = http end def expect_lookup_with_output(exitcode, out) expect { app.run }.to exit_with(exitcode).and output(out).to_stdout end it 'finds data in the environment' do app.command_line.args << 'a' expect_lookup_with_output(0, /value a/) end it "resolves hiera data using a top-level node parameter" do File.write(File.join(env_dir, env_name, 'hiera.yaml'), <<~YAML) --- version: 5 hierarchy: - name: "Per Node" data_hash: yaml_data path: "%{my_fact}.yaml" YAML File.write(File.join(env_dir, env_name, 'data', "my_fact_value.yaml"), <<~YAML) --- a: value from per node data YAML app.command_line.args << 'a' expect_lookup_with_output(0, /--- value from per node data/) end it "resolves hiera data using a top-level node parameter from enc" do Puppet.settings[:node_terminus] = 'exec' enc = tmpfile('enc.sh') Puppet.settings[:external_nodes] = enc File.write(File.join(env_dir, env_name, 'hiera.yaml'), <<~YAML) --- version: 5 hierarchy: - name: "Node parameters" data_hash: yaml_data path: "%{site}.yaml" YAML File.write(File.join(env_dir, env_name, 'data', "pdx.yaml"), <<~YAML) --- key: value YAML allow(Puppet::Util::Execution).to receive(:execute).with([enc, fqdn], anything).and_return(<<~YAML) parameters: site: pdx YAML app.command_line.args << 'key' << '--compile' Puppet.initialize_settings(['-E', env_name]) expect_lookup_with_output(0, /--- value/) end it "prefers the environment specified on the commandline over the enc environment" do Puppet.settings[:node_terminus] = 'exec' enc = tmpfile('enc.sh') Puppet.settings[:external_nodes] = enc File.write(File.join(env_dir, env_name, 'hiera.yaml'), <<~YAML) --- version: 5 hierarchy: - name: "Node parameters" data_hash: yaml_data path: "%{site}.yaml" YAML File.write(File.join(env_dir, env_name, 'data', "pdx.yaml"), <<~YAML) --- key: value YAML allow(Puppet::Util::Execution).to receive(:execute).with([enc, fqdn], anything).and_return(<<~YAML) --- # return 'someother' environment because it doesn't have any hiera data environment: someother parameters: site: pdx YAML app.command_line.args << 'key' << '--compile' Puppet.initialize_settings(['-E', env_name]) expect_lookup_with_output(0, /--- value/) end it 'loads trusted information from the node certificate' do Puppet.settings[:node_terminus] = 'exec' expect_any_instance_of(Puppet::Node::Exec).to receive(:find) do |args| info = Puppet.lookup(:trusted_information) expect(info.certname).to eq(fqdn) expect(info.extensions).to eq({ "1.3.6.1.4.1.34380.1.2.1.1" => "somevalue" }) end.and_return(node) app.command_line.args << 'a' << '--compile' expect_lookup_with_output(0, /--- value a/) end it 'loads external facts when running without --node' do expect(Puppet::Util).not_to receive(:skip_external_facts) expect(Facter).not_to receive(:load_external) app.command_line.args << 'a' expect_lookup_with_output(0, /--- value a/) end describe 'when using --node' do let(:fqdn) { 'random_node' } it 'skips loading of external facts' do app.command_line.args << 'a' << '--node' << fqdn expect(Puppet::Node::Facts.indirection).to receive(:find).and_return(facts) expect(Facter).to receive(:load_external).twice.with(false) expect(Facter).to receive(:load_external).twice.with(true) expect_lookup_with_output(0, /--- value a/) end end context 'uses node_terminus' do require 'puppet/indirector/node/exec' require 'puppet/indirector/node/plain' let(:node) { Puppet::Node.new('testnode', :facts => facts) } it ':plain without --compile' do Puppet.settings[:node_terminus] = 'exec' expect_any_instance_of(Puppet::Node::Plain).to receive(:find).and_return(node) expect_any_instance_of(Puppet::Node::Exec).not_to receive(:find) app.command_line.args << 'a' expect_lookup_with_output(0, /--- value a/) end it 'configured in Puppet settings with --compile' do Puppet.settings[:node_terminus] = 'exec' expect_any_instance_of(Puppet::Node::Plain).not_to receive(:find) expect_any_instance_of(Puppet::Node::Exec).to receive(:find).and_return(node) app.command_line.args << 'a' << '--compile' expect_lookup_with_output(0, /--- value a/) end end context 'configured with the wrong environment' do it 'does not find data in non-existing environment' do Puppet[:environment] = 'doesntexist' app.command_line.args << 'a' expect { app.run }.to raise_error(Puppet::Environments::EnvironmentNotFound, /Could not find a directory environment named 'doesntexist'/) end end context 'and a module' do let(:mod_a_files) do { 'mod_a' => { 'data' => { 'common.yaml' => <<-YAML.unindent --- mod_a::a: value mod_a::a (from mod_a) mod_a::b: value mod_a::b (from mod_a) mod_a::hash_a: a: value mod_a::hash_a.a (from mod_a) b: value mod_a::hash_a.b (from mod_a) mod_a::hash_b: a: value mod_a::hash_b.a (from mod_a) b: value mod_a::hash_b.b (from mod_a) mod_a::interpolated: "-- %{lookup('mod_a::a')} --" mod_a::a_a: "-- %{lookup('mod_a::hash_a.a')} --" mod_a::a_b: "-- %{lookup('mod_a::hash_a.b')} --" mod_a::b_a: "-- %{lookup('mod_a::hash_b.a')} --" mod_a::b_b: "-- %{lookup('mod_a::hash_b.b')} --" 'mod_a::a.quoted.key': 'value mod_a::a.quoted.key (from mod_a)' YAML }, 'hiera.yaml' => <<-YAML.unindent, --- version: 5 hierarchy: - name: "Common" data_hash: yaml_data path: "common.yaml" YAML } } end let(:populated_env_dir) do dir_contained_in(env_dir, DeepMerge.deep_merge!(environment_files, env_name => { 'modules' => mod_a_files })) env_dir end it 'finds data in the module' do app.command_line.args << 'mod_a::b' expect_lookup_with_output(0, /value mod_a::b \(from mod_a\)/) end it 'finds quoted keys in the module' do app.command_line.args << "'mod_a::a.quoted.key'" expect_lookup_with_output(0, /value mod_a::a.quoted.key \(from mod_a\)/) end it 'merges hashes from environment and module when merge strategy hash is used' do app.command_line.args << 'mod_a::hash_a' << '--merge' << 'hash' expect_lookup_with_output(0, <<~END) --- a: value mod_a::hash_a.a (from environment) b: value mod_a::hash_a.b (from mod_a) END end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/application/doc_spec.rb
spec/integration/application/doc_spec.rb
require 'spec_helper' require 'puppet/application/doc' describe Puppet::Application::Doc do include PuppetSpec::Files let(:app) { Puppet::Application[:doc] } it 'lists references' do app.command_line.args = ['-l'] expect { app.run }.to exit_with(0) .and output(/configuration - A reference for all settings/).to_stdout end { 'configuration' => /# Configuration Reference/, 'function' => /# Function Reference/, 'indirection' => /# Indirection Reference/, 'metaparameter' => /# Metaparameter Reference/, 'providers' => /# Provider Suitability Report/, 'report' => /# Report Reference/, 'type' => /# Type Reference/ }.each_pair do |type, expected| it "generates #{type} reference" do app.command_line.args = ['-r', type] expect { app.run }.to exit_with(0) .and output(expected).to_stdout end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/application/resource_spec.rb
spec/integration/application/resource_spec.rb
require 'spec_helper' require 'puppet_spec/files' describe "puppet resource", unless: Puppet::Util::Platform.jruby? do include PuppetSpec::Files let(:resource) { Puppet::Application[:resource] } context 'when given an invalid environment' do before { Puppet[:environment] = 'badenv' } it 'falls back to the default environment' do Puppet[:log_level] = 'debug' expect { resource.run }.to exit_with(1) .and output(/Debug: Specified environment 'badenv' does not exist on the filesystem, defaulting to 'production'/).to_stdout .and output(/Error: Could not run: You must specify the type to display/).to_stderr end it 'lists resources' do resource.command_line.args = ['file', Puppet[:confdir]] expect { resource.run }.to output(/file { '#{Puppet[:confdir]}':/).to_stdout end it 'lists types from the default environment' do begin modulepath = File.join(Puppet[:codedir], 'modules', 'test', 'lib', 'puppet', 'type') FileUtils.mkdir_p(modulepath) File.write(File.join(modulepath, 'test_resource_spec.rb'), 'Puppet::Type.newtype(:test_resource_spec)') resource.command_line.args = ['--types'] expect { resource.run }.to exit_with(0).and output(/test_resource_spec/).to_stdout ensure Puppet::Type.rmtype(:test_resource_spec) end end end context 'when handling file and tidy types' do let!(:dir) { dir_containing('testdir', 'testfile' => 'contents') } it 'does not raise when generating file resources' do resource.command_line.args = ['file', dir, 'ensure=directory', 'recurse=true'] expect { resource.run }.to output(/ensure.+=> 'directory'/).to_stdout end it 'correctly cleans up a given path' do resource.command_line.args = ['tidy', dir, 'rmdirs=true', 'recurse=true'] expect { resource.run }.to output(/Notice: \/File\[#{dir}\]\/ensure: removed/).to_stdout expect(Puppet::FileSystem.exist?(dir)).to be false end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/provider/file/windows_spec.rb
spec/integration/provider/file/windows_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'puppet_spec/files' # For some reason the provider test will not filter out on windows when using the # :if => Puppet.features.microsoft_windows? method of filtering the tests. if Puppet.features.microsoft_windows? require 'puppet/util/windows' describe Puppet::Type.type(:file).provider(:windows), '(integration)' do include PuppetSpec::Compiler include PuppetSpec::Files def create_temp_file(owner_sid, group_sid, initial_mode) tmp_file = tmpfile('filewindowsprovider') File.delete(tmp_file) if File.exist?(tmp_file) File.open(tmp_file, 'w') { |file| file.write("rspec test") } # There are other tests to ensure that these methods do indeed # set the owner and group. Therefore it's ok to depend on them # here Puppet::Util::Windows::Security.set_owner(owner_sid, tmp_file) unless owner_sid.nil? Puppet::Util::Windows::Security.set_group(group_sid, tmp_file) unless group_sid.nil? # Pretend we are managing the owner and group to FORCE this mode, even if it's "bad" Puppet::Util::Windows::Security.set_mode(initial_mode.to_i(8), tmp_file, true, true, true) unless initial_mode.nil? tmp_file end def strip_sticky(value) # For the purposes of these tests we don't care about the extra-ace bit in modes # This function removes it value & ~Puppet::Util::Windows::Security::S_IEXTRA end sids = { :system => Puppet::Util::Windows::SID::LocalSystem, :administrators => Puppet::Util::Windows::SID::BuiltinAdministrators, :users => Puppet::Util::Windows::SID::BuiltinUsers, :power_users => Puppet::Util::Windows::SID::PowerUsers, :none => Puppet::Util::Windows::SID::Nobody, :everyone => Puppet::Util::Windows::SID::Everyone } # Testcase Hash options # create_* : These options are used when creating the initial test file # create_owner (Required!) # create_group (Required!) # create_mode # # manifest_* : These options are used to craft the manifest which is applied to the test file after createion # manifest_owner, # manifest_group, # manifest_mode (Required!) # # actual_* : These options are used to check the _actual_ values as opposed to the munged values from puppet # actual_mode (Uses manifest_mode for checks if not set) RSpec.shared_examples "a mungable file resource" do |testcase| before(:each) do @tmp_file = create_temp_file(sids[testcase[:create_owner]], sids[testcase[:create_group]], testcase[:create_mode]) raise "Could not create temporary file" if @tmp_file.nil? end after(:each) do File.delete(@tmp_file) if File.exist?(@tmp_file) end context_name = "With initial owner '#{testcase[:create_owner]}' and initial group '#{testcase[:create_owner]}'" context_name += " and initial mode of '#{testcase[:create_mode]}'" unless testcase[:create_mode].nil? context_name += " and a mode of '#{testcase[:manifest_mode]}' in the manifest" context_name += " and an owner of '#{testcase[:manifest_owner]}' in the manifest" unless testcase[:manifest_owner].nil? context_name += " and a group of '#{testcase[:manifest_group]}' in the manifest" unless testcase[:manifest_group].nil? context context_name do is_idempotent = testcase[:is_idempotent].nil? || testcase[:is_idempotent] let(:manifest) do value = <<-MANIFEST file { 'rspec_example': ensure => present, path => '#{@tmp_file}', mode => '#{testcase[:manifest_mode]}', MANIFEST value += " owner => '#{testcase[:manifest_owner]}',\n" unless testcase[:manifest_owner].nil? value += " group => '#{testcase[:manifest_group]}',\n" unless testcase[:manifest_group].nil? value + "}" end it "should apply with no errors and have expected ACL" do apply_with_error_check(manifest) new_mode = strip_sticky(Puppet::Util::Windows::Security.get_mode(@tmp_file)) expect(new_mode.to_s(8)).to eq (testcase[:actual_mode].nil? ? testcase[:manifest_mode] : testcase[:actual_mode]) end it "should be idempotent", :if => is_idempotent do result = apply_with_error_check(manifest) result = apply_with_error_check(manifest) # Idempotent. Should be no changed resources expect(result.changed?.count).to eq 0 end it "should NOT be idempotent", :unless => is_idempotent do result = apply_with_error_check(manifest) result = apply_with_error_check(manifest) result = apply_with_error_check(manifest) result = apply_with_error_check(manifest) # Not idempotent. Expect changed resources expect(result.changed?.count).to be > 0 end end end # These scenarios round-trip permissions and are idempotent [ { :create_owner => :system, :create_group => :administrators, :manifest_mode => '760' }, { :create_owner => :administrators, :create_group => :administrators, :manifest_mode => '660' }, { :create_owner => :system, :create_group => :system, :manifest_mode => '770' }, ].each do |testcase| # What happens if the owner and group are not managed it_behaves_like "a mungable file resource", testcase # What happens if the owner is managed it_behaves_like "a mungable file resource", testcase.merge({ :manifest_owner => testcase[:create_owner]}) # What happens if the group is managed it_behaves_like "a mungable file resource", testcase.merge({ :manifest_group => testcase[:create_group]}) # What happens if both the owner and group are managed it_behaves_like "a mungable file resource", testcase.merge({ :manifest_owner => testcase[:create_owner], :manifest_group => testcase[:create_group] }) end # SYSTEM is special in that when specifying less than mode 7, the owner and/or group MUST be managed # otherwise it's munged to 7 behind the scenes and is not idempotent both_system_testcase = { :create_owner => :system, :create_group => :system, :manifest_mode => '660', :actual_mode => '770', :is_idempotent => false } # What happens if the owner and group are not managed it_behaves_like "a mungable file resource", both_system_testcase.merge({ :is_idempotent => true }) # What happens if the owner is managed it_behaves_like "a mungable file resource", both_system_testcase.merge({ :manifest_owner => both_system_testcase[:create_owner]}) # What happens if the group is managed it_behaves_like "a mungable file resource", both_system_testcase.merge({ :manifest_group => both_system_testcase[:create_group]}) # However when we manage SYSTEM explicitly, then the modes lower than 7 stick and the file provider # assumes it's insync (i.e. idempotent) it_behaves_like "a mungable file resource", both_system_testcase.merge({ :manifest_owner => both_system_testcase[:create_owner], :manifest_group => both_system_testcase[:create_group], :actual_mode => both_system_testcase[:manifest_mode], :is_idempotent => true }) # What happens if we _create_ a file that SYSTEM is a part of, and is Full Control, but the manifest says it should not be Full Control # Behind the scenes the mode should be changed to 7 and be idempotent [ { :create_owner => :system, :create_group => :system, :manifest_mode => '660' }, { :create_owner => :administrators, :create_group => :system, :manifest_mode => '760' }, { :create_owner => :system, :create_group => :administrators, :manifest_mode => '670' }, ].each do |testcase| it_behaves_like "a mungable file resource", testcase.merge({ :create_mode => '770', :actual_mode => '770'}) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/l10n/compiler_spec.rb
spec/integration/l10n/compiler_spec.rb
require 'spec_helper' describe 'compiler localization' do include_context 'l10n', 'ja' let(:envdir) { File.join(my_fixture_dir, '..', 'envs') } let(:environments) do Puppet::Environments::Cached.new( Puppet::Environments::Directories.new(envdir, []) ) end let(:env) { Puppet::Node::Environment.create(:prod, [File.join(envdir, 'prod', 'modules')]) } let(:node) { Puppet::Node.new('test', :environment => env) } around(:each) do |example| Puppet.override(current_environment: env, loaders: Puppet::Pops::Loaders.new(env), environments: environments) do example.run end end it 'localizes strings in functions' do Puppet[:code] = <<~END notify { 'demo': message => l10n() } END Puppet::Resource::Catalog.indirection.terminus_class = :compiler catalog = Puppet::Resource::Catalog.indirection.find(node.name) resource = catalog.resource(:notify, 'demo') expect(resource).to be expect(resource[:message]).to eq("それは楽しい時間です") end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/network/formats_spec.rb
spec/integration/network/formats_spec.rb
require 'spec_helper' require 'puppet/network/formats' class PsonIntTest attr_accessor :string def ==(other) other.class == self.class and string == other.string end def self.from_data_hash(data) new(data[0]) end def initialize(string) @string = string end def to_pson(*args) { 'type' => self.class.name, 'data' => [@string] }.to_pson(*args) end def self.canonical_order(s) s.gsub(/\{"data":\[(.*?)\],"type":"PsonIntTest"\}/,'{"type":"PsonIntTest","data":[\1]}') end end describe Puppet::Network::FormatHandler.format(:s) do before do @format = Puppet::Network::FormatHandler.format(:s) end it "should support certificates" do expect(@format).to be_supported(Puppet::SSL::Certificate) end it "should not support catalogs" do expect(@format).not_to be_supported(Puppet::Resource::Catalog) end end describe Puppet::Network::FormatHandler.format(:pson), if: Puppet.features.pson? do before do @pson = Puppet::Network::FormatHandler.format(:pson) end it "should be able to render an instance to pson" do instance = PsonIntTest.new("foo") expect(PsonIntTest.canonical_order(@pson.render(instance))).to eq(PsonIntTest.canonical_order('{"type":"PsonIntTest","data":["foo"]}' )) end it "should be able to render arrays to pson" do expect(@pson.render([1,2])).to eq('[1,2]') end it "should be able to render arrays containing hashes to pson" do expect(@pson.render([{"one"=>1},{"two"=>2}])).to eq('[{"one":1},{"two":2}]') end it "should be able to render multiple instances to pson" do one = PsonIntTest.new("one") two = PsonIntTest.new("two") expect(PsonIntTest.canonical_order(@pson.render([one,two]))).to eq(PsonIntTest.canonical_order('[{"type":"PsonIntTest","data":["one"]},{"type":"PsonIntTest","data":["two"]}]')) end it "should be able to intern pson into an instance" do expect(@pson.intern(PsonIntTest, '{"type":"PsonIntTest","data":["foo"]}')).to eq(PsonIntTest.new("foo")) end it "should be able to intern pson with no class information into an instance" do expect(@pson.intern(PsonIntTest, '["foo"]')).to eq(PsonIntTest.new("foo")) end it "should be able to intern multiple instances from pson" do expect(@pson.intern_multiple(PsonIntTest, '[{"type": "PsonIntTest", "data": ["one"]},{"type": "PsonIntTest", "data": ["two"]}]')).to eq([ PsonIntTest.new("one"), PsonIntTest.new("two") ]) end it "should be able to intern multiple instances from pson with no class information" do expect(@pson.intern_multiple(PsonIntTest, '[["one"],["two"]]')).to eq([ PsonIntTest.new("one"), PsonIntTest.new("two") ]) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/network/http_pool_spec.rb
spec/integration/network/http_pool_spec.rb
require 'spec_helper' require 'puppet_spec/https' require 'puppet_spec/files' require 'puppet/network/http_pool' describe Puppet::Network::HttpPool, unless: Puppet::Util::Platform.jruby? do include PuppetSpec::Files before :all do WebMock.disable! end after :all do WebMock.enable! end before :each do # make sure we don't take too long Puppet[:http_connect_timeout] = '5s' end let(:hostname) { '127.0.0.1' } let(:wrong_hostname) { 'localhost' } let(:server) { PuppetSpec::HTTPSServer.new } context "when calling deprecated HttpPool methods" do before(:each) do ssldir = tmpdir('http_pool') Puppet[:ssldir] = ssldir Puppet.settings.use(:main, :ssl) File.write(Puppet[:localcacert], server.ca_cert.to_pem) File.write(Puppet[:hostcrl], server.ca_crl.to_pem) File.write(Puppet[:hostcert], server.server_cert.to_pem) File.write(Puppet[:hostprivkey], server.server_key.to_pem) end def connection(host, port) Puppet::Network::HttpPool.http_instance(host, port, use_ssl: true) end shared_examples_for 'HTTPS client' do it "connects over SSL" do server.start_server do |port| http = connection(hostname, port) res = http.get('/') expect(res.code).to eq('200') end end it "raises if the server's cert doesn't match the hostname we connected to" do server.start_server do |port| http = connection(wrong_hostname, port) expect { http.get('/') }.to raise_error { |err| expect(err).to be_instance_of(Puppet::SSL::CertMismatchError) expect(err.message).to match(/\AServer hostname '#{wrong_hostname}' did not match server certificate; expected one of (.+)/) md = err.message.match(/expected one of (.+)/) expect(md[1].split(', ')).to contain_exactly('127.0.0.1', 'DNS:127.0.0.1', 'DNS:127.0.0.2') } end end it "raises if the server's CA is unknown" do # File must exist and by not empty so DefaultValidator doesn't # downgrade to VERIFY_NONE, so use a different CA that didn't # issue the server's cert capath = tmpfile('empty') File.write(capath, cert_fixture('netlock-arany-utf8.pem')) Puppet[:localcacert] = capath Puppet[:certificate_revocation] = false server.start_server do |port| http = connection(hostname, port) expect { http.get('/') }.to raise_error(Puppet::Error, %r{certificate verify failed.* .self.signed certificate in certificate chain for CN=Test CA.}) end end it "detects when the server has closed the connection and reconnects" do server.start_server do |port| http = connection(hostname, port) expect(http.request_get('/')).to be_a(Net::HTTPSuccess) expect(http.request_get('/')).to be_a(Net::HTTPSuccess) end end end context "when using persistent HTTPS connections" do around :each do |example| begin example.run ensure Puppet.runtime[:http].close end end include_examples 'HTTPS client' end shared_examples_for "an HttpPool connection" do |klass, legacy_api| before :each do Puppet::Network::HttpPool.http_client_class = klass end it "connects using the scheme, host and port from the http instance preserving the URL path and query" do request_line = nil response_proc = -> (req, res) { request_line = req.request_line } server.start_server(response_proc: response_proc) do |port| http = Puppet::Network::HttpPool.http_instance(hostname, port, true) path = "http://bogus.example.com:443/foo?q=a" http.get(path) if legacy_api # The old API uses 'absolute-form' and passes the bogus hostname # which isn't the host we connected to. expect(request_line).to eq("GET http://bogus.example.com:443/foo?q=a HTTP/1.1\r\n") else expect(request_line).to eq("GET /foo?q=a HTTP/1.1\r\n") end end end it "requires the caller to URL encode the path and query when using absolute form" do request_line = nil response_proc = -> (req, res) { request_line = req.request_line } server.start_server(response_proc: response_proc) do |port| http = Puppet::Network::HttpPool.http_instance(hostname, port, true) params = { 'key' => 'a value' } encoded_url = "https://#{hostname}:#{port}/foo%20bar?q=#{Puppet::Util.uri_query_encode(params.to_json)}" http.get(encoded_url) if legacy_api expect(request_line).to eq("GET #{encoded_url} HTTP/1.1\r\n") else expect(request_line).to eq("GET /foo%20bar?q=%7B%22key%22%3A%22a%20value%22%7D HTTP/1.1\r\n") end end end it "requires the caller to URL encode the path and query when using a path" do request_line = nil response_proc = -> (req, res) { request_line = req.request_line } server.start_server(response_proc: response_proc) do |port| http = Puppet::Network::HttpPool.http_instance(hostname, port, true) params = { 'key' => 'a value' } http.get("/foo%20bar?q=#{Puppet::Util.uri_query_encode(params.to_json)}") expect(request_line).to eq("GET /foo%20bar?q=%7B%22key%22%3A%22a%20value%22%7D HTTP/1.1\r\n") end end end describe Puppet::Network::HTTP::Connection do it_behaves_like "an HttpPool connection", described_class, false end end context "when calling HttpPool.connection method" do let(:ssl) { Puppet::SSL::SSLProvider.new } let(:ssl_context) { ssl.create_root_context(cacerts: [server.ca_cert], crls: [server.ca_crl]) } def connection(host, port, ssl_context:) Puppet::Network::HttpPool.connection(host, port, ssl_context: ssl_context) end # Configure the server's SSLContext to require a client certificate. The `client_ca` # setting allows the server to advertise which client CAs it will accept. def require_client_certs(ctx) ctx.verify_mode = OpenSSL::SSL::VERIFY_PEER|OpenSSL::SSL::VERIFY_FAIL_IF_NO_PEER_CERT ctx.client_ca = [cert_fixture('ca.pem')] end it "connects over SSL" do server.start_server do |port| http = connection(hostname, port, ssl_context: ssl_context) res = http.get('/') expect(res.code).to eq('200') end end it "raises if the server's cert doesn't match the hostname we connected to" do server.start_server do |port| http = connection(wrong_hostname, port, ssl_context: ssl_context) expect { http.get('/') }.to raise_error { |err| expect(err).to be_instance_of(Puppet::SSL::CertMismatchError) expect(err.message).to match(/\AServer hostname '#{wrong_hostname}' did not match server certificate; expected one of (.+)/) md = err.message.match(/expected one of (.+)/) expect(md[1].split(', ')).to contain_exactly('127.0.0.1', 'DNS:127.0.0.1', 'DNS:127.0.0.2') } end end it "raises if the server's CA is unknown" do server.start_server do |port| ssl_context = ssl.create_root_context(cacerts: [cert_fixture('netlock-arany-utf8.pem')], crls: [server.ca_crl]) http = Puppet::Network::HttpPool.connection(hostname, port, ssl_context: ssl_context) expect { http.get('/') }.to raise_error(Puppet::Error, %r{certificate verify failed.* .self.signed certificate in certificate chain for CN=Test CA.}) end end it "warns when client has an incomplete client cert chain" do expect(Puppet).to receive(:warning).with("The issuer 'CN=Test CA Agent Subauthority' of certificate 'CN=pluto' cannot be found locally") pluto = cert_fixture('pluto.pem') ssl_context = ssl.create_context( cacerts: [server.ca_cert], crls: [server.ca_crl], client_cert: pluto, private_key: key_fixture('pluto-key.pem') ) # verify client has incomplete chain expect(ssl_context.client_chain.map(&:to_der)).to eq([pluto.to_der]) # force server to require (not request) client certs ctx_proc = -> (ctx) { require_client_certs(ctx) # server needs to trust the client's intermediate CA to complete the client's chain ctx.cert_store.add_cert(cert_fixture('intermediate-agent.pem')) } server.start_server(ctx_proc: ctx_proc) do |port| http = Puppet::Network::HttpPool.connection(hostname, port, ssl_context: ssl_context) res = http.get('/') expect(res.code).to eq('200') end end it "sends a complete client cert chain" do pluto = cert_fixture('pluto.pem') client_ca = cert_fixture('intermediate-agent.pem') ssl_context = ssl.create_context( cacerts: [server.ca_cert, client_ca], crls: [server.ca_crl, crl_fixture('intermediate-agent-crl.pem')], client_cert: pluto, private_key: key_fixture('pluto-key.pem') ) # verify client has complete chain from leaf to root expect(ssl_context.client_chain.map(&:to_der)).to eq([pluto, client_ca, server.ca_cert].map(&:to_der)) server.start_server(ctx_proc: method(:require_client_certs)) do |port| http = Puppet::Network::HttpPool.connection(hostname, port, ssl_context: ssl_context) res = http.get('/') expect(res.code).to eq('200') end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/network/http/api/indirected_routes_spec.rb
spec/integration/network/http/api/indirected_routes_spec.rb
require 'spec_helper' require 'puppet/network/http' require 'puppet/network/http/api/indirected_routes' require 'puppet/indirector_proxy' require 'puppet_spec/files' require 'puppet_spec/network' require 'puppet/util/json' require 'puppet/file_serving/content' require 'puppet/file_serving/metadata' describe Puppet::Network::HTTP::API::IndirectedRoutes do include PuppetSpec::Files include PuppetSpec::Network include_context 'with supported checksum types' describe "when running the master application" do before :each do Puppet::FileServing::Content.indirection.terminus_class = :file_server Puppet::FileServing::Metadata.indirection.terminus_class = :file_server Puppet::FileBucket::File.indirection.terminus_class = :file end describe "using Puppet API to request file metadata" do let(:handler) { Puppet::Network::HTTP::API::IndirectedRoutes.new } let(:response) { Puppet::Network::HTTP::MemoryResponse.new } with_checksum_types 'file_content', 'lib/files/file.rb' do before :each do Puppet.settings[:modulepath] = env_path end it "should find the file metadata with expected checksum" do request = a_request_that_finds(Puppet::IndirectorProxy.new("modules/lib/file.rb", "file_metadata"), {:accept_header => 'unknown, application/json'}, {:environment => 'production', :checksum_type => checksum_type}) handler.call(request, response) resp = Puppet::Util::Json.load(response.body) expect(resp['checksum']['type']).to eq(checksum_type) expect(checksum_valid(checksum_type, checksum, resp['checksum']['value'])).to be_truthy end it "should search for the file metadata with expected checksum" do request = a_request_that_searches(Puppet::IndirectorProxy.new("modules/lib", "file_metadata"), {:accept_header => 'unknown, application/json'}, {:environment => 'production', :checksum_type => checksum_type, :recurse => 'yes'}) handler.call(request, response) resp = Puppet::Util::Json.load(response.body) expect(resp.length).to eq(2) file = resp.find {|x| x['relative_path'] == 'file.rb'} expect(file['checksum']['type']).to eq(checksum_type) expect(checksum_valid(checksum_type, checksum, file['checksum']['value'])).to be_truthy end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/environments/settings_interpolation_spec.rb
spec/integration/environments/settings_interpolation_spec.rb
require 'pp' require 'spec_helper' require 'puppet_spec/settings' module SettingsInterpolationSpec describe "interpolating $environment" do include PuppetSpec::Settings let(:confdir) { Puppet[:confdir] } let(:cmdline_args) { ['--confdir', confdir, '--vardir', Puppet[:vardir], '--hiera_config', Puppet[:hiera_config]] } shared_examples_for "a setting that does not interpolate $environment" do before(:each) do set_puppet_conf(confdir, <<-EOF) environmentpath=$confdir/environments #{setting}=#{value} EOF end it "does not interpolate $environment" do Puppet.initialize_settings(cmdline_args) expect(Puppet[:environmentpath]).to eq("#{confdir}/environments") expect(Puppet[setting.intern]).to eq(expected) end it "displays the interpolated value in the warning" do Puppet.initialize_settings(cmdline_args) Puppet[setting.intern] expect(@logs).to have_matching_log(/cannot interpolate \$environment within '#{setting}'.*Its value will remain #{Regexp.escape(expected)}/) end end describe "config_version" do it "interpolates $environment" do envname = 'testing' setting = 'config_version' value = '/some/script $environment' expected = "#{File.expand_path('/some/script')} testing" set_puppet_conf(confdir, <<-EOF) environmentpath=$confdir/environments environment=#{envname} EOF set_environment_conf("#{confdir}/environments", envname, <<-EOF) #{setting}=#{value} EOF Puppet.initialize_settings(cmdline_args) expect(Puppet[:environmentpath]).to eq("#{confdir}/environments") environment = Puppet.lookup(:environments).get(envname) expect(environment.config_version).to eq(expected) expect(@logs).to be_empty end end describe "basemodulepath" do let(:setting) { "basemodulepath" } let(:value) { "$confdir/environments/$environment/modules:$confdir/environments/$environment/other_modules" } let(:expected) { "#{confdir}/environments/$environment/modules:#{confdir}/environments/$environment/other_modules" } it_behaves_like "a setting that does not interpolate $environment" it "logs a single warning for multiple instaces of $environment in the setting" do set_puppet_conf(confdir, <<-EOF) environmentpath=$confdir/environments #{setting}=#{value} EOF Puppet.initialize_settings(cmdline_args) expect(@logs.map(&:to_s).grep(/cannot interpolate \$environment within '#{setting}'/).count).to eq(1) end end describe "environment" do let(:setting) { "environment" } let(:value) { "whatareyouthinking$environment" } let(:expected) { value } it_behaves_like "a setting that does not interpolate $environment" end describe "the default_manifest" do let(:setting) { "default_manifest" } let(:value) { "$confdir/manifests/$environment" } let(:expected) { "#{confdir}/manifests/$environment" } it_behaves_like "a setting that does not interpolate $environment" end it "does not interpolate $environment and logs a warning when interpolating environmentpath" do setting = 'environmentpath' value = "$confdir/environments/$environment" expected = "#{confdir}/environments/$environment" set_puppet_conf(confdir, <<-EOF) #{setting}=#{value} EOF Puppet.initialize_settings(cmdline_args) expect(Puppet[setting.intern]).to eq(expected) expect(@logs).to have_matching_log(/cannot interpolate \$environment within '#{setting}'/) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/environments/default_manifest_spec.rb
spec/integration/environments/default_manifest_spec.rb
require 'spec_helper' module EnvironmentsDefaultManifestsSpec describe "default manifests" do context "puppet with default_manifest settings" do let(:confdir) { Puppet[:confdir] } let(:environmentpath) { File.expand_path("envdir", confdir) } context "relative default" do let(:testingdir) { File.join(environmentpath, "testing") } before(:each) do FileUtils.mkdir_p(testingdir) end it "reads manifest from ./manifest of a basic directory environment" do manifestsdir = File.join(testingdir, "manifests") FileUtils.mkdir_p(manifestsdir) File.open(File.join(manifestsdir, "site.pp"), "w", :encoding => Encoding::UTF_8) do |f| f.puts("notify { 'ManifestFromRelativeDefault': }") end File.open(File.join(confdir, "puppet.conf"), "w", :encoding => Encoding::UTF_8) do |f| f.puts("environmentpath=#{environmentpath}") end expect(a_catalog_compiled_for_environment('testing')).to( include_resource('Notify[ManifestFromRelativeDefault]') ) end end context "set absolute" do let(:testingdir) { File.join(environmentpath, "testing") } before(:each) do FileUtils.mkdir_p(testingdir) end it "reads manifest from an absolute default_manifest" do manifestsdir = File.expand_path("manifests", confdir) FileUtils.mkdir_p(manifestsdir) File.open(File.join(confdir, "puppet.conf"), "w", :encoding => Encoding::UTF_8) do |f| f.puts(<<-EOF) environmentpath=#{environmentpath} default_manifest=#{manifestsdir} EOF end File.open(File.join(manifestsdir, "site.pp"), "w", :encoding => Encoding::UTF_8) do |f| f.puts("notify { 'ManifestFromAbsoluteDefaultManifest': }") end expect(a_catalog_compiled_for_environment('testing')).to( include_resource('Notify[ManifestFromAbsoluteDefaultManifest]') ) end it "reads manifest from directory environment manifest when environment.conf manifest set" do default_manifestsdir = File.expand_path("manifests", confdir) File.open(File.join(confdir, "puppet.conf"), "w", :encoding => Encoding::UTF_8) do |f| f.puts(<<-EOF) environmentpath=#{environmentpath} default_manifest=#{default_manifestsdir} EOF end manifestsdir = File.join(testingdir, "special_manifests") FileUtils.mkdir_p(manifestsdir) File.open(File.join(manifestsdir, "site.pp"), "w", :encoding => Encoding::UTF_8) do |f| f.puts("notify { 'ManifestFromEnvironmentConfManifest': }") end File.open(File.join(testingdir, "environment.conf"), "w", :encoding => Encoding::UTF_8) do |f| f.puts("manifest=./special_manifests") end expect(a_catalog_compiled_for_environment('testing')).to( include_resource('Notify[ManifestFromEnvironmentConfManifest]') ) expect(Puppet[:default_manifest]).to eq(default_manifestsdir) end it "ignores manifests in the local ./manifests if default_manifest specifies another directory" do default_manifestsdir = File.expand_path("manifests", confdir) FileUtils.mkdir_p(default_manifestsdir) File.open(File.join(confdir, "puppet.conf"), "w", :encoding => Encoding::UTF_8) do |f| f.puts(<<-EOF) environmentpath=#{environmentpath} default_manifest=#{default_manifestsdir} EOF end File.open(File.join(default_manifestsdir, "site.pp"), "w", :encoding => Encoding::UTF_8) do |f| f.puts("notify { 'ManifestFromAbsoluteDefaultManifest': }") end implicit_manifestsdir = File.join(testingdir, "manifests") FileUtils.mkdir_p(implicit_manifestsdir) File.open(File.join(implicit_manifestsdir, "site.pp"), "w", :encoding => Encoding::UTF_8) do |f| f.puts("notify { 'ManifestFromImplicitRelativeEnvironmentManifestDirectory': }") end expect(a_catalog_compiled_for_environment('testing')).to( include_resource('Notify[ManifestFromAbsoluteDefaultManifest]') ) end end context "with disable_per_environment_manifest true" do let(:manifestsdir) { File.expand_path("manifests", confdir) } let(:testingdir) { File.join(environmentpath, "testing") } before(:each) do FileUtils.mkdir_p(testingdir) end before(:each) do FileUtils.mkdir_p(manifestsdir) File.open(File.join(confdir, "puppet.conf"), "w", :encoding => Encoding::UTF_8) do |f| f.puts(<<-EOF) environmentpath=#{environmentpath} default_manifest=#{manifestsdir} disable_per_environment_manifest=true EOF end File.open(File.join(manifestsdir, "site.pp"), "w", :encoding => Encoding::UTF_8) do |f| f.puts("notify { 'ManifestFromAbsoluteDefaultManifest': }") end end it "reads manifest from the default manifest setting" do expect(a_catalog_compiled_for_environment('testing')).to( include_resource('Notify[ManifestFromAbsoluteDefaultManifest]') ) end it "refuses to compile if environment.conf specifies a different manifest" do File.open(File.join(testingdir, "environment.conf"), "w", :encoding => Encoding::UTF_8) do |f| f.puts("manifest=./special_manifests") end expect { a_catalog_compiled_for_environment('testing') }.to( raise_error(Puppet::Error, /disable_per_environment_manifest.*environment.conf.*manifest.*conflict/) ) end it "reads manifest from default_manifest setting when environment.conf has manifest set if setting equals default_manifest setting" do File.open(File.join(testingdir, "environment.conf"), "w", :encoding => Encoding::UTF_8) do |f| f.puts("manifest=#{manifestsdir}") end expect(a_catalog_compiled_for_environment('testing')).to( include_resource('Notify[ManifestFromAbsoluteDefaultManifest]') ) end it "logs errors if environment.conf specifies a different manifest" do File.open(File.join(testingdir, "environment.conf"), "w", :encoding => Encoding::UTF_8) do |f| f.puts("manifest=./special_manifests") end Puppet.initialize_settings expect(Puppet[:environmentpath]).to eq(environmentpath) environment = Puppet.lookup(:environments).get('testing') expect(environment.manifest).to eq(manifestsdir) expect(@logs.first.to_s).to match(%r{disable_per_environment_manifest.*is true, but.*environment.*at #{testingdir}.*has.*environment.conf.*manifest.*#{testingdir}/special_manifests}) end it "raises an error if default_manifest is not absolute" do File.open(File.join(confdir, "puppet.conf"), "w", :encoding => Encoding::UTF_8) do |f| f.puts(<<-EOF) environmentpath=#{environmentpath} default_manifest=./relative disable_per_environment_manifest=true EOF end expect { Puppet.initialize_settings }.to raise_error(Puppet::Settings::ValidationError, /default_manifest.*must be.*absolute.*when.*disable_per_environment_manifest.*true/) end end end RSpec::Matchers.define :include_resource do |expected| match do |actual| actual.resources.map(&:ref).include?(expected) end def failure_message "expected #{@actual.resources.map(&:ref)} to include #{expected}" end def failure_message_when_negated "expected #{@actual.resources.map(&:ref)} not to include #{expected}" end end def a_catalog_compiled_for_environment(envname) Puppet.initialize_settings expect(Puppet[:environmentpath]).to eq(environmentpath) node = Puppet::Node.new('testnode', :environment => 'testing') expect(node.environment).to eq(Puppet.lookup(:environments).get('testing')) Puppet::Parser::Compiler.compile(node) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/environments/settings_spec.rb
spec/integration/environments/settings_spec.rb
require 'spec_helper' require 'puppet_spec/settings' describe "environment settings" do include PuppetSpec::Settings let(:confdir) { Puppet[:confdir] } let(:cmdline_args) { ['--confdir', confdir, '--vardir', Puppet[:vardir], '--hiera_config', Puppet[:hiera_config]] } let(:environmentpath) { File.expand_path("envdir", confdir) } let(:testingdir) { File.join(environmentpath, "testing") } before(:each) do FileUtils.mkdir_p(testingdir) end def init_puppet_conf(settings = {}) set_puppet_conf(confdir, <<-EOF) environmentpath=#{environmentpath} #{settings.map { |k,v| "#{k}=#{v}" }.join("\n")} EOF Puppet.initialize_settings end it "raises an error if you set manifest in puppet.conf" do expect { init_puppet_conf("manifest" => "/something") }.to raise_error(Puppet::Settings::SettingsError, /Cannot set manifest.*in puppet.conf/) end it "raises an error if you set modulepath in puppet.conf" do expect { init_puppet_conf("modulepath" => "/something") }.to raise_error(Puppet::Settings::SettingsError, /Cannot set modulepath.*in puppet.conf/) end it "raises an error if you set config_version in puppet.conf" do expect { init_puppet_conf("config_version" => "/something") }.to raise_error(Puppet::Settings::SettingsError, /Cannot set config_version.*in puppet.conf/) end context "when given an environment" do before(:each) do init_puppet_conf end context "without an environment.conf" do it "reads manifest from environment.conf defaults" do expect(Puppet.settings.value(:manifest, :testing)).to eq(File.join(testingdir, "manifests")) end it "reads modulepath from environment.conf defaults" do expect(Puppet.settings.value(:modulepath, :testing)).to match(/#{File.join(testingdir, "modules")}/) end it "reads config_version from environment.conf defaults" do expect(Puppet.settings.value(:config_version, :testing)).to eq('') end end context "with an environment.conf" do before(:each) do set_environment_conf(environmentpath, 'testing', <<-EOF) manifest=/special/manifest modulepath=/special/modulepath config_version=/special/config_version EOF end it "reads the configured manifest" do expect(Puppet.settings.value(:manifest, :testing)).to eq(Puppet::FileSystem.expand_path('/special/manifest')) end it "reads the configured modulepath" do expect(Puppet.settings.value(:modulepath, :testing)).to eq(Puppet::FileSystem.expand_path('/special/modulepath')) end it "reads the configured config_version" do expect(Puppet.settings.value(:config_version, :testing)).to eq(Puppet::FileSystem.expand_path('/special/config_version')) end end context "with an environment.conf containing 8.3 style Windows paths", :if => Puppet::Util::Platform.windows? do before(:each) do # set 8.3 style Windows paths @modulepath = Puppet::Util::Windows::File.get_short_pathname(PuppetSpec::Files.tmpdir('fakemodulepath')) # for expansion to work, the file must actually exist @manifest = PuppetSpec::Files.tmpfile('foo.pp', @modulepath) # but tmpfile won't create an empty file Puppet::FileSystem.touch(@manifest) @manifest = Puppet::Util::Windows::File.get_short_pathname(@manifest) set_environment_conf(environmentpath, 'testing', <<-EOF) manifest=#{@manifest} modulepath=#{@modulepath} EOF end it "reads the configured manifest as a fully expanded path" do expect(Puppet.settings.value(:manifest, :testing)).to eq(Puppet::FileSystem.expand_path(@manifest)) end it "reads the configured modulepath as a fully expanded path" do expect(Puppet.settings.value(:modulepath, :testing)).to eq(Puppet::FileSystem.expand_path(@modulepath)) end end context "when environment name collides with a puppet.conf section" do let(:testingdir) { File.join(environmentpath, "main") } it "reads manifest from environment.conf defaults" do expect(Puppet.settings.value(:environmentpath)).to eq(environmentpath) expect(Puppet.settings.value(:manifest, :main)).to eq(File.join(testingdir, "manifests")) end context "and an environment.conf" do before(:each) do set_environment_conf(environmentpath, 'main', <<-EOF) manifest=/special/manifest EOF end it "reads manifest from environment.conf settings" do expect(Puppet.settings.value(:environmentpath)).to eq(environmentpath) expect(Puppet.settings.value(:manifest, :main)).to eq(Puppet::FileSystem.expand_path("/special/manifest")) end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/environments/setting_hooks_spec.rb
spec/integration/environments/setting_hooks_spec.rb
require 'spec_helper' describe "setting hooks" do let(:confdir) { Puppet[:confdir] } let(:environmentpath) { File.expand_path("envdir", confdir) } describe "reproducing PUP-3500" do let(:productiondir) { File.join(environmentpath, "production") } before(:each) do FileUtils.mkdir_p(productiondir) end it "accesses correct directory environment settings after initializing a setting with an on_write hook" do expect(Puppet.settings.setting(:strict).call_hook).to eq(:on_write_only) File.open(File.join(confdir, "puppet.conf"), "w:UTF-8") do |f| f.puts("environmentpath=#{environmentpath}") f.puts("certname=something") end Puppet.initialize_settings production_env = Puppet.lookup(:environments).get(:production) expect(Puppet.settings.value(:manifest, production_env)).to eq("#{productiondir}/manifests") end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/agent/logging_spec.rb
spec/integration/agent/logging_spec.rb
require 'spec_helper' require 'puppet' require 'puppet/daemon' require 'puppet/application/agent' # The command line flags affecting #20900 and #20919: # # --onetime # --daemonize # --no-daemonize # --logdest # --verbose # --debug # (no flags) (-) # # d and nd are mutally exclusive # # Combinations without logdest, verbose or debug: # # --onetime --daemonize # --onetime --no-daemonize # --onetime # --daemonize # --no-daemonize # - # # 6 cases X [--logdest=console, --logdest=syslog, --logdest=/some/file, <nothing added>] # = 24 cases to test # # X [--verbose, --debug, <nothing added>] # = 72 cases to test # # Expectations of behavior are defined in the expected_loggers, expected_level methods, # so adapting to a change in logging behavior should hopefully be mostly a matter of # adjusting the logic in those methods to define new behavior. # # Note that this test does not have anything to say about what happens to logging after # daemonizing. describe 'agent logging' do ONETIME = '--onetime' DAEMONIZE = '--daemonize' NO_DAEMONIZE = '--no-daemonize' LOGDEST_FILE = '--logdest=/dev/null/foo' LOGDEST_SYSLOG = '--logdest=syslog' LOGDEST_CONSOLE = '--logdest=console' VERBOSE = '--verbose' DEBUG = '--debug' DEFAULT_LOG_LEVEL = :notice INFO_LEVEL = :info DEBUG_LEVEL = :debug CONSOLE = :console SYSLOG = :syslog EVENTLOG = :eventlog FILE = :file ONETIME_DAEMONIZE_ARGS = [ [ONETIME], [ONETIME, DAEMONIZE], [ONETIME, NO_DAEMONIZE], [DAEMONIZE], [NO_DAEMONIZE], [], ] LOG_DEST_ARGS = [LOGDEST_FILE, LOGDEST_SYSLOG, LOGDEST_CONSOLE, nil] LOG_LEVEL_ARGS = [VERBOSE, DEBUG, nil] shared_examples "an agent" do |argv, expected| before(:each) do # Don't actually run the agent, bypassing cert checks, forking and the puppet run itself allow_any_instance_of(Puppet::Application::Agent).to receive(:run_command) # Let exceptions be raised instead of exiting allow_any_instance_of(Puppet::Application::Agent).to receive(:exit_on_fail).and_yield end def double_of_bin_puppet_agent_call(argv) argv.unshift('agent') command_line = Puppet::Util::CommandLine.new('puppet', argv) command_line.execute end if Puppet::Util::Platform.windows? && argv.include?(DAEMONIZE) it "should exit on a platform which cannot daemonize if the --daemonize flag is set" do expect { double_of_bin_puppet_agent_call(argv) }.to raise_error(SystemExit) end else if no_log_dest_set_in(argv) it "when evoked with #{argv}, logs to #{expected[:loggers].inspect} at level #{expected[:level]}" do # This logger is created by the Puppet::Settings object which creates and # applies a catalog to ensure that configuration files and users are in # place. # # It's not something we are specifically testing here since it occurs # regardless of user flags. expect(Puppet::Util::Log).to receive(:newdestination).with(instance_of(Puppet::Transaction::Report)) expected[:loggers].each do |logclass| expect(Puppet::Util::Log).to receive(:newdestination).with(logclass) end double_of_bin_puppet_agent_call(argv) expect(Puppet::Util::Log.level).to eq(expected[:level]) end end end end def self.no_log_dest_set_in(argv) ([LOGDEST_SYSLOG, LOGDEST_CONSOLE, LOGDEST_FILE] & argv).empty? end def self.verbose_or_debug_set_in_argv(argv) !([VERBOSE, DEBUG] & argv).empty? end def self.log_dest_is_set_to(argv, log_dest) argv.include?(log_dest) end # @param argv Array of commandline flags # @return Set<Symbol> of expected loggers def self.expected_loggers(argv) loggers = Set.new loggers << CONSOLE if verbose_or_debug_set_in_argv(argv) loggers << 'console' if log_dest_is_set_to(argv, LOGDEST_CONSOLE) loggers << '/dev/null/foo' if log_dest_is_set_to(argv, LOGDEST_FILE) if Puppet::Util::Platform.windows? # an explicit call to --logdest syslog on windows is swallowed silently with no # logger created (see #suitable() of the syslog Puppet::Util::Log::Destination subclass) # however Puppet::Util::Log.newdestination('syslog') does get called...so we have # to set an expectation loggers << 'syslog' if log_dest_is_set_to(argv, LOGDEST_SYSLOG) loggers << EVENTLOG if no_log_dest_set_in(argv) else # posix loggers << 'syslog' if log_dest_is_set_to(argv, LOGDEST_SYSLOG) loggers << SYSLOG if no_log_dest_set_in(argv) end return loggers end # @param argv Array of commandline flags # @return Symbol of the expected log level def self.expected_level(argv) case when argv.include?(VERBOSE) then INFO_LEVEL when argv.include?(DEBUG) then DEBUG_LEVEL else DEFAULT_LOG_LEVEL end end # @param argv Array of commandline flags # @return Hash of expected loggers and the expected log level def self.with_expectations_based_on(argv) { :loggers => expected_loggers(argv), :level => expected_level(argv), } end # For running a single spec (by line number): rspec -l150 spec/integration/agent/logging_spec.rb # debug_argv = [] # it_should_behave_like( "an agent", [debug_argv], with_expectations_based_on([debug_argv])) ONETIME_DAEMONIZE_ARGS.each do |onetime_daemonize_args| LOG_LEVEL_ARGS.each do |log_level_args| LOG_DEST_ARGS.each do |log_dest_args| argv = (onetime_daemonize_args + [log_level_args, log_dest_args]).flatten.compact describe "for #{argv}" do it_should_behave_like("an agent", argv, with_expectations_based_on(argv)) end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/parser/class_spec.rb
spec/integration/parser/class_spec.rb
require 'spec_helper' require 'puppet_spec/language' describe "Class expressions" do extend PuppetSpec::Language produces( "class hi { }" => '!defined(Class[hi])', "class hi { } include hi" => 'defined(Class[hi])', "include(hi) class hi { }" => 'defined(Class[hi])', "class hi { } class { hi: }" => 'defined(Class[hi])', "class { hi: } class hi { }" => 'defined(Class[hi])', "class bye { } class hi inherits bye { } include hi" => 'defined(Class[hi]) and defined(Class[bye])') produces(<<-EXAMPLE => 'defined(Notify[foo]) and defined(Notify[bar]) and !defined(Notify[foo::bar])') class bar { notify { 'bar': } } class foo::bar { notify { 'foo::bar': } } class foo inherits bar { notify { 'foo': } } include foo EXAMPLE produces(<<-EXAMPLE => 'defined(Notify[foo]) and defined(Notify[bar]) and !defined(Notify[foo::bar])') class bar { notify { 'bar': } } class foo::bar { notify { 'foo::bar': } } class foo inherits ::bar { notify { 'foo': } } include foo EXAMPLE end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/parser/scope_spec.rb
spec/integration/parser/scope_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' describe "Two step scoping for variables" do include PuppetSpec::Compiler def expect_the_message_to_be(message, node = Puppet::Node.new('the node')) catalog = compile_to_catalog(yield, node) expect(catalog.resource('Notify', 'something')[:message]).to eq(message) end def expect_the_message_not_to_be(message, node = Puppet::Node.new('the node')) catalog = compile_to_catalog(yield, node) expect(catalog.resource('Notify', 'something')[:message]).to_not eq(message) end before :each do expect(Puppet).not_to receive(:deprecation_warning) end describe "using unsupported operators" do it "issues an error for +=" do expect do compile_to_catalog(<<-MANIFEST) $var = ["top_msg"] node default { $var += ["override"] } MANIFEST end.to raise_error(/The operator '\+=' is no longer supported/) end it "issues an error for -=" do expect do compile_to_catalog(<<-MANIFEST) $var = ["top_msg"] node default { $var -= ["top_msg"] } MANIFEST end.to raise_error(/The operator '-=' is no longer supported/) end it "issues error about built-in variable when reassigning to name" do enc_node = Puppet::Node.new("the_node", { :parameters => { } }) expect { compile_to_catalog("$name = 'never in a 0xF4240 years'", enc_node) }.to raise_error( Puppet::Error, /Cannot reassign built in \(or already assigned\) variable '\$name' \(line: 1(, column: 7)?\) on node the_node/ ) end it "issues error about built-in variable when reassigning to title" do enc_node = Puppet::Node.new("the_node", { :parameters => { } }) expect { compile_to_catalog("$title = 'never in a 0xF4240 years'", enc_node) }.to raise_error( Puppet::Error, /Cannot reassign built in \(or already assigned\) variable '\$title' \(line: 1(, column: 8)?\) on node the_node/ ) end it "when using a template ignores the dynamic value of the var when using the @varname syntax" do expect_the_message_to_be('node_msg') do <<-MANIFEST node default { $var = "node_msg" include foo } class foo { $var = "foo_msg" include bar } class bar { notify { 'something': message => inline_template("<%= @var %>"), } } MANIFEST end end it "when using a template gets the var from an inherited class when using the @varname syntax" do expect_the_message_to_be('Barbamama') do <<-MANIFEST node default { $var = "node_msg" include bar_bamama include foo } class bar_bamama { $var = "Barbamama" } class foo { $var = "foo_msg" include bar } class bar inherits bar_bamama { notify { 'something': message => inline_template("<%= @var %>"), } } MANIFEST end end it "when using a template ignores the dynamic var when it is not present in an inherited class" do expect_the_message_to_be('node_msg') do <<-MANIFEST node default { $var = "node_msg" include bar_bamama include foo } class bar_bamama { } class foo { $var = "foo_msg" include bar } class bar inherits bar_bamama { notify { 'something': message => inline_template("<%= @var %>"), } } MANIFEST end end describe 'handles 3.x/4.x functions' do it 'can call a 3.x function via call_function' do expect_the_message_to_be('yes') do <<-MANIFEST $msg = inline_template('<%= scope().call_function("fqdn_rand", [30]).to_i <= 30 ? "yes" : "no" %>') notify { 'something': message => $msg } MANIFEST end end it 'it can call a 4.x function via call_function' do expect_the_message_to_be('yes') do <<-MANIFEST $msg = inline_template('<%= scope().call_function("with", ["yes"]) { |x| x } %>') notify { 'something': message => $msg } MANIFEST end end end end describe "fully qualified variable names" do it "keeps nodescope separate from topscope" do expect_the_message_to_be('topscope') do <<-MANIFEST $c = "topscope" node default { $c = "nodescope" notify { 'something': message => $::c } } MANIFEST end end end describe "when colliding class and variable names" do it "finds a topscope variable with the same name as a class" do expect_the_message_to_be('topscope') do <<-MANIFEST $c = "topscope" class c { } node default { include c notify { 'something': message => $c } } MANIFEST end end it "finds a node scope variable with the same name as a class" do expect_the_message_to_be('nodescope') do <<-MANIFEST class c { } node default { $c = "nodescope" include c notify { 'something': message => $c } } MANIFEST end end it "finds a class variable when the class collides with a nodescope variable" do expect_the_message_to_be('class') do <<-MANIFEST class c { $b = "class" } node default { $c = "nodescope" include c notify { 'something': message => $c::b } } MANIFEST end end it "finds a class variable when the class collides with a topscope variable" do expect_the_message_to_be('class') do <<-MANIFEST $c = "topscope" class c { $b = "class" } node default { include c notify { 'something': message => $::c::b } } MANIFEST end end end describe "when using shadowing and inheritance" do it "finds values in its local scope" do expect_the_message_to_be('local_msg') do <<-MANIFEST node default { include baz } class foo { } class bar inherits foo { $var = "local_msg" notify { 'something': message => $var, } } class baz { include bar } MANIFEST end end it "finds values in its inherited scope" do expect_the_message_to_be('foo_msg') do <<-MANIFEST node default { include baz } class foo { $var = "foo_msg" } class bar inherits foo { notify { 'something': message => $var, } } class baz { include bar } MANIFEST end end it "prefers values in its local scope over values in the inherited scope" do expect_the_message_to_be('local_msg') do <<-MANIFEST include bar class foo { $var = "inherited" } class bar inherits foo { $var = "local_msg" notify { 'something': message => $var, } } MANIFEST end end it "finds a qualified variable by following inherited scope of the specified scope" do expect_the_message_to_be("from parent") do <<-MANIFEST class c { notify { 'something': message => "$a::b" } } class parent { $b = 'from parent' } class a inherits parent { } node default { $b = "from node" include a include c } MANIFEST end end ['a:.b', '::a::b'].each do |ref| it "does not resolve a qualified name on the form #{ref} against top scope" do # strict mode is off so behavior this test is trying to check isn't stubbed out Puppet[:strict_variables] = false Puppet[:strict] = :warning expect_the_message_not_to_be("from topscope") do <<-"MANIFEST" class c { notify { 'something': message => "$#{ref}" } } class parent { $not_b = 'from parent' } class a inherits parent { } $b = "from topscope" node default { include a include c } MANIFEST end end end ['a:.b', '::a::b'].each do |ref| it "does not resolve a qualified name on the form #{ref} against node scope" do # strict mode is off so behavior this test is trying to check isn't stubbed out Puppet[:strict_variables] = false Puppet[:strict] = :warning expect_the_message_not_to_be("from node") do <<-MANIFEST class c { notify { 'something': message => "$a::b" } } class parent { $not_b = 'from parent' } class a inherits parent { } node default { $b = "from node" include a include c } MANIFEST end end end it 'resolves a qualified name in class parameter scope' do expect_the_message_to_be('Does it work? Yes!') do <<-PUPPET class a ( $var1 = 'Does it work?', $var2 = "${a::var1} Yes!" ) { notify { 'something': message => $var2 } } include a PUPPET end end it "finds values in its inherited scope when the inherited class is qualified to the top" do expect_the_message_to_be('foo_msg') do <<-MANIFEST node default { include baz } class foo { $var = "foo_msg" } class bar inherits ::foo { notify { 'something': message => $var, } } class baz { include bar } MANIFEST end end it "prefers values in its local scope over values in the inherited scope when the inherited class is fully qualified" do expect_the_message_to_be('local_msg') do <<-MANIFEST include bar class foo { $var = "inherited" } class bar inherits ::foo { $var = "local_msg" notify { 'something': message => $var, } } MANIFEST end end it "finds values in top scope when the inherited class is qualified to the top" do expect_the_message_to_be('top msg') do <<-MANIFEST $var = "top msg" class foo { } class bar inherits ::foo { notify { 'something': message => $var, } } include bar MANIFEST end end it "finds values in its inherited scope when the inherited class is a nested class that shadows another class at the top" do expect_the_message_to_be('inner baz') do <<-MANIFEST node default { include foo::bar } class baz { $var = "top baz" } class foo { class baz { $var = "inner baz" } class bar inherits foo::baz { notify { 'something': message => $var, } } } MANIFEST end end it "finds values in its inherited scope when the inherited class is qualified to a nested class and qualified to the top" do expect_the_message_to_be('top baz') do <<-MANIFEST node default { include foo::bar } class baz { $var = "top baz" } class foo { class baz { $var = "inner baz" } class bar inherits ::baz { notify { 'something': message => $var, } } } MANIFEST end end it "finds values in its inherited scope when the inherited class is qualified" do expect_the_message_to_be('foo_msg') do <<-MANIFEST node default { include bar } class foo { class baz { $var = "foo_msg" } } class bar inherits foo::baz { notify { 'something': message => $var, } } MANIFEST end end it "prefers values in its inherited scope over those in the node (with intermediate inclusion)" do expect_the_message_to_be('foo_msg') do <<-MANIFEST node default { $var = "node_msg" include baz } class foo { $var = "foo_msg" } class bar inherits foo { notify { 'something': message => $var, } } class baz { include bar } MANIFEST end end it "prefers values in its inherited scope over those in the node (without intermediate inclusion)" do expect_the_message_to_be('foo_msg') do <<-MANIFEST node default { $var = "node_msg" include bar } class foo { $var = "foo_msg" } class bar inherits foo { notify { 'something': message => $var, } } MANIFEST end end it "prefers values in its inherited scope over those from where it is included" do expect_the_message_to_be('foo_msg') do <<-MANIFEST node default { include baz } class foo { $var = "foo_msg" } class bar inherits foo { notify { 'something': message => $var, } } class baz { $var = "baz_msg" include bar } MANIFEST end end it "does not used variables from classes included in the inherited scope" do expect_the_message_to_be('node_msg') do <<-MANIFEST node default { $var = "node_msg" include bar } class quux { $var = "quux_msg" } class foo inherits quux { } class baz { include foo } class bar inherits baz { notify { 'something': message => $var, } } MANIFEST end end it "does not use a variable from a scope lexically enclosing it" do expect_the_message_to_be('node_msg') do <<-MANIFEST node default { $var = "node_msg" include other::bar } class other { $var = "other_msg" class bar { notify { 'something': message => $var, } } } MANIFEST end end it "finds values in its node scope" do expect_the_message_to_be('node_msg') do <<-MANIFEST node default { $var = "node_msg" include baz } class foo { } class bar inherits foo { notify { 'something': message => $var, } } class baz { include bar } MANIFEST end end it "finds values in its top scope" do expect_the_message_to_be('top_msg') do <<-MANIFEST $var = "top_msg" node default { include baz } class foo { } class bar inherits foo { notify { 'something': message => $var, } } class baz { include bar } MANIFEST end end it "prefers variables from the node over those in the top scope" do expect_the_message_to_be('node_msg') do <<-MANIFEST $var = "top_msg" node default { $var = "node_msg" include foo } class foo { notify { 'something': message => $var, } } MANIFEST end end it "finds top scope variables referenced inside a defined type" do expect_the_message_to_be('top_msg') do <<-MANIFEST $var = "top_msg" node default { foo { "testing": } } define foo() { notify { 'something': message => $var, } } MANIFEST end end it "finds node scope variables referenced inside a defined type" do expect_the_message_to_be('node_msg') do <<-MANIFEST $var = "top_msg" node default { $var = "node_msg" foo { "testing": } } define foo() { notify { 'something': message => $var, } } MANIFEST end end end describe "in situations that used to have dynamic lookup" do it "ignores the dynamic value of the var" do expect_the_message_to_be('node_msg') do <<-MANIFEST node default { $var = "node_msg" include foo } class baz { $var = "baz_msg" include bar } class foo inherits baz { } class bar { notify { 'something': message => $var, } } MANIFEST end end it "raises an evaluation error when the only set variable is in the dynamic scope" do expect { compile_to_catalog(<<-MANIFEST) node default { include baz } class foo { } class bar inherits foo { notify { 'something': message => $var, } } class baz { $var = "baz_msg" include bar } MANIFEST }.to raise_error(/Evaluation Error: Unknown variable: 'var'./) end it "ignores the value in the dynamic scope for a defined type" do expect_the_message_to_be('node_msg') do <<-MANIFEST node default { $var = "node_msg" include foo } class foo { $var = "foo_msg" bar { "testing": } } define bar() { notify { 'something': message => $var, } } MANIFEST end end it "when using a template ignores the dynamic value of the var when using scope.lookupvar" do expect_the_message_to_be('node_msg') do <<-MANIFEST node default { $var = "node_msg" include foo } class foo { $var = "foo_msg" include bar } class bar { notify { 'something': message => inline_template("<%= scope.lookupvar('var') %>"), } } MANIFEST end end end describe "when using an enc" do it "places enc parameters in top scope" do enc_node = Puppet::Node.new("the node", { :parameters => { "var" => 'from_enc' } }) expect_the_message_to_be('from_enc', enc_node) do <<-MANIFEST notify { 'something': message => $var, } MANIFEST end end it "does not allow the enc to specify an existing top scope var" do enc_node = Puppet::Node.new("the_node", { :parameters => { "var" => 'from_enc' } }) expect { compile_to_catalog("$var = 'top scope'", enc_node) }.to raise_error( Puppet::Error, /Cannot reassign variable '\$var' \(line: 1(, column: 6)?\) on node the_node/ ) end it "evaluates enc classes in top scope when there is no node" do enc_node = Puppet::Node.new("the node", { :classes => ['foo'], :parameters => { "var" => 'from_enc' } }) expect_the_message_to_be('from_enc', enc_node) do <<-MANIFEST class foo { notify { 'something': message => $var, } } MANIFEST end end it "overrides enc variables from a node scope var" do enc_node = Puppet::Node.new("the_node", { :classes => ['foo'], :parameters => { 'enc_var' => 'Set from ENC.' } }) expect_the_message_to_be('ENC overridden in node', enc_node) do <<-MANIFEST node the_node { $enc_var = "ENC overridden in node" } class foo { notify { 'something': message => $enc_var, } } MANIFEST end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/parser/script_compiler_spec.rb
spec/integration/parser/script_compiler_spec.rb
require 'puppet' require 'spec_helper' require 'puppet_spec/compiler' require 'matchers/resource' require 'puppet/parser/script_compiler' describe 'the script compiler' do include PuppetSpec::Compiler include PuppetSpec::Files include Matchers::Resource before(:each) do Puppet[:tasks] = true end context "when used" do let(:env_name) { 'testenv' } let(:environments_dir) { Puppet[:environmentpath] } let(:env_dir) { File.join(environments_dir, env_name) } let(:manifest) { Puppet::Node::Environment::NO_MANIFEST } let(:env) { Puppet::Node::Environment.create(env_name.to_sym, [File.join(populated_env_dir, 'modules')], manifest) } let(:node) { Puppet::Node.new("test", :environment => env) } let(:env_dir_files) { { 'manifests' => { 'good.pp' => "'good'\n" }, 'modules' => { 'test' => { 'plans' => { 'run_me.pp' => 'plan test::run_me() { "worked2" }' } } } } } let(:populated_env_dir) do dir_contained_in(environments_dir, env_name => env_dir_files) PuppetSpec::Files.record_tmp(env_dir) env_dir end let(:script_compiler) do Puppet::Parser::ScriptCompiler.new(env, node.name) end context 'is configured such that' do it 'returns what the script_compiler returns' do Puppet[:code] = <<-CODE 42 CODE expect(script_compiler.compile).to eql(42) end it 'referencing undefined variables raises an error' do expect do Puppet[:code] = <<-CODE notice $rubyversion CODE Puppet::Parser::ScriptCompiler.new(env, 'test_node_name').compile end.to raise_error(/Unknown variable: 'rubyversion'/) end it 'has strict=error behavior' do expect do Puppet[:code] = <<-CODE notice({a => 10, a => 20}) CODE Puppet::Parser::ScriptCompiler.new(env, 'test_node_name').compile end.to raise_error(/The key 'a' is declared more than once/) end it 'performing a multi assign from a class reference raises an error' do expect do Puppet[:code] = <<-CODE [$a] = Class[the_dalit] CODE Puppet::Parser::ScriptCompiler.new(env, 'test_node_name').compile end.to raise_error(/The catalog operation 'multi var assignment from class' is only available when compiling a catalog/) end end context 'when using environment manifest' do context 'set to single file' do let (:manifest) { "#{env_dir}/manifests/good.pp" } it 'loads and evaluates' do expect(script_compiler.compile).to eql('good') end end context 'set to directory' do let (:manifest) { "#{env_dir}/manifests" } it 'fails with an error' do expect{script_compiler.compile}.to raise_error(/manifest of environment 'testenv' appoints directory '.*\/manifests'. It must be a file/) end end context 'set to non existing path' do let (:manifest) { "#{env_dir}/manyfiests/good.pp" } it 'fails with an error' do expect{script_compiler.compile}.to raise_error(/manifest of environment 'testenv' appoints '.*\/good.pp'. It does not exist/) end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/parser/dynamic_scoping_spec.rb
spec/integration/parser/dynamic_scoping_spec.rb
require 'spec_helper' require 'puppet/pops' require 'puppet/parser/parser_factory' require 'puppet_spec/compiler' require 'puppet_spec/pops' require 'puppet_spec/scope' require 'matchers/resource' # These tests are in a separate file since othr compiler related tests have # been dramatically changed between 3.x and 4.x and it is a pain to merge # them. # describe "Puppet::Parser::Compiler when dealing with relative naming" do include PuppetSpec::Compiler include Matchers::Resource describe "the compiler when using 4.x parser and evaluator" do it "should use absolute references even if references are not anchored" do node = Puppet::Node.new("testnodex") catalog = compile_to_catalog(<<-PP, node) class foo::thing { notify {"from foo::thing":} } class thing { notify {"from ::thing":} } class foo { # include thing class {'thing':} } include foo PP catalog = Puppet::Parser::Compiler.compile(node) expect(catalog).to have_resource("Notify[from ::thing]") end it "should use absolute references when references are absolute" do node = Puppet::Node.new("testnodex") catalog = compile_to_catalog(<<-PP, node) class foo::thing { notify {"from foo::thing":} } class thing { notify {"from ::thing":} } class foo { # include thing class {'::thing':} } include foo PP catalog = Puppet::Parser::Compiler.compile(node) expect(catalog).to have_resource("Notify[from ::thing]") end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/parser/undef_param_spec.rb
spec/integration/parser/undef_param_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' describe "Parameter passing" do include PuppetSpec::Compiler before :each do # DataBinding will be consulted before falling back to a default value, # but we aren't testing that here allow(Puppet::DataBinding.indirection).to receive(:find) end def expect_the_message_to_be(message, node = Puppet::Node.new('the node')) catalog = compile_to_catalog(yield, node) expect(catalog.resource('Notify', 'something')[:message]).to eq(message) end def expect_puppet_error(message, node = Puppet::Node.new('the node')) expect { compile_to_catalog(yield, node) }.to raise_error(Puppet::Error, message) end it "overrides the default when a value is given" do expect_the_message_to_be('2') do <<-MANIFEST define a($x='1') { notify { 'something': message => $x }} a {'a': x => '2'} MANIFEST end end it "shadows an inherited variable with the default value when undef is passed" do expect_the_message_to_be('default') do <<-MANIFEST class a { $x = 'inherited' } class b($x='default') inherits a { notify { 'something': message => $x }} class { 'b': x => undef} MANIFEST end end it "uses a default value that comes from an inherited class when the parameter is undef" do expect_the_message_to_be('inherited') do <<-MANIFEST class a { $x = 'inherited' } class b($y=$x) inherits a { notify { 'something': message => $y }} class { 'b': y => undef} MANIFEST end end it "uses a default value that references another variable when the parameter is passed as undef" do expect_the_message_to_be('a') do <<-MANIFEST define a($a = $title) { notify { 'something': message => $a }} a {'a': a => undef} MANIFEST end end it "uses the default when 'undef' is given'" do expect_the_message_to_be('1') do <<-MANIFEST define a($x='1') { notify { 'something': message => $x }} a {'a': x => undef} MANIFEST end end it "uses the default when no parameter is provided" do expect_the_message_to_be('1') do <<-MANIFEST define a($x='1') { notify { 'something': message => $x }} a {'a': } MANIFEST end end it "uses a value of undef when the default is undef and no parameter is provided" do expect_the_message_to_be(true) do <<-MANIFEST define a($x=undef) { notify { 'something': message => $x == undef}} a {'a': } MANIFEST end end it "errors when no parameter is provided and there is no default" do expect_puppet_error(/A\[a\]: expects a value for parameter 'x'/) do <<-MANIFEST define a($x) { notify { 'something': message => $x }} a {'a': } MANIFEST end end it "uses a given undef and do not require a default expression" do expect_the_message_to_be(true) do <<-MANIFEST define a(Optional[Integer] $x) { notify { 'something': message => $x == undef}} a {'a': x => undef } MANIFEST end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/parser/conditionals_spec.rb
spec/integration/parser/conditionals_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'matchers/resource' describe "Evaluation of Conditionals" do include PuppetSpec::Compiler include Matchers::Resource context "a catalog built with conditionals" do it "evaluates an if block correctly" do catalog = compile_to_catalog(<<-CODE) if( 1 == 1) { notify { 'if': } } elsif(2 == 2) { notify { 'elsif': } } else { notify { 'else': } } CODE expect(catalog).to have_resource("Notify[if]") end it "evaluates elsif block" do catalog = compile_to_catalog(<<-CODE) if( 1 == 3) { notify { 'if': } } elsif(2 == 2) { notify { 'elsif': } } else { notify { 'else': } } CODE expect(catalog).to have_resource("Notify[elsif]") end it "reaches the else clause if no expressions match" do catalog = compile_to_catalog(<<-CODE) if( 1 == 2) { notify { 'if': } } elsif(2 == 3) { notify { 'elsif': } } else { notify { 'else': } } CODE expect(catalog).to have_resource("Notify[else]") end it "evalutes false to false" do catalog = compile_to_catalog(<<-CODE) if false { } else { notify { 'false': } } CODE expect(catalog).to have_resource("Notify[false]") end it "evaluates the string 'false' as true" do catalog = compile_to_catalog(<<-CODE) if 'false' { notify { 'true': } } else { notify { 'false': } } CODE expect(catalog).to have_resource("Notify[true]") end it "evaluates undefined variables as false" do # strict mode is off so behavior this test is trying to check isn't stubbed out Puppet[:strict_variables] = false Puppet[:strict] = :warning catalog = compile_to_catalog(<<-CODE) if $undef_var { } else { notify { 'undef': } } CODE expect(catalog).to have_resource("Notify[undef]") end it "evaluates empty string as true" do catalog = compile_to_catalog(<<-CODE) if '' { notify { 'true': } } else { notify { 'empty': } } CODE expect(catalog).to have_resource("Notify[true]") end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/parser/collection_spec.rb
spec/integration/parser/collection_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' describe 'collectors' do include PuppetSpec::Compiler def expect_the_message_to_be(expected_messages, code, node = Puppet::Node.new('the node')) catalog = compile_to_catalog(code, node) messages = catalog.resources.find_all { |resource| resource.type == 'Notify' }. collect { |notify| notify[:message] } expected_messages.each { |message| expect(messages).to include(message) } end def warnings @logs.select { |log| log.level == :warning }.map { |log| log.message } end context "virtual resource collection" do it "matches everything when no query given" do expect_the_message_to_be(["the other message", "the message"], <<-MANIFEST) @notify { "testing": message => "the message" } @notify { "other": message => "the other message" } Notify <| |> MANIFEST end it "matches regular resources " do expect_the_message_to_be(["changed", "changed"], <<-MANIFEST) notify { "testing": message => "the message" } notify { "other": message => "the other message" } Notify <| |> { message => "changed" } MANIFEST end it "matches on tags" do expect_the_message_to_be(["wanted"], <<-MANIFEST) @notify { "testing": tag => ["one"], message => "wanted" } @notify { "other": tag => ["two"], message => "unwanted" } Notify <| tag == one |> MANIFEST end it "matches on title" do expect_the_message_to_be(["the message"], <<-MANIFEST) @notify { "testing": message => "the message" } Notify <| title == "testing" |> MANIFEST end it "matches on other parameters" do expect_the_message_to_be(["the message"], <<-MANIFEST) @notify { "testing": message => "the message" } @notify { "other testing": message => "the wrong message" } Notify <| message == "the message" |> MANIFEST end it "matches against elements of an array valued parameter" do expect_the_message_to_be([["the", "message"]], <<-MANIFEST) @notify { "testing": message => ["the", "message"] } @notify { "other testing": message => ["not", "here"] } Notify <| message == "message" |> MANIFEST end it "matches with bare word" do expect_the_message_to_be(["wanted"], <<-MANIFEST) @notify { "testing": tag => ["one"], message => "wanted" } Notify <| tag == one |> MANIFEST end it "matches with single quoted string" do expect_the_message_to_be(["wanted"], <<-MANIFEST) @notify { "testing": tag => ["one"], message => "wanted" } Notify <| tag == 'one' |> MANIFEST end it "matches with double quoted string" do expect_the_message_to_be(["wanted"], <<-MANIFEST) @notify { "testing": tag => ["one"], message => "wanted" } Notify <| tag == "one" |> MANIFEST end it "matches with double quoted string with interpolated expression" do expect_the_message_to_be(["wanted"], <<-MANIFEST) @notify { "testing": tag => ["one"], message => "wanted" } $x = 'one' Notify <| tag == "$x" |> MANIFEST end it "matches with resource references" do expect_the_message_to_be(["wanted"], <<-MANIFEST) @notify { "foobar": } @notify { "testing": require => Notify["foobar"], message => "wanted" } Notify <| require == Notify["foobar"] |> MANIFEST end it "allows criteria to be combined with 'and'" do expect_the_message_to_be(["the message"], <<-MANIFEST) @notify { "testing": message => "the message" } @notify { "other": message => "the message" } Notify <| title == "testing" and message == "the message" |> MANIFEST end it "allows criteria to be combined with 'or'" do expect_the_message_to_be(["the message", "other message"], <<-MANIFEST) @notify { "testing": message => "the message" } @notify { "other": message => "other message" } @notify { "yet another": message => "different message" } Notify <| title == "testing" or message == "other message" |> MANIFEST end it "allows criteria to be combined with 'or'" do expect_the_message_to_be(["the message", "other message"], <<-MANIFEST) @notify { "testing": message => "the message" } @notify { "other": message => "other message" } @notify { "yet another": message => "different message" } Notify <| title == "testing" or message == "other message" |> MANIFEST end it "allows criteria to be grouped with parens" do expect_the_message_to_be(["the message", "different message"], <<-MANIFEST) @notify { "testing": message => "different message", withpath => true } @notify { "other": message => "the message" } @notify { "yet another": message => "the message", withpath => true } Notify <| (title == "testing" or message == "the message") and withpath == true |> MANIFEST end it "does not do anything if nothing matches" do expect_the_message_to_be([], <<-MANIFEST) @notify { "testing": message => "different message" } Notify <| title == "does not exist" |> MANIFEST end it "excludes items with inequalities" do expect_the_message_to_be(["good message"], <<-MANIFEST) @notify { "testing": message => "good message" } @notify { "the wrong one": message => "bad message" } Notify <| title != "the wrong one" |> MANIFEST end it "does not exclude resources with unequal arrays" do expect_the_message_to_be(["message", ["not this message", "or this one"]], <<-MANIFEST) @notify { "testing": message => "message" } @notify { "the wrong one": message => ["not this message", "or this one"] } Notify <| message != "not this message" |> MANIFEST end it "does not exclude tags with inequalities" do expect_the_message_to_be(["wanted message", "the way it works"], <<-MANIFEST) @notify { "testing": tag => ["wanted"], message => "wanted message" } @notify { "other": tag => ["why"], message => "the way it works" } Notify <| tag != "why" |> MANIFEST end it "does not collect classes" do node = Puppet::Node.new('the node') expect do compile_to_catalog(<<-MANIFEST, node) class theclass { @notify { "testing": message => "good message" } } Class <| |> MANIFEST end.to raise_error(/Classes cannot be collected/) end it "does not collect resources that don't exist" do node = Puppet::Node.new('the node') expect do compile_to_catalog(<<-MANIFEST, node) class theclass { @notify { "testing": message => "good message" } } SomeResource <| |> MANIFEST end.to raise_error(/Resource type someresource doesn't exist/) end it 'allows query for literal undef' do expect_the_message_to_be(["foo::baz::quux"], <<-MANIFEST) define foo ($x = undef, $y = undef) { notify { 'testing': message => "foo::${x}::${y}" } } foo { 'bar': y => 'quux' } Foo <| x == undef |> { x => 'baz' } MANIFEST end context "overrides" do it "modifies an existing array" do expect_the_message_to_be([["original message", "extra message"]], <<-MANIFEST) @notify { "testing": message => ["original message"] } Notify <| |> { message +> "extra message" } MANIFEST end it "converts a scalar to an array" do expect_the_message_to_be([["original message", "extra message"]], <<-MANIFEST) @notify { "testing": message => "original message" } Notify <| |> { message +> "extra message" } MANIFEST end it "splats attributes from a hash" do expect_the_message_to_be(["overridden message"], <<-MANIFEST) @notify { "testing": message => "original message" } Notify <| |> { * => { message => "overridden message" } } MANIFEST end it "collects with override when inside a class (#10963)" do expect_the_message_to_be(["overridden message"], <<-MANIFEST) @notify { "testing": message => "original message" } include collector_test class collector_test { Notify <| |> { message => "overridden message" } } MANIFEST end it "collects with override when inside a define (#10963)" do expect_the_message_to_be(["overridden message"], <<-MANIFEST) @notify { "testing": message => "original message" } collector_test { testing: } define collector_test() { Notify <| |> { message => "overridden message" } } MANIFEST end # Catches regression in implemented behavior, this is not to be taken as this is the wanted behavior # but it has been this way for a long time. it "collects and overrides user defined resources immediately (before queue is evaluated)" do expect_the_message_to_be(["overridden"], <<-MANIFEST) define foo($message) { notify { "testing": message => $message } } foo { test: message => 'given' } Foo <| |> { message => 'overridden' } MANIFEST end # Catches regression in implemented behavior, this is not to be taken as this is the wanted behavior # but it has been this way for a long time. it "collects and overrides user defined resources immediately (virtual resources not queued)" do expect_the_message_to_be(["overridden"], <<-MANIFEST) define foo($message) { @notify { "testing": message => $message } } foo { test: message => 'given' } Notify <| |> # must be collected or the assertion does not find it Foo <| |> { message => 'overridden' } MANIFEST end # Catches regression in implemented behavior, this is not to be taken as this is the wanted behavior # but it has been this way for a long time. # Note difference from none +> case where the override takes effect it "collects and overrides user defined resources with +>" do expect_the_message_to_be([["given", "overridden"]], <<-MANIFEST) define foo($message) { notify { "$name": message => $message } } foo { test: message => ['given'] } Notify <| |> { message +> ['overridden'] } MANIFEST end it "collects and overrides virtual resources multiple times using multiple collects" do expect_the_message_to_be(["overridden2"], <<-MANIFEST) @notify { "testing": message => "original" } Notify <| |> { message => 'overridden1' } Notify <| |> { message => 'overridden2' } MANIFEST end it "collects and overrides non virtual resources multiple times using multiple collects" do expect_the_message_to_be(["overridden2"], <<-MANIFEST) notify { "testing": message => "original" } Notify <| |> { message => 'overridden1' } Notify <| |> { message => 'overridden2' } MANIFEST end context 'when overriding an already evaluated resource' do let(:manifest) { <<-MANIFEST } define foo($message) { notify { "testing": message => $message } } foo { test: message => 'given' } define delayed { Foo <| |> { message => 'overridden' } } delayed {'do it now': } MANIFEST it 'and --strict=off, it silently skips the override' do Puppet[:strict] = :off expect_the_message_to_be(['given'], manifest) expect(warnings).to be_empty end it 'and --strict=warning, it warns about the attempt to override and skips it' do Puppet[:strict] = :warning expect_the_message_to_be(['given'], manifest) expect(warnings).to include( /Attempt to override an already evaluated resource, defined at \(line: 4\), with new values \(line: 6\)/) end it 'and --strict=error, it fails compilation' do Puppet[:strict] = :error expect { compile_to_catalog(manifest) }.to raise_error( /Attempt to override an already evaluated resource, defined at \(line: 4\), with new values \(line: 6\)/) expect(warnings).to be_empty end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/parser/parameter_defaults_spec.rb
spec/integration/parser/parameter_defaults_spec.rb
require 'spec_helper' require 'puppet_spec/language' ['Function', 'EPP'].each do |call_type| describe "#{call_type} parameter default expressions" do let! (:func_bodies) { [ '{}', '{ notice("\$a == ${a}") }', '{ notice("\$a == ${a}") notice("\$b == ${b}") }', '{ notice("\$a == ${a}") notice("\$b == ${b}") notice("\$c == ${c}") }' ] } let! (:epp_bodies) { [ '', '<% notice("\$a == ${a}") %>', '<% notice("\$a == ${a}") notice("\$b == ${b}") %>', '<% notice("\$a == ${a}") notice("\$b == ${b}") notice("\$c == ${c}") %>' ] } let! (:param_names) { ('a'..'c').to_a } let (:call_type) { call_type } let (:compiler) { Puppet::Parser::Compiler.new(Puppet::Node.new('specification')) } let (:topscope) { compiler.topscope } def collect_notices(code) logs = [] Puppet[:code] = code Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do compiler.compile do |catalog| yield catalog end end logs.select { |log| log.level == :notice }.map { |log| log.message } end # @param arg_list [String] comma separated parameter declarations. Not enclosed in parenthesis # @param body [String,Integer] verbatim body or index of an entry in func_bodies # @param call_params [Array[#to_s]] array of call parameters # @return [Array] array of notice output entries # def eval_collect_notices(arg_list, body, call_params) call = call_params.is_a?(String) ? call_params : "example(#{call_params.map {|p| p.nil? ? 'undef' : (p.is_a?(String) ? "'#{p}'" : p )}.join(',')})" body = func_bodies[body] if body.is_a?(Integer) evaluator = Puppet::Pops::Parser::EvaluatingParser.new() collect_notices("function example(#{arg_list}) #{body}") do evaluator.evaluate_string(compiler.topscope, call) end end # @param arg_list [String] comma separated parameter declarations. Not enclosed in parenthesis # @param body [String,Integer] verbatim body or index of an entry in bodies # @param call_params [Array] array of call parameters # @param code [String] code to evaluate # @return [Array] array of notice output entries # def epp_eval_collect_notices(arg_list, body, call_params, code, inline_epp) body = body.is_a?(Integer) ? epp_bodies[body] : body.strip source = "<%| #{arg_list} |%>#{body}" named_params = call_params.reduce({}) {|h, v| h[param_names[h.size]] = v; h } collect_notices(code) do if inline_epp Puppet::Pops::Evaluator::EppEvaluator.inline_epp(compiler.topscope, source, named_params) else file = Tempfile.new(['epp-script', '.epp']) begin file.write(source) file.close Puppet::Pops::Evaluator::EppEvaluator.epp(compiler.topscope, file.path, 'test', named_params) ensure file.unlink end end end end # evaluates a function or EPP call, collects notice output in a log and compares log to expected result # # @param decl [Array[]] two element array with argument list declaration and body. Body can a verbatim string # or an integer index of an entry in bodies # @param call_params [Array[#to_s]] array of call parameters # @param code [String] code to evaluate. Only applicable when call_type == 'EPP' # @param inline_epp [Boolean] true for inline_epp, false for file based epp, Only applicable when call_type == 'EPP' # @return [Array] array of notice output entries # def expect_log(decl, call_params, result, code = 'undef', inline_epp = true) if call_type == 'Function' expect(eval_collect_notices(decl[0], decl[1], call_params)).to include(*result) else expect(epp_eval_collect_notices(decl[0], decl[1], call_params, code, inline_epp)).to include(*result) end end # evaluates a function or EPP call and expects a failure # # @param decl [Array[]] two element array with argument list declaration and body. Body can a verbatim string # or an integer index of an entry in bodies # @param call_params [Array[#to_s]] array of call parameters # @param text [String,Regexp] expected error message def expect_fail(decl, call, text, inline_epp = true) if call_type == 'Function' expect{eval_collect_notices(decl[0], decl[1], call) }.to raise_error(StandardError, text) else expect{epp_eval_collect_notices(decl[0], decl[1], call, 'undef', inline_epp) }.to raise_error(StandardError, text) end end context 'that references a parameter to the left that has no default' do let!(:params) { [ <<-SOURCE, 2 ] $a, $b = $a SOURCE } it 'fails when no value is provided for required first parameter', :if => call_type == 'Function' do expect_fail(params, [], /expects between 1 and 2 arguments, got none/) end it 'fails when no value is provided for required first parameter', :if => call_type == 'EPP' do expect_fail(params, [], /expects a value for parameter \$a/) end it "will use the referenced parameter's given value" do expect_log(params, [2], ['$a == 2', '$b == 2']) end it 'will not be evaluated when a value is given' do expect_log(params, [2, 5], ['$a == 2', '$b == 5']) end end context 'that references a parameter to the left that has a default' do let!(:params) { [ <<-SOURCE, 2 ] $a = 10, $b = $a SOURCE } it "will use the referenced parameter's default value when no value is given for the referenced parameter" do expect_log(params, [], ['$a == 10', '$b == 10']) end it "will use the referenced parameter's given value" do expect_log(params, [2], ['$a == 2', '$b == 2']) end it 'will not be evaluated when a value is given' do expect_log(params, [2, 5], ['$a == 2', '$b == 5']) end end context 'that references a variable to the right' do let!(:params) { [ <<-SOURCE, 3 ] $a = 10, $b = $c, $c = 20 SOURCE } it 'fails when the reference is evaluated' do expect_fail(params, [1], /default expression for \$b tries to illegally access not yet evaluated \$c/) end it 'does not fail when a value is given for the culprit parameter' do expect_log(params, [1,2], ['$a == 1', '$b == 2', '$c == 20']) end it 'does not fail when all values are given' do expect_log(params, [1,2,3], ['$a == 1', '$b == 2', '$c == 3']) end end context 'with regular expressions' do it "evaluates unset match scope parameter's to undef" do expect_log([<<-SOURCE, 2], [], ['$a == ', '$b == ']) $a = $0, $b = $1 SOURCE end it 'does not leak match variables from one expression to the next' do expect_log([<<-SOURCE, 2], [], ['$a == [true, h, ello]', '$b == ']) $a = ['hello' =~ /(h)(.*)/, $1, $2], $b = $1 SOURCE end it 'can evaluate expressions in separate match scopes' do expect_log([<<-SOURCE, 3], [], ['$a == [true, h, ell, o]', '$b == [true, h, i, ]', '$c == ']) $a = ['hello' =~ /(h)(.*)(o)/, $1, $2, $3], $b = ['hi' =~ /(h)(.*)/, $1, $2, $3], $c = $1 SOURCE end it 'can have nested match expressions' do expect_log([<<-SOURCE, 2], [], ['$a == [true, h, oo, h, i]', '$b == '] ) $a = ['hi' =~ /(h)(.*)/, $1, if'foo' =~ /f(oo)/ { $1 }, $1, $2], $b = $0 SOURCE end it 'can not see match scope from calling scope', :if => call_type == 'Function' do expect_log([<<-SOURCE, <<-BODY], <<-CALL, ['$a == ']) $a = $0 SOURCE { notice("\\$a == ${a}") } function caller() { example() } BODY $tmp = 'foo' =~ /(f)(o)(o)/ caller() CALL end context 'matches in calling scope', :if => call_type == 'EPP' do it 'are available when using inlined epp' do # Note that CODE is evaluated before the EPP is evaluated # expect_log([<<-SOURCE, <<-BODY], [], ['$ax == true', '$bx == foo'], <<-CODE, true) $a = $tmp, $b = $0 SOURCE <% called_from_template($a, $b) %> BODY function called_from_template($ax, $bx) { notice("\\$ax == $ax") notice("\\$bx == $bx") } $tmp = 'foo' =~ /(f)(o)(o)/ CODE end it 'are not available when using epp file' do # Note that CODE is evaluated before the EPP is evaluated # expect_log([<<-SOURCE, <<-BODY], [], ['$ax == true', '$bx == '], <<-CODE, false) $a = $tmp, $b = $0 SOURCE <% called_from_template($a, $b) %> BODY function called_from_template($ax, $bx) { notice("\\$ax == $ax") notice("\\$bx == $bx") } $tmp = 'foo' =~ /(f)(o)(o)/ CODE end end it 'will allow nested lambdas to access enclosing match scope' do expect_log([<<-SOURCE, 1], [], ['$a == [1-ello, 2-ello, 3-ello]']) $a = case "hello" { /(h)(.*)/ : { [1,2,3].map |$x| { "$x-$2" } } } SOURCE end it "will not make match scope available to #{call_type} body" do expect_log([<<-SOURCE, call_type == 'Function' ? <<-BODY : <<-EPP_BODY], [], ['Yes']) $a = "hello" =~ /.*/ SOURCE { notice("Y${0}es") } BODY <% notice("Y${0}es") %> EPP_BODY end it 'can access earlier match results when produced using the match function' do expect_log([<<-SOURCE, 3], [], ['$a == [hello, h, ello]', '$b == hello', '$c == h']) $a = 'hello'.match(/(h)(.*)/), $b = $a[0], $c = $a[1] SOURCE end end context 'will not permit assignments' do it 'at top level' do expect_fail([<<-SOURCE, 0], [], /Syntax error at '='/) $a = $x = $0 SOURCE end it 'in arrays' do expect_fail([<<-SOURCE, 0], [], /Assignment not allowed here/) $a = [$x = 3] SOURCE end it 'of variable with the same name as a subsequently declared parameter' do expect_fail([<<-SOURCE, 0], [], /Assignment not allowed here/) $a = ($b = 3), $b = 5 SOURCE end it 'of variable with the same name as a previously declared parameter' do expect_fail([<<-SOURCE, 0], [], /Assignment not allowed here/) $a = 10, $b = ($a = 10) SOURCE end end it 'will permit assignments in nested scope' do expect_log([<<-SOURCE, 3], [], ['$a == [1, 2, 3]', '$b == 0', '$c == [6, 12, 18]']) $a = [1,2,3], $b = 0, $c = $a.map |$x| { $b = $x; $b * $a.reduce |$x, $y| {$x + $y} } SOURCE end it 'will not permit duplicate parameter names' do expect_fail([<<-SOURCE, 0], [], /The parameter 'a' is declared more than once/ ) $a = 2, $a = 5 SOURCE end it 'will permit undef for optional parameters' do expect_log([<<-SOURCE, 1], [nil], ['$a == ']) Optional[Integer] $a SOURCE end it 'undef will override parameter default', :if => call_type == 'Function' do expect_log([<<-SOURCE, 1], [nil], ['$a == ']) Optional[Integer] $a = 4 SOURCE end it 'undef will not override parameter default', :unless => call_type == 'Function' do expect_log([<<-SOURCE, 1], [nil], ['$a == 4']) Optional[Integer] $a = 4 SOURCE end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/parser/pcore_resource_spec.rb
spec/integration/parser/pcore_resource_spec.rb
require 'spec_helper' require 'puppet_spec/files' require 'puppet_spec/compiler' require 'puppet/face' describe 'when pcore described resources types are in use' do include PuppetSpec::Files include PuppetSpec::Compiler let(:genface) { Puppet::Face[:generate, :current] } context "in an environment with two modules" do let(:dir) do dir_containing('environments', { 'production' => { 'environment.conf' => "modulepath = modules", 'manifests' => { 'site.pp' => "" }, 'modules' => { 'm1' => { 'lib' => { 'puppet' => { 'type' => { 'test1.rb' => <<-EOF module Puppet Type.newtype(:test1) do @doc = "Docs for resource" newproperty(:message) do desc "Docs for 'message' property" end newparam(:name) do desc "Docs for 'name' parameter" isnamevar end newparam(:whatever) do desc "Docs for 'whatever' parameter" end end; end EOF } } }, }, 'm2' => { 'lib' => { 'puppet' => { 'type' => { 'test2.rb' => <<-EOF, module Puppet Type.newtype(:test2) do @doc = "Docs for resource" @isomorphic = false newproperty(:message) do desc "Docs for 'message' property" end newparam(:name) do desc "Docs for 'name' parameter" isnamevar end newparam(:color) do desc "Docs for 'color' parameter" newvalues(:red, :green, :blue, /#[0-9A-Z]{6}/) end end;end EOF 'test3.rb' => <<-RUBY, Puppet::Type.newtype(:test3) do newproperty(:message) newparam(:a) { isnamevar } newparam(:b) { isnamevar } newparam(:c) { isnamevar } def self.title_patterns [ [ /^((.+)\\/(.*))$/, [[:a], [:b], [:c]]] ] end end RUBY } } }, } }}}) end let(:modulepath) do File.join(dir, 'production', 'modules') end let(:m1) do File.join(modulepath, 'm1') end let(:m2) do File.join(modulepath, 'm2') end let(:outputdir) do File.join(dir, 'production', '.resource_types') end around(:each) do |example| Puppet.settings.initialize_global_settings Puppet[:manifest] = '' loader = Puppet::Environments::Directories.new(dir, []) Puppet.override(:environments => loader) do Puppet.override(:current_environment => loader.get('production')) do example.run end end end it 'can use generated types to compile a catalog' do genface.types catalog = compile_to_catalog(<<-MANIFEST) test1 { 'a': message => 'a works' } # Several instances of the type can be created - implicit test test1 { 'another a': message => 'another a works' } test2 { 'b': message => 'b works' } test3 { 'x/y': message => 'x/y works' } MANIFEST expect(catalog.resource(:test1, "a")['message']).to eq('a works') expect(catalog.resource(:test2, "b")['message']).to eq('b works') expect(catalog.resource(:test3, "x/y")['message']).to eq('x/y works') end it 'considers Pcore types to be builtin ' do genface.types catalog = compile_to_catalog(<<-MANIFEST) test1 { 'a': message => 'a works' } MANIFEST expect(catalog.resource(:test1, "a").kind).to eq('compilable_type') end it 'considers Pcore types to be builtin ' do genface.types catalog = compile_to_catalog(<<-MANIFEST) test1 { 'a': message => 'a works' } MANIFEST expect(catalog.resource(:test1, "a").kind).to eq('compilable_type') end it 'the validity of attribute names are checked' do genface.types expect do compile_to_catalog(<<-MANIFEST) test1 { 'a': mezzage => 'a works' } MANIFEST end.to raise_error(/no parameter named 'mezzage'/) end it 'meta-parameters such as noop can be used' do genface.types catalog = compile_to_catalog(<<-MANIFEST) test1 { 'a': message => 'noop works', noop => true } MANIFEST expect(catalog.resource(:test1, "a")['noop']).to eq(true) end it 'a generated type describes if it is isomorphic' do generate_and_in_a_compilers_context do |compiler| t1 = find_resource_type(compiler.topscope, 'test1') expect(t1.isomorphic?).to be(true) t2 = find_resource_type(compiler.topscope, 'test2') expect(t2.isomorphic?).to be(false) end end it 'a generated type returns parameters defined in pcore' do generate_and_in_a_compilers_context do |compiler| t1 = find_resource_type(compiler.topscope, 'test1') expect(t1.parameters.size).to be(2) expect(t1.parameters[0].name).to eql('name') expect(t1.parameters[1].name).to eql('whatever') end end it 'a generated type picks up and returns if a parameter is a namevar' do generate_and_in_a_compilers_context do |compiler| t1 = find_resource_type(compiler.topscope, 'test1') expect(t1.parameters[0].name_var).to be(true) expect(t1.parameters[1].name_var).to be(false) end end it 'a generated type returns properties defined in pcore' do generate_and_in_a_compilers_context do |compiler| t1 = find_resource_type(compiler.topscope, 'test1') expect(t1.properties.size).to be(1) expect(t1.properties[0].name).to eql('message') end end it 'a generated type returns [[/(.*)/m, <first attr>]] as default title_pattern when there is a namevar but no pattern specified' do generate_and_in_a_compilers_context do |compiler| t1 = find_resource_type(compiler.topscope, 'test1') expect(t1.title_patterns.size).to be(1) expect(t1.title_patterns[0][0]).to eql(/(?m-ix:(.*))/) end end it "the compiler asserts the type of parameters" do pending "assertion of parameter types not yet implemented" genface.types expect { compile_to_catalog(<<-MANIFEST) test2 { 'b': color => 'white is not a color' } MANIFEST }.to raise_error(/an error indicating that color cannot have that value/) # ERROR TBD. end end def find_resource_type(scope, name) Puppet::Pops::Evaluator::Runtime3ResourceSupport.find_resource_type(scope, name) end def generate_and_in_a_compilers_context(&block) genface.types # Since an instance of a compiler is needed and it starts an initial import that evaluates # code, and that code will be loaded from manifests with a glob (go figure) # the only way to stop that is to set 'code' to something as that overrides "importing" files. Puppet[:code] = "undef" node = Puppet::Node.new('test') # All loading must be done in a context configured as the compiler does it. # (Therefore: use the context a compiler creates as this test logic must otherwise # know how to do this). # compiler = Puppet::Parser::Compiler.new(node) Puppet::override(compiler.context_overrides) do block.call(compiler) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/parser/resource_expressions_spec.rb
spec/integration/parser/resource_expressions_spec.rb
require 'spec_helper' require 'puppet_spec/language' describe "Puppet resource expressions" do extend PuppetSpec::Language produces( "$a = notify $b = example $c = { message => hello } @@Resource[$a] { $b: * => $c } realize(Resource[$a, $b]) " => "Notify[example][message] == 'hello'") context "resource titles" do produces( "notify { thing: }" => "defined(Notify[thing])", "$x = thing notify { $x: }" => "defined(Notify[thing])", "notify { [thing]: }" => "defined(Notify[thing])", "$x = [thing] notify { $x: }" => "defined(Notify[thing])", "notify { [[nested, array]]: }" => "defined(Notify[nested]) and defined(Notify[array])", "$x = [[nested, array]] notify { $x: }" => "defined(Notify[nested]) and defined(Notify[array])", "notify { []: }" => [], # this asserts nothing added "$x = [] notify { $x: }" => [], # this asserts nothing added "notify { default: }" => "!defined(Notify['default'])", # nothing created because this is just a local default "$x = default notify { $x: }" => "!defined(Notify['default'])") fails( "notify { '': }" => /Empty string title/, "$x = '' notify { $x: }" => /Empty string title/, "notify { 1: }" => /Illegal title type.*Expected String, got Integer/, "$x = 1 notify { $x: }" => /Illegal title type.*Expected String, got Integer/, "notify { [1]: }" => /Illegal title type.*Expected String, got Integer/, "$x = [1] notify { $x: }" => /Illegal title type.*Expected String, got Integer/, "notify { 3.0: }" => /Illegal title type.*Expected String, got Float/, "$x = 3.0 notify { $x: }" => /Illegal title type.*Expected String, got Float/, "notify { [3.0]: }" => /Illegal title type.*Expected String, got Float/, "$x = [3.0] notify { $x: }" => /Illegal title type.*Expected String, got Float/, "notify { true: }" => /Illegal title type.*Expected String, got Boolean/, "$x = true notify { $x: }" => /Illegal title type.*Expected String, got Boolean/, "notify { [true]: }" => /Illegal title type.*Expected String, got Boolean/, "$x = [true] notify { $x: }" => /Illegal title type.*Expected String, got Boolean/, "notify { [false]: }" => /Illegal title type.*Expected String, got Boolean/, "$x = [false] notify { $x: }" => /Illegal title type.*Expected String, got Boolean/, "notify { undef: }" => /Missing title.*undef/, "$x = undef notify { $x: }" => /Missing title.*undef/, "notify { [undef]: }" => /Missing title.*undef/, "$x = [undef] notify { $x: }" => /Missing title.*undef/, "notify { {nested => hash}: }" => /Illegal title type.*Expected String, got Hash/, "$x = {nested => hash} notify { $x: }" => /Illegal title type.*Expected String, got Hash/, "notify { [{nested => hash}]: }" => /Illegal title type.*Expected String, got Hash/, "$x = [{nested => hash}] notify { $x: }" => /Illegal title type.*Expected String, got Hash/, "notify { /regexp/: }" => /Illegal title type.*Expected String, got Regexp/, "$x = /regexp/ notify { $x: }" => /Illegal title type.*Expected String, got Regexp/, "notify { [/regexp/]: }" => /Illegal title type.*Expected String, got Regexp/, "$x = [/regexp/] notify { $x: }" => /Illegal title type.*Expected String, got Regexp/, "notify { [dupe, dupe]: }" => /The title 'dupe' has already been used/, "notify { dupe:; dupe: }" => /The title 'dupe' has already been used/, "notify { [dupe]:; dupe: }" => /The title 'dupe' has already been used/, "notify { [default, default]:}" => /The title 'default' has already been used/, "notify { default:; default:}" => /The title 'default' has already been used/, "notify { [default]:; default:}" => /The title 'default' has already been used/) end context "type names" do produces( "notify { testing: }" => "defined(Notify[testing])") produces( "$a = notify; Resource[$a] { testing: }" => "defined(Notify[testing])") produces( "Resource['notify'] { testing: }" => "defined(Notify[testing])") produces( "Resource[sprintf('%s', 'notify')] { testing: }" => "defined(Notify[testing])") produces( "$a = ify; Resource[\"not$a\"] { testing: }" => "defined(Notify[testing])") produces( "Notify { testing: }" => "defined(Notify[testing])") produces( "Resource[Notify] { testing: }" => "defined(Notify[testing])") produces( "Resource['Notify'] { testing: }" => "defined(Notify[testing])") produces( "class a { notify { testing: } } class { a: }" => "defined(Notify[testing])") produces( "class a { notify { testing: } } Class { a: }" => "defined(Notify[testing])") produces( "class a { notify { testing: } } Resource['class'] { a: }" => "defined(Notify[testing])") produces( "define a::b { notify { testing: } } a::b { title: }" => "defined(Notify[testing])") produces( "define a::b { notify { testing: } } A::B { title: }" => "defined(Notify[testing])") produces( "define a::b { notify { testing: } } Resource['a::b'] { title: }" => "defined(Notify[testing])") fails( "'class' { a: }" => /Illegal Resource Type expression.*got String/) fails( "'' { testing: }" => /Illegal Resource Type expression.*got String/) fails( "1 { testing: }" => /Illegal Resource Type expression.*got Integer/) fails( "3.0 { testing: }" => /Illegal Resource Type expression.*got Float/) fails( "true { testing: }" => /Illegal Resource Type expression.*got Boolean/) fails( "'not correct' { testing: }" => /Illegal Resource Type expression.*got String/) fails( "Notify[hi] { testing: }" => /Illegal Resource Type expression.*got Notify\['hi'\]/) fails( "[Notify, File] { testing: }" => /Illegal Resource Type expression.*got Array\[Type\[Resource\]\]/) fails( "define a::b { notify { testing: } } 'a::b' { title: }" => /Illegal Resource Type expression.*got String/) fails( "Does::Not::Exist { title: }" => /Resource type not found: Does::Not::Exist/) end context "local defaults" do produces( "notify { example:; default: message => defaulted }" => "Notify[example][message] == 'defaulted'", "notify { example: message => specific; default: message => defaulted }" => "Notify[example][message] == 'specific'", "notify { example: message => undef; default: message => defaulted }" => "Notify[example][message] == undef", "notify { [example, other]: ; default: message => defaulted }" => "Notify[example][message] == 'defaulted' and Notify[other][message] == 'defaulted'", "notify { [example, default]: message => set; other: }" => "Notify[example][message] == 'set' and Notify[other][message] == 'set'") end context "order of evaluation" do fails("notify { hi: message => value; bye: message => Notify[hi][message] }" => /Resource not found: Notify\['hi'\]/) produces("notify { hi: message => (notify { param: message => set }); bye: message => Notify[param][message] }" => "defined(Notify[hi]) and Notify[bye][message] == 'set'") fails("notify { bye: message => Notify[param][message]; hi: message => (notify { param: message => set }) }" => /Resource not found: Notify\['param'\]/) end context "parameters" do produces( "notify { title: message => set }" => "Notify[title][message] == 'set'", "$x = set notify { title: message => $x }" => "Notify[title][message] == 'set'", "notify { title: *=> { message => set } }" => "Notify[title][message] == 'set'", "$x = { message => set } notify { title: * => $x }" => "Notify[title][message] == 'set'", # picks up defaults "$x = { owner => the_x } $y = { mode => '0666' } $t = '/tmp/x' file { default: * => $x; $t: path => '/somewhere', * => $y }" => "File[$t][mode] == '0666' and File[$t][owner] == 'the_x' and File[$t][path] == '/somewhere'", # explicit wins over default - no error "$x = { owner => the_x, mode => '0777' } $y = { mode => '0666' } $t = '/tmp/x' file { default: * => $x; $t: path => '/somewhere', * => $y }" => "File[$t][mode] == '0666' and File[$t][owner] == 'the_x' and File[$t][path] == '/somewhere'") produces("notify{title:}; Notify[title] { * => { message => set}}" => "Notify[title][message] == 'set'") produces("Notify { * => { message => set}}; notify{title:}" => "Notify[title][message] == 'set'") produces('define foo($x) { notify { "title": message =>"aaa${x}bbb"} } foo{ test: x => undef }' => "Notify[title][message] == 'aaabbb'") produces('define foo($x="xx") { notify { "title": message =>"aaa${x}bbb"} } foo{ test: x => undef }' => "Notify[title][message] == 'aaaxxbbb'") fails("notify { title: unknown => value }" => /no parameter named 'unknown'/) # this really needs to be a better error message. fails("notify { title: * => { hash => value }, message => oops }" => /no parameter named 'hash'/) # should this be a better error message? fails("notify { title: message => oops, * => { hash => value } }" => /no parameter named 'hash'/) fails("notify { title: * => { unknown => value } }" => /no parameter named 'unknown'/) fails(" $x = { mode => '0666' } $y = { owner => the_y } $t = '/tmp/x' file { $t: * => $x, * => $y }" => /Unfolding of attributes from Hash can only be used once per resource body/) end context "virtual" do produces( "@notify { example: }" => "!defined(Notify[example])", "@notify { example: } realize(Notify[example])" => "defined(Notify[example])", "@notify { virtual: message => set } notify { real: message => Notify[virtual][message] }" => "Notify[real][message] == 'set'") end context "exported" do produces( "@@notify { example: }" => "!defined(Notify[example])", "@@notify { example: } realize(Notify[example])" => "defined(Notify[example])", "@@notify { exported: message => set } notify { real: message => Notify[exported][message] }" => "Notify[real][message] == 'set'") end context "explicit undefs" do # PUP-3505 produces(" $x = 10 define foo($x = undef) { notify { example: message => \"'$x'\" } } foo {'blah': x => undef } " => "Notify[example][message] == \"''\"") end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/parser/catalog_spec.rb
spec/integration/parser/catalog_spec.rb
require 'spec_helper' require 'matchers/include_in_order' require 'puppet_spec/compiler' require 'puppet/indirector/catalog/compiler' describe "A catalog" do include PuppetSpec::Compiler context "when compiled" do let(:env) { Puppet::Node::Environment.create(:testing, []) } let(:node) { Puppet::Node.new('test', :environment => env) } let(:loaders) { Puppet::Pops::Loaders.new(env) } before(:each) do Puppet.push_context({:loaders => loaders, :current_environment => env}) allow_any_instance_of(Puppet::Parser::Compiler).to receive(:loaders).and_return(loaders) end after(:each) do Puppet.pop_context() end context "when transmitted to the agent" do it "preserves the order in which the resources are added to the catalog" do resources_in_declaration_order = ["Class[First]", "Second[position]", "Class[Third]", "Fourth[position]"] master_catalog, agent_catalog = master_and_agent_catalogs_for(<<-EOM) define fourth() { } class third { } define second() { fourth { "position": } } class first { second { "position": } class { "third": } } include first EOM expect(resources_in(master_catalog)). to include_in_order(*resources_in_declaration_order) expect(resources_in(agent_catalog)). to include_in_order(*resources_in_declaration_order) end end end def master_catalog_for(manifest) Puppet::Resource::Catalog::Compiler.new.filter(compile_to_catalog(manifest, node)) end def master_and_agent_catalogs_for(manifest) compiler = Puppet::Resource::Catalog::Compiler.new master_catalog = compiler.filter(compile_to_catalog(manifest, node)) agent_catalog = Puppet::Resource::Catalog.convert_from(:json, master_catalog.render(:json)) [master_catalog, agent_catalog] end def resources_in(catalog) catalog.resources.map(&:ref) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/parser/environment_spec.rb
spec/integration/parser/environment_spec.rb
require 'spec_helper' describe "A parser environment setting" do let(:confdir) { Puppet[:confdir] } let(:environmentpath) { File.expand_path("envdir", confdir) } let(:testingdir) { File.join(environmentpath, "testing") } before(:each) do FileUtils.mkdir_p(testingdir) end it "selects the given parser when compiling" do manifestsdir = File.expand_path("manifests", confdir) FileUtils.mkdir_p(manifestsdir) File.open(File.join(testingdir, "environment.conf"), "w") do |f| f.puts(<<-ENVCONF) parser='future' manifest =#{manifestsdir} ENVCONF end File.open(File.join(confdir, "puppet.conf"), "w") do |f| f.puts(<<-EOF) environmentpath=#{environmentpath} parser='current' EOF end File.open(File.join(manifestsdir, "site.pp"), "w") do |f| f.puts("notice( [1,2,3].map |$x| { $x*10 })") end expect { a_catalog_compiled_for_environment('testing') }.to_not raise_error end def a_catalog_compiled_for_environment(envname) Puppet.initialize_settings expect(Puppet[:environmentpath]).to eq(environmentpath) node = Puppet::Node.new('testnode', :environment => 'testing') expect(node.environment).to eq(Puppet.lookup(:environments).get('testing')) Puppet.override(:current_environment => Puppet.lookup(:environments).get('testing')) do Puppet::Parser::Compiler.compile(node) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/parser/compiler_spec.rb
spec/integration/parser/compiler_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'matchers/resource' # COPY OF UNIT TEST class CompilerTestResource attr_accessor :builtin, :virtual, :evaluated, :type, :title def initialize(type, title) @type = type @title = title end def [](attr) return nil if (attr == :stage || attr == :alias) :main end def ref "#{type.to_s.capitalize}[#{title}]" end def evaluated? @evaluated end def builtin_type? @builtin end def virtual? @virtual end def class? false end def stage? false end def evaluate end def file "/fake/file/goes/here" end def line "42" end def resource_type self.class end end describe Puppet::Parser::Compiler do include PuppetSpec::Files include Matchers::Resource def resource(type, title) Puppet::Parser::Resource.new(type, title, :scope => @scope) end let(:environment) { Puppet::Node::Environment.create(:testing, []) } before :each do # Push me faster, I wanna go back in time! (Specifically, freeze time # across the test since we have a bunch of version == timestamp code # hidden away in the implementation and we keep losing the race.) # --daniel 2011-04-21 now = Time.now allow(Time).to receive(:now).and_return(now) @node = Puppet::Node.new("testnode", :facts => Puppet::Node::Facts.new("facts", {}), :environment => environment) @known_resource_types = environment.known_resource_types @compiler = Puppet::Parser::Compiler.new(@node) @scope = Puppet::Parser::Scope.new(@compiler, :source => double('source')) @scope_resource = Puppet::Parser::Resource.new(:file, "/my/file", :scope => @scope) @scope.resource = @scope_resource end # NEW INTEGRATION TEST describe "when evaluating collections" do it 'matches on container inherited tags' do Puppet[:code] = <<-MANIFEST class xport_test { tag('foo_bar') @notify { 'nbr1': message => 'explicitly tagged', tag => 'foo_bar' } @notify { 'nbr2': message => 'implicitly tagged' } Notify <| tag == 'foo_bar' |> { message => 'overridden' } } include xport_test MANIFEST catalog = Puppet::Parser::Compiler.compile(Puppet::Node.new("mynode")) expect(catalog).to have_resource("Notify[nbr1]").with_parameter(:message, 'overridden') expect(catalog).to have_resource("Notify[nbr2]").with_parameter(:message, 'overridden') end end describe "when evaluating node classes" do include PuppetSpec::Compiler describe "when provided classes in hash format" do it 'looks up default parameter values from inherited class (PUP-2532)' do catalog = compile_to_catalog(<<-CODE) class a { Notify { message => "defaulted" } include c notify { bye: } } class b { Notify { message => "inherited" } } class c inherits b { notify { hi: } } include a notify {hi_test: message => Notify[hi][message] } notify {bye_test: message => Notify[bye][message] } CODE expect(catalog).to have_resource("Notify[hi_test]").with_parameter(:message, "inherited") expect(catalog).to have_resource("Notify[bye_test]").with_parameter(:message, "defaulted") end end end context "when converting catalog to resource" do it "the same environment is used for compilation as for transformation to resource form" do Puppet[:code] = <<-MANIFEST notify { 'dummy': } MANIFEST expect_any_instance_of(Puppet::Parser::Resource::Catalog).to receive(:to_resource) do |catalog| expect(Puppet.lookup(:current_environment).name).to eq(:production) end Puppet::Parser::Compiler.compile(Puppet::Node.new("mynode")) end end context 'when working with $settings name space' do include PuppetSpec::Compiler it 'makes $settings::strict available as string' do node = Puppet::Node.new("testing") catalog = compile_to_catalog(<<-MANIFEST, node) notify { 'test': message => $settings::strict == 'error' } MANIFEST expect(catalog).to have_resource("Notify[test]").with_parameter(:message, true) end it 'can return boolean settings as Boolean' do node = Puppet::Node.new("testing") catalog = compile_to_catalog(<<-MANIFEST, node) notify { 'test': message => $settings::storeconfigs == false } MANIFEST expect(catalog).to have_resource("Notify[test]").with_parameter(:message, true) end it 'makes all server settings available as $settings::all_local hash' do node = Puppet::Node.new("testing") catalog = compile_to_catalog(<<-MANIFEST, node) notify { 'test': message => $settings::all_local['strict'] == 'error' } MANIFEST expect(catalog).to have_resource("Notify[test]").with_parameter(:message, true) end end context 'when working with $server_facts' do include PuppetSpec::Compiler it '$trusted is available' do node = Puppet::Node.new("testing") node.add_server_facts({ "server_fact" => "foo" }) catalog = compile_to_catalog(<<-MANIFEST, node) notify { 'test': message => $server_facts[server_fact] } MANIFEST expect(catalog).to have_resource("Notify[test]").with_parameter(:message, "foo") end it 'does not allow assignment to $server_facts' do node = Puppet::Node.new("testing") node.add_server_facts({ "server_fact" => "foo" }) expect do compile_to_catalog(<<-MANIFEST, node) $server_facts = 'changed' notify { 'test': message => $server_facts == 'changed' } MANIFEST end.to raise_error(Puppet::PreformattedError, /Attempt to assign to a reserved variable name: '\$server_facts'.*/) end end describe "the compiler when using 4.x language constructs" do include PuppetSpec::Compiler if Puppet::Util::Platform.windows? it "should be able to determine the configuration version from a local version control repository" do pending("Bug #14071 about semantics of Puppet::Util::Execute on Windows") # This should always work, because we should always be # in the puppet repo when we run this. version = %x{git rev-parse HEAD}.chomp Puppet.settings[:config_version] = 'git rev-parse HEAD' compiler = Puppet::Parser::Compiler.new(Puppet::Node.new("testnode")) compiler.catalog.version.should == version end end it 'assigns multiple variables from a class' do node = Puppet::Node.new("testnodex") catalog = compile_to_catalog(<<-PP, node) class foo::bar::example($x = 100) { $a = 10 $c = undef } include foo::bar::example [$a, $x, $c] = Class['foo::bar::example'] notify{'check_me': message => "$a, $x, -${c}-" } PP expect(catalog).to have_resource("Notify[check_me]").with_parameter(:message, "10, 100, --") end it 'errors on attempt to assigns multiple variables from a class when variable does not exist' do node = Puppet::Node.new("testnodex") expect do compile_to_catalog(<<-PP, node) class foo::bar::example($x = 100) { $ah = 10 $c = undef } include foo::bar::example [$a, $x, $c] = Class['foo::bar::example'] notify{'check_me': message => "$a, $x, -${c}-" } PP end.to raise_error(/No value for required variable '\$foo::bar::example::a'/) end it "should not create duplicate resources when a class is referenced both directly and indirectly by the node classifier (4792)" do node = Puppet::Node.new("testnodex") node.classes = ['foo', 'bar'] compile_to_catalog(<<-PP, node) class foo { notify { foo_notify: } include bar } class bar { notify { bar_notify: } } PP catalog = Puppet::Parser::Compiler.compile(node) expect(catalog).to have_resource("Notify[foo_notify]") expect(catalog).to have_resource("Notify[bar_notify]") end it 'applies defaults for defines with qualified names (PUP-2302)' do catalog = compile_to_catalog(<<-CODE) define my::thing($msg = 'foo') { notify {'check_me': message => $msg } } My::Thing { msg => 'evoe' } my::thing { 'name': } CODE expect(catalog).to have_resource("Notify[check_me]").with_parameter(:message, "evoe") end it 'Applies defaults from dynamic scopes (3x and future with reverted PUP-867)' do catalog = compile_to_catalog(<<-CODE) class a { Notify { message => "defaulted" } include b notify { bye: } } class b { notify { hi: } } include a CODE expect(catalog).to have_resource("Notify[hi]").with_parameter(:message, "defaulted") expect(catalog).to have_resource("Notify[bye]").with_parameter(:message, "defaulted") end it 'gets default from inherited class (PUP-867)' do catalog = compile_to_catalog(<<-CODE) class a { Notify { message => "defaulted" } include c notify { bye: } } class b { Notify { message => "inherited" } } class c inherits b { notify { hi: } } include a CODE expect(catalog).to have_resource("Notify[hi]").with_parameter(:message, "inherited") expect(catalog).to have_resource("Notify[bye]").with_parameter(:message, "defaulted") end it 'looks up default parameter values from inherited class (PUP-2532)' do catalog = compile_to_catalog(<<-CODE) class a { Notify { message => "defaulted" } include c notify { bye: } } class b { Notify { message => "inherited" } } class c inherits b { notify { hi: } } include a notify {hi_test: message => Notify[hi][message] } notify {bye_test: message => Notify[bye][message] } CODE expect(catalog).to have_resource("Notify[hi_test]").with_parameter(:message, "inherited") expect(catalog).to have_resource("Notify[bye_test]").with_parameter(:message, "defaulted") end it 'does not allow override of class parameters using a resource override expression' do expect do compile_to_catalog(<<-CODE) Class[a] { x => 2} CODE end.to raise_error(/Resource Override can only.*got: Class\[a\].*/) end describe 'when resolving class references' do include Matchers::Resource { 'string' => 'myWay', 'class reference' => 'Class["myWay"]', 'resource reference' => 'Resource["class", "myWay"]' }.each do |label, code| it "allows camel cased class name reference in 'include' using a #{label}" do catalog = compile_to_catalog(<<-"PP") class myWay { notify { 'I did it': message => 'my way'} } include #{code} PP expect(catalog).to have_resource("Notify[I did it]") end end describe 'and classname is a Resource Reference' do # tested with strict == off since this was once conditional on strict # can be removed in a later version. before(:each) do Puppet[:strict] = :off end it 'is reported as an error' do expect { compile_to_catalog(<<-PP) notice Class[ToothFairy] PP }.to raise_error(/Illegal Class name in class reference. A TypeReference\['ToothFairy'\]-Type cannot be used where a String is expected/) end end it "should not favor local scope (with class included in topscope)" do catalog = compile_to_catalog(<<-PP) class experiment { class baz { } notify {"x" : require => Class['baz'] } notify {"y" : require => Class['experiment::baz'] } } class baz { } include baz include experiment include experiment::baz PP expect(catalog).to have_resource("Notify[x]").with_parameter(:require, be_resource("Class[Baz]")) expect(catalog).to have_resource("Notify[y]").with_parameter(:require, be_resource("Class[Experiment::Baz]")) end it "should not favor local name scope" do expect { compile_to_catalog(<<-PP) class experiment { class baz { } notify {"x" : require => Class['baz'] } notify {"y" : require => Class['experiment::baz'] } } class baz { } include experiment include experiment::baz PP }.to raise_error(/Could not find resource 'Class\[Baz\]' in parameter 'require'/) end end describe "(ticket #13349) when explicitly specifying top scope" do ["class {'::bar::baz':}", "include ::bar::baz"].each do |include| describe "with #{include}" do it "should find the top level class" do catalog = compile_to_catalog(<<-MANIFEST) class { 'foo::test': } class foo::test { #{include} } class bar::baz { notify { 'good!': } } class foo::bar::baz { notify { 'bad!': } } MANIFEST expect(catalog).to have_resource("Class[Bar::Baz]") expect(catalog).to have_resource("Notify[good!]") expect(catalog).not_to have_resource("Class[Foo::Bar::Baz]") expect(catalog).not_to have_resource("Notify[bad!]") end end end end it 'should recompute the version after input files are re-parsed' do Puppet[:code] = 'class foo { }' first_time = Time.at(1) second_time = Time.at(200) allow(Time).to receive(:now).and_return(first_time) node = Puppet::Node.new('mynode') expect(Puppet::Parser::Compiler.compile(node).version).to eq(first_time.to_i) allow(Time).to receive(:now).and_return(second_time) expect(Puppet::Parser::Compiler.compile(node).version).to eq(first_time.to_i) # no change because files didn't change Puppet[:code] = nil expect(Puppet::Parser::Compiler.compile(node).version).to eq(second_time.to_i) end ['define', 'class', 'node'].each do |thing| it "'#{thing}' is not allowed inside evaluated conditional constructs" do expect do compile_to_catalog(<<-PP) if true { #{thing} foo { } notify { decoy: } } PP end.to raise_error(Puppet::Error, /Classes, definitions, and nodes may only appear at toplevel/) end it "'#{thing}' is not allowed inside un-evaluated conditional constructs" do expect do compile_to_catalog(<<-PP) if false { #{thing} foo { } notify { decoy: } } PP end.to raise_error(Puppet::Error, /Classes, definitions, and nodes may only appear at toplevel/) end end describe "relationships to non existing resources (even with strict==off)" do [ 'before', 'subscribe', 'notify', 'require'].each do |meta_param| it "are reported as an error when formed via meta parameter #{meta_param}" do expect { compile_to_catalog(<<-PP) notify{ x : #{meta_param} => Notify[tooth_fairy] } PP }.to raise_error(/Could not find resource 'Notify\[tooth_fairy\]' in parameter '#{meta_param}'/) end end it 'is not reported for virtual resources' do expect { compile_to_catalog(<<-PP) @notify{ x : require => Notify[tooth_fairy] } PP }.to_not raise_error end it 'is reported for a realized virtual resources' do expect { compile_to_catalog(<<-PP) @notify{ x : require => Notify[tooth_fairy] } realize(Notify['x']) PP }.to raise_error(/Could not find resource 'Notify\[tooth_fairy\]' in parameter 'require'/) end it 'faulty references are reported with source location' do expect { compile_to_catalog(<<-PP) notify{ x : require => tooth_fairy } PP }.to raise_error(/"tooth_fairy" is not a valid resource reference.*\(line: 2\)/) end end describe "relationships can be formed" do def extract_name(ref) ref.sub(/File\[(\w+)\]/, '\1') end def assert_creates_relationships(relationship_code, expectations) base_manifest = <<-MANIFEST file { [a,b,c]: mode => '0644', } file { [d,e]: mode => '0755', } MANIFEST catalog = compile_to_catalog(base_manifest + relationship_code) resources = catalog.resources.select { |res| res.type == 'File' } actual_relationships, actual_subscriptions = [:before, :notify].map do |relation| resources.map do |res| dependents = Array(res[relation]) dependents.map { |ref| [res.title, extract_name(ref)] } end.inject(&:concat) end expect(actual_relationships).to match_array(expectations[:relationships] || []) expect(actual_subscriptions).to match_array(expectations[:subscriptions] || []) end it "of regular type" do assert_creates_relationships("File[a] -> File[b]", :relationships => [['a','b']]) end it "of subscription type" do assert_creates_relationships("File[a] ~> File[b]", :subscriptions => [['a', 'b']]) end it "between multiple resources expressed as resource with multiple titles" do assert_creates_relationships("File[a,b] -> File[c,d]", :relationships => [['a', 'c'], ['b', 'c'], ['a', 'd'], ['b', 'd']]) end it "between collection expressions" do assert_creates_relationships("File <| mode == '0644' |> -> File <| mode == '0755' |>", :relationships => [['a', 'd'], ['b', 'd'], ['c', 'd'], ['a', 'e'], ['b', 'e'], ['c', 'e']]) end it "between resources expressed as Strings" do assert_creates_relationships("'File[a]' -> 'File[b]'", :relationships => [['a', 'b']]) end it "between resources expressed as variables" do assert_creates_relationships(<<-MANIFEST, :relationships => [['a', 'b']]) $var = File[a] $var -> File[b] MANIFEST end it "between resources expressed as case statements" do assert_creates_relationships(<<-MANIFEST, :relationships => [['s1', 't2']]) $var = 10 case $var { 10: { file { s1: } } 12: { file { s2: } } } -> case $var + 2 { 10: { file { t1: } } 12: { file { t2: } } } MANIFEST end it "using deep access in array" do assert_creates_relationships(<<-MANIFEST, :relationships => [['a', 'b']]) $var = [ [ [ File[a], File[b] ] ] ] $var[0][0][0] -> $var[0][0][1] MANIFEST end it "using deep access in hash" do assert_creates_relationships(<<-MANIFEST, :relationships => [['a', 'b']]) $var = {'foo' => {'bar' => {'source' => File[a], 'target' => File[b]}}} $var[foo][bar][source] -> $var[foo][bar][target] MANIFEST end it "using resource declarations" do assert_creates_relationships("file { l: } -> file { r: }", :relationships => [['l', 'r']]) end it "between entries in a chain of relationships" do assert_creates_relationships("File[a] -> File[b] ~> File[c] <- File[d] <~ File[e]", :relationships => [['a', 'b'], ['d', 'c']], :subscriptions => [['b', 'c'], ['e', 'd']]) end it 'should close the gap created by an intermediate empty set produced by collection' do source = "file { [aa, bb]: } [File[a], File[aa]] -> Notify<| tag == 'na' |> ~> [File[b], File[bb]]" assert_creates_relationships(source, :relationships => [ ], :subscriptions => [['a', 'b'],['aa', 'b'],['a', 'bb'], ['aa', 'bb']]) end it 'should close the gap created by empty set followed by empty collection' do source = "file { [aa, bb]: } [File[a], File[aa]] -> [] -> Notify<| tag == 'na' |> ~> [File[b], File[bb]]" assert_creates_relationships(source, :relationships => [ ], :subscriptions => [['a', 'b'],['aa', 'b'],['a', 'bb'], ['aa', 'bb']]) end it 'should close the gap created by empty collection surrounded by empty sets' do source = "file { [aa, bb]: } [File[a], File[aa]] -> [] -> Notify<| tag == 'na' |> -> [] ~> [File[b], File[bb]]" assert_creates_relationships(source, :relationships => [ ], :subscriptions => [['a', 'b'],['aa', 'b'],['a', 'bb'], ['aa', 'bb']]) end it 'should close the gap created by several intermediate empty sets produced by collection' do source = "file { [aa, bb]: } [File[a], File[aa]] -> Notify<| tag == 'na' |> -> Notify<| tag == 'na' |> ~> [File[b], File[bb]]" assert_creates_relationships(source, :relationships => [ ], :subscriptions => [['a', 'b'],['aa', 'b'],['a', 'bb'], ['aa', 'bb']]) end end context "when dealing with variable references" do it 'an initial underscore in a variable name is ok' do catalog = compile_to_catalog(<<-MANIFEST) class a { $_a = 10} include a notify { 'test': message => $a::_a } MANIFEST expect(catalog).to have_resource("Notify[test]").with_parameter(:message, 10) end it 'an initial underscore in not ok if elsewhere than last segment' do expect do compile_to_catalog(<<-MANIFEST) class a { $_a = 10} include a notify { 'test': message => $_a::_a } MANIFEST end.to raise_error(/Illegal variable name/) end it 'a missing variable as default causes an evaluation error' do # strict mode on by default for 8.x expect { compile_to_catalog(<<-MANIFEST) class a ($b=$x) { notify {test: message=>"yes ${undef == $b}" } } include a MANIFEST }.to raise_error(/Evaluation Error: Unknown variable: 'x'/) end it 'a missing variable as default value becomes undef when strict mode is off' do Puppet[:strict_variables] = false Puppet[:strict] = :warning catalog = compile_to_catalog(<<-MANIFEST) class a ($b=$x) { notify {test: message=>"yes ${undef == $b}" } } include a MANIFEST expect(catalog).to have_resource("Notify[test]").with_parameter(:message, "yes true") end end context "when dealing with resources (e.g. File) that modifies its name from title" do [['', ''], ['', '/'], ['/', ''], ['/', '/']].each do |t, r| it "a circular reference can be compiled with endings: title='#{t}' and ref='#{r}'" do expect { node = Puppet::Node.new("testing") compile_to_catalog(<<-"MANIFEST", node) file { '/tmp/bazinga.txt#{t}': content => 'henrik testing', require => File['/tmp/bazinga.txt#{r}'] } MANIFEST }.not_to raise_error end end end context 'when working with the trusted data hash' do context 'and have opted in to hashed_node_data' do it 'should make $trusted available' do node = Puppet::Node.new("testing") node.trusted_data = { "data" => "value" } catalog = compile_to_catalog(<<-MANIFEST, node) notify { 'test': message => $trusted[data] } MANIFEST expect(catalog).to have_resource("Notify[test]").with_parameter(:message, "value") end it 'should not allow assignment to $trusted' do node = Puppet::Node.new("testing") node.trusted_data = { "data" => "value" } expect do compile_to_catalog(<<-MANIFEST, node) $trusted = 'changed' notify { 'test': message => $trusted == 'changed' } MANIFEST end.to raise_error(Puppet::PreformattedError, /Attempt to assign to a reserved variable name: '\$trusted'/) end end end context 'when using typed parameters in definition' do it 'accepts type compliant arguments' do catalog = compile_to_catalog(<<-MANIFEST) define foo(String $x) { } foo { 'test': x =>'say friend' } MANIFEST expect(catalog).to have_resource("Foo[test]").with_parameter(:x, 'say friend') end it 'accepts undef as the default for an Optional argument' do catalog = compile_to_catalog(<<-MANIFEST) define foo(Optional[String] $x = undef) { notify { "expected": message => $x == undef } } foo { 'test': } MANIFEST expect(catalog).to have_resource("Notify[expected]").with_parameter(:message, true) end it 'accepts anything when parameters are untyped' do expect do compile_to_catalog(<<-MANIFEST) define foo($a, $b, $c) { } foo { 'test': a => String, b=>10, c=>undef } MANIFEST end.to_not raise_error() end it 'denies non type compliant arguments' do expect do compile_to_catalog(<<-MANIFEST) define foo(Integer $x) { } foo { 'test': x =>'say friend' } MANIFEST end.to raise_error(/Foo\[test\]: parameter 'x' expects an Integer value, got String/) end it 'denies undef for a non-optional type' do expect do compile_to_catalog(<<-MANIFEST) define foo(Integer $x) { } foo { 'test': x => undef } MANIFEST end.to raise_error(/Foo\[test\]: parameter 'x' expects an Integer value, got Undef/) end it 'denies non type compliant default argument' do expect do compile_to_catalog(<<-MANIFEST) define foo(Integer $x = 'pow') { } foo { 'test': } MANIFEST end.to raise_error(/Foo\[test\]: parameter 'x' expects an Integer value, got String/) end it 'denies undef as the default for a non-optional type' do expect do compile_to_catalog(<<-MANIFEST) define foo(Integer $x = undef) { } foo { 'test': } MANIFEST end.to raise_error(/Foo\[test\]: parameter 'x' expects an Integer value, got Undef/) end it 'accepts a Resource as a Type' do catalog = compile_to_catalog(<<-MANIFEST) define bar($text) { } define foo(Type[Bar] $x) { notify { 'test': message => $x[text] } } bar { 'joke': text => 'knock knock' } foo { 'test': x => Bar[joke] } MANIFEST expect(catalog).to have_resource("Notify[test]").with_parameter(:message, 'knock knock') end it 'uses infer_set when reporting type mismatch' do expect do compile_to_catalog(<<-MANIFEST) define foo(Struct[{b => Integer, d=>String}] $a) { } foo{ bar: a => {b => 5, c => 'stuff'}} MANIFEST end.to raise_error(/Foo\[bar\]:\s+parameter 'a' expects a value for key 'd'\s+parameter 'a' unrecognized key 'c'/m) end it 'handles Sensitive type in resource array' do catalog = compile_to_catalog(<<-MANIFEST) define foo(Sensitive[String] $password) { notify{ "${title}": message => "${password}" } } foo { ['testA', 'testB']: password =>Sensitive('some password') } MANIFEST expect(catalog).to have_resource("Notify[testA]").with_parameter(:message, 'Sensitive [value redacted]') expect(catalog).to have_resource("Notify[testB]").with_parameter(:message, 'Sensitive [value redacted]') end end context 'when using typed parameters in class' do it 'accepts type compliant arguments' do catalog = compile_to_catalog(<<-MANIFEST) class foo(String $x) { } class { 'foo': x =>'say friend' } MANIFEST expect(catalog).to have_resource("Class[Foo]").with_parameter(:x, 'say friend') end it 'accepts undef as the default for an Optional argument' do catalog = compile_to_catalog(<<-MANIFEST) class foo(Optional[String] $x = undef) { notify { "expected": message => $x == undef } } class { 'foo': } MANIFEST expect(catalog).to have_resource("Notify[expected]").with_parameter(:message, true) end it 'accepts anything when parameters are untyped' do expect do compile_to_catalog(<<-MANIFEST) class foo($a, $b, $c) { } class { 'foo': a => String, b=>10, c=>undef } MANIFEST end.to_not raise_error() end it 'denies non type compliant arguments' do expect do compile_to_catalog(<<-MANIFEST) class foo(Integer $x) { } class { 'foo': x =>'say friend' } MANIFEST end.to raise_error(/Class\[Foo\]: parameter 'x' expects an Integer value, got String/) end it 'denies undef for a non-optional type' do expect do compile_to_catalog(<<-MANIFEST) class foo(Integer $x) { } class { 'foo': x => undef } MANIFEST end.to raise_error(/Class\[Foo\]: parameter 'x' expects an Integer value, got Undef/) end it 'denies non type compliant default argument' do expect do compile_to_catalog(<<-MANIFEST) class foo(Integer $x = 'pow') { } class { 'foo': } MANIFEST end.to raise_error(/Class\[Foo\]: parameter 'x' expects an Integer value, got String/) end it 'denies undef as the default for a non-optional type' do expect do compile_to_catalog(<<-MANIFEST) class foo(Integer $x = undef) { } class { 'foo': } MANIFEST end.to raise_error(/Class\[Foo\]: parameter 'x' expects an Integer value, got Undef/) end it 'denies a regexp (rich data) argument given to class String parameter (even if later encoding of it is a string)' do expect do compile_to_catalog(<<-MANIFEST) class foo(String $x) { } class { 'foo': x => /I am a regexp and I don't want to be a String/} MANIFEST end.to raise_error(/Class\[Foo\]: parameter 'x' expects a String value, got Regexp/) end it 'denies a regexp (rich data) argument given to define String parameter (even if later encoding of it is a string)' do expect do compile_to_catalog(<<-MANIFEST) define foo(String $x) { } foo { 'foo': x => /I am a regexp and I don't want to be a String/} MANIFEST end.to raise_error(/Foo\[foo\]: parameter 'x' expects a String value, got Regexp/) end it 'accepts a Resource as a Type' do catalog = compile_to_catalog(<<-MANIFEST) define bar($text) { } class foo(Type[Bar] $x) { notify { 'test': message => $x[text] } } bar { 'joke': text => 'knock knock' } class { 'foo': x => Bar[joke] } MANIFEST expect(catalog).to have_resource("Notify[test]").with_parameter(:message, 'knock knock') end end context 'when using typed parameters in lambdas' do it 'accepts type compliant arguments' do catalog = compile_to_catalog(<<-MANIFEST) with('value') |String $x| { notify { "$x": } } MANIFEST
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
true
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/parser/node_spec.rb
spec/integration/parser/node_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'matchers/resource' describe 'node statements' do include PuppetSpec::Compiler include Matchers::Resource context 'nodes' do it 'selects a node where the name is just a number' do # Future parser doesn't allow a number in this position catalog = compile_to_catalog(<<-MANIFEST, Puppet::Node.new("5")) node 5 { notify { 'matched': } } MANIFEST expect(catalog).to have_resource('Notify[matched]') end it 'selects the node with a matching name' do catalog = compile_to_catalog(<<-MANIFEST, Puppet::Node.new("nodename")) node noden {} node nodename { notify { matched: } } node name {} MANIFEST expect(catalog).to have_resource('Notify[matched]') end it 'prefers a node with a literal name over one with a regex' do catalog = compile_to_catalog(<<-MANIFEST, Puppet::Node.new("nodename")) node /noden.me/ { notify { ignored: } } node nodename { notify { matched: } } MANIFEST expect(catalog).to have_resource('Notify[matched]') end it 'selects a node where one of the names matches' do catalog = compile_to_catalog(<<-MANIFEST, Puppet::Node.new("nodename")) node different, nodename, other { notify { matched: } } MANIFEST expect(catalog).to have_resource('Notify[matched]') end it 'arbitrarily selects one of the matching nodes' do catalog = compile_to_catalog(<<-MANIFEST, Puppet::Node.new("nodename")) node /not/ { notify { 'is not matched': } } node /name.*/ { notify { 'could be matched': } } node /na.e/ { notify { 'could also be matched': } } MANIFEST expect([catalog.resource('Notify[could be matched]'), catalog.resource('Notify[could also be matched]')].compact).to_not be_empty end it 'selects a node where one of the names matches with a mixture of literals and regex' do catalog = compile_to_catalog(<<-MANIFEST, Puppet::Node.new("nodename")) node different, /name/, other { notify { matched: } } MANIFEST expect(catalog).to have_resource('Notify[matched]') end it 'that have regex names should not collide with matching class names' do catalog = compile_to_catalog(<<-MANIFEST, Puppet::Node.new("foo")) class foo { $bar = 'one' } node /foo/ { $bar = 'two' include foo notify{"${::foo::bar}":} } MANIFEST expect(catalog).to have_resource('Notify[one]') end it 'does not raise an error with regex and non-regex node names are the same' do expect do compile_to_catalog(<<-MANIFEST) node /a.*(c)?/ { } node 'a.c' { } MANIFEST end.not_to raise_error end it 'does not raise an error with 2 regex node names are the same due to lookarround pattern' do expect do compile_to_catalog(<<-MANIFEST, Puppet::Node.new("async")) node /(?<!a)sync/ { } node /async/ { } MANIFEST end.not_to raise_error end it 'errors when two nodes with regexes collide after some regex syntax is removed' do expect do compile_to_catalog(<<-MANIFEST) node /a.*(c)?/ { } node /a.*c/ { } MANIFEST end.to raise_error(Puppet::Error, /Node '__node_regexp__a.c' is already defined/) end it 'provides captures from the regex in the node body' do catalog = compile_to_catalog(<<-MANIFEST, Puppet::Node.new("nodename")) node /(.*)/ { notify { "$1": } } MANIFEST expect(catalog).to have_resource('Notify[nodename]') end it 'selects the node with the matching regex' do catalog = compile_to_catalog(<<-MANIFEST, Puppet::Node.new("nodename")) node /node.*/ { notify { matched: } } MANIFEST expect(catalog).to have_resource('Notify[matched]') end it 'selects a node that is a literal string' do catalog = compile_to_catalog(<<-MANIFEST, Puppet::Node.new("node.name")) node 'node.name' { notify { matched: } } MANIFEST expect(catalog).to have_resource('Notify[matched]') end it 'does not treat regex symbols as a regex inside a string literal' do catalog = compile_to_catalog(<<-MANIFEST, Puppet::Node.new("nodexname")) node 'node.name' { notify { 'not matched': } } node 'nodexname' { notify { 'matched': } } MANIFEST expect(catalog).to have_resource('Notify[matched]') end it 'errors when two nodes have the same name' do expect do compile_to_catalog(<<-MANIFEST) node name { } node 'name' { } MANIFEST end.to raise_error(Puppet::Error, /Node 'name' is already defined/) end it 'is unable to parse a name that is an invalid number' do expect do compile_to_catalog('node 5name {} ') end.to raise_error(Puppet::Error, /Illegal number '5name'/) end it 'parses a node name that is dotted numbers' do catalog = compile_to_catalog(<<-MANIFEST, Puppet::Node.new("1.2.3.4")) node 1.2.3.4 { notify { matched: } } MANIFEST expect(catalog).to have_resource('Notify[matched]') end it 'raises error for node inheritance' do expect do compile_to_catalog(<<-MANIFEST, Puppet::Node.new("nodename")) node default {} node nodename inherits default { } MANIFEST end.to raise_error(/Node inheritance is not supported in Puppet >= 4\.0\.0/) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/integration/http/client_spec.rb
spec/integration/http/client_spec.rb
require 'spec_helper' require 'puppet_spec/https' require 'puppet_spec/files' describe Puppet::HTTP::Client, unless: Puppet::Util::Platform.jruby? do include PuppetSpec::Files include_context "https client" let(:wrong_hostname) { 'localhost' } let(:client) { Puppet::HTTP::Client.new } let(:ssl_provider) { Puppet::SSL::SSLProvider.new } let(:root_context) { ssl_provider.create_root_context(cacerts: [https_server.ca_cert], crls: [https_server.ca_crl]) } context "when verifying an HTTPS server" do it "connects over SSL" do https_server.start_server do |port| res = client.get(URI("https://127.0.0.1:#{port}"), options: {ssl_context: root_context}) expect(res).to be_success end end it "raises connection error if we can't connect" do Puppet[:http_connect_timeout] = '0s' # get available port, but don't bind to it tcps = TCPServer.new("127.0.0.1", 0) port = tcps.connect_address.ip_port expect { client.get(URI("https://127.0.0.1:#{port}"), options: {ssl_context: root_context}) }.to raise_error(Puppet::HTTP::ConnectionError, %r{^Request to https://127.0.0.1:#{port} timed out connect operation after .* seconds}) end it "raises if the server's cert doesn't match the hostname we connected to" do https_server.start_server do |port| expect { client.get(URI("https://#{wrong_hostname}:#{port}"), options: {ssl_context: root_context}) }.to raise_error { |err| expect(err).to be_instance_of(Puppet::SSL::CertMismatchError) expect(err.message).to match(/Server hostname '#{wrong_hostname}' did not match server certificate; expected one of (.+)/) md = err.message.match(/expected one of (.+)/) expect(md[1].split(', ')).to contain_exactly('127.0.0.1', 'DNS:127.0.0.1', 'DNS:127.0.0.2') } end end it "raises if the server's CA is unknown" do wrong_ca = cert_fixture('netlock-arany-utf8.pem') alt_context = ssl_provider.create_root_context(cacerts: [wrong_ca], revocation: false) https_server.start_server do |port| expect { client.get(URI("https://127.0.0.1:#{port}"), options: {ssl_context: alt_context}) }.to raise_error(Puppet::SSL::CertVerifyError, %r{certificate verify failed.* .self.signed certificate in certificate chain for CN=Test CA.}) end end it "prints TLS protocol and ciphersuite in debug" do Puppet[:log_level] = 'debug' https_server.start_server do |port| client.get(URI("https://127.0.0.1:#{port}"), options: {ssl_context: root_context}) # TLS version string can be TLSv1 or TLSv1.[1-3], but not TLSv1.0 expect(@logs).to include( an_object_having_attributes(level: :debug, message: /Using TLSv1(\.[1-3])? with cipher .*/), ) end end end context "with client certs" do let(:ctx_proc) { -> ctx { # configures the server to require the client to present a client cert ctx.verify_mode = OpenSSL::SSL::VERIFY_PEER | OpenSSL::SSL::VERIFY_FAIL_IF_NO_PEER_CERT } } let(:cert_file) do res = tmpfile('cert_file') File.write(res, https_server.ca_cert) res end it "mutually authenticates the connection using an explicit context" do client_context = ssl_provider.create_context( cacerts: [https_server.ca_cert], crls: [https_server.ca_crl], client_cert: https_server.server_cert, private_key: https_server.server_key ) https_server.start_server(ctx_proc: ctx_proc) do |port| res = client.get(URI("https://127.0.0.1:#{port}"), options: {ssl_context: client_context}) expect(res).to be_success end end it "mutually authenticates the connection when the client and server certs are issued from different CAs" do # this is the client cert's CA, key and cert Puppet[:localcacert] = fixtures('ssl/unknown-ca.pem') Puppet[:hostprivkey] = fixtures('ssl/unknown-127.0.0.1-key.pem') Puppet[:hostcert] = fixtures('ssl/unknown-127.0.0.1.pem') # this is the server cert's CA that the client needs in order to authenticate the server Puppet[:ssl_trust_store] = fixtures('ssl/ca.pem') # need to pass both the client and server CAs. The former is needed so the server can authenticate our client cert https_server = PuppetSpec::HTTPSServer.new(ca_cert: [cert_fixture('ca.pem'), cert_fixture('unknown-ca.pem')]) https_server.start_server(ctx_proc: ctx_proc) do |port| res = client.get(URI("https://127.0.0.1:#{port}"), options: {include_system_store: true}) expect(res).to be_success end end it "connects when the server's CA is in the system store and the connection is mutually authenticated using create_context" do Puppet::Util.withenv("SSL_CERT_FILE" => cert_file) do client_context = ssl_provider.create_context( cacerts: [], crls: [], client_cert: https_server.server_cert, private_key: https_server.server_key, revocation: false, include_system_store: true ) https_server.start_server(ctx_proc: ctx_proc) do |port| res = client.get(URI("https://127.0.0.1:#{port}"), options: {ssl_context: client_context}) expect(res).to be_success end end end it "connects when the server's CA is in the system store and the connection is mutually authenticated using load_context" do Puppet::Util.withenv("SSL_CERT_FILE" => cert_file) do client_context = ssl_provider.load_context(revocation: false, include_system_store: true) https_server.start_server(ctx_proc: ctx_proc) do |port| res = client.get(URI("https://127.0.0.1:#{port}"), options: {ssl_context: client_context}) expect(res).to be_success end end end end context "with a system trust store" do it "connects when the client trusts the server's CA" do system_context = ssl_provider.create_system_context(cacerts: [https_server.ca_cert]) https_server.start_server do |port| res = client.get(URI("https://127.0.0.1:#{port}"), options: {ssl_context: system_context}) expect(res).to be_success end end it "connects when the server's CA is in the system store" do # create a temp cacert bundle cert_file = tmpfile('cert_file') File.write(cert_file, https_server.ca_cert) # override path to system cacert bundle, this must be done before # the SSLContext is created and the call to X509::Store.set_default_paths Puppet::Util.withenv("SSL_CERT_FILE" => cert_file) do system_context = ssl_provider.create_system_context(cacerts: []) https_server.start_server do |port| res = client.get(URI("https://127.0.0.1:#{port}"), options: {ssl_context: system_context}) expect(res).to be_success end end end it "raises if the server's CA is not in the context or system store" do system_context = ssl_provider.create_system_context(cacerts: [cert_fixture('netlock-arany-utf8.pem')]) https_server.start_server do |port| expect { client.get(URI("https://127.0.0.1:#{port}"), options: {ssl_context: system_context}) }.to raise_error(Puppet::SSL::CertVerifyError, %r{certificate verify failed.* .self.signed certificate in certificate chain for CN=Test CA.}) end end end context 'ensure that retrying does not attempt to read the body after closing the connection' do let(:client) { Puppet::HTTP::Client.new(retry_limit: 1) } it 'raises a retry error instead' do response_proc = -> (req, res) { res['Retry-After'] = 1 res.status = 503 } https_server.start_server(response_proc: response_proc) do |port| uri = URI("https://127.0.0.1:#{port}") kwargs = {headers: {'Content-Type' => 'text/plain'}, options: {ssl_context: root_context}} expect{client.post(uri, '', **kwargs)}.to raise_error(Puppet::HTTP::TooManyRetryAfters) end end end context 'persistent connections' do it "detects when the server has closed the connection and reconnects" do Puppet[:http_debug] = true # advertise that we support keep-alive, but we don't really response_proc = -> (req, res) { res['Connection'] = 'Keep-Alive' } https_server.start_server(response_proc: response_proc) do |port| uri = URI("https://127.0.0.1:#{port}") kwargs = {headers: {'Content-Type' => 'text/plain'}, options: {ssl_context: root_context}} expect { expect(client.post(uri, '', **kwargs)).to be_success # the server closes its connection after each request, so posting # again will force ruby to detect that the remote side closed the # connection, and reconnect expect(client.post(uri, '', **kwargs)).to be_success }.to output(/Conn close because of EOF/).to_stderr end end end context 'ciphersuites' do it "does not connect when using an SSLv3 ciphersuite", :if => Puppet::Util::Package.versioncmp(OpenSSL::OPENSSL_LIBRARY_VERSION.split[1], '1.1.1e') > 0 do Puppet[:ciphers] = "DES-CBC3-SHA" https_server.start_server do |port| expect { client.get(URI("https://127.0.0.1:#{port}"), options: {ssl_context: root_context}) }.to raise_error(Puppet::HTTP::ConnectionError, /no cipher match|sslv3 alert handshake failure/) end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/fixtures/integration/application/apply/environments/spec/modules/amod/lib/puppet/type/applytest.rb
spec/fixtures/integration/application/apply/environments/spec/modules/amod/lib/puppet/type/applytest.rb
# If you make changes to this file, regenerate the pcore resource type using # bundle exec puppet generate types --environmentpath spec/fixtures/integration/application/apply/environments -E spec Puppet::Type.newtype(:applytest) do newproperty(:message) do def sync Puppet.send(@resource[:loglevel], self.should) end def retrieve :absent end def insync?(is) false end defaultto { @resource[:name] } end newparam(:name) do desc "An arbitrary tag for your own reference; the name of the message." Puppet.notice('the Puppet::Type says hello') isnamevar end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/fixtures/integration/application/apply/environments/spec/modules/amod/lib/puppet/provider/applytest/applytest.rb
spec/fixtures/integration/application/apply/environments/spec/modules/amod/lib/puppet/provider/applytest/applytest.rb
Puppet::Type.type(:applytest).provide(:applytest) do end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/fixtures/integration/application/agent/lib/facter/agent_spec_role.rb
spec/fixtures/integration/application/agent/lib/facter/agent_spec_role.rb
Facter.add(:agent_spec_role) do setcode { 'web' } end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/fixtures/integration/l10n/envs/prod/modules/demo/lib/puppet/functions/l10n.rb
spec/fixtures/integration/l10n/envs/prod/modules/demo/lib/puppet/functions/l10n.rb
Puppet::Functions.create_function(:l10n) do dispatch :l10n_impl do end def l10n_impl _("IT'S HAPPY FUN TIME") end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/fixtures/faulty_face/puppet/face/syntax.rb
spec/fixtures/faulty_face/puppet/face/syntax.rb
Puppet::Face.define(:syntax, '1.0.0') do action :foo do when_invoked do |whom| "hello, #{whom}" end # This 'end' is deliberately omitted, to induce a syntax error. # Please don't fix that, as it is used for testing. --daniel 2011-05-02 end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/fixtures/ssl/generate_fixtures.rb
spec/fixtures/ssl/generate_fixtures.rb
# This will regenerate SSL fixtures. It does not cover all fixtures yet. # Run it from the spec/fixtures/ssl directory. require_relative '../../lib/puppet_spec/ssl' def make_subject(name) OpenSSL::X509::Name.new([["CN", name]]) end def write_pem(content, path) File.write(path, "#{content.to_text}\n#{content.to_pem}") puts "Wrote #{content.class} to #{path}" end def read_pem(path, type) text = File.read(path, encoding: 'UTF-8') type.new(text) end def load_or_generate_key(path, size = nil) if File.exist?(path) puts "Loading RSA key from #{path}" read_pem(path, OpenSSL::PKey::RSA) else puts "Generating new RSA key" PuppetSpec::SSL.create_private_key(size) end end def load_or_generate_csr(path, key = nil, name = nil) if File.exist?(path) puts "Loading CSR from #{path}" return read_pem(path, OpenSSL::X509::Request) end raise "Must pass key and name parameters if CSR needs to be generated" unless key && name csr = PuppetSpec::SSL.create_csr(key, "CN=#{name}") puts "Generating new CSR for #{csr.subject}" write_pem(csr, 'request.pem') end # Load or generate request-key.pem and request.pem req_key = load_or_generate_key('request-key.pem') req_csr = load_or_generate_csr('request.pem', req_key, 'pending') # Swap associated public key in request.pem to create a tampered CSR: unless File.exist?('tampered-csr.pem') tampered_csr = load_or_generate_csr('request.pem') tampered_csr.subject = make_subject('signed') write_pem(tampered_csr, 'tampered-csr.pem') end puts "NOTE: Most fixtures are not yet able to be generated with this script"
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/fixtures/unit/pops/binder/bindings_composer/ok/modules/awesome2/lib/puppet_x/awesome2/echo_scheme_handler.rb
spec/fixtures/unit/pops/binder/bindings_composer/ok/modules/awesome2/lib/puppet_x/awesome2/echo_scheme_handler.rb
require 'puppet/plugins/binding_schemes' module PuppetX module Awesome2 # A binding scheme that echos its path # 'echo:/quick/brown/fox' becomes key '::quick::brown::fox' => 'echo: quick brown fox'. # (silly class for testing loading of extension) # class EchoSchemeHandler < Puppet::Plugins::BindingSchemes::BindingsSchemeHandler def contributed_bindings(uri, scope, composer) factory = ::Puppet::Pops::Binder::BindingsFactory bindings = factory.named_bindings("echo") bindings.bind.name(uri.path.gsub(/\//, '::')).to("echo: #{uri.path.gsub(/\//, ' ').strip!}") factory.contributed_bindings("echo", bindings.model) ### , nil) end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/fixtures/unit/pops/binder/bindings_composer/ok/modules/awesome2/lib/puppet/bindings/awesome2/default.rb
spec/fixtures/unit/pops/binder/bindings_composer/ok/modules/awesome2/lib/puppet/bindings/awesome2/default.rb
Puppet::Bindings.newbindings('awesome2::default') do |scope| bind.name('all your base').to('are belong to us') bind.name('env_meaning_of_life').to(puppet_string("$environment thinks it is 42", __FILE__)) bind { name 'awesome_x' to 'golden' } bind { name 'the_meaning_of_life' to 100 } bind { name 'has_funny_hat' to 'kkk' } bind { name 'good_x' to 'golden' } end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/fixtures/unit/pops/binder/bindings_composer/ok/modules/good/lib/puppet/bindings/good/default.rb
spec/fixtures/unit/pops/binder/bindings_composer/ok/modules/good/lib/puppet/bindings/good/default.rb
Puppet::Bindings.newbindings('good::default') do |scope| bind { name 'the_meaning_of_life' to 300 } end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/fixtures/unit/pops/binder/bindings_composer/ok/modules/bad/lib/puppet/bindings/bad/default.rb
spec/fixtures/unit/pops/binder/bindings_composer/ok/modules/bad/lib/puppet/bindings/bad/default.rb
nil + nil + nil # broken on purpose, this file should never be loaded Puppet::Bindings.newbindings('bad::default') do |scope| nil + nil + nil # broken on purpose, this should never be evaluated end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/fixtures/unit/pops/binder/bindings_composer/ok/lib/puppet/bindings/confdirtest.rb
spec/fixtures/unit/pops/binder/bindings_composer/ok/lib/puppet/bindings/confdirtest.rb
Puppet::Bindings.newbindings('confdirtest') do |scope| bind { name 'has_funny_hat' to 'the pope' } bind { name 'the_meaning_of_life' to 42 } end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/fixtures/unit/pops/loaders/loaders/dependent_modules_with_metadata/modules/user/lib/puppet/functions/user/caller.rb
spec/fixtures/unit/pops/loaders/loaders/dependent_modules_with_metadata/modules/user/lib/puppet/functions/user/caller.rb
Puppet::Functions.create_function(:'user::caller') do def caller() call_function('usee::callee', 'passed value') + " + I am user::caller()" end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/fixtures/unit/pops/loaders/loaders/dependent_modules_with_metadata/modules/user/lib/puppet/functions/user/ruby_calling_puppet.rb
spec/fixtures/unit/pops/loaders/loaders/dependent_modules_with_metadata/modules/user/lib/puppet/functions/user/ruby_calling_puppet.rb
Puppet::Functions.create_function(:'user::ruby_calling_puppet') do def ruby_calling_puppet() call_function('usee::usee_puppet') end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/fixtures/unit/pops/loaders/loaders/dependent_modules_with_metadata/modules/user/lib/puppet/functions/user/caller2.rb
spec/fixtures/unit/pops/loaders/loaders/dependent_modules_with_metadata/modules/user/lib/puppet/functions/user/caller2.rb
Puppet::Functions.create_function(:'user::caller2') do def caller2() call_function('usee2::callee', 'passed value') + " + I am user::caller2()" end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/fixtures/unit/pops/loaders/loaders/dependent_modules_with_metadata/modules/user/lib/puppet/functions/user/ruby_calling_ruby.rb
spec/fixtures/unit/pops/loaders/loaders/dependent_modules_with_metadata/modules/user/lib/puppet/functions/user/ruby_calling_ruby.rb
Puppet::Functions.create_function(:'user::ruby_calling_ruby') do def ruby_calling_ruby() call_function('usee::usee_ruby') end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/fixtures/unit/pops/loaders/loaders/dependent_modules_with_metadata/modules/user/lib/puppet/functions/user/ruby_calling_puppet_init.rb
spec/fixtures/unit/pops/loaders/loaders/dependent_modules_with_metadata/modules/user/lib/puppet/functions/user/ruby_calling_puppet_init.rb
Puppet::Functions.create_function(:'user::ruby_calling_puppet_init') do def ruby_calling_puppet_init() call_function('usee_puppet_init') end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/fixtures/unit/pops/loaders/loaders/dependent_modules_with_metadata/modules/usee/lib/puppet/type/usee_type.rb
spec/fixtures/unit/pops/loaders/loaders/dependent_modules_with_metadata/modules/usee/lib/puppet/type/usee_type.rb
Puppet::Type.newtype(:usee_type) do newparam(:name, :namevar => true) do desc 'An arbitrary name used as the identity of the resource.' end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/fixtures/unit/pops/loaders/loaders/dependent_modules_with_metadata/modules/usee/lib/puppet/functions/usee/callee.rb
spec/fixtures/unit/pops/loaders/loaders/dependent_modules_with_metadata/modules/usee/lib/puppet/functions/usee/callee.rb
Puppet::Functions.create_function(:'usee::callee') do def callee(value) "usee::callee() was told '#{value}'" end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/fixtures/unit/pops/loaders/loaders/dependent_modules_with_metadata/modules/usee/lib/puppet/functions/usee/usee_ruby.rb
spec/fixtures/unit/pops/loaders/loaders/dependent_modules_with_metadata/modules/usee/lib/puppet/functions/usee/usee_ruby.rb
Puppet::Functions.create_function(:'usee::usee_ruby') do def usee_ruby() "I'm the function usee::usee_ruby()" end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/fixtures/unit/pops/loaders/loaders/dependent_modules_with_metadata/modules/usee2/lib/puppet/functions/usee2/callee.rb
spec/fixtures/unit/pops/loaders/loaders/dependent_modules_with_metadata/modules/usee2/lib/puppet/functions/usee2/callee.rb
Puppet::Functions.create_function(:'usee2::callee') do def callee(value) "usee2::callee() was told '#{value}'" end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/fixtures/unit/pops/loaders/loaders/mix_4x_and_3x_functions/user/lib/puppet/functions/user/caller.rb
spec/fixtures/unit/pops/loaders/loaders/mix_4x_and_3x_functions/user/lib/puppet/functions/user/caller.rb
Puppet::Functions.create_function(:'user::caller') do def caller() call_function('callee', 'first') + ' - ' + call_function('callee', 'second') end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/fixtures/unit/pops/loaders/loaders/mix_4x_and_3x_functions/user/lib/puppet/functions/user/callingpuppet.rb
spec/fixtures/unit/pops/loaders/loaders/mix_4x_and_3x_functions/user/lib/puppet/functions/user/callingpuppet.rb
Puppet::Functions.create_function(:'user::callingpuppet') do def callingpuppet() call_function('user::puppetcalled', 'me') end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/fixtures/unit/pops/loaders/loaders/mix_4x_and_3x_functions/user/lib/puppet/functions/user/caller_ws.rb
spec/fixtures/unit/pops/loaders/loaders/mix_4x_and_3x_functions/user/lib/puppet/functions/user/caller_ws.rb
Puppet::Functions.create_function(:'user::caller_ws', Puppet::Functions::InternalFunction) do dispatch :caller_ws do scope_param param 'String', :value end def caller_ws(scope, value) scope = scope.compiler.newscope(scope) scope['passed_in_scope'] = value call_function_with_scope(scope, 'callee_ws') end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/fixtures/unit/pops/loaders/loaders/mix_4x_and_3x_functions/usee/lib/puppet/parser/functions/bad_func_load.rb
spec/fixtures/unit/pops/loaders/loaders/mix_4x_and_3x_functions/usee/lib/puppet/parser/functions/bad_func_load.rb
module Puppet::Parser::Functions newfunction(:bad_func_load, :type => :rvalue, :doc => <<-EOS A function using the 3x API EOS ) do |arguments| "the returned value" end def method_here_is_illegal() end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/fixtures/unit/pops/loaders/loaders/mix_4x_and_3x_functions/usee/lib/puppet/parser/functions/bad_func_load2.rb
spec/fixtures/unit/pops/loaders/loaders/mix_4x_and_3x_functions/usee/lib/puppet/parser/functions/bad_func_load2.rb
module Puppet::Parser::Functions x = newfunction(:bad_func_load2, :type => :rvalue, :doc => <<-EOS A function using the 3x API EOS ) do |arguments| "some return value" end end def illegal_method_here end x
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/fixtures/unit/pops/loaders/loaders/mix_4x_and_3x_functions/usee/lib/puppet/parser/functions/callee_ws.rb
spec/fixtures/unit/pops/loaders/loaders/mix_4x_and_3x_functions/usee/lib/puppet/parser/functions/callee_ws.rb
module Puppet::Parser::Functions newfunction(:callee_ws, :type => :rvalue, :doc => <<-EOS A function using the 3x API EOS ) do |arguments| "usee::callee_ws() got '#{self['passed_in_scope']}'" end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/fixtures/unit/pops/loaders/loaders/mix_4x_and_3x_functions/usee/lib/puppet/parser/functions/bad_func_load5.rb
spec/fixtures/unit/pops/loaders/loaders/mix_4x_and_3x_functions/usee/lib/puppet/parser/functions/bad_func_load5.rb
x = module Puppet::Parser::Functions newfunction(:bad_func_load5, :type => :rvalue, :doc => <<-EOS A function using the 3x API EOS ) do |arguments| "some return value" end end def self.bad_func_load5_illegal_method end # Attempt to get around problem of not returning what newfunction returns x
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/fixtures/unit/pops/loaders/loaders/mix_4x_and_3x_functions/usee/lib/puppet/parser/functions/bad_func_load4.rb
spec/fixtures/unit/pops/loaders/loaders/mix_4x_and_3x_functions/usee/lib/puppet/parser/functions/bad_func_load4.rb
module Puppet::Parser::Functions newfunction(:bad_func_load4, :type => :rvalue, :doc => <<-EOS A function using the 3x API EOS ) do |arguments| def self.bad_func_load4_illegal_method "some return value from illegal method" end "some return value" end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/fixtures/unit/pops/loaders/loaders/mix_4x_and_3x_functions/usee/lib/puppet/parser/functions/callee.rb
spec/fixtures/unit/pops/loaders/loaders/mix_4x_and_3x_functions/usee/lib/puppet/parser/functions/callee.rb
module Puppet::Parser::Functions newfunction(:callee, :type => :rvalue, :doc => <<-EOS A function using the 3x API EOS ) do |arguments| "usee::callee() got '#{arguments[0]}'" end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/spec/fixtures/unit/pops/loaders/loaders/mix_4x_and_3x_functions/usee/lib/puppet/parser/functions/good_func_load.rb
spec/fixtures/unit/pops/loaders/loaders/mix_4x_and_3x_functions/usee/lib/puppet/parser/functions/good_func_load.rb
module Puppet::Parser::Functions newfunction(:good_func_load, :type => :rvalue, :doc => <<-EOS A function using the 3x API EOS ) do |arguments| # This is not illegal Float("3.14") end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false