repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
true
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/fixtures/unit/pops/loaders/loaders/mix_4x_and_3x_functions/usee/lib/puppet/parser/functions/bad_func_load3.rb
spec/fixtures/unit/pops/loaders/loaders/mix_4x_and_3x_functions/usee/lib/puppet/parser/functions/bad_func_load3.rb
module Puppet::Parser::Functions newfunction(:bad_func_load3, :type => :rvalue, :doc => <<-EOS A function using the 3x API EOS ) do |arguments| def bad_func_load3_illegal_method "some return value from illegal method" end "some return value" end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/fixtures/unit/pops/loaders/loaders/mix_4x_and_3x_functions/usee/lib/puppet/parser/functions/func_with_syntax_error.rb
spec/fixtures/unit/pops/loaders/loaders/mix_4x_and_3x_functions/usee/lib/puppet/parser/functions/func_with_syntax_error.rb
module Puppet::Parser::Functions newfunction(:func_with_syntax_error, :type => :rvalue, :doc => <<-EOS A function using the 3x API having a syntax error EOS ) do |arguments| # this syntax error is here on purpose! 1+ + + + end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/fixtures/unit/pops/loaders/loaders/single_module/modules/modulea/lib/puppet/functions/rb_func_a.rb
spec/fixtures/unit/pops/loaders/loaders/single_module/modules/modulea/lib/puppet/functions/rb_func_a.rb
Puppet::Functions.create_function(:rb_func_a) do def rb_func_a() "I am rb_func_a()" end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/fixtures/unit/pops/loaders/loaders/single_module/modules/modulea/lib/puppet/functions/modulea/rb_func_a.rb
spec/fixtures/unit/pops/loaders/loaders/single_module/modules/modulea/lib/puppet/functions/modulea/rb_func_a.rb
Puppet::Functions.create_function(:'modulea::rb_func_a') do def rb_func_a() "I am modulea::rb_func_a()" end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/fixtures/unit/pops/loaders/loaders/wo_metadata_module/modules/moduleb/lib/puppet/functions/moduleb/rb_func_b.rb
spec/fixtures/unit/pops/loaders/loaders/wo_metadata_module/modules/moduleb/lib/puppet/functions/moduleb/rb_func_b.rb
Puppet::Functions.create_function(:'moduleb::rb_func_b') do def rb_func_b() # Should be able to call modulea::rb_func_a() call_function('modulea::rb_func_a') + " + I am moduleb::rb_func_b()" end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/fixtures/unit/data_providers/environments/production/modules/abc/lib/puppet/functions/abc/data.rb
spec/fixtures/unit/data_providers/environments/production/modules/abc/lib/puppet/functions/abc/data.rb
Puppet::Functions.create_function(:'abc::data') do def data() { 'abc::def::test1' => 'module_test1', 'abc::def::test2' => 'module_test2', 'abc::def::test3' => 'module_test3', 'abc::def::ipl' => '%{lookup("abc::def::test2")}-ipl' } end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/fixtures/unit/data_providers/environments/production/lib/puppet/functions/environment/data.rb
spec/fixtures/unit/data_providers/environments/production/lib/puppet/functions/environment/data.rb
Puppet::Functions.create_function(:'environment::data') do def data() { 'abc::def::test1' => 'env_test1', 'abc::def::test2' => 'env_test2', 'xyz::def::test1' => 'env_test1', 'xyz::def::test2' => 'env_test2' } end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/fixtures/unit/functions/lookup_fixture/environments/production/modules/bad_data/lib/puppet/functions/bad_data/data.rb
spec/fixtures/unit/functions/lookup_fixture/environments/production/modules/bad_data/lib/puppet/functions/bad_data/data.rb
Puppet::Functions.create_function(:'bad_data::data') do def data() { 'b' => 'module_b', # Intentionally bad key (no module prefix) 'bad_data::c' => 'module_c' # Good key. Should be OK } end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/fixtures/unit/functions/lookup_fixture/environments/production/modules/abc/lib/puppet/functions/abc/data.rb
spec/fixtures/unit/functions/lookup_fixture/environments/production/modules/abc/lib/puppet/functions/abc/data.rb
Puppet::Functions.create_function(:'abc::data') do def data() { 'abc::b' => 'module_b', 'abc::c' => 'module_c', 'abc::e' => { 'k1' => 'module_e1', 'k2' => 'module_e2' }, 'abc::f' => { 'k1' => { 's1' => 'module_f11', 's3' => 'module_f13' }, 'k2' => { 's1' => 'module_f21', 's2' => 'module_f22' }}, } end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/fixtures/unit/functions/lookup_fixture/environments/production/modules/bca/lib/puppet/functions/bca/data.rb
spec/fixtures/unit/functions/lookup_fixture/environments/production/modules/bca/lib/puppet/functions/bca/data.rb
Puppet::Functions.create_function(:'bca::data') do def data() { 'bca::b' => 'module_bca_b', 'bca::c' => 'module_bca_c', 'bca::e' => { 'k1' => 'module_bca_e1', 'k2' => 'module_bca_e2' }, 'bca::f' => { 'k1' => { 's1' => 'module_bca_f11', 's3' => 'module_bca_f13' }, 'k2' => { 's1' => 'module_bca_f21', 's2' => 'module_bca_f22' }}, } end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/fixtures/unit/functions/lookup_fixture/environments/production/modules/meta/lib/puppet/functions/meta/data.rb
spec/fixtures/unit/functions/lookup_fixture/environments/production/modules/meta/lib/puppet/functions/meta/data.rb
Puppet::Functions.create_function(:'meta::data') do def data() { 'meta::b' => 'module_b', 'meta::c' => 'module_c', 'meta::e' => { 'k1' => 'module_e1', 'k2' => 'module_e2' }, 'meta::f' => { 'k1' => { 's1' => 'module_f11', 's3' => 'module_f13' }, 'k2' => { 's1' => 'module_f21', 's2' => 'module_f22' }}, } end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/fixtures/unit/functions/lookup_fixture/environments/production/lib/puppet/functions/environment/data.rb
spec/fixtures/unit/functions/lookup_fixture/environments/production/lib/puppet/functions/environment/data.rb
Puppet::Functions.create_function(:'environment::data') do def data() { 'abc::a' => 'env_a', 'abc::c' => 'env_c', 'abc::d' => { 'k1' => 'env_d1', 'k2' => 'env_d2', 'k3' => 'env_d3' }, 'abc::e' => { 'k1' => 'env_e1', 'k3' => 'env_e3' }, 'bca::e' => { 'k1' => 'env_bca_e1', 'k3' => 'env_bca_e3' }, 'no_provider::e' => { 'k1' => 'env_no_provider_e1', 'k3' => 'env_no_provider_e3' }, 'abc::f' => { 'k1' => { 's1' => 'env_f11', 's2' => 'env_f12' }, 'k2' => { 's1' => 'env_f21', 's3' => 'env_f23' }}, 'abc::n' => nil } end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/fixtures/unit/functions/lookup/hiera/backend/other_backend.rb
spec/fixtures/unit/functions/lookup/hiera/backend/other_backend.rb
class Hiera::Backend::Other_backend def lookup(key, scope, order_override, resolution_type, context) value = Hiera::Config[:other][key.to_sym] throw :no_such_key if value.nil? value end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/fixtures/unit/functions/lookup/hiera/backend/custom_backend.rb
spec/fixtures/unit/functions/lookup/hiera/backend/custom_backend.rb
class Hiera::Backend::Custom_backend def lookup(key, scope, order_override, resolution_type, context) case key when 'hash_c' { 'hash_ca' => { 'cad' => 'value hash_c.hash_ca.cad (from global custom)' }} when 'hash' { 'array' => [ 'x5,x6' ] } when 'array' [ 'x5,x6' ] when 'datasources' Hiera::Backend.datasources(scope, order_override) { |source| source } when 'dotted.key' 'custom backend received request for dotted.key value' else throw :no_such_key end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/fixtures/unit/functions/hiera/hiera/backend/hieraspec_backend.rb
spec/fixtures/unit/functions/hiera/hiera/backend/hieraspec_backend.rb
class Hiera::Backend::Hieraspec_backend def initialize(cache = nil) Hiera.debug('Custom_backend starting') end def lookup(key, scope, order_override, resolution_type, context) case key when 'datasources' Hiera::Backend.datasources(scope, order_override) { |source| source } when 'resolution_type' if resolution_type == :hash { key => resolution_type.to_s } elsif resolution_type == :array [ key, resolution_type.to_s ] else "resolution_type=#{resolution_type}" end else throw :no_such_key end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/fixtures/releases/jamtur01-apache/lib/puppet/type/a2mod.rb
spec/fixtures/releases/jamtur01-apache/lib/puppet/type/a2mod.rb
Puppet::Type.newtype(:a2mod) do @doc = "Manage Apache 2 modules" ensurable newparam(:name) do desc "The name of the module to be managed" isnamevar end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/fixtures/releases/jamtur01-apache/lib/puppet/provider/a2mod/debian.rb
spec/fixtures/releases/jamtur01-apache/lib/puppet/provider/a2mod/debian.rb
Puppet::Type.type(:a2mod).provide(:debian) do desc "Manage Apache 2 modules on Debian-like OSes (e.g. Ubuntu)" commands :encmd => "a2enmod" commands :discmd => "a2dismod" defaultfor 'os.name' => [:debian, :ubuntu] def create encmd resource[:name] end def destroy discmd resource[:name] end def exists? mod= "/etc/apache2/mods-enabled/" + resource[:name] + ".load" Puppet::FileSystem.exist?(mod) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/shared_examples/rhel_package_provider.rb
spec/shared_examples/rhel_package_provider.rb
shared_examples "RHEL package provider" do |provider_class, provider_name| describe provider_name do let(:name) { 'mypackage' } let(:resource) do Puppet::Type.type(:package).new( :name => name, :ensure => :installed, :provider => provider_name ) end let(:provider) do provider = provider_class.new provider.resource = resource provider end let(:arch) { 'x86_64' } let(:arch_resource) do Puppet::Type.type(:package).new( :name => "#{name}.#{arch}", :ensure => :installed, :provider => provider_name ) end let(:arch_provider) do provider = provider_class.new provider.resource = arch_resource provider end case provider_name when 'yum' let(:error_level) { '0' } when 'dnf' let(:error_level) { '1' } when 'tdnf' let(:error_level) { '1' } end case provider_name when 'yum' let(:upgrade_command) { 'update' } when 'dnf' let(:upgrade_command) { 'upgrade' } when 'tdnf' let(:upgrade_command) { 'upgrade' } end before do allow(provider_class).to receive(:command).with(:cmd).and_return("/usr/bin/#{provider_name}") allow(provider).to receive(:rpm).and_return('rpm') allow(provider).to receive(:get).with(:version).and_return('1') allow(provider).to receive(:get).with(:release).and_return('1') allow(provider).to receive(:get).with(:arch).and_return('i386') end describe 'provider features' do it { is_expected.to be_versionable } it { is_expected.to be_install_options } it { is_expected.to be_virtual_packages } end # provider should repond to the following methods [:install, :latest, :update, :purge, :install_options].each do |method| it "should have a(n) #{method}" do expect(provider).to respond_to(method) end end describe 'when installing' do before(:each) do allow(Puppet::Util).to receive(:which).with("rpm").and_return("/bin/rpm") allow(provider).to receive(:which).with("rpm").and_return("/bin/rpm") expect(Puppet::Util::Execution).to receive(:execute).with(["/bin/rpm", "--version"], {:combine => true, :custom_environment => {}, :failonfail => true}).and_return(Puppet::Util::Execution::ProcessOutput.new("4.10.1\n", 0)).at_most(:once) allow(Facter).to receive(:value).with('os.release.major').and_return('6') end it "should call #{provider_name} install for :installed" do allow(resource).to receive(:should).with(:ensure).and_return(:installed) expect(Puppet::Util::Execution).to receive(:execute).with(["/usr/bin/#{provider_name}", '-d', '0', '-e', error_level, '-y', :install, 'mypackage']) provider.install end if provider_name == 'yum' context 'on el-5' do before(:each) do allow(Facter).to receive(:value).with('os.release.major').and_return('5') end it "should catch #{provider_name} install failures when status code is wrong" do allow(resource).to receive(:should).with(:ensure).and_return(:installed) expect(Puppet::Util::Execution).to receive(:execute).with(["/usr/bin/#{provider_name}", '-e', error_level, '-y', :install, name]).and_return(Puppet::Util::Execution::ProcessOutput.new("No package #{name} available.", 0)) expect { provider.install }.to raise_error(Puppet::Error, "Could not find package #{name}") end end end it 'should use :install to update' do expect(provider).to receive(:install) provider.update end it 'should be able to set version' do version = '1.2' resource[:ensure] = version expect(Puppet::Util::Execution).to receive(:execute).with(["/usr/bin/#{provider_name}", '-d', '0', '-e', error_level, '-y', :install, "#{name}-#{version}"]) allow(provider).to receive(:query).and_return(:ensure => version) provider.install end it 'should handle partial versions specified' do version = '1.3.4' resource[:ensure] = version expect(Puppet::Util::Execution).to receive(:execute).with(["/usr/bin/#{provider_name}", '-d', '0', '-e', error_level, '-y', :install, 'mypackage-1.3.4']) allow(provider).to receive(:query).and_return(:ensure => '1.3.4-1.el6') provider.install end it 'should be able to downgrade' do current_version = '1.2' version = '1.0' resource[:ensure] = '1.0' expect(Puppet::Util::Execution).to receive(:execute).with(["/usr/bin/#{provider_name}", '-d', '0', '-e', error_level, '-y', :downgrade, "#{name}-#{version}"]) allow(provider).to receive(:query).and_return({:ensure => current_version}, {:ensure => version}) provider.install end it 'should be able to upgrade' do current_version = '1.0' version = '1.2' resource[:ensure] = '1.2' expect(Puppet::Util::Execution).to receive(:execute).with(["/usr/bin/#{provider_name}", '-d', '0', '-e', error_level, '-y', upgrade_command, "#{name}-#{version}"]) allow(provider).to receive(:query).and_return({:ensure => current_version}, {:ensure => version}) provider.install end it 'should not run upgrade command if absent and ensure latest' do current_version = '' version = '1.2' resource[:ensure] = :latest expect(Puppet::Util::Execution).to receive(:execute).with(["/usr/bin/#{provider_name}", '-d', '0', '-e', error_level, '-y', :install, name]) allow(provider).to receive(:query).and_return({:ensure => current_version}, {:ensure => version}) provider.install end it 'should run upgrade command if present and ensure latest' do current_version = '1.0' version = '1.2' resource[:ensure] = :latest expect(Puppet::Util::Execution).to receive(:execute).with(["/usr/bin/#{provider_name}", '-d', '0', '-e', error_level, '-y', upgrade_command, name]) allow(provider).to receive(:query).and_return({:ensure => current_version}, {:ensure => version}) provider.install end it 'should accept install options' do resource[:ensure] = :installed resource[:install_options] = ['-t', {'-x' => 'expackage'}] expect(Puppet::Util::Execution).to receive(:execute).with(["/usr/bin/#{provider_name}", '-d', '0', '-e', error_level, '-y', ['-t', '-x=expackage'], :install, name]) provider.install end it 'allow virtual packages' do resource[:ensure] = :installed resource[:allow_virtual] = true expect(Puppet::Util::Execution).not_to receive(:execute).with(["/usr/bin/#{provider_name}", '-d', '0', '-e', error_level, '-y', :list, name]) expect(Puppet::Util::Execution).to receive(:execute).with(["/usr/bin/#{provider_name}", '-d', '0', '-e', error_level, '-y', :install, name]) provider.install end it 'moves architecture to end of version' do version = '1.2.3' arch_resource[:ensure] = version expect(Puppet::Util::Execution).to receive(:execute).with(["/usr/bin/#{provider_name}", '-d', '0', '-e', error_level, '-y', :install, "#{name}-#{version}.#{arch}"]) allow(arch_provider).to receive(:query).and_return(:ensure => version) arch_provider.install end it "does not move '-noarch' to the end of version" do version = '1.2.3' resource = Puppet::Type.type(:package).new( :name => "#{name}-noarch", :ensure => version, :provider =>provider_name ) expect(Puppet::Util::Execution).to receive(:execute).with(["/usr/bin/#{provider_name}", '-d', '0', '-e', error_level, '-y', :install, "#{name}-noarch-#{version}"]) provider = provider_class.new provider.resource = resource allow(provider).to receive(:query).and_return(:ensure => version) provider.install end end describe 'when uninstalling' do it 'should use erase to purge' do expect(Puppet::Util::Execution).to receive(:execute).with(["/usr/bin/#{provider_name}", '-y', :erase, name]) provider.purge end end it 'should be versionable' do expect(provider).to be_versionable end describe 'determining the latest version available for a package' do it "passes the value of enablerepo install_options when querying" do resource[:install_options] = [ {'--enablerepo' => 'contrib'}, {'--enablerepo' => 'centosplus'}, ] allow(provider).to receive(:properties).and_return({:ensure => '3.4.5'}) expect(described_class).to receive(:latest_package_version).with(name, [], ['contrib', 'centosplus'], []) provider.latest end it "passes the value of disablerepo install_options when querying" do resource[:install_options] = [ {'--disablerepo' => 'updates'}, {'--disablerepo' => 'centosplus'}, ] allow(provider).to receive(:properties).and_return({:ensure => '3.4.5'}) expect(described_class).to receive(:latest_package_version).with(name, ['updates', 'centosplus'], [], []) provider.latest end it "passes the value of disableexcludes install_options when querying" do resource[:install_options] = [ {'--disableexcludes' => 'main'}, {'--disableexcludes' => 'centosplus'}, ] allow(provider).to receive(:properties).and_return({:ensure => '3.4.5'}) expect(described_class).to receive(:latest_package_version).with(name, [], [], ['main', 'centosplus']) provider.latest end describe 'and a newer version is not available' do before :each do allow(described_class).to receive(:latest_package_version).with(name, [], [], []).and_return(nil) end it 'raises an error the package is not installed' do allow(provider).to receive(:properties).and_return({:ensure => :absent}) expect { provider.latest }.to raise_error(Puppet::DevError, 'Tried to get latest on a missing package') end it 'returns version of the currently installed package' do allow(provider).to receive(:properties).and_return({:ensure => '3.4.5'}) expect(provider.latest).to eq('3.4.5') end end describe 'and a newer version is available' do let(:latest_version) do { :name => name, :epoch => '1', :version => '2.3.4', :release => '5', :arch => 'i686', } end it 'includes the epoch in the version string' do allow(described_class).to receive(:latest_package_version).with(name, [], [], []).and_return(latest_version) expect(provider.latest).to eq('1:2.3.4-5') end end end describe "lazy loading of latest package versions" do before { described_class.clear } after { described_class.clear } let(:mypackage_version) do { :name => name, :epoch => '1', :version => '2.3.4', :release => '5', :arch => 'i686', } end let(:mypackage_newerversion) do { :name => name, :epoch => '1', :version => '4.5.6', :release => '7', :arch => 'i686', } end let(:latest_versions) { {name => [mypackage_version]} } let(:enabled_versions) { {name => [mypackage_newerversion]} } it "returns the version hash if the package was found" do expect(described_class).to receive(:check_updates).with([], [], []).once.and_return(latest_versions) version = described_class.latest_package_version(name, [], [], []) expect(version).to eq(mypackage_version) end it "is nil if the package was not found in the query" do expect(described_class).to receive(:check_updates).with([], [], []).once.and_return(latest_versions) version = described_class.latest_package_version('nopackage', [], [], []) expect(version).to be_nil end it "caches the package list and reuses that for subsequent queries" do expect(described_class).to receive(:check_updates).with([], [], []).once.and_return(latest_versions) 2.times { version = described_class.latest_package_version(name, [], [], []) expect(version).to eq mypackage_version } end it "caches separate lists for each combination of 'disablerepo' and 'enablerepo' and 'disableexcludes'" do expect(described_class).to receive(:check_updates).with([], [], []).once.and_return(latest_versions) expect(described_class).to receive(:check_updates).with(['disabled'], ['enabled'], ['disableexcludes']).once.and_return(enabled_versions) 2.times { version = described_class.latest_package_version(name, [], [], []) expect(version).to eq mypackage_version } 2.times { version = described_class.latest_package_version(name, ['disabled'], ['enabled'], ['disableexcludes']) expect(version).to eq(mypackage_newerversion) } end end describe "executing #{provider_name} check-update" do it "passes repos to enable to '#{provider_name} check-update'" do expect(Puppet::Util::Execution).to receive(:execute).with( %W[/usr/bin/#{provider_name} check-update --enablerepo=updates --enablerepo=centosplus], any_args ).and_return(double(:exitstatus => 0)) described_class.check_updates([], %W[updates centosplus], []) end it "passes repos to disable to '#{provider_name} check-update'" do expect(Puppet::Util::Execution).to receive(:execute).with( %W[/usr/bin/#{provider_name} check-update --disablerepo=updates --disablerepo=centosplus], any_args ).and_return(double(:exitstatus => 0)) described_class.check_updates(%W[updates centosplus], [], []) end it "passes a combination of repos to enable and disable to '#{provider_name} check-update'" do expect(Puppet::Util::Execution).to receive(:execute).with( %W[/usr/bin/#{provider_name} check-update --disablerepo=updates --disablerepo=centosplus --enablerepo=os --enablerepo=contrib ], any_args ).and_return(double(:exitstatus => 0)) described_class.check_updates(%W[updates centosplus], %W[os contrib], []) end it "passes disableexcludes to '#{provider_name} check-update'" do expect(Puppet::Util::Execution).to receive(:execute).with( %W[/usr/bin/#{provider_name} check-update --disableexcludes=main --disableexcludes=centosplus], any_args ).and_return(double(:exitstatus => 0)) described_class.check_updates([], [], %W[main centosplus]) end it "passes all options to '#{provider_name} check-update'" do expect(Puppet::Util::Execution).to receive(:execute).with( %W[/usr/bin/#{provider_name} check-update --disablerepo=a --disablerepo=b --enablerepo=c --enablerepo=d --disableexcludes=e --disableexcludes=f], any_args ).and_return(double(:exitstatus => 0)) described_class.check_updates(%W[a b], %W[c d], %W[e f]) end it "returns an empty hash if '#{provider_name} check-update' returned 0" do expect(Puppet::Util::Execution).to receive(:execute).and_return(double(:exitstatus => 0)) expect(described_class.check_updates([], [], [])).to be_empty end it "returns a populated hash if '#{provider_name} check-update returned 100'" do output = double(:exitstatus => 100) expect(Puppet::Util::Execution).to receive(:execute).and_return(output) expect(described_class).to receive(:parse_updates).with(output).and_return({:has => :updates}) expect(described_class.check_updates([], [], [])).to eq({:has => :updates}) end it "returns an empty hash if '#{provider_name} check-update' returned an exit code that was not 0 or 100" do expect(Puppet::Util::Execution).to receive(:execute).and_return(double(:exitstatus => 1)) expect(described_class).to receive(:warning).with("Could not check for updates, \'/usr/bin/#{provider_name} check-update\' exited with 1") expect(described_class.check_updates([], [], [])).to eq({}) end end describe "parsing a line from #{provider_name} check-update" do it "splits up the package name and architecture fields" do checkupdate = %W[curl.i686 7.32.0-10.fc20] parsed = described_class.update_to_hash(*checkupdate) expect(parsed[:name]).to eq 'curl' expect(parsed[:arch]).to eq 'i686' end it "splits up the epoch, version, and release fields" do checkupdate = %W[dhclient.i686 12:4.1.1-38.P1.el6.centos] parsed = described_class.update_to_hash(*checkupdate) expect(parsed[:epoch]).to eq '12' expect(parsed[:version]).to eq '4.1.1' expect(parsed[:release]).to eq '38.P1.el6.centos' end it "sets the epoch to 0 when an epoch is not specified" do checkupdate = %W[curl.i686 7.32.0-10.fc20] parsed = described_class.update_to_hash(*checkupdate) expect(parsed[:epoch]).to eq '0' expect(parsed[:version]).to eq '7.32.0' expect(parsed[:release]).to eq '10.fc20' end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/shared_contexts/provider.rb
spec/shared_contexts/provider.rb
require 'spec_helper' RSpec.shared_context('provider specificity') do around do |example| old_defaults = described_class.instance_variable_get(:@defaults) old_notdefaults = described_class.instance_variable_get(:@notdefaults) begin described_class.instance_variable_set(:@defaults, []) described_class.instance_variable_set(:@notdefaults, []) example.run ensure described_class.instance_variable_set(:@defaults, old_defaults) described_class.instance_variable_set(:@notdefaults, old_notdefaults) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/shared_contexts/l10n.rb
spec/shared_contexts/l10n.rb
require 'spec_helper' RSpec.shared_context('l10n') do |locale| before :all do @old_locale = Locale.current Locale.current = locale @old_gettext_disabled = Puppet::GettextConfig.instance_variable_get(:@gettext_disabled) Puppet::GettextConfig.instance_variable_set(:@gettext_disabled, false) Puppet::GettextConfig.setup_locale Puppet::GettextConfig.create_default_text_domain # overwrite stubs with real implementation ::Object.send(:remove_method, :_) ::Object.send(:remove_method, :n_) class ::Object include FastGettext::Translation end end after :all do Locale.current = @old_locale Puppet::GettextConfig.instance_variable_set(:@gettext_disabled, @old_gettext_disabled) # restore stubs load File.expand_path(File.join(__dir__, '../../lib/puppet/gettext/stubs.rb')) end before :each do Puppet[:disable_i18n] = false end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/shared_contexts/checksum.rb
spec/shared_contexts/checksum.rb
# Shared contexts for testing against all supported checksum types. # # These helpers define nested rspec example groups to test code against all our # supported checksum types. Example groups that need to be run against all # types should use the `with_checksum_types` helper which will # create a new example group for each types and will run the given block # in each example group. CHECKSUM_PLAINTEXT = "1\r\n"*4000 CHECKSUM_TYPES_TO_TRY = [ ['md5', 'a7a169ac84bb863b30484d0aa03139c1'], ['md5lite', '22b4182363e81b326e98231fde616782'], ['sha256', '47fcae62967db2fb5cba2fc0d9cf3e6767035d763d825ecda535a7b1928b9746'], ['sha256lite', 'fd50217a2b0286ba25121bf2297bbe6c197933992de67e4e568f19861444ecf8'], ['sha224', '6894cd976b60b2caa825bc699b54f715853659f0243f67cda4dd7ac4'], ['sha384', 'afc3d952fe1a4d3aa083d438ea464f6e7456c048d34ff554340721b463b38547e5ee7c964513dfba0d65dd91ac97deb5'], ['sha512', 'a953dcd95824cfa2a555651585d3980b1091a740a785d52ee5e72a55c9038242433e55026758636b0a29d0e5f9e77f24bc888ea5d5e01ab36d2bbcb3d3163859'] ] CHECKSUM_STAT_TIME = Time.now TIME_TYPES_TO_TRY = [ ['ctime', "#{CHECKSUM_STAT_TIME}"], ['mtime', "#{CHECKSUM_STAT_TIME}"] ] shared_context('with supported checksum types') do def self.with_checksum_types(path, file, &block) def checksum_valid(checksum_type, expected_checksum, actual_checksum_signature) case checksum_type when 'mtime', 'ctime' expect(DateTime.parse(actual_checksum_signature)).to be >= DateTime.parse(expected_checksum) else expect(actual_checksum_signature).to eq("{#{checksum_type}}#{expected_checksum}") end end def expect_correct_checksum(meta, checksum_type, checksum, type) expect(meta).to_not be_nil expect(meta).to be_instance_of(type) expect(meta.checksum_type).to eq(checksum_type) expect(checksum_valid(checksum_type, checksum, meta.checksum)).to be_truthy end (CHECKSUM_TYPES_TO_TRY + TIME_TYPES_TO_TRY).each do |checksum_type, checksum| describe("when checksum_type is #{checksum_type}") do let(:checksum_type) { checksum_type } let(:plaintext) { CHECKSUM_PLAINTEXT } let(:checksum) { checksum } let(:env_path) { tmpfile(path) } let(:checksum_file) { File.join(env_path, file) } def digest(content) Puppet::Util::Checksums.send(checksum_type, content) end before(:each) do FileUtils.mkdir_p(File.dirname(checksum_file)) File.open(checksum_file, "wb") { |f| f.write plaintext } end instance_eval(&block) end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/shared_contexts/digests.rb
spec/shared_contexts/digests.rb
# Shared contexts for testing against all supported digest algorithms. # # These helpers define nested rspec example groups to test code against all our # supported digest algorithms. Example groups that need to be run against all # algorithms should use the `with_digest_algorithms` helper which will # create a new example group for each algorithm and will run the given block # in each example group. # # For each algorithm a shared context is defined for the given algorithm that # has precomputed checksum values and paths. These contexts are included # automatically based on the rspec metadata selected with # `with_digest_algorithms`. DIGEST_ALGORITHMS_TO_TRY = ['md5', 'sha256', 'sha384', 'sha512', 'sha224'] shared_context('with supported digest algorithms', :uses_checksums => true) do def self.with_digest_algorithms(&block) DIGEST_ALGORITHMS_TO_TRY.each do |digest_algorithm| describe("when digest_algorithm is #{digest_algorithm}", :digest_algorithm => digest_algorithm) do instance_eval(&block) end end end end shared_context("when digest_algorithm is set to sha256", :digest_algorithm => 'sha256') do before { Puppet[:digest_algorithm] = 'sha256' } after { Puppet[:digest_algorithm] = nil } let(:digest_algorithm) { 'sha256' } let(:plaintext) { "my\r\ncontents" } let(:checksum) { '409a11465ed0938227128b1756c677a8480a8b84814f1963853775e15a74d4b4' } let(:bucket_dir) { '4/0/9/a/1/1/4/6/409a11465ed0938227128b1756c677a8480a8b84814f1963853775e15a74d4b4' } def digest(content) Puppet::Util::Checksums.sha256(content) end end shared_context("when digest_algorithm is set to md5", :digest_algorithm => 'md5') do before { Puppet[:digest_algorithm] = 'md5' } after { Puppet[:digest_algorithm] = nil } let(:digest_algorithm) { 'md5' } let(:plaintext) { "my\r\ncontents" } let(:checksum) { 'f0d7d4e480ad698ed56aeec8b6bd6dea' } let(:bucket_dir) { 'f/0/d/7/d/4/e/4/f0d7d4e480ad698ed56aeec8b6bd6dea' } def digest(content) Puppet::Util::Checksums.md5(content) end end shared_context("when digest_algorithm is set to sha512", :digest_algorithm => 'sha512') do before { Puppet[:digest_algorithm] = 'sha512' } after { Puppet[:digest_algorithm] = nil } let(:digest_algorithm) { 'sha512' } let(:plaintext) { "my\r\ncontents" } let(:checksum) { 'ed9b62ae313c8e4e3e6a96f937101e85f8f8af8d51dea7772177244087e5d6152778605ad6bdb42886ff1436abaec4fa44acbfe171fda755959b52b0e4e015d4' } let(:bucket_dir) { 'e/d/9/b/6/2/a/e/ed9b62ae313c8e4e3e6a96f937101e85f8f8af8d51dea7772177244087e5d6152778605ad6bdb42886ff1436abaec4fa44acbfe171fda755959b52b0e4e015d4' } def digest(content) Puppet::Util::Checksums.sha512(content) end end shared_context("when digest_algorithm is set to sha384", :digest_algorithm => 'sha384') do before { Puppet[:digest_algorithm] = 'sha384' } after { Puppet[:digest_algorithm] = nil } let(:digest_algorithm) { 'sha384' } let(:plaintext) { "my\r\ncontents" } let(:checksum) { 'f40debfec135e4f2b9fb92110c53aadb8e9bda28bb05f09901480fd70126fe3b70f9f074ce6182ec8184eb1bcabe4440' } let(:bucket_dir) { 'f/4/0/d/e/b/f/e/f40debfec135e4f2b9fb92110c53aadb8e9bda28bb05f09901480fd70126fe3b70f9f074ce6182ec8184eb1bcabe4440' } def digest(content) Puppet::Util::Checksums.sha384(content) end end shared_context("when digest_algorithm is set to sha224", :digest_algorithm => 'sha224') do before { Puppet[:digest_algorithm] = 'sha224' } after { Puppet[:digest_algorithm] = nil } let(:digest_algorithm) { 'sha224' } let(:plaintext) { "my\r\ncontents" } let(:checksum) { 'b8c05079b24c37a0e03f03e611167a3ea24455db3ad638a3a0c7e9cb' } let(:bucket_dir) { 'b/8/c/0/5/0/7/9/b8c05079b24c37a0e03f03e611167a3ea24455db3ad638a3a0c7e9cb' } def digest(content) Puppet::Util::Checksums.sha224(content) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/shared_contexts/types_setup.rb
spec/shared_contexts/types_setup.rb
shared_context 'types_setup' do # Do not include the special type Unit in this list # Do not include the type Variant in this list as it needs to be parameterized to be meaningful def self.all_types [ Puppet::Pops::Types::PAnyType, Puppet::Pops::Types::PUndefType, Puppet::Pops::Types::PNotUndefType, Puppet::Pops::Types::PScalarType, Puppet::Pops::Types::PScalarDataType, Puppet::Pops::Types::PStringType, Puppet::Pops::Types::PNumericType, Puppet::Pops::Types::PIntegerType, Puppet::Pops::Types::PFloatType, Puppet::Pops::Types::PRegexpType, Puppet::Pops::Types::PBooleanType, Puppet::Pops::Types::PCollectionType, Puppet::Pops::Types::PArrayType, Puppet::Pops::Types::PHashType, Puppet::Pops::Types::PIterableType, Puppet::Pops::Types::PIteratorType, Puppet::Pops::Types::PRuntimeType, Puppet::Pops::Types::PClassType, Puppet::Pops::Types::PResourceType, Puppet::Pops::Types::PPatternType, Puppet::Pops::Types::PEnumType, Puppet::Pops::Types::PStructType, Puppet::Pops::Types::PTupleType, Puppet::Pops::Types::PCallableType, Puppet::Pops::Types::PTypeType, Puppet::Pops::Types::POptionalType, Puppet::Pops::Types::PDefaultType, Puppet::Pops::Types::PTypeReferenceType, Puppet::Pops::Types::PTypeAliasType, Puppet::Pops::Types::PSemVerType, Puppet::Pops::Types::PSemVerRangeType, Puppet::Pops::Types::PTimespanType, Puppet::Pops::Types::PTimestampType, Puppet::Pops::Types::PSensitiveType, Puppet::Pops::Types::PBinaryType, Puppet::Pops::Types::PInitType, Puppet::Pops::Types::PURIType, ] end def all_types self.class.all_types end # Do not include the Variant type in this list - while it is abstract it is also special in that # it must be parameterized to be meaningful. # def self.abstract_types [ Puppet::Pops::Types::PAnyType, Puppet::Pops::Types::PCallableType, Puppet::Pops::Types::PEnumType, Puppet::Pops::Types::PClassType, Puppet::Pops::Types::PDefaultType, Puppet::Pops::Types::PCollectionType, Puppet::Pops::Types::PInitType, Puppet::Pops::Types::PIterableType, Puppet::Pops::Types::PIteratorType, Puppet::Pops::Types::PNotUndefType, Puppet::Pops::Types::PResourceType, Puppet::Pops::Types::PRuntimeType, Puppet::Pops::Types::POptionalType, Puppet::Pops::Types::PPatternType, Puppet::Pops::Types::PScalarType, Puppet::Pops::Types::PScalarDataType, Puppet::Pops::Types::PUndefType, Puppet::Pops::Types::PTypeReferenceType, Puppet::Pops::Types::PTypeAliasType, ] end def abstract_types self.class.abstract_types end # Internal types. Not meaningful in pp def self.internal_types [ Puppet::Pops::Types::PTypeReferenceType, Puppet::Pops::Types::PTypeAliasType, ] end def internal_types self.class.internal_types end def self.scalar_data_types # PVariantType is also scalar data, if its types are all ScalarData [ Puppet::Pops::Types::PScalarDataType, Puppet::Pops::Types::PStringType, Puppet::Pops::Types::PNumericType, Puppet::Pops::Types::PIntegerType, Puppet::Pops::Types::PFloatType, Puppet::Pops::Types::PBooleanType, Puppet::Pops::Types::PEnumType, Puppet::Pops::Types::PPatternType, ] end def scalar_data_types self.class.scalar_data_types end def self.scalar_types # PVariantType is also scalar, if its types are all Scalar [ Puppet::Pops::Types::PScalarType, Puppet::Pops::Types::PScalarDataType, Puppet::Pops::Types::PStringType, Puppet::Pops::Types::PNumericType, Puppet::Pops::Types::PIntegerType, Puppet::Pops::Types::PFloatType, Puppet::Pops::Types::PRegexpType, Puppet::Pops::Types::PBooleanType, Puppet::Pops::Types::PPatternType, Puppet::Pops::Types::PEnumType, Puppet::Pops::Types::PSemVerType, Puppet::Pops::Types::PTimespanType, Puppet::Pops::Types::PTimestampType, ] end def scalar_types self.class.scalar_types end def self.numeric_types # PVariantType is also numeric, if its types are all numeric [ Puppet::Pops::Types::PNumericType, Puppet::Pops::Types::PIntegerType, Puppet::Pops::Types::PFloatType, ] end def numeric_types self.class.numeric_types end def self.string_types # PVariantType is also string type, if its types are all compatible [ Puppet::Pops::Types::PStringType, Puppet::Pops::Types::PPatternType, Puppet::Pops::Types::PEnumType, ] end def string_types self.class.string_types end def self.collection_types # PVariantType is also string type, if its types are all compatible [ Puppet::Pops::Types::PCollectionType, Puppet::Pops::Types::PHashType, Puppet::Pops::Types::PArrayType, Puppet::Pops::Types::PStructType, Puppet::Pops::Types::PTupleType, ] end def collection_types self.class.collection_types end def self.data_compatible_types tf = Puppet::Pops::Types::TypeFactory result = scalar_data_types result << Puppet::Pops::Types::PArrayType.new(tf.data) result << Puppet::Pops::Types::PHashType.new(Puppet::Pops::Types::PStringType::DEFAULT, tf.data) result << Puppet::Pops::Types::PUndefType result << Puppet::Pops::Types::PTupleType.new([tf.data]) result end def data_compatible_types self.class.data_compatible_types end def self.rich_data_compatible_types tf = Puppet::Pops::Types::TypeFactory result = scalar_types result << Puppet::Pops::Types::PArrayType.new(tf.rich_data) result << Puppet::Pops::Types::PHashType.new(tf.rich_data_key, tf.rich_data) result << Puppet::Pops::Types::PUndefType result << Puppet::Pops::Types::PDefaultType result << Puppet::Pops::Types::PURIType result << Puppet::Pops::Types::PTupleType.new([tf.rich_data]) result << Puppet::Pops::Types::PObjectType result << Puppet::Pops::Types::PTypeType result << Puppet::Pops::Types::PTypeSetType result end def rich_data_compatible_types self.class.rich_data_compatible_types end def self.type_from_class(c) c.is_a?(Class) ? c::DEFAULT : c end def type_from_class(c) self.class.type_from_class(c) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/shared_contexts/https.rb
spec/shared_contexts/https.rb
require 'spec_helper' RSpec.shared_context('https client') do 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' Puppet[:server] = '127.0.0.1' Puppet[:certname] = '127.0.0.1' Puppet[:localcacert] = File.join(PuppetSpec::FIXTURE_DIR, 'ssl', 'ca.pem') Puppet[:hostcrl] = File.join(PuppetSpec::FIXTURE_DIR, 'ssl', 'crl.pem') Puppet[:hostprivkey] = File.join(PuppetSpec::FIXTURE_DIR, 'ssl', '127.0.0.1-key.pem') Puppet[:hostcert] = File.join(PuppetSpec::FIXTURE_DIR, 'ssl', '127.0.0.1.pem') # set in memory facts since certname is changed above facts = Puppet::Node::Facts.new(Puppet[:certname]) Puppet::Node::Facts.indirection.save(facts) end let(:https_server) { PuppetSpec::HTTPSServer.new } end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/lib/matchers/match_tokens2.rb
spec/lib/matchers/match_tokens2.rb
# Matches tokens produced by lexer # The given exepected is one or more entries where an entry is one of # - a token symbol # - an Array with a token symbol and the text value # - an Array with a token symbol and a Hash specifying all attributes of the token # - nil (ignore) # RSpec::Matchers.define :match_tokens2 do | *expected | match do | actual | expected.zip(actual).all? do |e, a| compare(e, a) end end def failure_message msg = ["Expected (#{expected.size}):"] expected.each {|e| msg << e.to_s } zipped = expected.zip(actual) msg << "\nGot (#{actual.size}):" actual.each_with_index do |e, idx| if zipped[idx] zipped_expected = zipped[idx][0] zipped_actual = zipped[idx][1] prefix = compare(zipped_expected, zipped_actual) ? ' ' : '*' msg2 = ["#{prefix}[:"] msg2 << e[0].to_s msg2 << ', ' if e[1] == false msg2 << 'false' else msg2 << e[1][:value].to_s.dump end # If expectation has options, output them if zipped_expected.is_a?(Array) && zipped_expected[2] && zipped_expected[2].is_a?(Hash) msg2 << ", {" msg3 = [] zipped_expected[2].each do |k,v| prefix = e[1][k] != v ? "*" : '' msg3 << "#{prefix}:#{k}=>#{e[1][k]}" end msg2 << msg3.join(", ") msg2 << "}" end msg2 << ']' msg << msg2.join('') end end msg.join("\n") end def compare(e, a) # if expected ends before actual return true if !e # If actual ends before expected return false if !a # Simple - only expect token to match return true if a[0] == e # Expect value and optional attributes to match if e.is_a? Array # tokens must match return false unless a[0] == e[0] if e[2].is_a?(Hash) e[2].each {|k,v| return false unless a[1][k] == v } end return (a[1] == e[1] || (a[1][:value] == e[1])) end false end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/lib/matchers/resource.rb
spec/lib/matchers/resource.rb
module Matchers; module Resource extend RSpec::Matchers::DSL matcher :have_resource do |expected_resource| def resource_match(expected_resource, actual_resource) matched = true failures = [] if actual_resource.ref != expected_resource matched = false failures << "expected #{expected_resource} but was #{actual_resource.ref}" end @params ||= {} @params.each do |name, value| case value when RSpec::Matchers::DSL::Matcher if !value.matches?(actual_resource[name]) matched = false failures << "expected #{name} to match '#{value.description}' but was '#{actual_resource[name]}'" end else if actual_resource[name] != value matched = false failures << "expected #{name} to be '#{value}' but was '#{actual_resource[name]}'" end end end @mismatch = failures.join("\n") matched end match do |actual_catalog| @mismatch = "" if resource = actual_catalog.resource(expected_resource) resource_match(expected_resource, resource) else @mismatch = "expected #{@actual.to_dot} to include #{expected_resource}" false end end chain :with_parameter do |name, value| @params ||= {} @params[name] = value end def failure_message @mismatch end end matcher :be_resource do |expected_resource| def resource_match(expected_resource, actual_resource) if actual_resource.ref == expected_resource true else @mismatch = "expected #{expected_resource} but was #{actual_resource.ref}" false end end match do |actual_resource| resource_match(expected_resource, actual_resource) end def failure_message @mismatch end end end; end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/lib/matchers/relationship_graph_matchers.rb
spec/lib/matchers/relationship_graph_matchers.rb
module RelationshipGraphMatchers class EnforceOrderWithEdge def initialize(before, after) @before = before @after = after end def matches?(actual_graph) @actual_graph = actual_graph @reverse_edge = actual_graph.edge?( vertex_called(actual_graph, @after), vertex_called(actual_graph, @before)) @forward_edge = actual_graph.edge?( vertex_called(actual_graph, @before), vertex_called(actual_graph, @after)) @forward_edge && !@reverse_edge end def failure_message "expect #{@actual_graph.to_dot_graph} to only contain an edge from #{@before} to #{@after} but #{[forward_failure_message, reverse_failure_message].compact.join(' and ')}" end def forward_failure_message if !@forward_edge "did not contain an edge from #{@before} to #{@after}" end end def reverse_failure_message if @reverse_edge "contained an edge from #{@after} to #{@before}" end end private def vertex_called(graph, name) graph.vertices.find { |v| v.ref =~ /#{Regexp.escape(name)}/ } end end def enforce_order_with_edge(before, after) EnforceOrderWithEdge.new(before, after) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/lib/matchers/json.rb
spec/lib/matchers/json.rb
module JSONMatchers class SetJsonAttribute def initialize(attributes) @attributes = attributes end def format @format ||= Puppet::Network::FormatHandler.format('json') end def json(instance) Puppet::Util::Json.load(instance.to_json) end def attr_value(attrs, instance) attrs = attrs.dup hash = json(instance) while attrs.length > 0 name = attrs.shift hash = hash[name] end hash end def to(value) @value = value self end def matches?(instance) @instance = instance result = attr_value(@attributes, instance) if @value result == @value else ! result.nil? end end def failure_message if @value "expected #{@instance.inspect} to set #{@attributes.inspect} to #{@value.inspect}; got #{attr_value(@attributes, @instance).inspect}" else "expected #{@instance.inspect} to set #{@attributes.inspect} but was nil" end end def failure_message_when_negated if @value "expected #{@instance.inspect} not to set #{@attributes.inspect} to #{@value.inspect}" else "expected #{@instance.inspect} not to set #{@attributes.inspect} to nil" end end end class ReadJsonAttribute def initialize(attribute) @attribute = attribute end def format @format ||= Puppet::Network::FormatHandler.format('json') end def from(value) @json = value self end def as(as) @value = as self end def matches?(klass) raise "Must specify json with 'from'" unless @json @klass = klass @instance = format.intern(klass, @json) if @value @instance.send(@attribute) == @value else ! @instance.send(@attribute).nil? end end def failure_message if @value "expected #{@klass} to read #{@attribute} from #{@json} as #{@value.inspect}; got #{@instance.send(@attribute).inspect}" else "expected #{@klass} to read #{@attribute} from #{@json} but was nil" end end def failure_message_when_negated if @value "expected #{@klass} not to set #{@attribute} to #{@value}" else "expected #{@klass} not to set #{@attribute} to nil" end end end require 'puppet/util/json' require 'json-schema' class SchemaMatcher JSON_META_SCHEMA = Puppet::Util::Json.load(File.read('api/schemas/json-meta-schema.json')) def initialize(schema) @schema = schema end def matches?(json) JSON::Validator.validate!(JSON_META_SCHEMA, @schema) JSON::Validator.validate!(@schema, json) end end def validate_against(schema_file) schema = Puppet::Util::Json.load(File.read(schema_file)) SchemaMatcher.new(schema) end def set_json_attribute(*attributes) SetJsonAttribute.new(attributes) end def read_json_attribute(attribute) ReadJsonAttribute.new(attribute) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/lib/matchers/containment_matchers.rb
spec/lib/matchers/containment_matchers.rb
module ContainmentMatchers class ContainClass def initialize(containee) @containee = containee end def in(container) @container = container self end def matches?(catalog) @catalog = catalog raise ArgumentError, "You must set the container using #in" unless @container @container_resource = catalog.resource("Class", @container) @containee_resource = catalog.resource("Class", @containee) if @containee_resource && @container_resource catalog.edge?(@container_resource, @containee_resource) else false end end def failure_message message = "Expected #{@catalog.to_dot} to contain Class #{@containee.inspect} inside of Class #{@container.inspect} but " missing = [] if @container_resource.nil? missing << @container end if @containee_resource.nil? missing << @containee end if ! missing.empty? message << "the catalog does not contain #{missing.map(&:inspect).join(' or ')}" else message << "no containment relationship exists" end message end end # expect(catalog).to contain_class(containee).in(container) def contain_class(containee) ContainClass.new(containee) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/lib/matchers/include_in_order_spec.rb
spec/lib/matchers/include_in_order_spec.rb
require 'spec_helper' require 'matchers/include_in_order' describe "Matching whether elements are included in order" do context "an empty array" do it "is included in an empty array" do expect([]).to include_in_order() end it "is included in a non-empty array" do expect([1]).to include_in_order() end end it "[1,2,3] is included in [0,1,2,3,4]" do expect([0,1,2,3,4]).to include_in_order(1,2,3) end it "[2,1] is not included in order in [1,2]" do expect([1,2]).not_to include_in_order(2,1) end it "[2,4,6] is included in order in [1,2,3,4,5,6]" do expect([1,2,3,4,5,6]).to include_in_order(2,4,6) end it "overlapping ordered array is not included" do expect([1,2,3]).not_to include_in_order(2,3,4) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/lib/matchers/include_in_order.rb
spec/lib/matchers/include_in_order.rb
RSpec::Matchers.define :include_in_order do |*expected| match do |actual| elements = expected.dup actual.each do |elt| if elt == elements.first elements.shift end end elements.empty? end def failure_message "expected #{@actual.inspect} to include#{expected} in order" end def failure_message_when_negated "expected #{@actual.inspect} not to include#{expected} in order" end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/lib/puppet_spec/language.rb
spec/lib/puppet_spec/language.rb
require 'puppet_spec/compiler' require 'matchers/resource' module PuppetSpec::Language extend RSpec::Matchers::DSL def produces(expectations) calledFrom = caller expectations.each do |manifest, resources| it "evaluates #{manifest} to produce #{resources}" do begin case resources when String node = Puppet::Node.new('specification') Puppet[:code] = manifest compiler = Puppet::Parser::Compiler.new(node) evaluator = Puppet::Pops::Parser::EvaluatingParser.new() # see lib/puppet/indirector/catalog/compiler.rb#filter catalog = compiler.compile.filter { |r| r.virtual? } compiler.send(:instance_variable_set, :@catalog, catalog) Puppet.override(:loaders => compiler.loaders) do expect(evaluator.evaluate_string(compiler.topscope, resources)).to eq(true) end when Array catalog = PuppetSpec::Compiler.compile_to_catalog(manifest) if resources.empty? base_resources = ["Class[Settings]", "Class[main]", "Stage[main]"] expect(catalog.resources.collect(&:ref) - base_resources).to eq([]) else resources.each do |reference| if reference.is_a?(Array) matcher = Matchers::Resource.have_resource(reference[0]) reference[1].each do |name, value| matcher = matcher.with_parameter(name, value) end else matcher = Matchers::Resource.have_resource(reference) end expect(catalog).to matcher end end else raise "Unsupported creates specification: #{resources.inspect}" end rescue Puppet::Error, RSpec::Expectations::ExpectationNotMetError => e # provide the backtrace from the caller, or it is close to impossible to find some originators e.set_backtrace(calledFrom) raise end end end end def fails(expectations) calledFrom = caller expectations.each do |manifest, pattern| it "fails to evaluate #{manifest} with message #{pattern}" do begin expect do PuppetSpec::Compiler.compile_to_catalog(manifest) end.to raise_error(Puppet::Error, pattern) rescue RSpec::Expectations::ExpectationNotMetError => e # provide the backgrace from the caller, or it is close to impossible to find some originators e.set_backtrace(calledFrom) raise end end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/lib/puppet_spec/fixtures.rb
spec/lib/puppet_spec/fixtures.rb
module PuppetSpec::Fixtures def fixtures(*rest) File.join(PuppetSpec::FIXTURE_DIR, *rest) end def my_fixture_dir callers = caller while line = callers.shift do next unless found = line.match(%r{/spec/(.*)_spec\.rb:}) return fixtures(found[1]) end fail "sorry, I couldn't work out your path from the caller stack!" end def my_fixture(name) file = File.join(my_fixture_dir, name) unless File.readable? file then fail Puppet::DevError, "fixture '#{name}' for #{my_fixture_dir} is not readable" end return file end def my_fixtures(glob = '*', flags = 0) files = Dir.glob(File.join(my_fixture_dir, glob), flags) unless files.length > 0 then fail Puppet::DevError, "fixture '#{glob}' for #{my_fixture_dir} had no files!" end block_given? and files.each do |file| yield file end files end def pem_content(name) File.read(File.join(PuppetSpec::FIXTURE_DIR, 'ssl', name), encoding: 'UTF-8') end def cert_fixture(name) OpenSSL::X509::Certificate.new(pem_content(name)) end def crl_fixture(name) OpenSSL::X509::CRL.new(pem_content(name)) end def key_fixture(name) OpenSSL::PKey::RSA.new(pem_content(name)) end def ec_key_fixture(name) OpenSSL::PKey::EC.new(pem_content(name)) end def request_fixture(name) OpenSSL::X509::Request.new(pem_content(name)) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/lib/puppet_spec/files.rb
spec/lib/puppet_spec/files.rb
require 'fileutils' require 'tempfile' require 'tmpdir' require 'pathname' # A support module for testing files. module PuppetSpec::Files def self.cleanup $global_tempfiles ||= [] while path = $global_tempfiles.pop do begin FileUtils.rm_rf path, secure: true rescue Errno::ENOENT # nothing to do end end end module_function def make_absolute(path) path = File.expand_path(path) path[0] = 'c' if Puppet::Util::Platform.windows? path end def tmpfile(name, dir = nil) dir ||= Dir.tmpdir path = Puppet::FileSystem.expand_path(make_tmpname(name, nil).encode(Encoding::UTF_8), dir) record_tmp(File.expand_path(path)) path end def file_containing(name, contents) file = tmpfile(name) File.open(file, 'wb') { |f| f.write(contents) } file end def script_containing(name, contents) file = tmpfile(name) if Puppet::Util::Platform.windows? file += '.bat' text = contents[:windows] else text = contents[:posix] end File.open(file, 'wb') { |f| f.write(text) } Puppet::FileSystem.chmod(0755, file) file end def tmpdir(name) dir = Puppet::FileSystem.expand_path(Dir.mktmpdir(name).encode!(Encoding::UTF_8)) record_tmp(dir) dir end # Copied from ruby 2.4 source def make_tmpname((prefix, suffix), n) prefix = (String.try_convert(prefix) or raise ArgumentError, "unexpected prefix: #{prefix.inspect}") suffix &&= (String.try_convert(suffix) or raise ArgumentError, "unexpected suffix: #{suffix.inspect}") t = Time.now.strftime("%Y%m%d") path = "#{prefix}#{t}-#{$$}-#{rand(0x100000000).to_s(36)}".dup path << "-#{n}" if n path << suffix if suffix path end def dir_containing(name, contents_hash) dir_contained_in(tmpdir(name), contents_hash) end def dir_contained_in(dir, contents_hash) contents_hash.each do |k,v| if v.is_a?(Hash) Dir.mkdir(tmp = File.join(dir,k)) dir_contained_in(tmp, v) else file = File.join(dir, k) File.open(file, 'wb') {|f| f.write(v) } end end dir end def record_tmp(tmp) # ...record it for cleanup, $global_tempfiles ||= [] $global_tempfiles << tmp end def expect_file_mode(file, mode) actual_mode = "%o" % Puppet::FileSystem.stat(file).mode target_mode = if Puppet::Util::Platform.windows? mode else "10" + "%04i" % mode.to_i end expect(actual_mode).to eq(target_mode) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/lib/puppet_spec/matchers.rb
spec/lib/puppet_spec/matchers.rb
require 'stringio' ######################################################################## # Custom matchers... RSpec::Matchers.define :have_matching_element do |expected| match do |actual| actual.any? { |item| item =~ expected } end end RSpec::Matchers.define :have_matching_log do |expected| match do |actual| actual.map(&:to_s).any? { |item| item =~ expected } end end RSpec::Matchers.define :have_matching_log_with_source do |expected, file, line, pos| match do |actual| actual.any? { |item| item.message =~ expected && item.file == file && item.line == line && item.pos == pos } end end RSpec::Matchers.define :exit_with do |expected| actual = nil match do |block| begin block.call rescue SystemExit => e actual = e.status end actual and actual == expected end supports_block_expectations failure_message do |block| "expected exit with code #{expected} but " + (actual.nil? ? " exit was not called" : "we exited with #{actual} instead") end failure_message_when_negated do |block| "expected that exit would not be called with #{expected}" end description do "expect exit with #{expected}" end end RSpec::Matchers.define :equal_attributes_of do |expected| match do |actual| actual.instance_variables.all? do |attr| actual.instance_variable_get(attr) == expected.instance_variable_get(attr) end end end RSpec::Matchers.define :equal_resource_attributes_of do |expected| match do |actual| actual.keys do |attr| actual[attr] == expected[attr] end end end RSpec::Matchers.define :be_one_of do |*expected| match do |actual| expected.include? actual end failure_message do |actual| "expected #{actual.inspect} to be one of #{expected.map(&:inspect).join(' or ')}" end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/lib/puppet_spec/compiler.rb
spec/lib/puppet_spec/compiler.rb
module PuppetSpec::Compiler module_function def compile_to_catalog(string, node = Puppet::Node.new('test')) Puppet[:code] = string # see lib/puppet/indirector/catalog/compiler.rb#filter Puppet::Parser::Compiler.compile(node).filter { |r| r.virtual? } end # Does not removed virtual resources in compiled catalog (i.e. keeps unrealized) def compile_to_catalog_unfiltered(string, node = Puppet::Node.new('test')) Puppet[:code] = string # see lib/puppet/indirector/catalog/compiler.rb#filter Puppet::Parser::Compiler.compile(node) end def compile_to_ral(manifest, node = Puppet::Node.new('test')) catalog = compile_to_catalog(manifest, node) ral = catalog.to_ral ral.finalize ral end def compile_to_relationship_graph(manifest, prioritizer = Puppet::Graph::SequentialPrioritizer.new) ral = compile_to_ral(manifest) graph = Puppet::Graph::RelationshipGraph.new(prioritizer) graph.populate_from(ral) graph end def apply_compiled_manifest(manifest, prioritizer = Puppet::Graph::SequentialPrioritizer.new) catalog = compile_to_ral(manifest) if block_given? catalog.resources.each { |res| yield res } end transaction = Puppet::Transaction.new(catalog, Puppet::Transaction::Report.new, prioritizer) transaction.evaluate transaction.report.finalize_report transaction end def apply_with_error_check(manifest) apply_compiled_manifest(manifest) do |res| expect(res).not_to receive(:err) end end def order_resources_traversed_in(relationships) order_seen = [] relationships.traverse { |resource| order_seen << resource.ref } order_seen end def collect_notices(code, node = Puppet::Node.new('foonode')) Puppet[:code] = code compiler = Puppet::Parser::Compiler.new(node) node.environment.check_for_reparse logs = [] Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do yield(compiler) end logs = logs.select { |log| log.level == :notice }.map { |log| log.message } logs end def eval_and_collect_notices(code, node = Puppet::Node.new('foonode'), topscope_vars = {}) collect_notices(code, node) do |compiler| unless topscope_vars.empty? scope = compiler.topscope topscope_vars.each {|k,v| scope.setvar(k, v) } end if block_given? compiler.compile do |catalog| yield(compiler.topscope, catalog) catalog end else compiler.compile end end end # Compiles a catalog, and if source is given evaluates it and returns its result. # The catalog is returned if no source is given. # Topscope variables are set before compilation # Uses a created node 'testnode' if none is given. # (Parameters given by name) # def evaluate(code: 'undef', source: nil, node: Puppet::Node.new('testnode'), variables: {}) source_location = caller[0] Puppet[:code] = code compiler = Puppet::Parser::Compiler.new(node) unless variables.empty? scope = compiler.topscope variables.each {|k,v| scope.setvar(k, v) } end if source.nil? compiler.compile # see lib/puppet/indirector/catalog/compiler.rb#filter return compiler.filter { |r| r.virtual? } end # evaluate given source is the context of the compiled state and return its result compiler.compile do |catalog | Puppet::Pops::Parser::EvaluatingParser.singleton.evaluate_string(compiler.topscope, source, source_location) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/lib/puppet_spec/network.rb
spec/lib/puppet_spec/network.rb
require 'spec_helper' require 'puppet/network/http' require 'puppet/network/http/api/indirected_routes' require 'puppet/indirector_testing' module PuppetSpec::Network def not_found_error Puppet::Network::HTTP::Error::HTTPNotFoundError end def not_acceptable_error Puppet::Network::HTTP::Error::HTTPNotAcceptableError end def bad_request_error Puppet::Network::HTTP::Error::HTTPBadRequestError end def not_authorized_error Puppet::Network::HTTP::Error::HTTPNotAuthorizedError end def method_not_allowed_error Puppet::Network::HTTP::Error::HTTPMethodNotAllowedError end def unsupported_media_type_error Puppet::Network::HTTP::Error::HTTPUnsupportedMediaTypeError end def params { :environment => "production" } end def acceptable_content_types types = ['application/json'] types << 'application/x-msgpack' if Puppet.features.msgpack? types << 'text/pson' if Puppet.features.pson? types end def acceptable_content_types_string acceptable_content_types.join(', ') end def acceptable_catalog_content_types types = %w[application/vnd.puppet.rich+json application/json] types.concat(%w[application/vnd.puppet.rich+msgpack application/x-msgpack]) if Puppet.features.msgpack? types << 'text/pson' if Puppet.features.pson? types end def master_url_prefix "#{Puppet::Network::HTTP::MASTER_URL_PREFIX}/v3" end def ca_url_prefix "#{Puppet::Network::HTTP::CA_URL_PREFIX}/v1" end def a_request_that_heads(data, request = {}, params = params()) Puppet::Network::HTTP::Request.from_hash({ :headers => { 'accept' => request[:accept_header], 'content-type' => "application/json" }, :method => "HEAD", :path => "#{master_url_prefix}/#{data.class.indirection.name}/#{data.value}", :params => params, }) end def a_request_that_submits(data, request = {}, params = params()) Puppet::Network::HTTP::Request.from_hash({ :headers => { 'accept' => request[:accept_header], 'content-type' => request[:content_type_header] || "application/json" }, :method => "PUT", :path => "#{master_url_prefix}/#{data.class.indirection.name}/#{data.value}", :params => params, :body => request[:body].nil? ? data.render("json") : request[:body] }) end def a_request_that_destroys(data, request = {}, params = params()) Puppet::Network::HTTP::Request.from_hash({ :headers => { 'accept' => request[:accept_header], 'content-type' => "application/json" }, :method => "DELETE", :path => "#{master_url_prefix}/#{data.class.indirection.name}/#{data.value}", :params => params, :body => '' }) end def a_request_that_finds(data, request = {}, params = params()) Puppet::Network::HTTP::Request.from_hash({ :headers => { 'accept' => request[:accept_header], 'content-type' => "application/json" }, :method => "GET", :path => "#{master_url_prefix}/#{data.class.indirection.name}/#{data.value}", :params => params, :body => '' }) end def a_request_that_searches(data, request = {}, params = params()) Puppet::Network::HTTP::Request.from_hash({ :headers => { 'accept' => request[:accept_header], 'content-type' => "application/json" }, :method => "GET", :path => "#{master_url_prefix}/#{data.class.indirection.name}s/#{data.name}", :params => params, :body => '' }) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/lib/puppet_spec/ssl.rb
spec/lib/puppet_spec/ssl.rb
require 'openssl' module PuppetSpec module SSL PRIVATE_KEY_LENGTH = 2048 FIVE_YEARS = 5 * 365 * 24 * 60 * 60 CA_EXTENSIONS = [ ["basicConstraints", "CA:TRUE", true], ["keyUsage", "keyCertSign, cRLSign", true], ["subjectKeyIdentifier", "hash", false], ["authorityKeyIdentifier", "keyid:always", false] ] NODE_EXTENSIONS = [ ["keyUsage", "digitalSignature", true], ["subjectKeyIdentifier", "hash", false] ] DEFAULT_SIGNING_DIGEST = OpenSSL::Digest::SHA256.new DEFAULT_REVOCATION_REASON = OpenSSL::OCSP::REVOKED_STATUS_KEYCOMPROMISE ROOT_CA_NAME = "/CN=root-ca-\u{2070E}" REVOKED_INT_CA_NAME = "/CN=revoked-int-ca-\u16A0" INT_CA_NAME = "/CN=unrevoked-int-ca\u06FF\u16A0\u{2070E}" LEAF_CA_NAME = "/CN=leaf-ca-\u06FF" EXPLANATORY_TEXT = <<-EOT # Root Issuer: #{ROOT_CA_NAME} # Intermediate Issuer: #{INT_CA_NAME} # Leaf Issuer: #{LEAF_CA_NAME} EOT def self.create_private_key(length = PRIVATE_KEY_LENGTH) OpenSSL::PKey::RSA.new(length) end def self.self_signed_ca(key, name) cert = OpenSSL::X509::Certificate.new cert.public_key = key.public_key cert.subject = OpenSSL::X509::Name.parse(name) cert.issuer = cert.subject cert.version = 2 cert.serial = rand(2**128) not_before = just_now cert.not_before = not_before cert.not_after = not_before + FIVE_YEARS ext_factory = extension_factory_for(cert, cert) CA_EXTENSIONS.each do |ext| extension = ext_factory.create_extension(*ext) cert.add_extension(extension) end cert.sign(key, DEFAULT_SIGNING_DIGEST) cert end def self.create_csr(key, name) csr = OpenSSL::X509::Request.new csr.public_key = key.public_key csr.subject = OpenSSL::X509::Name.parse(name) csr.version = 2 csr.sign(key, DEFAULT_SIGNING_DIGEST) csr end def self.sign(ca_key, ca_cert, csr, extensions = NODE_EXTENSIONS) cert = OpenSSL::X509::Certificate.new cert.public_key = csr.public_key cert.subject = csr.subject cert.issuer = ca_cert.subject cert.version = 2 cert.serial = rand(2**128) not_before = just_now cert.not_before = not_before cert.not_after = not_before + FIVE_YEARS ext_factory = extension_factory_for(ca_cert, cert) extensions.each do |ext| extension = ext_factory.create_extension(*ext) cert.add_extension(extension) end cert.sign(ca_key, DEFAULT_SIGNING_DIGEST) cert end def self.create_crl_for(ca_cert, ca_key) crl = OpenSSL::X509::CRL.new crl.version = 1 crl.issuer = ca_cert.subject ef = extension_factory_for(ca_cert) crl.add_extension( ef.create_extension(["authorityKeyIdentifier", "keyid:always", false])) crl.add_extension( OpenSSL::X509::Extension.new("crlNumber", OpenSSL::ASN1::Integer(0))) not_before = just_now crl.last_update = not_before crl.next_update = not_before + FIVE_YEARS crl.sign(ca_key, DEFAULT_SIGNING_DIGEST) crl end def self.revoke(serial, crl, ca_key) revoked = OpenSSL::X509::Revoked.new revoked.serial = serial revoked.time = Time.now revoked.add_extension( OpenSSL::X509::Extension.new("CRLReason", OpenSSL::ASN1::Enumerated(DEFAULT_REVOCATION_REASON))) crl.add_revoked(revoked) extensions = crl.extensions.group_by{|e| e.oid == 'crlNumber' } crl_number = extensions[true].first unchanged_exts = extensions[false] next_crl_number = crl_number.value.to_i + 1 new_crl_number_ext = OpenSSL::X509::Extension.new("crlNumber", OpenSSL::ASN1::Integer(next_crl_number)) crl.extensions = unchanged_exts + [new_crl_number_ext] crl.sign(ca_key, DEFAULT_SIGNING_DIGEST) crl end # Creates a self-signed root ca, then signs two node certs, revoking one of them. # Creates an intermediate CA and one node cert off of it. # Creates a second intermediate CA and one node cert off if it. # Creates a leaf CA off of the intermediate CA, then signs two node certs revoking one of them. # Revokes an intermediate CA. # Returns the ca bundle, crl chain, and all the node certs # # ----- # / \ # / \ # | root +-------------------o------------------o # \ CA / | | # \ / | | # --+-- | | # | | | # | | | # | | | # | --+-- --+-- # +---------+ | +---------+ / \ / \ # | revoked | | | | /revoked\ / \ # | node +--o---+ node | | int | | int | # | | | | \ CA / \ CA / # +---------+ +---------+ \ / \ / # --+-- --+-- # | | # | | # | | # --+-- | # / \ +---+-----+ # / \ | | # | leaf | | node | # \ CA / | | # \ / +---------+ # --+-- # | # | # +---------+ | +----------+ # | revoked | | | | # | node +--o--+ node | # | | | | # +---------+ +----------+ def self.create_chained_pki root_key = create_private_key root_cert = self_signed_ca(root_key, ROOT_CA_NAME) root_crl = create_crl_for(root_cert, root_key) unrevoked_root_node_key = create_private_key unrevoked_root_node_csr = create_csr(unrevoked_root_node_key, "/CN=unrevoked-root-node") unrevoked_root_node_cert = sign(root_key, root_cert, unrevoked_root_node_csr) revoked_root_node_key = create_private_key revoked_root_node_csr = create_csr(revoked_root_node_key, "/CN=revoked-root-node") revoked_root_node_cert = sign(root_key, root_cert, revoked_root_node_csr) revoke(revoked_root_node_cert.serial, root_crl, root_key) revoked_int_key = create_private_key revoked_int_csr = create_csr(revoked_int_key, REVOKED_INT_CA_NAME) revoked_int_cert = sign(root_key, root_cert, revoked_int_csr, CA_EXTENSIONS) revoked_int_crl = create_crl_for(revoked_int_cert, revoked_int_key) int_key = create_private_key int_csr = create_csr(int_key, INT_CA_NAME) int_cert = sign(root_key, root_cert, int_csr, CA_EXTENSIONS) int_node_key = create_private_key int_node_csr = create_csr(int_node_key, "/CN=unrevoked-int-node") int_node_cert = sign(int_key, int_cert, int_node_csr) unrevoked_int_node_key = create_private_key unrevoked_int_node_csr = create_csr(unrevoked_int_node_key, "/CN=unrevoked-int-node") unrevoked_int_node_cert = sign(revoked_int_key, revoked_int_cert, unrevoked_int_node_csr) leaf_key = create_private_key leaf_csr = create_csr(leaf_key, LEAF_CA_NAME) leaf_cert = sign(revoked_int_key, revoked_int_cert, leaf_csr, CA_EXTENSIONS) leaf_crl = create_crl_for(leaf_cert, leaf_key) revoke(revoked_int_cert.serial, root_crl, root_key) unrevoked_leaf_node_key = create_private_key unrevoked_leaf_node_csr = create_csr(unrevoked_leaf_node_key, "/CN=unrevoked-leaf-node") unrevoked_leaf_node_cert = sign(leaf_key, leaf_cert, unrevoked_leaf_node_csr) revoked_leaf_node_key = create_private_key revoked_leaf_node_csr = create_csr(revoked_leaf_node_key, "/CN=revoked-leaf-node") revoked_leaf_node_cert = sign(leaf_key, leaf_cert, revoked_leaf_node_csr) revoke(revoked_leaf_node_cert.serial, leaf_crl, leaf_key) ca_bundle = bundle(root_cert, revoked_int_cert, leaf_cert) crl_chain = bundle(root_crl, revoked_int_crl, leaf_crl) { :root_cert => root_cert, :int_cert => int_cert, :int_node_cert => int_node_cert, :leaf_cert => leaf_cert, :leaf_key => leaf_key, :revoked_root_node_cert => revoked_root_node_cert, :revoked_int_cert => revoked_int_cert, :revoked_leaf_node_cert => revoked_leaf_node_cert, :unrevoked_root_node_cert => unrevoked_root_node_cert, :unrevoked_int_node_cert => unrevoked_int_node_cert, :unrevoked_leaf_node_cert => unrevoked_leaf_node_cert, :ca_bundle => ca_bundle, :crl_chain => crl_chain, } end private def self.just_now Time.now - 1 end def self.extension_factory_for(ca, cert = nil) ef = OpenSSL::X509::ExtensionFactory.new ef.issuer_certificate = ca ef.subject_certificate = cert if cert ef end def self.bundle(*items) items.map {|i| EXPLANATORY_TEXT + i.to_pem }.join("\n") end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/lib/puppet_spec/verbose.rb
spec/lib/puppet_spec/verbose.rb
# Support code for running stuff with warnings disabled or enabled module Kernel def with_verbose_disabled verbose, $VERBOSE = $VERBOSE, nil begin yield ensure $VERBOSE = verbose end end def with_verbose_enabled verbose, $VERBOSE = $VERBOSE, true begin yield ensure $VERBOSE = verbose end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/lib/puppet_spec/settings.rb
spec/lib/puppet_spec/settings.rb
module PuppetSpec::Settings # It would probably be preferable to refactor defaults.rb such that the real definitions of # these settings were available as a variable, which was then accessible for use during tests. # However, I'm not doing that yet because I don't want to introduce any additional moving parts # to this already very large changeset. # Would be nice to clean this up later. --cprice 2012-03-20 TEST_APP_DEFAULT_DEFINITIONS = { :name => { :default => "test", :desc => "name" }, :logdir => { :type => :directory, :default => "test", :desc => "logdir" }, :confdir => { :type => :directory, :default => "test", :desc => "confdir" }, :codedir => { :type => :directory, :default => "test", :desc => "codedir" }, :vardir => { :type => :directory, :default => "test", :desc => "vardir" }, :publicdir => { :type => :directory, :default => "test", :desc => "publicdir" }, :rundir => { :type => :directory, :default => "test", :desc => "rundir" }, }.freeze TEST_APP_DEFAULT_VALUES = TEST_APP_DEFAULT_DEFINITIONS.inject({}) do |memo, (key, value)| memo[key] = value[:default] memo end.freeze def set_puppet_conf(confdir, settings) FileUtils.mkdir_p(confdir) write_file(File.join(confdir, "puppet.conf"), settings) end def set_environment_conf(environmentpath, environment, settings) envdir = File.join(environmentpath, environment) FileUtils.mkdir_p(envdir) write_file(File.join(envdir, 'environment.conf'), settings) end def write_file(file, contents) File.open(file, "w") do |f| f.puts(contents) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/lib/puppet_spec/scope.rb
spec/lib/puppet_spec/scope.rb
module PuppetSpec::Scope # Initialize a new scope suitable for testing. # def create_test_scope_for_node(node_name) node = Puppet::Node.new(node_name) compiler = Puppet::Parser::Compiler.new(node) scope = Puppet::Parser::Scope.new(compiler) scope.source = Puppet::Resource::Type.new(:node, node_name) scope.parent = compiler.topscope scope end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/lib/puppet_spec/handler.rb
spec/lib/puppet_spec/handler.rb
require 'puppet/network/http/handler' class PuppetSpec::Handler include Puppet::Network::HTTP::Handler def initialize(* routes) register(routes) end def set_content_type(response, format) response[:content_type_header] = format end def set_response(response, body, status = 200) response[:body] = body response[:status] = status end def http_method(request) request[:method] end def path(request) request[:path] end def params(request) request[:params] end def client_cert(request) request[:client_cert] end def body(request) request[:body] end def headers(request) request[:headers] || {} end end class PuppetSpec::HandlerProfiler def start(metric, description) end def finish(context, metric, description) end def shutdown() end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/lib/puppet_spec/puppetserver.rb
spec/lib/puppet_spec/puppetserver.rb
require 'spec_helper' require 'webrick' require "webrick/ssl" class PuppetSpec::Puppetserver include PuppetSpec::Fixtures include PuppetSpec::Files attr_reader :ca_cert, :ca_crl, :server_cert, :server_key class NodeServlet < WEBrick::HTTPServlet::AbstractServlet def do_GET request, response node = Puppet::Node.new(Puppet[:certname]) response.body = node.render(:json) response['Content-Type'] = 'application/json' end end class CatalogServlet < WEBrick::HTTPServlet::AbstractServlet def do_POST request, response response['Content-Type'] = 'application/json' response['X-Puppet-Compiler-Name'] = 'test-compiler-hostname' catalog = Puppet::Resource::Catalog.new(Puppet[:certname], 'production') response.body = catalog.render(:json) end end class FileMetadatasServlet < WEBrick::HTTPServlet::AbstractServlet def do_GET request, response response['Content-Type'] = 'application/json' 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}]" end end class FileMetadataServlet < WEBrick::HTTPServlet::AbstractServlet def do_GET request, response response['Content-Type'] = 'application/json' 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}" end end class FileContentServlet < WEBrick::HTTPServlet::AbstractServlet def do_GET request, response response.status = 404 end end class ReportServlet < WEBrick::HTTPServlet::AbstractServlet def do_PUT request, response response['Content-Type'] = 'application/json' response.body = "[]" end end class StaticFileContentServlet < WEBrick::HTTPServlet::AbstractServlet def do_GET request, response response.status = 404 end end class FilebucketServlet < WEBrick::HTTPServlet::AbstractServlet def do_GET request, response end def do_PUT request, response upload = File.join(@config.config[:TempDir], 'filebucket') File.open(upload, 'wb') { |f| f.write(request.body) } response['Content-Type'] = 'application/octet-stream' end def do_HEAD request, response response.status = 404 end end class CertificateServlet < WEBrick::HTTPServlet::AbstractServlet def initialize(server, ca_cert) super(server) @ca_cert = ca_cert end def do_GET request, response if request.path =~ %r{/puppet-ca/v1/certificate/ca$} response['Content-Type'] = 'text/plain' response.body = @ca_cert.to_pem else response.status = 404 end end end class CertificateRevocationListServlet < WEBrick::HTTPServlet::AbstractServlet def initialize(server, crl) super(server) @crl = crl end def do_GET request, response response['Content-Type'] = 'text/plain' response.body = @crl.to_pem end end class CertificateRequestServlet < WEBrick::HTTPServlet::AbstractServlet def do_PUT request, response response.status = 404 end end def initialize @ca_cert = cert_fixture('ca.pem') @ca_crl = crl_fixture('crl.pem') @server_key = key_fixture('127.0.0.1-key.pem') @server_cert = cert_fixture('127.0.0.1.pem') @path = tmpfile('webrick') @https = WEBrick::HTTPServer.new( BindAddress: "127.0.0.1", Port: 0, # webrick will choose the first available port, and set it in the config SSLEnable: true, SSLStartImmediately: true, SSLCACertificateFile: File.join(PuppetSpec::FIXTURE_DIR, 'ssl', 'ca.pem'), SSLCertificate: @server_cert, SSLPrivateKey: @server_key, Logger: WEBrick::Log.new(@path), AccessLog: [ [@path, WEBrick::AccessLog::COMBINED_LOG_FORMAT], ] ) trap('INT') do @https.shutdown end # Enable this line for more detailed webrick logging # @https.logger.level = 5 # DEBUG end def start_server(mounts: {}, &block) register_mounts(mounts: mounts) Thread.new do @https.start end begin yield @https.config[:Port] ensure @https.shutdown end end def register_mounts(mounts: {}) register_mount('/status/v1/simple/server', proc { |req, res| }, nil) register_mount('/puppet/v3/node', mounts[:node], NodeServlet) register_mount('/puppet/v3/catalog', mounts[:catalog], CatalogServlet) register_mount('/puppet/v3/file_metadata', mounts[:file_metadata], FileMetadataServlet) register_mount('/puppet/v3/file_metadatas', mounts[:file_metadatas], FileMetadatasServlet) register_mount('/puppet/v3/file_content', mounts[:file_content], FileContentServlet) register_mount('/puppet/v3/static_file_content', mounts[:static_file_content], StaticFileContentServlet) register_mount('/puppet/v3/report', mounts[:report], ReportServlet) register_mount('/puppet/v3/file_bucket_file', mounts[:filebucket], FilebucketServlet) register_mount('/puppet-ca/v1/certificate', mounts[:certificate], CertificateServlet, @ca_cert) register_mount('/puppet-ca/v1/certificate_revocation_list', mounts[:certificate_revocation_list], CertificateRevocationListServlet, @ca_crl) register_mount('/puppet-ca/v1/certificate_request', mounts[:certificate_request], CertificateRequestServlet) end def register_mount(path, user_proc, default_servlet, *args) handler = if user_proc WEBrick::HTTPServlet::ProcHandler.new(user_proc) else default_servlet end @https.mount(path, handler, *args) end def upload_directory @https.config[:TempDir] end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/lib/puppet_spec/unindent.rb
spec/lib/puppet_spec/unindent.rb
class String def unindent(left_padding = '') gsub(/^#{scan(/^\s*/).min_by{ |l| l.length }}/, left_padding) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/lib/puppet_spec/https.rb
spec/lib/puppet_spec/https.rb
require 'spec_helper' require 'webrick' class PuppetSpec::HTTPSServer include PuppetSpec::Fixtures attr_reader :ca_cert, :ca_crl, :server_cert, :server_key def initialize(ca_cert: nil, ca_crl: nil, server_key: nil, server_cert: nil) @ca_cert = ca_cert || cert_fixture('ca.pem') @ca_crl = ca_crl || crl_fixture('crl.pem') @server_key = server_key || key_fixture('127.0.0.1-key.pem') @server_cert = server_cert || cert_fixture('127.0.0.1.pem') @config = WEBrick::Config::HTTP.dup end def handle_request(ctx, ssl, response_proc) req = WEBrick::HTTPRequest.new(@config) req.parse(ssl) # always drain request body req.body res = WEBrick::HTTPResponse.new(@config) res.status = 200 res.body = 'OK' # The server explicitly closes the connection after handling it, # so explicitly tell the client we're not going to keep it open. # Without this, ruby will add `Connection: Keep-Alive`, which # confuses the client when it tries to reuse the half-closed # connection. res['Connection'] = 'close' response_proc.call(req, res) if response_proc res.send_response(ssl) end def start_server(ctx_proc: nil, response_proc: nil, &block) errors = [] IO.pipe {|stop_pipe_r, stop_pipe_w| store = OpenSSL::X509::Store.new Array(@ca_cert).each { |c| store.add_cert(c) } store.purpose = OpenSSL::X509::PURPOSE_SSL_CLIENT ctx = OpenSSL::SSL::SSLContext.new ctx.cert_store = store ctx.cert = @server_cert ctx.key = @server_key ctx.verify_mode = OpenSSL::SSL::VERIFY_NONE ctx_proc.call(ctx) if ctx_proc Socket.do_not_reverse_lookup = true tcps = TCPServer.new("127.0.0.1", 0) begin port = tcps.connect_address.ip_port begin server_thread = Thread.new do begin ssls = OpenSSL::SSL::SSLServer.new(tcps, ctx) ssls.start_immediately = true loop do readable, = IO.select([ssls, stop_pipe_r]) break if readable.include?(stop_pipe_r) ssl = ssls.accept begin handle_request(ctx, ssl, response_proc) ensure ssl.close end end rescue => e # uncomment this line if something goes wrong # puts "SERVER #{e.message}" errors << e end end begin yield port ensure stop_pipe_w.close end ensure server_thread.join end ensure tcps.close end } errors end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false