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/acceptance/tests/agent/agent_parses_json_catalog.rb
acceptance/tests/agent/agent_parses_json_catalog.rb
test_name "C99978: Agent parses a JSON catalog" tag 'risk:high', 'audit:high', # tests defined catalog format 'audit:integration', # There is no OS specific risk here. 'server', 'catalog:json' require 'puppet/acceptance/common_utils' require 'json' step "Agent parses a JSON catalog" do agents.each do |agent| # Path to a ruby binary ruby = Puppet::Acceptance::CommandUtils.ruby_command(agent) # Refresh the catalog on(agent, puppet("agent --test")) # The catalog file should be parseable JSON json_catalog = File.join(agent.puppet['client_datadir'], 'catalog', "#{agent.puppet['certname']}.json") on(agent, "cat #{json_catalog} | #{ruby} -rjson -e 'JSON.parse(STDIN.read)'") # Can the agent parse it as JSON? on(agent, puppet("catalog find --terminus json > /dev/null")) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/tests/agent/fallback_to_cached_catalog.rb
acceptance/tests/agent/fallback_to_cached_catalog.rb
test_name "fallback to the cached catalog" tag 'audit:high', 'audit:integration', # This test is not OS sensitive. 'audit:refactor' # A catalog fixture can be used for this test. Remove the usage of `with_puppet_running_on`. step "run agents once to cache the catalog" do with_puppet_running_on master, {} do on(agents, puppet("agent -t")) end end step "run agents again, verify they use cached catalog" do agents.each do |agent| # can't use --test, because that will set usecacheonfailure=false # We use a server that the agent can't possibly talk to in order # to guarantee that no communication can take place. on(agent, puppet("agent --onetime --no-daemonize --server puppet.example.com --verbose")) do |result| assert_match(/Using cached catalog/, result.stdout) unless agent['locale'] == 'ja' end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/tests/direct_puppet/static_catalog_env_control.rb
acceptance/tests/direct_puppet/static_catalog_env_control.rb
test_name "Environment control of static catalogs" tag 'audit:high', 'audit:acceptance', 'audit:refactor', # use mk_tmp_environment_with_teardown helper for environment construction 'server' skip_test 'requires puppetserver to test static catalogs' if @options[:type] != 'aio' require 'json' @testroot = master.tmpdir(File.basename(__FILE__, '/*')) @coderoot = "#{@testroot}/code" @confdir = master['puppetserver-confdir'] @master_opts = { 'main' => { 'environmentpath' => "#{@coderoot}/environments", }, } @production_files = {} @canary_files = {} @agent_manifests = {} @catalog_files = {} agents.each do |agent| hn = agent.node_name resdir = agent.tmpdir('results') @production_files[hn] = "#{resdir}/prod_hello_from_puppet_uri" @canary_files[hn] = "#{resdir}/can_hello_from_puppet_uri" @catalog_files[hn] = "#{on(agent, puppet('config', 'print', 'client_datadir')).stdout.chomp}/catalog/#{hn}.json" @agent_manifests[hn] = <<MANIFESTAGENT file { '#{@coderoot}/environments/production/modules/hello/manifests/init.pp': ensure => file, mode => "0644", content => "class hello { notice('hello from production-hello') file { '#{resdir}' : ensure => directory, mode => '0755', } file { '#{resdir}/prod_hello_from_puppet_uri' : ensure => file, mode => '0644', source => 'puppet:///modules/hello/hello_msg', } }", } file { '#{@coderoot}/environments/canary/modules/can_hello/manifests/init.pp': ensure => file, mode => "0644", content => 'class can_hello { notice("hello from production-hello") file { "#{resdir}": ensure => directory, mode => "0755", } file { "#{resdir}/can_hello_from_puppet_uri" : ensure => file, mode => "0644", source => "puppet:///modules/can_hello/hello_msg", } }', } MANIFESTAGENT end # The code_content script needs to return the correct content whose checksum # matches the metadata contained in the static catalog. PRODUCTION_CONTENT = "Hello message from production/hello module, content from source attribute.".freeze CANARY_CONTENT = "Hello message from canary/can_hello module, content from source attribute.".freeze @manifest = <<MANIFEST File { ensure => directory, mode => "0755", } file { '#{@testroot}':; '#{@coderoot}':; '#{@coderoot}/environments':; '#{@coderoot}/environments/production':; '#{@coderoot}/environments/production/manifests':; '#{@coderoot}/environments/production/modules':; '#{@coderoot}/environments/production/modules/hello':; '#{@coderoot}/environments/production/modules/hello/manifests':; '#{@coderoot}/environments/production/modules/hello/files':; '#{@coderoot}/environments/canary':; '#{@coderoot}/environments/canary/manifests':; '#{@coderoot}/environments/canary/modules':; '#{@coderoot}/environments/canary/modules/can_hello':; '#{@coderoot}/environments/canary/modules/can_hello/manifests':; '#{@coderoot}/environments/canary/modules/can_hello/files':; } file { '#{@coderoot}/code_id.sh' : ensure => file, mode => "0755", content => '#! /bin/bash echo "code_version_1" ', } file { '#{@coderoot}/code_content.sh' : ensure => file, mode => "0755", content => '#! /bin/bash # script arguments: # $1 environment # $2 code_id # $3 path relative to mount # use echo -n to omit newline if [ $1 == "production" ] ; then echo -n "#{PRODUCTION_CONTENT}" else echo -n "#{CANARY_CONTENT}" fi ', } file { '#{@coderoot}/environments/production/environment.conf': ensure => file, mode => "0644", content => 'environment_timeout = 0 ', } file { '#{@coderoot}/environments/canary/environment.conf': ensure => file, mode => "0644", content => 'environment_timeout = 0 static_catalogs = false ', } file { '#{@coderoot}/environments/production/manifests/site.pp': ensure => file, mode => "0644", content => "node default { include hello } ", } file { '#{@coderoot}/environments/canary/manifests/site.pp': ensure => file, mode => "0644", content => "node default { include can_hello } ", } file { '#{@coderoot}/environments/production/modules/hello/files/hello_msg': ensure => file, mode => "0644", content => "#{PRODUCTION_CONTENT}", } file { '#{@coderoot}/environments/canary/modules/can_hello/files/hello_msg': ensure => file, mode => "0644", content => "#{CANARY_CONTENT}", } MANIFEST teardown do on(master, "mv #{@confdir}/puppetserver.conf.bak #{@confdir}/puppetserver.conf") on(master, "rm -rf #{@testroot}") agents.each do |agent| on(agent, puppet('config print lastrunfile')) do |command_result| agent.rm_rf(command_result.stdout) end end end step 'apply main manifest, static_catalogs unspecified in global scope, unspecified in production environment, disabled in canary environment' on( master, "cp #{@confdir}/puppetserver.conf #{@confdir}/puppetserver.conf.bak" ) apply_manifest_on(master, @manifest, :catch_failures => true) step "Add versioned-code parameters to puppetserver.conf and ensure the server is running" puppetserver_config = "#{master['puppetserver-confdir']}/puppetserver.conf" on master, "cp #{puppetserver_config} #{@coderoot}/puppetserver.conf.bak" versioned_code_settings = { "jruby-puppet" => { "master-code-dir" => @coderoot }, "versioned-code" => { "code-id-command" => "#{@coderoot}/code_id.sh", "code-content-command" => "#{@coderoot}/code_content.sh" } } modify_tk_config(master, puppetserver_config, versioned_code_settings) step 'start puppet server' with_puppet_running_on master, @master_opts, @coderoot do agents.each do |agent| hn = agent.node_name apply_manifest_on(master, @agent_manifests[hn], :catch_failures => true) step 'agent gets a production catalog, should be static catalog by default' on( agent, puppet( 'agent', '-t', '--environment', 'production' ), :acceptable_exit_codes => [0, 2] ) step 'verify production environment' r = on(agent, "cat #{@catalog_files[hn]}") catalog_content = JSON.parse(r.stdout) assert_equal( catalog_content['environment'], 'production', 'catalog for unexpectected environment' ) step 'verify static catalog by finding metadata section in catalog' assert( catalog_content['metadata'] && catalog_content['metadata'][@production_files[hn]], 'metadata section of catalog not found' ) step 'agent gets a canary catalog, static catalog should be disabled' on( agent, puppet( 'agent', '-t', '--environment', 'canary' ), :acceptable_exit_codes => [0, 2] ) step 'verify canary environment' r = on(agent, "cat #{@catalog_files[hn]}") catalog_content = JSON.parse(r.stdout) assert_equal( catalog_content['environment'], 'canary', 'catalog for unexpectected environment' ) step 'verify not static catalog by absence of metadata section in catalog' assert_nil( catalog_content['metadata'], 'unexpected metadata section found in catalog' ) end end step 'enable static catalog for canary environment' @static_canary_manifest = <<MANIFEST2 file { '#{@coderoot}/environments/canary/environment.conf': ensure => file, mode => "0644", content => 'environment_timeout = 0 static_catalogs = true ', } MANIFEST2 apply_manifest_on(master, @static_canary_manifest, :catch_failures => true) step 'disable global static catalog setting' @master_opts = { 'master' => { 'static_catalogs' => false }, 'main' => { 'environmentpath' => "#{@coderoot}/environments", }, } step 'bounce server for static catalog disable setting to take effect.' with_puppet_running_on master, @master_opts, @coderoot do agents.each do |agent| hn = agent.node_name apply_manifest_on(master, @agent_manifests[hn], :catch_failures => true) step 'agent gets a production catalog, should not be a static catalog' on( agent, puppet( 'agent', '-t', '--environment', 'production' ), :acceptable_exit_codes => [0, 2] ) step 'verify production environment' r = on(agent, "cat #{@catalog_files[hn]}") catalog_content = JSON.parse(r.stdout) assert_equal( catalog_content['environment'], 'production', 'catalog for unexpectected environment' ) step 'verify production environment, not static catalog' assert_nil( catalog_content['metadata'], 'unexpected metadata section found in catalog' ) step 'agent gets a canary catalog, static catalog should be enabled' on( agent, puppet( 'agent', '-t', '--environment', 'canary' ), :acceptable_exit_codes => [0, 2] ) step 'verify canary catalog' r = on(agent, "cat #{@catalog_files[hn]}") catalog_content = JSON.parse(r.stdout) assert_equal( catalog_content['environment'], 'canary', 'catalog for unexpectected environment' ) step 'verify canary static catalog' assert( catalog_content['metadata'] && catalog_content['metadata'][@canary_files[hn]], 'metadata section of catalog not found' ) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/tests/direct_puppet/supports_utf8.rb
acceptance/tests/direct_puppet/supports_utf8.rb
test_name "C97172: static catalogs support utf8" do require 'puppet/acceptance/environment_utils' extend Puppet::Acceptance::EnvironmentUtils require 'puppet/acceptance/agent_fqdn_utils' extend Puppet::Acceptance::AgentFqdnUtils tag 'audit:high', 'audit:acceptance', 'audit:refactor' # Review for agent side UTF validation. app_type = File.basename(__FILE__, '.*') tmp_environment = mk_tmp_environment_with_teardown(master, app_type) tmp_file = {} agents.each do |agent| tmp_file[agent_to_fqdn(agent)] = agent.tmpfile(tmp_environment) end teardown do # Remove all traces of the last used environment agents.each do |agent| on(agent, puppet('config print lastrunfile')) do |command_result| agent.rm_rf(command_result.stdout) end end step 'clean out produced resources' do agents.each do |agent| if tmp_file.has_key?(agent_to_fqdn(agent)) && !tmp_file[agent_to_fqdn(agent)].empty? on(agent, "rm -f '#{tmp_file[agent_to_fqdn(agent)]}'") end end end end file_contents = 'Mønti Pythøn ik den Hølie Gräilen, yër? € ‰ ㄘ 万 竹 Ü Ö' step 'create site.pp with utf8 chars' do manifest = <<MANIFEST file { '#{environmentpath}/#{tmp_environment}/manifests/site.pp': ensure => file, content => ' \$test_path = \$facts["networking"]["fqdn"] ? #{tmp_file} file { \$test_path: content => @(UTF8) #{file_contents} | UTF8 } ', } MANIFEST apply_manifest_on(master, manifest, :catch_failures => true) end step 'run agent(s)' do with_puppet_running_on(master, {}) do agents.each do |agent| config_version = '' config_version_matcher = /configuration version '(\d+)'/ on(agent, puppet("agent -t --environment '#{tmp_environment}'"), :acceptable_exit_codes => 2).stdout do |result| config_version = result.match(config_version_matcher)[1] end on(agent, "cat '#{tmp_file[agent_to_fqdn(agent)]}'").stdout do |result| assert_equal(file_contents, result, 'file contents did not match accepted') end on(agent, "rm -f '#{tmp_file[agent_to_fqdn(agent)]}'") on(agent, puppet("agent -t --environment '#{tmp_environment}' --use_cached_catalog"), :acceptable_exit_codes => 2).stdout do |result| assert_match(config_version_matcher, result, 'agent did not use cached catalog') second_config_version = result.match(config_version_matcher)[1] asset_equal(config_version, second_config_version, 'config version should have been the same') end on(agent, "cat '#{tmp_file[agent_to_fqdn(agent)]}'").stdout do |result| assert_equal(file_contents, result, 'file contents did not match accepted') 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/acceptance/tests/direct_puppet/catalog_uuid_correlates_catalogs_with_reports.rb
acceptance/tests/direct_puppet/catalog_uuid_correlates_catalogs_with_reports.rb
test_name "PUP-5872: catalog_uuid correlates catalogs with reports" do tag 'audit:high', 'audit:acceptance', 'audit:refactor' # remove dependence on server by adding a # catalog and report fixture to validate against. master_reportdir = create_tmpdir_for_user(master, 'reportdir') def remove_reports_on_master(master_reportdir, agent_node_name) on(master, "rm -rf #{master_reportdir}/#{agent_node_name}/*") end def get_catalog_uuid_from_cached_catalog(host, agent_vardir, agent_node_name) cache_catalog_uuid = nil on(host, "cat #{agent_vardir}/client_data/catalog/#{agent_node_name}.json") do |result| cache_catalog_uuid = result.stdout.match(/"catalog_uuid":"([a-z0-9\-]*)",/)[1] end cache_catalog_uuid end def get_catalog_uuid_from_report(master_reportdir, agent_node_name) report_catalog_uuid = nil on(master, "cat #{master_reportdir}/#{agent_node_name}/*") do |result| report_catalog_uuid = result.stdout.match(/catalog_uuid: '?([a-z0-9\-]*)'?/)[1] end report_catalog_uuid end with_puppet_running_on(master, :master => { :reportdir => master_reportdir, :reports => 'store' }) do agents.each do |agent| agent_vardir = agent.tmpdir(File.basename(__FILE__, '.*')) step "agent: #{agent}: Initial run to retrieve a catalog and generate the first report" do on(agent, puppet("agent", "-t", "--vardir #{agent_vardir}"), :acceptable_exit_codes => [0,2]) end cache_catalog_uuid = get_catalog_uuid_from_cached_catalog(agent, agent_vardir, agent.node_name) step "agent: #{agent}: Ensure the catalog and report share the same catalog_uuid" do report_catalog_uuid = get_catalog_uuid_from_report(master_reportdir, agent.node_name) assert_equal(cache_catalog_uuid, report_catalog_uuid, "catalog_uuid found in cached catalog, #{cache_catalog_uuid} did not match report #{report_catalog_uuid}") end step "cleanup reports on master" do remove_reports_on_master(master_reportdir, agent.node_name) end step "Run with --use_cached_catalog and ensure catalog_uuid in the new report matches the cached catalog" do on(agent, puppet("agent", "--onetime", "--no-daemonize", "--use_cached_catalog", "--vardir #{agent_vardir}"), :acceptance_exit_codes => [0,2]) report_catalog_uuid = get_catalog_uuid_from_report(master_reportdir, agent.node_name) assert_equal(cache_catalog_uuid, report_catalog_uuid, "catalog_uuid found in cached catalog, #{cache_catalog_uuid} did not match report #{report_catalog_uuid}") 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/acceptance/tests/direct_puppet/cached_catalog_remediate_local_drift.rb
acceptance/tests/direct_puppet/cached_catalog_remediate_local_drift.rb
require 'puppet/acceptance/static_catalog_utils' extend Puppet::Acceptance::StaticCatalogUtils test_name "PUP-5122: Puppet remediates local drift using code_id and content_uri" do tag 'audit:high', 'audit:acceptance', 'audit:refactor', # use mk_tmp_environment_with_teardown helper for environment construction 'server' skip_test 'requires puppetserver installation' if @options[:type] != 'aio' basedir = master.tmpdir(File.basename(__FILE__, '.*')) module_dir = "#{basedir}/environments/production/modules" master_opts = { 'main' => { 'environmentpath' => "#{basedir}/environments" } } step "Add versioned-code parameters to puppetserver.conf and ensure the server is running" do setup_puppetserver_code_id_scripts(master, basedir) end teardown do cleanup_puppetserver_code_id_scripts(master, basedir) on master, "rm -rf #{basedir}" agents.each do |agent| on(agent, puppet('config print lastrunfile')) do |command_result| agent.rm_rf(command_result.stdout) end end end step "Create a module and a file with content representing the first code_id version" do apply_manifest_on(master, <<MANIFEST, :catch_failures => true) File { ensure => directory, mode => "0750", owner => #{master.puppet['user']}, group => #{master.puppet['group']}, } file { '#{basedir}':; '#{basedir}/environments':; '#{basedir}/environments/production':; '#{basedir}/environments/production/manifests':; '#{module_dir}':; '#{module_dir}/foo':; '#{module_dir}/foo/files':; } MANIFEST end with_puppet_running_on master, master_opts, basedir do agents.each do |agent| agent_test_file_path = agent.tmpfile('foo_file') step "Add test file resource to site.pp on master with agent-specific file path" do apply_manifest_on(master, <<MANIFEST, :catch_failures => true) File { owner => #{master.puppet['user']}, group => #{master.puppet['group']}, } file { "#{basedir}/environments/production/manifests/site.pp" : ensure => file, mode => "0640", content => "node default { file { '#{agent_test_file_path}' : ensure => file, source => 'puppet:///modules/foo/foo.txt' } }", } file { "#{module_dir}/foo/files/foo.txt" : ensure => file, content => "code_version_1", mode => "0640", } MANIFEST end step "agent: #{agent}: Initial run: create the file with code version 1 and cache the catalog" on(agent, puppet("agent", "-t"), :acceptable_exit_codes => [0,2]) # When there is no drift, there should be no request made to the server # for file metadata or file content. A puppet run depending on # a non-server will fail if such a request is made. Verify the agent # sends a report. step "Remove existing reports from server reports directory" on(master, "rm -rf /opt/puppetlabs/server/data/puppetserver/reports/#{agent.node_name}/*") r = on(master, "ls /opt/puppetlabs/server/data/puppetserver/reports/#{agent.node_name} | wc -l").stdout.chomp assert_equal(r, '0', "reports directory should be empty!") step "Verify puppet run without drift does not make file request from server" r = on(agent, puppet("agent", "--use_cached_catalog", "--server", "no_such_host", "--report_server", master.hostname, "--onetime", "--no-daemonize", "--detailed-exitcodes", "--verbose" )).stderr assert_equal(r, "", "Fail: Did agent try to contact server?") step "Verify report was delivered to server" r = on(master, "ls /opt/puppetlabs/server/data/puppetserver/reports/#{agent.node_name} | wc -l").stdout.chomp assert_equal(r, '1', "Reports directory should have one file") step "agent: #{agent}: Remove the test file to simulate drift" on(agent, "rm -rf #{agent_test_file_path}") step "Alter the source file on the master to simulate a code update" apply_manifest_on(master, <<MANIFEST, :catch_failures => true) file { "#{module_dir}/foo/files/foo.txt" : ensure => file, mode => "0640", content => "code_version_2", } MANIFEST step "Run agent again using --use_cached_catalog and ensure content from the first code_id is used" on(agent, puppet("agent", "-t", "--use_cached_catalog"), :acceptable_exit_codes => [0,2]) on(agent, "cat #{agent_test_file_path}") do |result| assert_equal('code_version_1', result.stdout) 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/acceptance/tests/face/parser_validate.rb
acceptance/tests/face/parser_validate.rb
test_name 'parser validate' do tag 'audit:high', 'audit:unit' # Parser validation should be core to ruby # and platform agnostic. require 'puppet/acceptance/environment_utils' extend Puppet::Acceptance::EnvironmentUtils require 'puppet/acceptance/temp_file_utils' extend Puppet::Acceptance::TempFileUtils app_type = File.basename(__FILE__, '.*') teardown do agents.each do |agent| on(agent, puppet('config print lastrunfile')) do |command_result| agent.rm_rf(command_result.stdout) end end end agents.each do |agent| skip_test('this test fails on windows French due to Cygwin/UTF Issues - PUP-8319,IMAGES-492') if agent['platform'] =~ /windows/ && agent['locale'] == 'fr' step 'manifest with parser function call' do if agent.platform !~ /windows/ tmp_environment = mk_tmp_environment_with_teardown(agent, app_type) create_sitepp(agent, tmp_environment, <<-SITE) function validate_this() { notice('hello, puppet') } validate_this() SITE on(agent, puppet("parser validate --environment #{tmp_environment}"), :pty => true) # default manifest end # manifest with Type aliases create_test_file(agent, "#{app_type}.pp", <<-PP) function validate_this() { notice('hello, puppet') } validate_this() type MyInteger = Integer notice 42 =~ MyInteger PP tmp_manifest = get_test_file_path(agent, "#{app_type}.pp") on(agent, puppet("parser validate #{tmp_manifest}")) end step 'manifest with bad syntax' do create_test_file(agent, "#{app_type}_broken.pp", "notify 'hello there'") tmp_manifest = get_test_file_path(agent, "#{app_type}_broken.pp") on(agent, puppet("parser validate #{tmp_manifest}"), :accept_all_exit_codes => true) do |result| assert_equal(result.exit_code, 1, 'parser validate did not exit with 1 upon parse failure') expected = /Error: Could not parse for environment production: This Name has no effect\. A value was produced and then forgotten \(one or more preceding expressions may have the wrong form\) \(file: .*_broken\.pp, line: 1, column: 1\)/ assert_match(expected, result.output, "parser validate did not output correctly: '#{result.output}'. expected: '#{expected.to_s}'") unless agent['locale'] == 'ja' end end step '(large) manifest with exported resources' do fixture_path = File.join(File.dirname(__FILE__), '..', '..', 'fixtures/manifest_large_exported_classes_node.pp') create_test_file(agent, "#{app_type}_exported.pp", File.read(fixture_path)) tmp_manifest = get_test_file_path(agent, "#{app_type}_exported.pp") on(agent, puppet("parser validate #{tmp_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/acceptance/tests/face/loadable_from_modules.rb
acceptance/tests/face/loadable_from_modules.rb
test_name "Exercise loading a face from a module" # Because the module tool does not work on windows, we can't run this test there confine :except, :platform => 'windows' tag 'audit:high', 'audit:acceptance', # This has been OS sensitive. 'audit:refactor' # Remove the confine against windows and refactor to # accommodate the Windows platform. require 'puppet/acceptance/temp_file_utils' extend Puppet::Acceptance::TempFileUtils initialize_temp_dirs metadata_json_file = <<-FILE { "name": "puppetlabs-helloworld", "version": "0.0.1", "author": "Puppet Labs", "summary": "Nginx Module", "license": "Apache Version 2.0", "source": "https://github.com/puppetlabs/puppetlabs-nginx", "project_page": "https://github.com/puppetlabs/puppetlabs-nginx", "issues_url": "https://github.com/puppetlabs/puppetlabs-nginx", "dependencies": [ {"name":"puppetlabs-stdlub","version_requirement":">= 1.0.0"} ] } FILE agents.each do |agent| if on(agent, facter("fips_enabled")).stdout =~ /true/ puts "Module build, loading and installing not supported on fips enabled platforms" next end environmentpath = get_test_file_path(agent, 'environments') dev_modulepath = "#{environmentpath}/dev/modules" module_base_dir = "#{dev_modulepath}/helloworld" teardown do on agent, "rm -rf #{module_base_dir}" end # make sure that we use the modulepath from the dev environment puppetconf = get_test_file_path(agent, 'puppet.conf') on agent, puppet("config", "set", "environmentpath", environmentpath, "--section", "main", "--config", puppetconf) on agent, puppet("config", "set", "environment", "dev", "--section", "user", "--config", puppetconf) mkdirs agent, module_base_dir create_remote_file(agent, "#{module_base_dir}/metadata.json", metadata_json_file) mkdirs agent, "#{module_base_dir}/lib/puppet/application" mkdirs agent, "#{module_base_dir}/lib/puppet/face" # copy application, face, and utility module create_remote_file(agent, "#{module_base_dir}/lib/puppet/application/helloworld.rb", <<'EOM') require 'puppet/face' require 'puppet/application/face_base' class Puppet::Application::Helloworld < Puppet::Application::FaceBase end EOM create_remote_file(agent, "#{module_base_dir}/lib/puppet/face/helloworld.rb", <<'EOM') Puppet::Face.define(:helloworld, '0.1.0') do summary "Hello world face" description "This is the hello world face" action 'actionprint' do summary "Prints hello world from an action" when_invoked do |options| puts "Hello world from an action" end end action 'moduleprint' do summary "Prints hello world from a required module" when_invoked do |options| require 'puppet/helloworld.rb' Puppet::Helloworld.print end end end EOM create_remote_file(agent, "#{module_base_dir}/lib/puppet/helloworld.rb", <<'EOM') module Puppet::Helloworld def print puts "Hello world from a required module" end module_function :print end EOM on(agent, puppet('help', '--config', puppetconf)) do |result| assert_match(/helloworld\s*Hello world face/, result.stdout, "Face missing from list of available subcommands") end on(agent, puppet('help', 'helloworld', '--config', puppetconf)) do |result| assert_match(/This is the hello world face/, result.stdout, "Descripion help missing") assert_match(/moduleprint\s*Prints hello world from a required module/, result.stdout, "help for moduleprint action missing") assert_match(/actionprint\s*Prints hello world from an action/, result.stdout, "help for actionprint action missing") end on(agent, puppet('helloworld', 'actionprint', '--config', puppetconf)) do |result| assert_match(/^Hello world from an action$/, result.stdout, "face did not print hello world") end on(agent, puppet('helloworld', 'moduleprint', '--config', puppetconf)) do |result| assert_match(/^Hello world from a required module$/, result.stdout, "face did not load module to print hello world") end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/tests/face/4654_facts_face.rb
acceptance/tests/face/4654_facts_face.rb
test_name "Puppet facts face should resolve custom and external facts" tag 'audit:high', 'audit:integration' # The facter acceptance tests should be acceptance. # However, the puppet face merely needs to interact with libfacter. # So, this should be an integration test. # # This test is intended to ensure that custom and external facts present # on the agent are resolved and displayed by the puppet facts face. # custom_fact = <<CFACT Facter.add('custom_fact') do setcode do 'foo' end end CFACT unix_external_fact = <<EFACT #!/bin/sh echo 'external_fact=bar' EFACT win_external_fact = <<EFACT @echo off echo external_fact=bar EFACT agents.each do |agent| if agent['platform'] =~ /windows/ external_fact = win_external_fact ext = '.bat' else external_fact = unix_external_fact ext = '.sh' end step "Create custom and external facts in their default directories on the agent" teardown do on agent, "rm -rf #{agent.puppet['plugindest']}/facter" on agent, "rm -rf #{agent.puppet['pluginfactdest']}/external#{ext}" end on agent, puppet('apply'), :stdin => <<MANIFEST file { "#{agent.puppet['plugindest']}/facter": ensure => directory, } file { "#{agent.puppet['plugindest']}/facter/custom.rb": ensure => file, content => "#{custom_fact}", } file { "#{agent.puppet['pluginfactdest']}/external#{ext}": ensure => file, mode => "0755", content => "#{external_fact}", } MANIFEST step "Agent #{agent}: custom_fact and external_fact should be present in the output of `puppet facts`" on agent, puppet('facts') do |result| assert_match(/"custom_fact": "foo"/, result.stdout, "custom_fact did not match expected output") assert_match(/"external_fact": "bar"/, result.stdout, "external_fact did not match expected output") end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/tests/language/sensitive_data_type.rb
acceptance/tests/language/sensitive_data_type.rb
test_name 'C98120, C98077: Sensitive Data is redacted on CLI, logs, reports' do require 'puppet/acceptance/puppet_type_test_tools.rb' extend Puppet::Acceptance::PuppetTypeTestTools tag 'audit:high', 'audit:acceptance', # Tests that sensitive data is retains integrity # between server and agent transport/application. # Leaving at acceptance layer due to validate # written logs. 'server' teardown do agents.each do |agent| on(agent, puppet('config print lastrunfile')) do |command_result| agent.rm_rf(command_result.stdout) end end end app_type = File.basename(__FILE__, '.*') tmp_environment = mk_tmp_environment_with_teardown(master, app_type) tmp_filename_win = tmp_filename_else = '' agents.each do |agent| # ugh... this won't work with more than two agents of two types if agent.platform =~ /32$/ tmp_filename_win = "C:\\cygwin\\tmp\\#{tmp_environment}.txt" else tmp_filename_win = "C:\\cygwin64\\tmp\\#{tmp_environment}.txt" end tmp_filename_else = "/tmp/#{tmp_environment}.txt" on agent, "echo 'old content' > /tmp/#{tmp_environment}.txt" end # first attempts at a reasonable table driven test. needs API work # FIXME: # expand this to other resource types, make parameters arbitrary, make assertions arbitrary # FIXME: add context messaging to each instance notify_redacted = 'Sensitive \[value redacted\]' file_redacted = 'changed \[redacted\] to \[redacted\]' test_resources = [ {:type => 'notify', :parameters => {:namevar => "1:${Sensitive.new('sekrit1')}"}, :assertions => [{:refute_match => 'sekrit1'}, {:assert_match => "1:#{notify_redacted}"}]}, {:type => 'notify', :parameters => {:namevar => "2:${Sensitive.new($meh2)}"}, :pre_code => '$meh2="sekrit2"', :assertions => [{:refute_match => 'sekrit2'}, {:assert_match => "2:#{notify_redacted}"}]}, {:type => 'notify', :parameters => {:namevar => "3:meh", :message => '"3:${Sensitive.new(\'sekrit3\')}"'}, :assertions => [{:refute_match => 'sekrit3'}, {:assert_match => "3:#{notify_redacted}"}]}, {:type => 'notify', :parameters => {:namevar => "4:meh", :message => "Sensitive.new($meh4)"}, :pre_code => '$meh4="sekrit4"', :assertions => [{:refute_match => 'sekrit4'}, {:assert_match => file_redacted}]}, {:type => 'notify', :parameters => {:namevar => "5:meh", :message => "$meh5"}, :pre_code => '$meh5=Sensitive.new("sekrit5")', :assertions => [{:refute_match => 'sekrit5'}, {:assert_match => file_redacted}]}, {:type => 'notify', :parameters => {:namevar => "6:meh", :message => '"6:${meh6}"'}, :pre_code => '$meh6=Sensitive.new("sekrit6")', :assertions => [{:refute_match => 'sekrit6'}, {:assert_match => "6:#{notify_redacted}"}]}, {:type => 'notify', :parameters => {:namevar => "7:${Sensitive('sekrit7')}"}, :assertions => [{:refute_match => 'sekrit7'}, {:assert_match => "7:#{notify_redacted}"}]}, # unwrap(), these should be en-clair {:type => 'notify', :parameters => {:namevar => "8:${unwrap(Sensitive.new('sekrit8'))}"}, :assertions => {:assert_match => "8:sekrit8"}}, {:type => 'notify', :parameters => {:namevar => "9:meh", :message => '"9:${unwrap(Sensitive.new(\'sekrit9\'))}"'}, :assertions => {:assert_match => "9:sekrit9"}}, {:type => 'notify', :parameters => {:namevar => "A:meh", :message => '"A:${unwrap($mehA)}"'}, :pre_code => '$mehA=Sensitive.new("sekritA")', :assertions => {:assert_match => "A:sekritA"}}, {:type => 'notify', :parameters => {:namevar => "B:meh", :message => '"B:${$mehB.unwrap}"'}, :pre_code => '$mehB=Sensitive.new("sekritB")', :assertions => {:assert_match => "B:sekritB"}}, {:type => 'notify', :parameters => {:namevar => "C:meh", :message => '"C:${$mehC.unwrap |$unwrapped| { "blk_${unwrapped}_blk" } } nonblk_${mehC}_nonblk"'}, :pre_code => '$mehC=Sensitive.new("sekritC")', :assertions => {:assert_match => ["C:blk_sekritC_blk", "nonblk_#{notify_redacted}_nonblk"]}}, # for --show_diff {:type => 'file', :parameters => {:namevar => "$pup_tmp_filename", :content => "Sensitive.new('sekritD')"}, :pre_code => "$pup_tmp_filename = if $facts['os']['family'] == 'windows' { '#{tmp_filename_win}' } else { '#{tmp_filename_else}' }", :assertions => [{:refute_match => 'sekritD'}, {:assert_match => /#{tmp_environment}\.txt..content. #{file_redacted}/}]}, ] sitepp_content = generate_manifest(test_resources) assertion_code = generate_assertions(test_resources) # Make a copy of the full set of 'test_resources' but filtered down to include # only the assertions of type ':refute_match'. So for example, where the # 'test_resources' array might have an entry like this... # # {:type => 'notify', ... # :assertions => [{:refute_match => 'sekrit1'}, # {:assert_match => "1:#{notify_redacted}"}]} # # ... the ':assert_match' entry would be filtered out in the new # 'refutation_resources' array, producing: # # {:type => 'notify', ... # :assertions => [{:refute_match => 'sekrit1'}]} # # This is done so that when validating the log output, we can refute the # existence of any of the sensitive info in the log without having to # assert that redacted info is in the log. The redacted info appears in # the console output from the Puppet agent run - by virtue of including a # '--debug' flag on the agent command line - whereas the redacted info is not # expected to be piped into the log. refutation_resources = test_resources.collect do |assertion_group| refutation_group = assertion_group.clone refutation_group[:assertions] = assertion_group[:assertions].select do |assertion| assertion.has_key?(:refute_match) end refutation_group end refutation_code = generate_assertions(refutation_resources) create_sitepp(master, tmp_environment, sitepp_content) step "run agent in #{tmp_environment}, run all assertions" do with_puppet_running_on(master,{}) do agents.each do |agent| # redirect logging to a temp location to avoid platform specific syslogs on(agent, puppet("agent -t --debug --trace --show_diff --environment #{tmp_environment}"), :accept_all_exit_codes => true) do |result| assert_equal(result.exit_code, 2,'puppet agent run failed') run_assertions(assertion_code, result) unless agent['locale'] == 'ja' step "assert no redacted data in log" do run_assertions(refutation_code, result) end end # don't do this before the agent log scanning, above. it will skew the results step "assert no redacted data in vardir" do # no recursive grep in solaris :facepalm: on(agent, "find #{agent.puppet['vardir']} -type f | xargs grep sekrit", :accept_all_exit_codes => true) do |result| refute_match(/sekrit(1|2|3|6|7)/, result.stdout, 'found redacted data we should not have') #TODO: if/when this is fixed, we should just be able to eval(assertion_code_ in this result block also! expect_failure 'file resource contents will end up in the cached catalog en-clair' do refute_match(/sekritD/, result.stdout, 'found redacted file data we should not have') end end end end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/tests/language/pcore_generate_env_isolation.rb
acceptance/tests/language/pcore_generate_env_isolation.rb
test_name 'C98345: ensure puppet generate assures env. isolation' do require 'puppet/acceptance/environment_utils.rb' extend Puppet::Acceptance::EnvironmentUtils tag 'audit:high', 'audit:integration', 'server' teardown do agents.each do |agent| on(agent, puppet('config print lastrunfile')) do |command_result| agent.rm_rf(command_result.stdout) end end end app_type = File.basename(__FILE__, '.*') tmp_environment = mk_tmp_environment_with_teardown(master, app_type) tmp_environment2 = mk_tmp_environment_with_teardown(master, app_type) fq_tmp_environmentpath = "#{environmentpath}/#{tmp_environment}" fq_tmp_environmentpath2 = "#{environmentpath}/#{tmp_environment2}" type_name = 'conflicting' relative_type_dir = 'modules/conflict/lib/puppet/type' relative_type_path = "#{relative_type_dir}/#{type_name}.rb" step 'create custom type in two environments' do on(master, "mkdir -p #{fq_tmp_environmentpath}/#{relative_type_dir}") on(master, "mkdir -p #{fq_tmp_environmentpath2}/#{relative_type_dir}") custom_type1 = <<-END Puppet::Type.newtype(:#{type_name}) do newparam :name, :namevar => true END custom_type2 = "#{custom_type1}" custom_type2 << " newparam :other\n" custom_type1 << " end\n" custom_type2 << " end\n" create_remote_file(master, "#{fq_tmp_environmentpath}/#{relative_type_path}", custom_type1) create_remote_file(master, "#{fq_tmp_environmentpath2}/#{relative_type_path}", custom_type2) site_pp1 = <<-PP notify{$environment:} #{type_name}{"somename":} PP site_pp2 = <<-PP notify{$environment:} #{type_name}{"somename": other => "uhoh"} PP create_sitepp(master, tmp_environment, site_pp1) create_sitepp(master, tmp_environment2, site_pp2) end on master, "chmod -R 755 /tmp/#{tmp_environment}" on master, "chmod -R 755 /tmp/#{tmp_environment2}" with_puppet_running_on(master,{}) do agents.each do |agent| on(agent, puppet("agent -t --environment #{tmp_environment}"), :acceptable_exit_codes => 2) step 'run agent in environment with type with an extra parameter. try to use this parameter' do on(agent, puppet("agent -t --environment #{tmp_environment2}"), :accept_all_exit_codes => true) do |result| unless agent['locale'] == 'ja' assert_match("Error: no parameter named 'other'", result.output, 'did not produce environment isolation issue as expected') end end end end step 'generate pcore files' do on(master, puppet("generate types --environment #{tmp_environment}")) on(master, puppet("generate types --environment #{tmp_environment2}")) end agents.each do |agent| step 'rerun agents after generate, ensure proper runs' do on(agent, puppet("agent -t --environment #{tmp_environment}"), :acceptable_exit_codes => 2) on(agent, puppet("agent -t --environment #{tmp_environment2}"), :acceptable_exit_codes => 2) 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/acceptance/tests/language/functions_in_puppet_language.rb
acceptance/tests/language/functions_in_puppet_language.rb
test_name 'Puppet executes functions written in the Puppet language' tag 'audit:high', 'audit:integration', 'audit:refactor', # use mk_tmp_environment_with_teardown helper for environment construction 'server' teardown do on master, 'rm -rf /etc/puppetlabs/code/modules/jenny' on master, 'rm -rf /etc/puppetlabs/code/environments/tommy' on master, 'rm -rf /etc/puppetlabs/code/environments/production/modules/one' on master, 'rm -rf /etc/puppetlabs/code/environments/production/modules/three' agents.each do |agent| on(agent, puppet('config print lastrunfile')) do |command_result| agent.rm_rf(command_result.stdout) end end end step 'Create some functions' do manifest = <<-EOF File { ensure => 'present', owner => 'root', group => 'root', mode => '0644', } file {['/etc/puppetlabs/', '/etc/puppetlabs/code/', '/etc/puppetlabs/code/modules/', '/etc/puppetlabs/code/modules/jenny', '/etc/puppetlabs/code/modules/jenny/functions', '/etc/puppetlabs/code/modules/jenny/functions/nested', '/etc/puppetlabs/code/environments', '/etc/puppetlabs/code/environments/production', '/etc/puppetlabs/code/environments/production/modules', '/etc/puppetlabs/code/environments/production/modules/one', '/etc/puppetlabs/code/environments/production/modules/one/functions', '/etc/puppetlabs/code/environments/production/modules/one/manifests', '/etc/puppetlabs/code/environments/production/modules/three', '/etc/puppetlabs/code/environments/production/modules/three/functions', '/etc/puppetlabs/code/environments/production/modules/three/manifests', '/etc/puppetlabs/code/environments/tommy', '/etc/puppetlabs/code/environments/tommy/modules', '/etc/puppetlabs/code/environments/tommy/modules/two', '/etc/puppetlabs/code/environments/tommy/modules/two/functions', ]: ensure => directory, mode => '0755', } # "Global" functions, no env file { '/etc/puppetlabs/code/modules/jenny/functions/mini.pp': content => 'function jenny::mini($a, $b) {if $a <= $b {$a} else {$b}}', require => File['/etc/puppetlabs/code/modules/jenny/functions'], } file { '/etc/puppetlabs/code/modules/jenny/functions/nested/maxi.pp': content => 'function jenny::nested::maxi($a, $b) {if $a >= $b {$a} else {$b}}', require => File['/etc/puppetlabs/code/modules/jenny/functions/nested'], } # Module "one", "production" env file { '/etc/puppetlabs/code/environments/production/modules/one/functions/foo.pp': content => 'function one::foo() {"This is the one::foo() function in the production environment"}', require => File['/etc/puppetlabs/code/environments/production/modules/one/functions'], } file { '/etc/puppetlabs/code/environments/production/modules/one/manifests/init.pp': content => 'class one { }', require => File['/etc/puppetlabs/code/environments/production/modules/one/manifests'], } # Module "three", "production" env file { '/etc/puppetlabs/code/environments/production/modules/three/functions/baz.pp': content => 'function three::baz() {"This is the three::baz() function in the production environment"}', require => File['/etc/puppetlabs/code/environments/production/modules/three/functions'], } file { '/etc/puppetlabs/code/environments/production/modules/three/manifests/init.pp': content => 'class three { }', require => File['/etc/puppetlabs/code/environments/production/modules/three/functions'], } # Module "two", "tommy" env file { '/etc/puppetlabs/code/environments/tommy/modules/two/functions/bar.pp': content => 'function two::bar() {"This is the two::bar() function in the tommy environment"}', require => File['/etc/puppetlabs/code/environments/tommy/modules/two/functions'], } EOF apply_manifest_on(master, manifest, {:catch_failures => true, :acceptable_exit_codes => [0,1]}) end manifest = <<-MANIFEST notice 'jenny::mini(1, 2) =', jenny::mini(1,2) notice 'jenny::nested::maxi(1, 2) =', jenny::nested::maxi(1,2) notice 'one::foo() =', one::foo() require 'one'; notice 'three::baz() =', three::baz() MANIFEST rc = apply_manifest_on(master, manifest, {:accept_all_exit_codes => true,}) step 'Call a global function' do fail_test 'Failed to call a "global" function' \ unless rc.stdout.include?('jenny::mini(1, 2) = 1') end step 'Call a global nested function' do fail_test 'Failed to call a "global" nested function' \ unless rc.stdout.include?('jenny::nested::maxi(1, 2) = 2') end step 'Call an env-specific function' do fail_test 'Failed to call a function defined in the current environment' \ unless rc.stdout.include?('This is the one::foo() function in the production environment') end step 'Call a function defined in an un-included module' do fail_test 'Failed to call a function defined in an un-required module' \ unless rc.stdout.include?('This is the three::baz() function in the production environment') end manifest = <<-MANIFEST.strip notice "two::bar() =", two::bar() MANIFEST # This should fail step 'Call a function not defined in the current environment' do rc = on master, puppet("apply -e '#{manifest}' --environment production"), {:accept_all_exit_codes => true,} fail_test 'Should not be able to call a function not defined in the current environment' \ unless rc.stderr.include?("Error: Evaluation Error: Unknown function: 'two::bar'") end step 'Call an env-specific function in a non-default environment' do rc = on master, puppet("apply -e '#{manifest}' --environment tommy") fail_test 'Failed to call env-specific function from that environment' \ unless rc.stdout.include?('This is the two::bar() function in the tommy environment') end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/tests/language/server_set_facts.rb
acceptance/tests/language/server_set_facts.rb
test_name 'C64667: ensure server_facts is set and error if any value is overwritten by an agent' do require 'puppet/acceptance/environment_utils.rb' extend Puppet::Acceptance::EnvironmentUtils tag 'audit:high', 'audit:acceptance', # Validating server/client interaction 'server' teardown do agents.each do |agent| on(agent, puppet('config print lastrunfile')) do |command_result| agent.rm_rf(command_result.stdout) end end end app_type = File.basename(__FILE__, '.*') tmp_environment = mk_tmp_environment_with_teardown(master, app_type) step 'ensure $server_facts exist' do create_sitepp(master, tmp_environment, <<-SITE) notify{"abc$server_facts":} SITE master_opts = {} with_puppet_running_on(master, master_opts) do agents.each do |agent| on(agent, puppet("agent -t --environment #{tmp_environment}"), :acceptable_exit_codes => 2) do |result| assert_match(/abc{serverversion/, result.stdout, "#{agent}: $server_facts should have some stuff" ) end end end end step 'ensure puppet issues a warning if an agent overwrites a server fact' do agents.each do |agent| on(agent, puppet("agent -t", 'ENV' => { 'FACTER_server_facts' => 'overwrite' }), :acceptable_exit_codes => 1) do |result| # Do not perform this check on non-English hosts unless agent['locale'] == 'ja' assert_match(/Error.*Attempt to assign to a reserved variable name: 'server_facts'/, result.stderr, "#{agent}: $server_facts should error if overwritten" ) 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/acceptance/tests/language/objects_in_catalog.rb
acceptance/tests/language/objects_in_catalog.rb
test_name 'C99627: can use Object types in the catalog and apply/agent' do require 'puppet/acceptance/environment_utils.rb' extend Puppet::Acceptance::EnvironmentUtils tag 'audit:high', 'audit:integration', 'audit:refactor' # The use of apply on a reference system should # be adequate to test puppet. Running this in # context of server/agent should not be necessary. manifest = <<-PP type Mod::Foo = Object[{ attributes => { 'name' => String, 'size' => Integer[0, default] } }] define mod::foo_notifier(Mod::Foo $foo) { notify { $foo.name: } } class mod { mod::foo_notifier { xyz: foo => Mod::Foo('A foo', 42) } } include mod PP agents.each do |agent| # This is currently only expected to work with apply as the custom data type # definition will not be present on the agent to deserialize properly step "apply manifest on agent #{agent.hostname} and assert notify output" do apply_manifest_on(agent, manifest) do |result| assert(result.exit_code == 0, "agent didn't exit properly: (#{result.exit_code})") assert_match(/A foo/, result.stdout, 'agent didn\'t notify correctly') 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/acceptance/tests/language/resource_refs_with_nested_arrays.rb
acceptance/tests/language/resource_refs_with_nested_arrays.rb
test_name "#7681: Allow using array variables in resource references" tag 'audit:high', 'audit:unit' agents.each do |agent| test_manifest = <<MANIFEST $exec_names = ["first", "second"] exec { "first": command => "#{agent.echo('the first command')}", path => "#{agent.path}", logoutput => true, } exec { "second": command => "#{agent.echo('the second command')}", path => "#{agent.path}", logoutput => true, } exec { "third": command => "#{agent.echo('the final command')}", path => "#{agent.path}", logoutput => true, require => Exec[$exec_names], } MANIFEST apply_manifest_on(agent, test_manifest) do |result| assert_match(/Exec\[third\].*the final command/, result.stdout) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/tests/language/binary_data_type.rb
acceptance/tests/language/binary_data_type.rb
test_name 'C98346: Binary data type' do require 'puppet/acceptance/puppet_type_test_tools.rb' extend Puppet::Acceptance::PuppetTypeTestTools tag 'audit:high', 'audit:integration', # Tests that binary data is retains integrity # between server and agent transport/application. # The weak link here is final ruby translation and # should not be OS sensitive. 'server' teardown do agents.each do |agent| on(agent, puppet('config print lastrunfile')) do |command_result| agent.rm_rf(command_result.stdout) end end end app_type = File.basename(__FILE__, '.*') tmp_environment = mk_tmp_environment_with_teardown(master, app_type) tmp_filename_win = tmp_filename_else = '' agents.each do |agent| # ugh... this won't work with more than two agents of two types if agent.platform =~ /32$/ tmp_filename_win = "C:\\cygwin\\tmp\\#{tmp_environment}.txt" else tmp_filename_win = "C:\\cygwin64\\tmp\\#{tmp_environment}.txt" end tmp_filename_else = "/tmp/#{tmp_environment}.txt" on(agent, "echo 'old content' > '/tmp/#{tmp_environment}.txt'") end # create a fake module files... file for binary_file() on(master, puppet_apply("-e 'file{[\"#{environmentpath}/#{tmp_environment}/modules\",\"#{environmentpath}/#{tmp_environment}/modules/empty\",\"#{environmentpath}/#{tmp_environment}/modules/empty/files\"]: ensure => \"directory\"} file{\"#{environmentpath}/#{tmp_environment}/modules/empty/files/blah.txt\": content => \"binary, yo\"}'")) base64_relaxed = Base64.encode64("invasionfromspace#{random_string}").strip base64_strict = Base64.strict_encode64("invasion from space #{random_string}\n") base64_urlsafe = Base64.urlsafe_encode64("invasion from-space/#{random_string}\n") test_resources = [ { :type => 'notify', :parameters => { :namevar => "1:$hell" }, :pre_code => "$hell = Binary('hello','%b')", :assertions => { :assert_match => 'Notice: 1:hell' } }, { :type => 'notify', :parameters => { :namevar => "2:$relaxed" }, :pre_code => "$relaxed = Binary('#{base64_relaxed}')", :assertions => { :assert_match => "Notice: 2:#{base64_relaxed}" } }, { :type => 'notify', :parameters => { :namevar => "3:$cHVwcGV0" }, :pre_code => "$cHVwcGV0 = Binary('cHVwcGV0')", :assertions => { :assert_match => 'Notice: 3:cHVwcGV0' } }, { :type => 'notify', :parameters => { :namevar => "4:$strict" }, :pre_code => "$strict = Binary('#{base64_strict}')", :assertions => { :assert_match => "Notice: 4:#{base64_strict}" } }, { :type => 'notify', :parameters => { :namevar => "5:$urlsafe" }, :pre_code => "$urlsafe = Binary('#{base64_urlsafe}')", :assertions => { :assert_match => "Notice: 5:#{base64_urlsafe}" } }, { :type => 'notify', :parameters => { :namevar => "6:$byte_array" }, :pre_code => "$byte_array = Binary([67,68])", :assertions => { :assert_match => "Notice: 6:Q0Q=" } }, { :type => 'notify', :parameters => { :namevar => "7:${empty_array}empty" }, :pre_code => "$empty_array = Binary([])", :assertions => { :assert_match => "Notice: 7:empty" } }, { :type => 'notify', :parameters => { :namevar => "8:${relaxed[1]}" }, :assertions => { :assert_match => "Notice: 8:bg==" } }, { :type => 'notify', :parameters => { :namevar => "9:${relaxed[1,3]}" }, :assertions => { :assert_match => "Notice: 9:bnZh" } }, { :type => 'notify', :parameters => { :namevar => "A:${utf8}" }, :pre_code => '$utf8=String(Binary([0xF0, 0x9F, 0x91, 0x92]),"%s")', :assertions => { :assert_match => 'Notice: A:\\xF0\\x9F\\x91\\x92' } }, { :type => 'notify', :parameters => { :namevar => "B:${type($bin_file)}" }, :pre_code => '$bin_file=binary_file("empty/blah.txt")', :assertions => { :assert_match => 'Notice: B:Binary' } }, { :type => 'file', :parameters => { :namevar => "$pup_tmp_filename", :content => "$relaxed" }, :pre_code => "$pup_tmp_filename = if $facts['os']['family'] == 'windows' { '#{tmp_filename_win}' } else { '#{tmp_filename_else}' }", :assertions => { :assert_match => /#{base64_relaxed}/ } }, ] sitepp_content = generate_manifest(test_resources) assertion_code = generate_assertions(test_resources) create_sitepp(master, tmp_environment, sitepp_content) step "run agent in #{tmp_environment}, run all assertions" do with_puppet_running_on(master, {}) do agents.each do |agent| on(agent, puppet("agent -t --environment '#{tmp_environment}'"), :acceptable_exit_codes => [2]) do |result| run_assertions(assertion_code, result) 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/acceptance/tests/language/exported_resources.rb
acceptance/tests/language/exported_resources.rb
test_name "C94788: exported resources using a yaml terminus for storeconfigs" do require 'puppet/acceptance/environment_utils' extend Puppet::Acceptance::EnvironmentUtils tag 'audit:high', 'audit:integration', 'audit:refactor', # This could be a component of a larger workflow scenario. 'server' skip_test 'requires puppetserver to service restart' if @options[:type] != 'aio' app_type = File.basename(__FILE__, '.*') tmp_environment = mk_tmp_environment_with_teardown(master, app_type) exported_username = 'er0ck' teardown do step 'stop puppet server' do on(master, "service #{master['puppetservice']} stop") end step 'remove cached agent json catalogs from the master' do on(master, "rm -f #{File.join(master.puppet['yamldir'],'catalog','*')}", :accept_all_exit_codes => true) end on(master, "mv #{File.join('','tmp','puppet.conf')} #{master.puppet['confdir']}", :accept_all_exit_codes => true) step 'clean out collected resources' do on(hosts, puppet_resource("user #{exported_username} ensure=absent"), :accept_all_exit_codes => true) end agents.each do |agent| on(agent, puppet('config print lastrunfile')) do |command_result| agent.rm_rf(command_result.stdout) end end end storeconfigs_backend_name = 'json_storeconfigs' step 'create a yaml storeconfigs terminus in the modulepath' do moduledir = File.join(environmentpath,tmp_environment,'modules') terminus_class_name = 'JsonStoreconfigs' manifest = <<MANIFEST File { ensure => directory, } file { '#{moduledir}':; '#{moduledir}/yaml_terminus':; '#{moduledir}/yaml_terminus/lib':; '#{moduledir}/yaml_terminus/lib/puppet':; '#{moduledir}/yaml_terminus/lib/puppet/indirector':; '#{moduledir}/yaml_terminus/lib/puppet/indirector/catalog':; '#{moduledir}/yaml_terminus/lib/puppet/indirector/facts':; '#{moduledir}/yaml_terminus/lib/puppet/indirector/node':; '#{moduledir}/yaml_terminus/lib/puppet/indirector/resource':; } file { '#{moduledir}/yaml_terminus/lib/puppet/indirector/catalog/#{storeconfigs_backend_name}.rb': ensure => file, content => ' require "puppet/indirector/catalog/yaml" class Puppet::Resource::Catalog::#{terminus_class_name} < Puppet::Resource::Catalog::Yaml def save(request) raise ArgumentError.new("You can only save objects that respond to :name") unless request.instance.respond_to?(:name) file = path(request.key) basedir = File.dirname(file) # This is quite likely a bad idea, since we are not managing ownership or modes. Dir.mkdir(basedir) unless Puppet::FileSystem.exist?(basedir) begin # We cannot dump anonymous modules in yaml, so dump to json File.open(file, "w") { |f| f.write request.instance.to_json } rescue TypeError => detail Puppet.err "Could not save \#{self.name} \#{request.key}: \#{detail}" end end def find(request) nil end end ', } file { '#{moduledir}/yaml_terminus/lib/puppet/indirector/facts/#{storeconfigs_backend_name}.rb': ensure => file, content => ' require "puppet/indirector/facts/yaml" class Puppet::Node::Facts::#{terminus_class_name} < Puppet::Node::Facts::Yaml def find(request) nil end end ', } file { '#{moduledir}/yaml_terminus/lib/puppet/indirector/node/#{storeconfigs_backend_name}.rb': ensure => file, content => ' require "puppet/indirector/node/yaml" class Puppet::Node::#{terminus_class_name} < Puppet::Node::Yaml def find(request) nil end end ', } file { '#{moduledir}/yaml_terminus/lib/puppet/indirector/resource/#{storeconfigs_backend_name}.rb': ensure => file, content => ' require "puppet/indirector/yaml" require "puppet/resource/catalog" class Puppet::Resource::#{terminus_class_name} < Puppet::Indirector::Yaml desc "Read resource instances from cached catalogs" def search(request) catalog_dir = File.join(Puppet.run_mode.server? ? Puppet[:yamldir] : Puppet[:clientyamldir], "catalog", "*") results = Dir.glob(catalog_dir).collect { |file| catalog = Puppet::Resource::Catalog.convert_from(:json, File.read(file)) if catalog.name == request.options[:host] next end catalog.resources.select { |resource| resource.type == request.key && resource.exported }.map! { |res| data_hash = res.to_data_hash parameters = data_hash["parameters"].map do |name, value| Puppet::Parser::Resource::Param.new(:name => name, :value => value) end attrs = {:parameters => parameters, :scope => request.options[:scope]} result = Puppet::Parser::Resource.new(res.type, res.title, attrs) result.collector_id = "\#{catalog.name}|\#{res.type}|\#{res.title}" result } }.flatten.compact results end end ', } # all the filtering is taken care of in the terminii # so any tests on filtering belong with puppetdb or pe file { '#{environmentpath}/#{tmp_environment}/manifests/site.pp': ensure => file, content => ' node "#{master.hostname}" { @@user{"#{exported_username}": ensure => present,} } node "default" { # collect resources on all nodes (puppet prevents collection on same node) User<<| |>> } ', } MANIFEST apply_manifest_on(master, manifest, :catch_failures => true) end # must specify environment in puppet.conf for it to pickup the terminus code in an environment module # but we have to bounce the server to pickup the storeconfigs... config anyway # we can't use with_puppet_running_on here because it uses puppet resource to bounce the server # puppet resource tries to use yaml_storeconfig's path() which doesn't exist # and fails back to yaml which indicates an attempted directory traversal and fails. # we could implemnt path() properly, but i'm just going to start the server the old fashioned way # and... config set is broken and doesn't add a main section step 'turn on storeconfigs, start puppetserver the old fashioned way' do on(master, "cp #{File.join(master.puppet['confdir'],'puppet.conf')} #{File.join('','tmp')}") on(master, "echo [main] >> #{File.join(master.puppet['confdir'],'puppet.conf')}") on(master, "echo environment=#{tmp_environment} >> #{File.join(master.puppet['confdir'],'puppet.conf')}") on(master, puppet('config set storeconfigs true --section main')) on(master, puppet("config set storeconfigs_backend #{storeconfigs_backend_name} --section main")) on(master, "service #{master['puppetservice']} restart") step 'run the master agent to export the resources' do on(master, puppet("agent -t --environment #{tmp_environment}")) end agents.each do |agent| next if agent == master step 'run the agents to collect exported resources' do on(agent, puppet("agent -t --environment #{tmp_environment}"), :acceptable_exit_codes => 2) on(agent, puppet_resource("user #{exported_username}"), :accept_all_exit_codes => true) do |result| assert_match(/present/, result.stdout, 'collected resource not found') 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/acceptance/tests/language/pcore_resource_types_should_have_precedence_over_ruby.rb
acceptance/tests/language/pcore_resource_types_should_have_precedence_over_ruby.rb
test_name 'C98097 - generated pcore resource types should be loaded instead of ruby for custom types' do tag 'audit:high', 'audit:integration', 'audit:refactor', # use `mk_tmp_environment_with_teardown` helper to build environment 'server' environment = 'production' step 'setup - install module with custom ruby resource type' do #{{{ testdir = master.tmpdir('c98097') codedir = "#{testdir}/codedir" site_manifest_content =<<EOM node default { notice(mycustomtype{"foobar":}) } EOM custom_type_content =<<EOM Puppet::Type.newtype(:mycustomtype) do @doc = "Create a new mycustomtype thing." newparam(:name, :namevar => true) do desc "Name of mycustomtype instance" $stderr.puts "this indicates that we are running ruby code and should not be seen when running generated pcore resource" end def refresh end end EOM apply_manifest_on(master, <<MANIFEST, :catch_failures => true) File { ensure => directory, mode => "0755", } file {[ '#{codedir}', '#{codedir}/environments', '#{codedir}/environments/#{environment}', '#{codedir}/environments/#{environment}/manifests', '#{codedir}/environments/#{environment}/modules', '#{codedir}/environments/#{environment}/modules/mymodule', '#{codedir}/environments/#{environment}/modules/mymodule/manifests', '#{codedir}/environments/#{environment}/modules/mymodule/lib', '#{codedir}/environments/#{environment}/modules/mymodule/lib/puppet', '#{codedir}/environments/#{environment}/modules/mymodule/lib/puppet/type' ]: } file { '#{codedir}/environments/#{environment}/manifests/site.pp': ensure => file, content => '#{site_manifest_content}', } file { '#{codedir}/environments/#{environment}/modules/mymodule/lib/puppet/type/mycustomtype.rb': ensure => file, content => '#{custom_type_content}', } MANIFEST conf_opts = { 'main' => { 'environmentpath' => "#{codedir}/environments" } } backup_file = backup_the_file(master, puppet_config(master, 'confdir', section: 'master'), testdir, 'puppet.conf') lay_down_new_puppet_conf master, conf_opts, testdir teardown do restore_puppet_conf_from_backup( master, backup_file ) # See PUP-6995 on(master, "rm -f #{puppet_config(master, 'yamldir', section: 'master')}/node/*.yaml") agents.each do |agent| on(agent, puppet('config print lastrunfile')) do |command_result| agent.rm_rf(command_result.stdout) end end end #}}} catalog_results = {} catalog_results[master.hostname] = { 'ruby_cat' => '', 'pcore_cat' => '' } step 'compile catalog using ruby resource' do on master, puppet('catalog', 'find', master.hostname) do |result| assert_match(/running ruby code/, result.stderr) catalog_results[master.hostname]['ruby_cat'] = JSON.parse(result.stdout.sub(/^[^{]+/,'')) end end step 'generate pcore type from ruby type' do on master, puppet('generate', 'types', '--environment', environment) end step 'compile catalog and make sure that ruby code is NOT executed' do on master, puppet('catalog', 'find', master.hostname) do |result| refute_match(/running ruby code/, result.stderr) catalog_results[master.hostname]['pcore_cat'] = JSON.parse(result.stdout.sub(/^[^{]+/,'')) end end step 'ensure that the resources created in the catalog using ruby and pcore are the same' do assert_equal(catalog_results[master.hostname]['ruby_cat']['resources'], catalog_results[master.hostname]['pcore_cat']['resources']) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/tests/utf8/utf8-in-puppet-describe.rb
acceptance/tests/utf8/utf8-in-puppet-describe.rb
test_name 'utf-8 characters in module doc string, puppet describe' do tag 'audit:high', # utf-8 is high impact in general, puppet describe low risk? 'audit:integration', # not package dependent but may want to vary platform by LOCALE/encoding 'audit:refactor' # if keeping, use mk_tmp_environment_with_teardown # remove with_puppet_running_on unless pluginsync is absolutely necessary # (if it is, add 'server' tag # utf8chars = "€‰ㄘ万竹ÜÖ" utf8chars = "\u20ac\u2030\u3118\u4e07\u7af9\u00dc\u00d6" master_mod_dir = master.tmpdir("describe_master") on(master, "chmod -R 755 #{master_mod_dir}"); teardown do on(master, "rm -rf #{master_mod_dir}") agents.each do |agent| on(agent, puppet('config print lastrunfile')) do |command_result| agent.rm_rf(command_result.stdout) end end end master_manifest = <<MASTER_MANIFEST File { ensure => directory, mode => "0755", } file { '#{master_mod_dir}/code':; '#{master_mod_dir}/code/environments':; '#{master_mod_dir}/code/environments/production':; '#{master_mod_dir}/code/environments/production/modules':; '#{master_mod_dir}/code/environments/production/modules/master_mytype_module':; '#{master_mod_dir}/code/environments/production/modules/master_mytype_module/lib':; '#{master_mod_dir}/code/environments/production/modules/master_mytype_module/lib/puppet':; '#{master_mod_dir}/code/environments/production/modules/master_mytype_module/lib/puppet/type':; } file { '#{master_mod_dir}/code/environments/production/modules/master_mytype_module/lib/puppet/type/master_mytype.rb' : ensure => file, mode => '0755', content => ' Puppet::Type.newtype(:master_mytype) do @doc = "Testing to see if puppet handles describe blocks correctly when they contain utf8 characters, such as #{utf8chars} " newparam(:name) do isnamevar desc " name parameter for mytype, also with some utf8 chars #{utf8chars}" end end ', } MASTER_MANIFEST step "Apply master manifest" do apply_manifest_on(master, master_manifest) end master_opts = { 'main' => { 'environmentpath' => "#{master_mod_dir}/code/environments", } } step "Start puppet server" with_puppet_running_on(master, master_opts, master_mod_dir) do agents.each do |agent| puts "agent name: #{agent.hostname}, platform: #{agent.platform}" step "Run puppet agent for plugin sync" do on( agent, puppet("agent", "-t"), :acceptable_exit_codes => [0, 2] ) end step "Puppet describe for master-hosted mytype" do on(agent, puppet("describe", "master_mytype")) do |result| assert_match( /master_mytype.*such as #{utf8chars}/m, result.stdout, "Main description of master_mytype did not match utf8 chars, '#{utf8chars}'" ) assert_match( /name parameter.*chars #{utf8chars}/, result.stdout, "Name parameter description of master_mytype did not match utf8 chars, '#{utf8chars}'" ) 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/acceptance/tests/utf8/utf8-in-function-args.rb
acceptance/tests/utf8/utf8-in-function-args.rb
test_name 'utf-8 characters in function parameters' do confine :except, :platform => /debian-12-amd64/ # PUP-12020 tag 'audit:high', 'audit:integration', # not package dependent but may want to vary platform by LOCALE/encoding 'audit:refactor' # if keeping, use mk_tmp_environment_with_teardown confine :except, :platform => [ 'windows', # PUP-6983 'aix', # PUP-7194 ] teardown do agents.each do |agent| on(agent, puppet('config print lastrunfile')) do |command_result| agent.rm_rf(command_result.stdout) end end end # utf8chars = "€‰ㄘ万竹ÜÖ" utf8chars = "\u20ac\u2030\u3118\u4e07\u7af9\u00dc\u00d6" agents.each do |agent| step 'alert' do result = on( agent, puppet("apply", "-e" "'alert(\"alert #{utf8chars}\")'"), :environment => {:LANG => "en_US.UTF-8"} ) assert_match( /#{utf8chars}/, result.stderr, "Did not find the utf8 chars." ) end step 'assert_type' do on( agent, puppet( "apply", "-e", "'notice(assert_type(String, \"#{utf8chars}\"))'" ), { :environment => {:LANG => "en_US.UTF-8"}, :acceptable_exit_codes => [0], } ) on( agent, puppet("apply", "-e 'notice(assert_type(Float, \"#{utf8chars}\"))'"), { :environment => {:LANG => "en_US.UTF-8"}, :acceptable_exit_codes => [1], } ) end step 'filter' do puppet_cmd = "' [$a] = [[\"abc\", \"#{utf8chars}\", \"100\"]]; [$f] = [filter($a) |$p| {$p =~ /#{utf8chars}/}]; notice(\"f = $f\") '" result = on( agent, puppet("apply", "-e", puppet_cmd), :environment => {:LANG => "en_US.UTF-8"} ) assert_match(/#{utf8chars}/, result.stdout, "filter() failed.") end agent_lookup_test_dir = agent.tmpdir("lookup_test_dir") mod_name = "lookup_module" mod_key = "#{mod_name}::mod_key_#{utf8chars}" mod_val = "mod_val_#{utf8chars}" env_key = "env_key_#{utf8chars}" env_val = "env_val_#{utf8chars}" array_key = "array_key_with_utf8_#{utf8chars}" array_val_2 = "array value 2 with utf8 #{utf8chars}" scalar_key = "scalar_key_with_utf8_#{utf8chars}" scalar_val = "scalar value with utf8 #{utf8chars}" non_key = "non_key_#{utf8chars}" step 'apply hiera/lookup manifest' do # I want the banner in the output but # some results: orig_hiera_config, # orig_environmentpath from operations # here are used later, so I don't want # them local to a step block. end lookup_manifest = <<LOOKUP_MANIFEST File { ensure => directory, mode => "0755", } file { "#{agent_lookup_test_dir}" :; "#{agent_lookup_test_dir}/hiera_data" :; "#{agent_lookup_test_dir}/environments" :; "#{agent_lookup_test_dir}/environments/production" :; "#{agent_lookup_test_dir}/environments/production/data" :; "#{agent_lookup_test_dir}/environments/production/manifests" :; "#{agent_lookup_test_dir}/environments/production/modules" :; "#{agent_lookup_test_dir}/environments/production/modules/#{mod_name}" :; "#{agent_lookup_test_dir}/environments/production/modules/#{mod_name}/manifests" :; "#{agent_lookup_test_dir}/environments/production/modules/#{mod_name}/data" :; } file { "#{agent_lookup_test_dir}/environments/production/modules/#{mod_name}/hiera.yaml" : ensure => file, mode => "0644", content => '--- version: 5 ', } file { "#{agent_lookup_test_dir}/environments/production/modules/#{mod_name}/data/common.yaml" : ensure => "file", mode => "0644", content => '--- #{mod_key}: #{mod_val} ', } file { "#{agent_lookup_test_dir}/environments/production/environment.conf" : ensure => file, mode => "0644", content => ' # environment_data_provider = "hiera" ' } file { "#{agent_lookup_test_dir}/environments/production/hiera.yaml" : ensure => file, mode => "0644", content => ' --- version: 5 ' } file { "#{agent_lookup_test_dir}/environments/production/data/common.yaml" : ensure => file, mode => "0644", content => ' --- #{env_key} : #{env_val} ', } file { "#{agent_lookup_test_dir}/hiera.yaml" : ensure => file, mode => "0644", content => '--- :backends: - yaml :hierarchy: - common :yaml: :datadir: #{agent_lookup_test_dir}/hiera_data ', } file { "#{agent_lookup_test_dir}/hiera_data/common.yaml" : ensure => file, mode => "0644", content => ' #{array_key} : - "array value 1" - "#{array_val_2}" #{scalar_key} : "#{scalar_val}" ', } LOOKUP_MANIFEST apply_manifest_on( agent, lookup_manifest, :environment => {:LANG => "en_US.UTF-8"} ) result = on( agent, puppet("config", "print hiera_config"), :environment => {:LANG => "en_US.UTF-8"} ) orig_hiera_config = result.stdout.chomp result = on( agent, puppet("config", "print environmentpath"), :environment => {:LANG => "en_US.UTF-8"} ) orig_environmentpath = result.stdout.chomp on( agent, puppet( "config", "set hiera_config #{agent_lookup_test_dir}/hiera.yaml" ), :environment => {:LANG => "en_US.UTF-8"} ) on( agent, puppet( "config", "set environmentpath #{agent_lookup_test_dir}/environments" ), :environment => {:LANG => "en_US.UTF-8"} ) step 'hiera' do result = on( agent, puppet("apply", "-e", "'notice(hiera(\"#{array_key}\"))'"), :environment => {:LANG => "en_US.UTF-8"} ) assert_match(/#{array_val_2}/, result.stdout, "hiera array lookup") result = on( agent, puppet("apply", "-e", "'notice(hiera(\"#{scalar_key}\"))'"), :environment => {:LANG => "en_US.UTF-8"} ) assert_match(/#{scalar_val}/, result.stdout, "hiera scalar lookup") result = on( agent, puppet("apply", "-e", "'notice(hiera(\"#{non_key}\"))'"), { :acceptable_exit_codes => (0..255), :environment => {:LANG => "en_US.UTF-8"} } ) assert_match( /did not find a value for the name '#{non_key}'/, result.stderr, "hiera non_key lookup" ) end step 'lookup' do result = on( agent, puppet("apply", "-e", "'notice(lookup(\"#{env_key}\"))'"), :environment => {:LANG => "en_US.UTF-8"} ) assert_match( /#{env_val}/, result.stdout, "env lookup failed for '#{env_key}'" ) result = on( agent, puppet("apply", "-e", "'notice(lookup(\"#{mod_key}\"))'"), :environment => {:LANG => "en_US.UTF-8"} ) assert_match( /#{mod_val}/, result.stdout, "module lookup failed for '#{mod_key}'" ) on( agent, puppet("config", "set hiera_config #{orig_hiera_config}"), :environment => {:LANG => "en_US.UTF-8"} ) on( agent, puppet("config", "set environmentpath #{orig_environmentpath}"), :environment => {:LANG => "en_US.UTF-8"} ) end step 'dig' do hash_string = "{ a => { b => [ { x => 10, y => 20, }, { x => 100, y => \"dig_result = #{utf8chars}\" }, ] } }" puppet_cmd = "' [$v] = [#{hash_string}]; [$dig_result] = [dig($v, a, b, 1, y)]; notice($dig_result) '" result = on( agent, puppet("apply", "-e", puppet_cmd), :environment => {:LANG => "en_US.UTF-8"} ) assert_match( /dig_result = #{utf8chars}/, result.stdout, "dig() test failed." ) end step 'match' do strings = [ "string1_#{utf8chars}", "string2_#{utf8chars}", "string3_no-utf8", "string4_no-utf8" ] puppet_cmd = "' [$vec] = [#{strings}]; [$found] = [match($vec, /#{utf8chars}/)]; notice($found) '" result = on( agent, puppet("apply", "-e", puppet_cmd), :environment => {:LANG => "en_US.UTF-8"} ) assert_match( /[[#{utf8chars}], [#{utf8chars}], , ]/, result.stdout, "match() result unexpected" ) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/tests/utf8/utf8-in-catalog.rb
acceptance/tests/utf8/utf8-in-catalog.rb
test_name 'utf-8 characters in cached catalog' do tag 'audit:high', # utf-8 is high impact in general 'audit:integration', # not package dependent but may want to vary platform by LOCALE/encoding 'audit:refactor', # use mk_tmp_environment_with_teardown 'server' utf8chars = "\u20ac\u2030\u3118\u4e07\u7af9\u00dc\u00d6" file_content = "This is the file content. file #{utf8chars}" codedir = master.tmpdir("code") on(master, "rm -rf '#{codedir}'") env_dir = "#{codedir}/environments" agents.each do |agent| step "agent name: #{agent.hostname}, platform: #{agent.platform}" agent_vardir = agent.tmpdir("agent_vardir") agent_file = agent.tmpfile("file" + utf8chars) teardown do on(agent, "rm -rf '#{agent_vardir}' '#{agent_file}'") on(agent, puppet('config print lastrunfile')) do |command_result| agent.rm_rf(command_result.stdout) end end step "Apply manifest" do on(agent, "rm -rf '#{agent_file}'", :environment => { :LANG => "en_US.UTF-8" }) master_manifest = <<PP File { ensure => directory, mode => "0755", } file { '#{codedir}/':; '#{codedir}/environments':; '#{codedir}/environments/production':; '#{codedir}/environments/production/manifests':; } file { '#{env_dir}/production/manifests/site.pp' : ensure => file, mode => '0644', content => ' file { "#{agent_file}" : ensure => file, mode => "0644", content => "#{file_content} ", } ', } PP apply_manifest_on(master, master_manifest, {:acceptable_exit_codes => [0, 2], :catch_failures => true, :environment => { :LANG => "en_US.UTF-8" }}) end master_opts = { 'main' => { 'environmentpath' => "#{env_dir}", }, 'agent' => { 'use_cached_catalog' => 'true' } } with_puppet_running_on(master, master_opts, codedir) do step "apply utf-8 catalog" do on(agent, puppet("agent -t --vardir '#{agent_vardir}'"), { :acceptable_exit_codes => [2], :environment => { :LANG => "en_US.UTF-8" } }) end step "verify cached catalog" do catalog_file_name = "#{agent_vardir}/client_data/catalog/#{agent.node_name}.json" on(agent, "cat '#{catalog_file_name}'", :environment => { :LANG => "en_US.UTF-8" }) do |result| assert_match(/#{agent_file}/, result.stdout, "cached catalog does not contain expected agent file name") assert_match(/#{file_content}/, result.stdout, "cached catalog does not contain expected file content") end end step "apply cached catalog" do on(agent, puppet("resource file '#{agent_file}' ensure=absent"), :environment => { :LANG => "en_US.UTF-8" }) on(agent, puppet("catalog apply --vardir '#{agent_vardir}' --terminus json"), :environment => { :LANG => "en_US.UTF-8" }) on(agent, "cat '#{agent_file}'", :environment => { :LANG => "en_US.UTF-8" }) do |result| assert_match(/#{utf8chars}/, result.stdout, "result stdout did not contain \"#{utf8chars}\"") 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/acceptance/tests/utf8/utf8-in-file-resource.rb
acceptance/tests/utf8/utf8-in-file-resource.rb
test_name 'utf-8 characters in resource title and param values' do tag 'audit:high', # utf-8 is high impact in general 'audit:integration' # not package dependent but may want to vary platform by LOCALE/encoding confine :except, :platform => [ 'windows', # PUP-6983 'aix', # PUP-7194 ] # utf8chars = "€‰ㄘ万竹ÜÖ" utf8chars = "\u20ac\u2030\u3118\u4e07\u7af9\u00dc\u00d6" agents.each do |agent| puts "agent name: #{agent.node_name}, platform: #{agent.platform}" agent_file = agent.tmpfile("file" + utf8chars) teardown do on(agent, "rm -rf #{agent_file}") end # remove this file, so puppet can create it and not merely correct # its drift. on(agent, "rm -rf #{agent_file}", :environment => {:LANG => "en_US.UTF-8"}) manifest = <<PP file { "#{agent_file}" : ensure => file, mode => "0644", content => "This is the file content. file #{utf8chars} ", } PP step "Apply manifest" do apply_manifest_on( agent, manifest, { :acceptable_exit_codes => [2], :catch_failures => true, :environment => {:LANG => "en_US.UTF-8"} } ) on(agent, "cat #{agent_file}", :environment => {:LANG => "en_US.UTF-8"}) do |result| assert_match(/#{utf8chars}/, result.stdout, "result stdout did not contain \"#{utf8chars}\"") end end step "Drift correction" do on( agent, "echo '' > #{agent_file}", :environment => {:LANG => "en_US.UTF-8"} ) apply_manifest_on( agent, manifest, { :acceptable_exit_codes => [2], :catch_failures => true, :environment => {:LANG => "en_US.UTF-8"} } ) on(agent, "cat #{agent_file}", :environment => {:LANG => "en_US.UTF-8"}) do |result| assert_match(/#{utf8chars}/, result.stdout, "result stdout did not contain \"#{utf8chars}\"") 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/acceptance/tests/utf8/utf8-recursive-copy.rb
acceptance/tests/utf8/utf8-recursive-copy.rb
test_name "PUP-8735: UTF-8 characters are preserved after recursively copying directories" do tag 'audit:high', # utf-8 is high impact in general 'audit:integration' # not package dependent but may want to vary platform by LOCALE/encoding # Translation is not supported on these platforms: confine :except, :platform => /^solaris/ # for file_exists? require 'puppet/acceptance/temp_file_utils' extend Puppet::Acceptance::TempFileUtils # for enable_locale_language require 'puppet/acceptance/i18n_utils' extend Puppet::Acceptance::I18nUtils agents.each do |host| filename = "Fișier" content = <<-CONTENT 閑けさや 岩にしみいる 蝉の声 CONTENT workdir = host.tmpdir("tmp#{rand(999999).to_i}") source_dir = "#{workdir}/Adresář" target_dir = "#{workdir}/目录" manifest = %Q| file { ["#{workdir}", "#{source_dir}"]: ensure => directory, } file { "#{source_dir}/#{filename}": ensure => file, content => "#{content}", } file { "#{source_dir}/#{filename}_Copy": ensure => file, source => "#{source_dir}/#{filename}", } file { "#{target_dir}": ensure => directory, source => "#{source_dir}", recurse => remote, replace => true, }| step "Ensure the en_US locale is enabled (and skip this test if not)" do if enable_locale_language(host, 'en_US').nil? skip_test("Host #{host} is missing the en_US locale. Skipping this test.") end end step "Create and recursively copy a directory with UTF-8 filenames and contents" do apply_manifest_on(host, manifest, environment: {'LANGUAGE' => 'en_US', 'LANG' => 'en_US'}) end step "Ensure that the files' names and their contents are preserved" do ["#{target_dir}/#{filename}", "#{target_dir}/#{filename}_Copy"]. each do |filepath| assert(file_exists?(host, filepath), "Expected the UTF-8 directory's files to be recursivly copied, but they were not") assert(file_contents(host, filepath) == content, "Expected the contents of the copied UTF-8 files to be preserved, but they were not") 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/acceptance/teardown/common/099_Archive_Logs.rb
acceptance/teardown/common/099_Archive_Logs.rb
require 'date' def file_glob(host, path) result = on(host, "ls #{path}", :acceptable_exit_codes => [0, 2]) return [] if result.exit_code != 0 return result.stdout.strip.split("\n") end # This test is prefixed with zzz so it will hopefully run last. test_name 'Backup puppet logs and app data on all hosts' do today = Date.today().to_s # truncate the job name so it only has the name-y part and no parameters job_name = (ENV['JOB_NAME'] || 'unknown_jenkins_job') .sub(/[A-Z0-9_]+=.*$/, '') .gsub(/[\/,.]/, '_')[0..200] archive_name = "#{job_name}__#{ENV['BUILD_ID']}__#{today}__sut-files.tgz" archive_root = "SUT_#{today}" hosts.each do |host| step("Capturing log errors for #{host}") do case host[:platform] when /windows/ # on Windows, all of the desired data (including logs) is in the data dir puppetlabs_data = 'C:/ProgramData/PuppetLabs' archive_file_from(host, puppetlabs_data, {}, archive_root, archive_name) # Note: Windows `ls` uses absolute paths for all matches when an absolute path is supplied. tempdir = 'C:/Windows/TEMP' file_glob(host, File.join(tempdir, 'install-puppet-*.log')).each do |install_log| archive_file_from(host, install_log, {}, archive_root, archive_name) end file_glob(host, File.join(tempdir, 'puppet-*-installer.log')).each do |install_log| archive_file_from(host, install_log, {}, archive_root, archive_name) end else puppetlabs_logdir = '/var/log/puppetlabs' grep_for_alerts = if host[:platform] =~ /solaris/ "egrep -i 'warn|error|fatal'" elsif host[:platform] =~ /aix/ "grep -iE -B5 -A10 'warn|error|fatal'" else "grep -i -B5 -A10 'warn\\|error\\|fatal'" end ## If there are any PL logs, try to echo all warning, error, and fatal ## messages from all PL logs to the job's output on(host, <<-GREP_FOR_ALERTS, :accept_all_exit_codes => true ) if [ -d #{puppetlabs_logdir} ] && [ -n "$(find #{puppetlabs_logdir} -name '*.log*')" ]; then for log in $(find #{puppetlabs_logdir} -name '*.log*'); do # grep /dev/null only to get grep to print filenames, since -H is not in POSIX spec for grep #{grep_for_alerts} $log /dev/null; echo "" done fi GREP_FOR_ALERTS step("Archiving logs for #{host} into #{archive_name} (muzzling everything but :warn or higher beaker logs...)") do ## turn the logger off to avoid getting hundreds of lines of scp progress output previous_level = @logger.log_level @logger.log_level = :warn pxp_cache = '/opt/puppetlabs/pxp-agent/spool' puppetlabs_data = '/etc/puppetlabs' version_lookup_result = on(host, "cat /opt/puppetlabs/puppet/VERSION", :accept_all_exit_codes => true) # If we can't find a VERSION file, chances are puppet wasn't # installed and these paths aren't present. Beaker's # archive_file_from() will fail if it can't find the file, and we # want to proceed... if version_lookup_result.exit_code == 0 agent_version = version_lookup_result.output.strip archive_file_from(host, pxp_cache, {}, archive_root, archive_name) unless version_is_less(agent_version, "1.3.2") archive_file_from(host, puppetlabs_data, {}, archive_root, archive_name) archive_file_from(host, puppetlabs_logdir, {}, archive_root, archive_name) end syslog_dir = '/var/log' syslog_name = 'messages' if host[:platform] =~ /ubuntu|debian/ syslog_name = 'syslog' elsif host[:platform] =~ /solaris/ syslog_dir = '/var/adm' # Next few lines are for debugging POOLER-200, once that is resolved this can be removed @logger.log_level = previous_level on(host, 'egrep -i \'reboot after panic\' /var/adm/messages', :acceptable_exit_codes => [0,1,2]) @logger.log_level = :warn elsif host[:platform] =~ /osx/ syslog_name = "system.log" elsif host[:platform] =~ /fedora/ on(host, "journalctl --no-pager > /var/log/messages") elsif host[:platform] =~ /aix/ on(host, "alog -o -t console > /var/log/messages") end syslog_path = File.join(syslog_dir, syslog_name) if host.file_exist?(syslog_path) archive_file_from(host, syslog_path, {}, archive_root, archive_name) end ## turn the logger back on in case someone else wants to log things @logger.log_level = previous_level 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/acceptance/lib/helper.rb
acceptance/lib/helper.rb
$LOAD_PATH << File.expand_path(File.dirname(__FILE__)) require 'beaker-puppet'
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/lib/acceptance_spec_helper.rb
acceptance/lib/acceptance_spec_helper.rb
require 'fileutils' dir = File.expand_path(File.dirname(__FILE__)) $LOAD_PATH.unshift dir RSpec.configure do |config| config.mock_with :mocha end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/lib/puppet/acceptance/environment_utils_spec.rb
acceptance/lib/puppet/acceptance/environment_utils_spec.rb
require File.join(File.dirname(__FILE__),'../../acceptance_spec_helper.rb') require 'puppet/acceptance/environment_utils' module EnvironmentUtilsSpec describe 'EnvironmentUtils' do class ATestCase include Puppet::Acceptance::EnvironmentUtils def step(str) yield end def on(host, command, options = nil) stdout = host.do(command, options) yield TestResult.new(stdout) if block_given? end end class TestResult attr_accessor :stdout def initialize(stdout) self.stdout = stdout end end class TestHost attr_accessor :did, :directories, :attributes def initialize(directories, attributes = {}) self.directories = directories self.did = [] self.attributes = attributes end def do(command, options) did << (options.nil? ? command : [command, options]) case command when /^ls (.*)/ then directories[$1] end end def [](param) attributes[param] end end let(:testcase) { ATestCase.new } let(:host) { TestHost.new(directory_contents, 'user' => 'root', 'group' => 'puppet') } let(:directory_contents) do { '/etc/puppetlabs/puppet' => 'foo bar baz widget', '/tmp/dir' => 'foo dingo bar thing', } end it "runs the block of code" do ran_code = false testcase.safely_shadow_directory_contents_and_yield(host, '/etc/puppetlabs/puppet', '/tmp/dir') do ran_code = true end expect(ran_code).to be true expect(host.did).to eq([ "ls /etc/puppetlabs/puppet", "ls /tmp/dir", "mv /etc/puppetlabs/puppet/foo /etc/puppetlabs/puppet/foo.bak", "mv /etc/puppetlabs/puppet/bar /etc/puppetlabs/puppet/bar.bak", "cp -R /tmp/dir/foo /etc/puppetlabs/puppet/foo", "cp -R /tmp/dir/dingo /etc/puppetlabs/puppet/dingo", "cp -R /tmp/dir/bar /etc/puppetlabs/puppet/bar", "cp -R /tmp/dir/thing /etc/puppetlabs/puppet/thing", "chown -R root:puppet /etc/puppetlabs/puppet/foo /etc/puppetlabs/puppet/dingo /etc/puppetlabs/puppet/bar /etc/puppetlabs/puppet/thing", "chmod -R 770 /etc/puppetlabs/puppet/foo /etc/puppetlabs/puppet/dingo /etc/puppetlabs/puppet/bar /etc/puppetlabs/puppet/thing", "rm -rf /etc/puppetlabs/puppet/foo /etc/puppetlabs/puppet/dingo /etc/puppetlabs/puppet/bar /etc/puppetlabs/puppet/thing", "mv /etc/puppetlabs/puppet/foo.bak /etc/puppetlabs/puppet/foo", "mv /etc/puppetlabs/puppet/bar.bak /etc/puppetlabs/puppet/bar" ]) end it "backs up the original items that are shadowed by tmp items" do testcase.safely_shadow_directory_contents_and_yield(host, '/etc/puppetlabs/puppet', '/tmp/dir') {} expect(host.did.grep(%r{mv /etc/puppetlabs/puppet/\w+ })).to eq([ "mv /etc/puppetlabs/puppet/foo /etc/puppetlabs/puppet/foo.bak", "mv /etc/puppetlabs/puppet/bar /etc/puppetlabs/puppet/bar.bak", ]) end it "copies in all the tmp items into the working dir" do testcase.safely_shadow_directory_contents_and_yield(host, '/etc/puppetlabs/puppet', '/tmp/dir') {} expect(host.did.grep(%r{cp})).to eq([ "cp -R /tmp/dir/foo /etc/puppetlabs/puppet/foo", "cp -R /tmp/dir/dingo /etc/puppetlabs/puppet/dingo", "cp -R /tmp/dir/bar /etc/puppetlabs/puppet/bar", "cp -R /tmp/dir/thing /etc/puppetlabs/puppet/thing", ]) end it "opens the permissions on all copied files to 770 and sets ownership based on host settings" do testcase.safely_shadow_directory_contents_and_yield(host, '/etc/puppetlabs/puppet', '/tmp/dir') {} expect(host.did.grep(%r{ch(mod|own)})).to eq([ "chown -R root:puppet /etc/puppetlabs/puppet/foo /etc/puppetlabs/puppet/dingo /etc/puppetlabs/puppet/bar /etc/puppetlabs/puppet/thing", "chmod -R 770 /etc/puppetlabs/puppet/foo /etc/puppetlabs/puppet/dingo /etc/puppetlabs/puppet/bar /etc/puppetlabs/puppet/thing", ]) end it "deletes all the tmp items from the working dir" do testcase.safely_shadow_directory_contents_and_yield(host, '/etc/puppetlabs/puppet', '/tmp/dir') {} expect(host.did.grep(%r{rm})).to eq([ "rm -rf /etc/puppetlabs/puppet/foo /etc/puppetlabs/puppet/dingo /etc/puppetlabs/puppet/bar /etc/puppetlabs/puppet/thing", ]) end it "replaces the original items that had been shadowed into the working dir" do testcase.safely_shadow_directory_contents_and_yield(host, '/etc/puppetlabs/puppet', '/tmp/dir') {} expect(host.did.grep(%r{mv /etc/puppetlabs/puppet/\w+\.bak})).to eq([ "mv /etc/puppetlabs/puppet/foo.bak /etc/puppetlabs/puppet/foo", "mv /etc/puppetlabs/puppet/bar.bak /etc/puppetlabs/puppet/bar" ]) end it "always cleans up, even if the code we yield to raises an error" do expect do testcase.safely_shadow_directory_contents_and_yield(host, '/etc/puppetlabs/puppet', '/tmp/dir') do raise 'oops' end end.to raise_error('oops') expect(host.did).to eq([ "ls /etc/puppetlabs/puppet", "ls /tmp/dir", "mv /etc/puppetlabs/puppet/foo /etc/puppetlabs/puppet/foo.bak", "mv /etc/puppetlabs/puppet/bar /etc/puppetlabs/puppet/bar.bak", "cp -R /tmp/dir/foo /etc/puppetlabs/puppet/foo", "cp -R /tmp/dir/dingo /etc/puppetlabs/puppet/dingo", "cp -R /tmp/dir/bar /etc/puppetlabs/puppet/bar", "cp -R /tmp/dir/thing /etc/puppetlabs/puppet/thing", "chown -R root:puppet /etc/puppetlabs/puppet/foo /etc/puppetlabs/puppet/dingo /etc/puppetlabs/puppet/bar /etc/puppetlabs/puppet/thing", "chmod -R 770 /etc/puppetlabs/puppet/foo /etc/puppetlabs/puppet/dingo /etc/puppetlabs/puppet/bar /etc/puppetlabs/puppet/thing", "rm -rf /etc/puppetlabs/puppet/foo /etc/puppetlabs/puppet/dingo /etc/puppetlabs/puppet/bar /etc/puppetlabs/puppet/thing", "mv /etc/puppetlabs/puppet/foo.bak /etc/puppetlabs/puppet/foo", "mv /etc/puppetlabs/puppet/bar.bak /etc/puppetlabs/puppet/bar" ]) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/lib/puppet/acceptance/static_catalog_utils.rb
acceptance/lib/puppet/acceptance/static_catalog_utils.rb
module Puppet module Acceptance module StaticCatalogUtils # Adds code-id-command and code-content-command scripts # to the server and updates puppetserver.conf. This is # necessary for testing static catalogs. # @param master [String] the host running puppetserver. # @param scriptdir [String] the path to the directory where the scripts should be placed. def setup_puppetserver_code_id_scripts(master, scriptdir) code_id_command = <<EOF #! /bin/bash echo -n 'code_version_1' EOF code_content_command = <<EOF #! /bin/bash if [ \\\$2 == 'code_version_1' ] ; then echo -n 'code_version_1' else echo -n 'newer_code_version' fi EOF apply_manifest_on(master, <<MANIFEST, :catch_failures => true) file { '#{scriptdir}/code_id.sh': ensure => file, content => "#{code_id_command}", mode => "0755", } file { '#{scriptdir}/code_content.sh': ensure => file, content => "#{code_content_command}", mode => "0755", } MANIFEST puppetserver_config = "#{master['puppetserver-confdir']}/puppetserver.conf" on master, "cp #{puppetserver_config} #{scriptdir}/puppetserver.conf.bak" versioned_code_settings = {"versioned-code" => {"code-id-command" => "#{scriptdir}/code_id.sh", "code-content-command" => "#{scriptdir}/code_content.sh"}} modify_tk_config(master, puppetserver_config, versioned_code_settings) end def cleanup_puppetserver_code_id_scripts(master, scriptdir) # These are -f so we don't bail on the teardown if for some reason they didn't get laid down on master, "rm -f #{scriptdir}/code_id.sh" on master, "rm -f #{scriptdir}/code_content.sh" puppetserver_config = "#{master['puppetserver-confdir']}/puppetserver.conf" on master, "cp #{scriptdir}/puppetserver.conf.bak #{puppetserver_config}" 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/acceptance/lib/puppet/acceptance/agent_fqdn_utils.rb
acceptance/lib/puppet/acceptance/agent_fqdn_utils.rb
module Puppet module Acceptance module AgentFqdnUtils @@hostname_to_fqdn = {} # convert from an Beaker::Host (agent) to the systems fqdn as returned by facter def agent_to_fqdn(agent) unless @@hostname_to_fqdn.has_key?(agent.hostname) @@hostname_to_fqdn[agent.hostname] = on(agent, facter('networking.fqdn')).stdout.chomp end @@hostname_to_fqdn[agent.hostname] 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/acceptance/lib/puppet/acceptance/i18ndemo_utils.rb
acceptance/lib/puppet/acceptance/i18ndemo_utils.rb
module Puppet module Acceptance module I18nDemoUtils require 'puppet/acceptance/i18n_utils' extend Puppet::Acceptance::I18nUtils I18NDEMO_NAME = "i18ndemo" I18NDEMO_MODULE_NAME = "eputnam-#{I18NDEMO_NAME}" def configure_master_system_locale(language) language = enable_locale_language(master, language) fail_test("puppet server machine is missing #{language} locale. help...") if language.nil? on(master, "localectl set-locale LANG=#{language}") on(master, "service #{master['puppetservice']} restart") end def reset_master_system_locale language = language_name(master, 'en_US') || 'en_US' on(master, "localectl set-locale LANG=#{language}") on(master, "service #{master['puppetservice']} restart") end def install_i18n_demo_module(node, environment=nil) env_options = environment.nil? ? '' : "--environment #{environment}" on(node, puppet("module install #{I18NDEMO_MODULE_NAME} #{env_options}")) end def uninstall_i18n_demo_module(node, environment=nil) env_options = environment.nil? ? '' : "--environment #{environment}" [I18NDEMO_MODULE_NAME, 'puppetlabs-stdlib', 'puppetlabs-translate'].each do |module_name| on(node, puppet("module uninstall #{module_name} #{env_options}"), :acceptable_exit_codes => [0,1]) end var_dir = on(node, puppet('config print vardir')).stdout.chomp on(node, "rm -rf '#{File.join(var_dir, 'locales', 'ja')}' '#{File.join(var_dir, 'locales', 'fi')}'") 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/acceptance/lib/puppet/acceptance/common_utils.rb
acceptance/lib/puppet/acceptance/common_utils.rb
module Puppet module Acceptance module BeakerUtils # TODO: This should be added to Beaker def assert_matching_arrays(expected, actual, message = "") assert_equal(expected.sort, actual.sort, message) end end module PackageUtils def package_present(host, package, version = nil) host.install_package(package, '', version) end def package_absent(host, package, cmdline_args = '', opts = {}) host.uninstall_package(package, cmdline_args, opts) end end module CommandUtils def ruby_command(host) "env PATH=\"#{host['privatebindir']}:${PATH}\" ruby" end module_function :ruby_command def gem_command(host, type='aio') if type == 'aio' if host['platform'] =~ /windows/ "env PATH=\"#{host['privatebindir']}:${PATH}\" cmd /c gem" else "env PATH=\"#{host['privatebindir']}:${PATH}\" gem" end else on(host, 'which gem').stdout.chomp end end module_function :gem_command end module ManifestUtils def resource_manifest(resource, title, params = {}) params_str = params.map do |param, value| # This is not quite correct for all parameter values, # but it is good enough for most purposes. value_str = value.to_s value_str = "\"#{value_str}\"" if value.is_a?(String) " #{param} => #{value_str}" end.join(",\n") <<-MANIFEST #{resource} { '#{title}': #{params_str} } MANIFEST end def file_manifest(path, params = {}) resource_manifest('file', path, params) end def user_manifest(username, params = {}) resource_manifest('user', username, params) 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/acceptance/lib/puppet/acceptance/windows_utils.rb
acceptance/lib/puppet/acceptance/windows_utils.rb
require 'puppet/acceptance/common_utils' module Puppet module Acceptance module WindowsUtils require 'puppet/acceptance/windows_utils/service.rb' require 'puppet/acceptance/windows_utils/package_installer.rb' def profile_base(agent) ruby = Puppet::Acceptance::CommandUtils.ruby_command(agent) getbasedir = <<'END' puts ENV['USERPROFILE'].match(/(.*)\\\\[^\\\\]*/)[1] END on(agent, "#{ruby} -e \"#{getbasedir}\"").stdout.chomp end # Checks whether the account with the given username has the given password on a host def assert_password_matches_on(host, username, password, msg = nil) script = <<-PS1 Add-Type -AssemblyName System.DirectoryServices.AccountManagement $ctx = New-Object System.DirectoryServices.AccountManagement.PrincipalContext([System.DirectoryServices.AccountManagement.ContextType]::Machine, $env:COMPUTERNAME) $ctx.ValidateCredentials("#{username}", "#{password}") PS1 result = execute_powershell_script_on(host, script) assert_match(/True/, result.stdout.strip, msg) end def deny_administrator_access_to(host, filepath) # we need to create a fake directory in the user's tempdir with powershell because the ACL # perms set down by cygwin when making tempdirs makes the ACL unusable. Thus we create a # tempdir using powershell and pull its' ACL as a starting point for the new ACL. script = <<-PS1 mkdir -Force $env:TMP\\fake-dir-for-acl $acl = Get-ACL $env:TMP\\fake-dir-for-acl rm -Force $env:TMP\\fake-dir-for-acl $ar = New-Object system.security.accesscontrol.filesystemaccessrule("Administrator","FullControl","Deny") $acl.SetAccessRule($ar) Set-ACL #{filepath} $acl PS1 execute_powershell_script_on(host, script) 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/acceptance/lib/puppet/acceptance/classifier_utils.rb
acceptance/lib/puppet/acceptance/classifier_utils.rb
require 'httparty' require 'tempfile' require 'stringio' require 'uuidtools' require 'json' require 'pp' module Puppet module Acceptance module ClassifierUtils DEFAULT_GROUP_ID = "00000000-0000-4000-8000-000000000000" SSL_PORT = 4433 PREFIX = "/classifier-api" # Keep track of our local tmpdirs for cleanup def self.tmpdirs @classifier_utils_tmpdirs ||= [] end # PE creates a "Production environment" group during installation which # all nodes are a member of by default. This method just looks up this # group and returns its uuid so that other methods may reference it. def get_production_environment_group_uuid step "Get classifier groups so we can locate the 'Production environment' group" response = classifier_handle.get("/v1/groups") assert_equal(200, response.code, "Unable to get classifer groups: #{response.body}") groups_json = response.body groups = JSON.parse(groups_json) if production_environment = groups.find { |g| g['name'] == 'Production environment' } production_environment['id'] else nil end end # Create a Classifier Group which by default will apply to all of the passed # nodes. The Group will merge in the passed group_hash which will be converted # into the json body for a Classifier PUT /v1/groups/:id request. # # A teardown body is registered to delete the created group at the end of the test. # # @returns String the created uuid for the group. def create_group_for_nodes(nodes, group_hash) group_uuid = UUIDTools::UUID.random_create() response = nil teardown do step "Deleting group #{group_uuid}" do response = classifier_handle.delete("/v1/groups/#{group_uuid}") assert_equal(204, response.code, "Failed to delete group #{group_uuid}, #{response.code}:#{response.body}") end if response && response.code == 201 end teardown do step "Cleaning up classifier certs on test host" do cleanup_local_classifier_certs end end hostnames = nodes.map { |n| n.hostname } step "Add group #{group_uuid} for #{hostnames.join(", ")}" rule = hostnames.inject(["or"]) do |r,name| r << ["~", "name", name] r end # In order to override the environment for test nodes, we need the # groups we create to be a child of this "Production environment" group, # otherwise we get a classification error from the conflicting groups. parent = get_production_environment_group_uuid || Puppet::Acceptance::ClassifierUtils::DEFAULT_GROUP_ID body = { "description" => "A classification group for the following acceptance test nodes: (#{hostnames.join(", ")})", "parent" => parent, "rule" => rule, "classes" => {} }.merge group_hash response = classifier_handle.put("/v1/groups/#{group_uuid}", :body => body.to_json) assert_equal(201, response.code, "Unexpected response code: #{response.code}, #{response.body}") return group_uuid end # Creates a group which allows the given nodes to specify their own environments. # Will be torn down at the end of the test. def classify_nodes_as_agent_specified(nodes) create_group_for_nodes(nodes, { "name" => "Agent Specified Test Nodes", "environment" => "agent-specified", "environment_trumps" => true, "description" => "The following acceptance suite nodes (#{nodes.map { |n| n.hostname }.join(", ")}) expect to be able to specify their environment for tesing purposes.", }) end def classify_nodes_as_agent_specified_if_classifer_present classifier_node = false begin classifier_node = find_only_one(:classifier) rescue Beaker::DSL::Outcomes::FailTest end if classifier_node || master.is_pe? classify_nodes_as_agent_specified(agents) end end def classifier_host find_only_one(:classifier) rescue Beaker::DSL::Outcomes::FailTest # fallback to master since currently the sqautils genconfig does not recognize # a classifier role. master end def master_cert @master_cert ||= on(master, "cat `puppet config print hostcert`", :silent => true).stdout end def master_key @master_key ||= on(master, "cat `puppet config print hostprivkey`", :silent => true).stdout end def master_ca_cert_file unless @ca_cert_file ca_cert = on(master, "cat `puppet config print localcacert`", :silent => true).stdout cert_dir = Dir.mktmpdir("pe_classifier_certs") Puppet::Acceptance::ClassifierUtils.tmpdirs << cert_dir @ca_cert_file = File.join(cert_dir, "cacert.pem") # RFC 1421 states PEM is 7-bit ASCII https://tools.ietf.org/html/rfc1421 File.open(@ca_cert_file, "w:ASCII") do |f| f.write(ca_cert) end end @ca_cert_file end def cleanup_local_classifier_certs Puppet::Acceptance::ClassifierUtils.tmpdirs.each do |d| FileUtils.rm_rf(d) end end def clear_classifier_utils_cache @master_cert = nil @master_key = nil @ca_cert_file = nil @classifier_handle = nil end def classifier_handle(options = {}) unless @classifier_handle server = options[:server] || classifier_host.reachable_name port = options[:port] || SSL_PORT prefix = options[:prefix] || PREFIX cert = options[:cert] || master_cert key = options[:key] || master_key ca_cert_file = options[:ca_cert_file] || master_ca_cert_file logger = options[:logger] || self.logger # HTTParty performs a lot of configuration at the class level. # This is inconvenient for our needs because we don't have the # server/cert info available at the time the class is loaded. I'm # sidestepping this by generating an anonymous class on the fly when # the test code actually requests a handle to the classifier. @classifier_handle = Class.new do include HTTParty extend Classifier @debugout = StringIO.new @logger = logger base_uri("https://#{server}:#{port}#{prefix}") debug_output(@debugout) headers({'Content-Type' => 'application/json'}) pem(cert + key) ssl_ca_file(ca_cert_file) end end @classifier_handle end # Handle logging module Classifier [:head, :get, :post, :put, :delete].each do |method| define_method(method) do |*args, &block| log_output do super(*args, &block) end end end private # Ensure that the captured debugging output is logged to Beaker. def log_output yield ensure @debugout.rewind @debugout.each_line { |l| @logger.info(l) } @debugout.truncate(0) 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/acceptance/lib/puppet/acceptance/environment_utils.rb
acceptance/lib/puppet/acceptance/environment_utils.rb
require 'puppet/acceptance/module_utils' module Puppet module Acceptance module EnvironmentUtils include Puppet::Acceptance::ModuleUtils # Generate puppet manifest for the creation of an environment with # the given modulepath and manifest and env_name. The created environment # will have on testing_mod module, and manifest site.pp which includes it. # # @param options [Hash<Sym,String>] # @option options [String] :modulepath Modules directory # @option options [String] :manifest Manifest directory # @option options [String] :env_name Environment name # @return [String] Puppet manifest to create the environment files def generate_environment(options) modulepath = options[:modulepath] manifestpath = options[:manifestpath] env_name = options[:env_name] <<-MANIFEST_SNIPPET file { ################################################### # #{env_name} #{generate_module("testing_mod", env_name, modulepath)} "#{manifestpath}":; "#{manifestpath}/site.pp": ensure => file, mode => "0640", content => ' notify { "in #{env_name} site.pp": } include testing_mod ' ; } MANIFEST_SNIPPET end # Generate one module's manifest code. def generate_module(module_name, env_name, modulepath) <<-MANIFEST_SNIPPET "#{modulepath}":; "#{modulepath}/#{module_name}":; "#{modulepath}/#{module_name}/manifests":; "#{modulepath}/#{module_name}/manifests/init.pp": ensure => file, mode => "0640", content => 'class #{module_name} { notify { "include #{env_name} #{module_name}": } }' ; MANIFEST_SNIPPET end # Default, legacy, dynamic and directory environments # using generate_manifest(), all rooted in testdir. # # @param [String] testdir path to the temp directory which will be the confdir all # the environments live in # @return [String] Puppet manifest to generate all of the environment files. def environment_manifest(testdir) <<-MANIFEST File { ensure => directory, owner => #{master.puppet['user']}, group => #{master.puppet['group']}, mode => "0750", } file { "#{testdir}": } #{generate_environment( :modulepath => "#{testdir}/modules", :manifestpath => "#{testdir}/manifests", :env_name => "default environment")} #{generate_environment( :modulepath => "#{testdir}/testing-modules", :manifestpath => "#{testdir}/testing-manifests", :env_name => "legacy testing environment")} file { "#{testdir}/dynamic":; "#{testdir}/dynamic/testing":; } #{generate_environment( :modulepath => "#{testdir}/dynamic/testing/modules", :manifestpath => "#{testdir}/dynamic/testing/manifests", :env_name => "dynamic testing environment")} file { "#{testdir}/environments":; "#{testdir}/environments/testing":; } #{generate_environment( :modulepath => "#{testdir}/environments/testing/modules", :manifestpath => "#{testdir}/environments/testing/manifests", :env_name => "directory testing environment")} file { "#{testdir}/environments/testing_environment_conf":; } #{generate_environment( :modulepath => "#{testdir}/environments/testing_environment_conf/nonstandard-modules", :manifestpath => "#{testdir}/environments/testing_environment_conf/nonstandard-manifests", :env_name => "directory testing with environment.conf")} file { "#{testdir}/environments/testing_environment_conf/environment.conf": ensure => file, mode => "0640", content => ' modulepath = nonstandard-modules:$basemodulepath manifest = nonstandard-manifests config_version = local-version.sh ' } file { "#{testdir}/environments/testing_environment_conf/local-version.sh": ensure => file, mode => "0640", content => '#! /usr/bin/env bash echo "local testing_environment_conf"' ; } ################### # Services file { "#{testdir}/services":; "#{testdir}/services/testing":; #{generate_module('service_mod', "service testing environment", "#{testdir}/services/testing/modules")} } ####################### # Config version script file { "#{testdir}/static-version.sh": ensure => file, mode => "0640", content => '#! /usr/bin/env bash echo "static"' ; } MANIFEST end def get_directory_hash_from(host, path) dir_hash = {} on(host, "ls #{path}") do |result| result.stdout.split.inject(dir_hash) do |hash,f| hash[f] = "#{path}/#{f}" hash end end dir_hash end def safely_shadow_directory_contents_and_yield(host, original_path, new_path, &block) original_files = get_directory_hash_from(host, original_path) new_files = get_directory_hash_from(host, new_path) conflicts = original_files.keys & new_files.keys step "backup original files" do conflicts.each do |c| on(host, "mv #{original_files[c]} #{original_files[c]}.bak") end end step "shadow original files with temporary files" do new_files.each do |name,full_path_name| on(host, "cp -R #{full_path_name} #{original_path}/#{name}") end end new_file_list = new_files.keys.map { |name| "#{original_path}/#{name}" }.join(' ') step "open permissions to 755 on all temporary files copied into working dir and set ownership" do on(host, "chown -R #{host.puppet['user']}:#{host.puppet['group']} #{new_file_list}") on(host, "chmod -R 755 #{new_file_list}") end if host.check_for_command("selinuxenabled") result = on(host, "selinuxenabled", :acceptable_exit_codes => [0,1]) if result.exit_code == 0 step "mirror selinux contexts" do context = on(host, "matchpathcon #{original_path}").stdout.chomp.split(' ')[1] on(host, "chcon -R #{context} #{new_file_list}") end end end yield ensure step "clear out the temporary files" do files_to_delete = new_files.keys.map { |name| "#{original_path}/#{name}" } on(host, "rm -rf #{files_to_delete.join(' ')}") end step "move the shadowed files back to their original places" do conflicts.each do |c| on(host, "mv #{original_files[c]}.bak #{original_files[c]}") end end end # Stand up a puppet master on the master node with the given master_opts # using the passed envdir as the source of the puppet environment files, # and passed confdir as the directory to use for the temporary # puppet.conf. It then runs through a series of environment tests for the # passed environment and returns a hashed structure of the results. # # @return [Hash<Beaker::Host,Hash<Sym,Beaker::Result>>] Hash of # Beaker::Hosts for each agent run keyed to a hash of Beaker::Result # objects keyed by each subtest that was performed. def use_an_environment(environment, description, master_opts, envdir, confdir, options = {}) master_puppet_conf = master_opts.dup # shallow clone results = {} safely_shadow_directory_contents_and_yield(master, puppet_config(master, 'codedir', section: 'master'), envdir) do config_print = options[:config_print] directory_environments = options[:directory_environments] with_puppet_running_on(master, master_puppet_conf, confdir) do agents.each do |agent| agent_results = results[agent] = {} step "puppet agent using #{description} environment" args = "-t", "--server", master args << ["--environment", environment] if environment # Test agents configured to use directory environments (affects environment # loading on the agent, especially with regards to requests/node environment) args << "--environmentpath='$confdir/environments'" if directory_environments && agent != master on(agent, puppet("agent", *args), :acceptable_exit_codes => (0..255)) do |result| agent_results[:puppet_agent] = result end args = ["--trace"] args << ["--environment", environment] if environment step "print puppet config for #{description} environment" on(master, puppet(*(["config", "print", "basemodulepath", "modulepath", "manifest", "config_version", config_print] + args)), :acceptable_exit_codes => (0..255)) do |result| agent_results[:puppet_config] = result end step "puppet apply using #{description} environment" on(master, puppet(*(["apply", '-e', '"include testing_mod"'] + args)), :acceptable_exit_codes => (0..255)) do |result| agent_results[:puppet_apply] = result end end end end return results end # For each Beaker::Host in the results Hash, generates a chart, comparing # the expected exit code and regexp matches from expectations to the # Beaker::Result.output for a particular command that was executed in the # environment. Outputs either 'ok' or text highlighting the errors, and # returns false if any errors were found. # # @param [Hash<Beaker::Host,Hash<Sym,Beaker::Result>>] results # @param [Hash<Sym,Hash{Sym => Integer,Array<Regexp>}>] expectations # @return [Array] Returns an empty array of there were no failures, or an # Array of failed cases. def review_results(results, expectations) failed = [] results.each do |agent, agent_results| divider = "-" * 79 logger.info divider logger.info "For: (#{agent.name}) #{agent}" logger.info divider agent_results.each do |testname, execution_results| expected_exit_code = expectations[testname][:exit_code] match_tests = expectations[testname][:matches] || [] not_match_tests = expectations[testname][:does_not_match] || [] expect_failure = expectations[testname][:expect_failure] notes = expectations[testname][:notes] errors = [] if execution_results.exit_code != expected_exit_code errors << "To exit with an exit code of '#{expected_exit_code}', instead of '#{execution_results.exit_code}'" end match_tests.each do |regexp| if execution_results.output !~ regexp errors << "#{errors.empty? ? "To" : "And"} match: #{regexp}" end end not_match_tests.each do |regexp| if execution_results.output =~ regexp errors << "#{errors.empty? ? "Not to" : "And not"} match: #{regexp}" end end error_msg = "Expected the output:\n#{execution_results.output}\n#{errors.join("\n")}" unless errors.empty? case_failed = case when errors.empty? && expect_failure then 'ok - failed as expected' when errors.empty? && !expect_failure then 'ok' else '*UNEXPECTED FAILURE*' end logger.info "#{testname}: #{case_failed}" if case_failed == 'ok - failed as expected' logger.info divider logger.info "Case is known to fail as follows:\n#{execution_results.output}\n" elsif case_failed == '*UNEXPECTED FAILURE*' failed << "Unexpected failure for #{testname}" logger.info divider logger.info "#{error_msg}" end logger.info("------\nNotes: #{notes}") if notes logger.info divider end end return failed end def assert_review(review) failures = [] review.each do |failed| if !failed.empty? problems = "Problems in the output reported above:\n #{failed}" logger.warn(problems) failures << problems end end assert failures.empty?, "Failed Review:\n\n#{failures.join("\n")}\n" end # generate a random string of 6 letters and numbers. NOT secure def random_string [*('a'..'z'),*('0'..'9')].shuffle[0,8].join end private :random_string # if the first test to call this has changed the environmentpath, this will cause trouble # maybe not the best idea to memoize this? def environmentpath @@memoized_environmentpath ||= master.puppet['environmentpath'] end module_function :environmentpath # create a tmpdir to hold a temporary environment bound by puppet environment naming restrictions # symbolically link environment into environmentpath # we can't use the temp_file utils in our own lib because host.tmpdir violates puppet's naming requirements # in rare cases we want to do this on agents when testing things that use the default manifest def mk_tmp_environment_with_teardown(host, environment) # add the tmp_environment to a set to ensure no collisions @@tmp_environment_set ||= Set.new deadman = 100; loop_num = 0 while @@tmp_environment_set.include?(tmp_environment = environment.downcase + '_' + random_string) do break if (loop_num = loop_num + 1) > deadman end @@tmp_environment_set << tmp_environment tmpdir = File.join('','tmp',tmp_environment) on host, "mkdir -p #{tmpdir}/manifests #{tmpdir}/modules; chmod -R 755 #{tmpdir}" # register teardown to remove the link below teardown do on host, "rm -rf #{File.join(environmentpath,tmp_environment)}" end # WARNING: this won't work with filesync (symlinked environments are not supported) on host, "mkdir -p #{environmentpath}; ln -sf #{tmpdir} #{File.join(environmentpath,tmp_environment)}" return tmp_environment end module_function :mk_tmp_environment_with_teardown # create sitepp in a tmp_environment as created by mk_tmp_environment_with_teardown def create_sitepp(host, tmp_environment, file_content) file_path = File.join('','tmp',tmp_environment,'manifests','site.pp') create_remote_file(host, file_path, file_content) on host, "chmod -R 755 #{file_path}" 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/acceptance/lib/puppet/acceptance/service_utils.rb
acceptance/lib/puppet/acceptance/service_utils.rb
require 'puppet/acceptance/common_utils' module Puppet module Acceptance module ServiceUtils # Return whether a host supports the systemd provider. # @param host [String] hostname # @return [Boolean] whether the systemd provider is supported. def supports_systemd?(host) # The Windows MSI doesn't put Puppet in the Ruby vendor or site dir, so loading it fails. return false if host.platform.variant == 'windows' ruby = Puppet::Acceptance::CommandUtils.ruby_command(host) suitable = on(host, "#{ruby} -e \"require 'puppet'; puts Puppet::Type.type(:service).provider(:systemd).suitable?\"" ).stdout.chomp suitable == "true" ? true : false end # Construct manifest ensuring service status. # @param service [String] name of the service # @param status [Hash] properties to set - can include 'ensure' and 'enable' keys. # @return [String] a manifest def service_manifest(service, status) ensure_status = "ensure => '#{status[:ensure]}'," if status[:ensure] enable_status = "enable => '#{status[:enable]}'," if status[:enable] %Q{ service { '#{service}': #{ensure_status} #{enable_status} } } end # Alter the state of a service using puppet apply and assert that a change was logged. # Assumes the starting state is not the desired state. # @param host [String] hostname. # @param service [String] name of the service. # @param status [Hash] properties to set - can include 'ensure' and 'enable' keys. # @return None def ensure_service_change_on_host(host, service, status) # the process of creating the service will also start it # to avoid a flickering test from the race condition, this test will ensure # that the exit code is either # 2 => something changed, or # 0 => no change needed apply_manifest_on(host, service_manifest(service, status), :acceptable_exit_codes => [0, 2]) do |result| assert_match(/Service\[#{service}\]\/ensure: ensure changed '\w+' to '#{status[:ensure]}'/, result.stdout, 'Service status change failed') if status[:ensure] assert_match(/Service\[#{service}\]\/enable: enable changed '\w+' to '#{status[:enable]}'/, result.stdout, 'Service enable change failed') if status[:enable] end end # Ensure the state of a service using puppet apply and assert that no change was logged. # Assumes the starting state is the ensured state. # @param host [String] hostname. # @param service [String] name of the service. # @param status [Hash] properties to set - can include 'ensure' and 'enable' keys. # @return None def ensure_service_idempotent_on_host(host, service, status) # ensure idempotency apply_manifest_on(host, service_manifest(service, status)) do |result| refute_match(/Service\[#{service}\]\/ensure/, result.stdout, 'Service status not idempotent') if status[:ensure] refute_match(/Service\[#{service}\]\/enable/, result.stdout, 'Service enable not idempotent') if status[:enable] end end # Alter the state of a service using puppet apply, assert that it changed and change is idempotent. # Can set 'ensure' and 'enable'. Assumes the starting state is not the desired state. # @param host [String] hostname. # @param service [String] name of the service. # @param status [Hash] properties to set - can include 'ensure' and 'enable' keys. # @param block [Proc] optional: block to verify service state # @return None def ensure_service_on_host(host, service, status, &block) ensure_service_change_on_host(host, service, status) assert_service_status_on_host(host, service, status, &block) ensure_service_idempotent_on_host(host, service, status) assert_service_status_on_host(host, service, status, &block) end # Checks that the ensure and/or enable status of a service are as expected. # @param host [String] hostname. # @param service [String] name of the service. # @param status [Hash] properties to set - can include 'ensure' and 'enable' keys. # @param block [Proc] optional: block to verify service state # @return None def assert_service_status_on_host(host, service, status, &block) ensure_status = "ensure.+=> '#{status[:ensure]}'" if status[:ensure] enable_status = "enable.+=> '#{status[:enable]}'" if status[:enable] on(host, puppet_resource('service', service)) do |result| assert_match(/'#{service}'.+#{ensure_status}.+#{enable_status}/m, result.stdout, "Service status does not match expectation #{status}") end # Verify service state on the system using a custom block if block yield block end end # Refreshes a service. # @param host [String] hostname. # @param service [String] name of the service to refresh. # @return None def refresh_service_on_host(host, service) refresh_manifest = %Q{ service { '#{service}': } notify { 'Refreshing #{service}': notify => Service['#{service}'], } } apply_manifest_on(host, refresh_manifest) end # Runs some common acceptance tests for nonexistent services. # @param service [String] name of the service # @return None def run_nonexistent_service_tests(service) step "Verify that a nonexistent service is considered stopped, disabled and no logonaccount is reported" do on(agent, puppet_resource('service', service)) do |result| { enable: false, ensure: :stopped }.each do |property, value| assert_match(/#{property}.*#{value}.*$/, result.stdout, "Puppet does not report #{property}=#{value} for a non-existent service") end refute_match(/logonaccount\s+=>/, result.stdout, "Puppet reports logonaccount for a non-existent service") end end step "Verify that stopping and disabling a nonexistent service is a no-op" do manifest = service_manifest(service, ensure: :stopped, enable: false) apply_manifest_on(agent, manifest, catch_changes: true) end [ [ :enabling, [ :enable, true ]], [ :starting, [ :ensure, :running ]] ].each do |operation, (property, value)| manifest = service_manifest(service, property => value) step "Verify #{operation} a non-existent service prints an error message but does not fail the run without detailed exit codes" do apply_manifest_on(agent, manifest) do |result| assert_match(/Error:.*#{service}.*$/, result.stderr, "Puppet does not error when #{operation} a non-existent service.") end end step "Verify #{operation} a non-existent service with detailed exit codes correctly returns an error code" do apply_manifest_on(agent, manifest, :acceptable_exit_codes => [4]) end end end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/lib/puppet/acceptance/temp_file_utils.rb
acceptance/lib/puppet/acceptance/temp_file_utils.rb
module Puppet module Acceptance module TempFileUtils RWXR_XR_X = '0755' PUPPET_CODEDIR_PERMISSIONS = RWXR_XR_X # Return the name of the root user, as appropriate for the platform. def root_user(host) case host['platform'] when /windows/ 'Administrator' else 'root' end end # Return the name of the root group, as appropriate for the platform. def root_group(host) case host['platform'] when /windows/ 'Administrators' when /aix/ 'system' when /osx|bsd/ 'wheel' else 'root' end end # Create a file on the host. # Parameters: # [host] the host to create the file on # [file_path] the path to the file to be created # [file_content] a string containing the contents to be written to the file # [options] a hash containing additional behavior options. Currently supported: # * :mkdirs (default false) if true, attempt to create the parent directories on the remote host before writing # the file # * :owner (default 'root') the username of the user that the file should be owned by # * :group (default 'puppet') the name of the group that the file should be owned by # * :mode (default '644') the mode (file permissions) that the file should be created with def create_test_file(host, file_rel_path, file_content, options = {}) # set default options options[:mkdirs] ||= false options[:mode] ||= "755" unless options[:owner] if host['roles'].include?('master') then options[:owner] = host.puppet['user'] else options[:owner] = root_user(host) end end unless options[:group] if host['roles'].include?('master') then options[:group] = host.puppet['group'] else options[:group] = root_group(host) end end file_path = get_test_file_path(host, file_rel_path) mkdirs(host, File.dirname(file_path)) if (options[:mkdirs] == true) create_remote_file(host, file_path, file_content) # # NOTE: we need these chown/chmod calls because the acceptance framework connects to the nodes as "root", but # puppet 'master' runs as user 'puppet'. Therefore, in order for puppet master to be able to read any files # that we've created, we have to carefully set their permissions # chown(host, options[:owner], options[:group], file_path) chmod(host, options[:mode], file_path) end # Given a relative path, returns an absolute path for a test file. Basically, this just prepends the # a unique temp dir path (specific to the current test execution) to your relative path. def get_test_file_path(host, file_rel_path) initialize_temp_dirs unless @host_test_tmp_dirs File.join(@host_test_tmp_dirs[host.name], file_rel_path) end # Check for the existence of a temp file for the current test; basically, this just calls file_exists?(), # but prepends the path to the current test's temp dir onto the file_rel_path parameter. This allows # tests to be written using only a relative path to specify file locations, while still taking advantage # of automatic temp file cleanup at test completion. def test_file_exists?(host, file_rel_path) file_exists?(host, get_test_file_path(host, file_rel_path)) end def file_exists?(host, file_path) host.execute("test -f \"#{file_path}\"", :acceptable_exit_codes => [0, 1]) do |result| return result.exit_code == 0 end end def dir_exists?(host, dir_path) host.execute("test -d \"#{dir_path}\"", :acceptable_exit_codes => [0, 1]) do |result| return result.exit_code == 0 end end def link_exists?(host, link_path) host.execute("test -L \"#{link_path}\"", :acceptable_exit_codes => [0, 1]) do |result| return result.exit_code == 0 end end def file_contents(host, file_path) host.execute("cat \"#{file_path}\"") do |result| return result.stdout end end def tmpdir(host, basename) host_tmpdir = host.tmpdir(basename) # we need to make sure that the puppet user can traverse this directory... chmod(host, "755", host_tmpdir) host_tmpdir end def mkdirs(host, dir_path) on(host, "mkdir -p #{dir_path}") end def chown(host, owner, group, path) on(host, "chown #{owner}:#{group} #{path}") end def chmod(host, mode, path) on(host, "chmod #{mode} #{path}") end # Returns an array containing the owner, group and mode of # the file specified by path. The returned mode is an integer # value containing only the file mode, excluding the type, e.g # S_IFDIR 0040000 def stat(host, path) require File.join(File.dirname(__FILE__),'common_utils.rb') ruby = Puppet::Acceptance::CommandUtils.ruby_command(host) owner = on(host, "#{ruby} -e 'require \"etc\"; puts (Etc.getpwuid(File.stat(\"#{path}\").uid).name)'").stdout.chomp group = on(host, "#{ruby} -e 'require \"etc\"; puts (Etc.getgrgid(File.stat(\"#{path}\").gid).name)'").stdout.chomp mode = on(host, "#{ruby} -e 'puts (File.stat(\"#{path}\").mode & 07777)'").stdout.chomp.to_i [owner, group, mode] end def initialize_temp_dirs() # pluck this out of the test case environment; not sure if there is a better way @cur_test_file = @path @cur_test_file_shortname = File.basename(@cur_test_file, File.extname(@cur_test_file)) # we need one list of all of the hosts, to assist in managing temp dirs. It's possible # that the master is also an agent, so this will consolidate them into a unique set @all_hosts = Set[master, *agents] # now we can create a hash of temp dirs--one per host, and unique to this test--without worrying about # doing it twice on any individual host @host_test_tmp_dirs = Hash[@all_hosts.map do |host| [host.name, tmpdir(host, @cur_test_file_shortname)] end ] end def remove_temp_dirs() @all_hosts.each do |host| on(host, "rm -rf #{@host_test_tmp_dirs[host.name]}") end end # a silly variable for keeping track of whether or not all of the tests passed... @all_tests_passed = 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/acceptance/lib/puppet/acceptance/solaris_util.rb
acceptance/lib/puppet/acceptance/solaris_util.rb
module Puppet module Acceptance module IPSUtils def clean(agent, o={}) o = {:repo => '/var/tstrepo', :pkg => 'mypkg', :publisher => 'tstpub.lan'}.merge(o) on agent, "rm -rf %s||:" % o[:repo] on agent, "rm -rf /tst||:" on agent, "pkg uninstall %s||:" % o[:pkg] on agent, "pkg unset-publisher %s ||:" % o[:publisher] end def setup(agent, o={}) o = {:repo => '/var/tstrepo', :publisher => 'tstpub.lan'}.merge(o) on agent, "mkdir -p %s" % o[:repo] on agent, "pkgrepo create %s" % o[:repo] on agent, "pkgrepo set -s %s publisher/prefix=%s" % [o[:repo], o[:publisher]] on agent, "pkgrepo -s %s refresh" % o[:repo] end def setup_fakeroot(agent, o={}) o = {:root=>'/opt/fakeroot'}.merge(o) on agent, "rm -rf %s" % o[:root] on agent, "mkdir -p %s/tst/usr/bin" % o[:root] on agent, "mkdir -p %s/tst/etc" % o[:root] on agent, "echo dummy > %s/tst/usr/bin/x" % o[:root] on agent, "echo val > %s/tst/etc/y" % o[:root] end def setup_fakeroot2(agent, o={}) o = {:root=>'/opt/fakeroot'}.merge(o) on agent, "rm -rf %s" % o[:root] on agent, "mkdir -p %s/tst2/usr/bin" % o[:root] on agent, "mkdir -p %s/tst2/etc" % o[:root] on agent, "echo dummy > %s/tst2/usr/bin/x" % o[:root] on agent, "echo val > %s/tst2/etc/y" % o[:root] end def send_pkg2(agent, o={}) o = {:repo=>'/var/tstrepo', :root=>'/opt/fakeroot', :publisher=>'tstpub.lan', :pkg=>'mypkg2@0.0.1', :pkgdep => 'mypkg@0.0.1'}.merge(o) on agent, "(pkgsend generate %s; echo set name=pkg.fmri value=pkg://%s/%s)> /tmp/%s.p5m" % [o[:root], o[:publisher], o[:pkg], o[:pkg]] on agent, "echo depend type=require fmri=%s >> /tmp/%s.p5m" % [o[:pkgdep], o[:pkg]] on agent, "pkgsend publish -d %s -s %s /tmp/%s.p5m" % [o[:root], o[:repo], o[:pkg]] on agent, "pkgrepo refresh -p %s -s %s" % [o[:publisher], o[:repo]] on agent, "pkg refresh" on agent, "pkg list -g %s" % o[:repo] end def send_pkg(agent, o={}) o = {:repo=>'/var/tstrepo', :root=>'/opt/fakeroot', :publisher=>'tstpub.lan', :pkg=>'mypkg@0.0.1'}.merge(o) on agent, "(pkgsend generate %s; echo set name=pkg.fmri value=pkg://%s/%s)> /tmp/%s.p5m" % [o[:root], o[:publisher], o[:pkg], o[:pkg]] on agent, "pkgsend publish -d %s -s %s /tmp/%s.p5m" % [o[:root], o[:repo], o[:pkg]] on agent, "pkgrepo refresh -p %s -s %s" % [o[:publisher], o[:repo]] on agent, "pkg refresh" end def set_publisher(agent, o={}) o = {:repo=>'/var/tstrepo', :publisher=>'tstpub.lan'}.merge(o) on agent, "pkg set-publisher -g %s %s" % [o[:repo], o[:publisher]] on agent, "pkg refresh" end end module SMFUtils def clean(agent, o={}) o = {:service => 'tstapp'}.merge(o) on(agent, "svcs -l %s" % o[:service], acceptable_exit_codes: [0, 1]) do |result| next if result.stdout =~ /doesn't match/ lines = result.stdout.chomp.lines instances = lines.select { |line| line =~ /^fmri/ }.map { |line| line.split(' ')[1].chomp } instances.each do |instance| on agent, "svcadm disable %s ||:" % instance on agent, "svccfg delete %s ||:" % instance end end on agent, "rm -rf /var/svc/manifest/application/%s.xml ||:" % o[:service] on agent, "rm -f /opt/bin/%s ||:" % o[:service] end def setup(agent, o={}) setup_methodscript(agent, o) end def setup_methodscript(agent, o={}) o = {:service => 'tstapp'}.merge(o) on agent, "mkdir -p /opt/bin" create_remote_file agent, '/lib/svc/method/%s' % o[:service], %[ #!/usr/bin/sh . /lib/svc/share/smf_include.sh case "$1" in start) /opt/bin/%s ;; stop) ctid=`svcprop -p restarter/contract $SMF_FMRI` if [ -n "$ctid" ]; then smf_kill_contract $ctid TERM fi ;; *) echo "Usage: $0 { start | stop }" ; exit 1 ;; esac exit $SMF_EXIT_OK ] % ([o[:service]] * 4) create_remote_file agent, ('/opt/bin/%s' % o[:service]), %[ #!/usr/bin/sh cleanup() { rm -f /tmp/%s.pidfile; exit 0 } trap cleanup INT TERM trap '' HUP (while :; do sleep 1; done) & echo $! > /tmp/%s.pidfile ] % ([o[:service]] * 2) on agent, "chmod 755 /lib/svc/method/%s" % o[:service] on agent, "chmod 755 /opt/bin/%s" % o[:service] on agent, "mkdir -p /var/svc/manifest/application" create_remote_file agent, ('/var/smf-%s.xml' % o[:service]), %[<?xml version="1.0"?> <!DOCTYPE service_bundle SYSTEM "/usr/share/lib/xml/dtd/service_bundle.dtd.1"> <service_bundle type='manifest' name='%s:default'> <service name='application/tstapp' type='service' version='1'> <create_default_instance enabled='false' /> <method_context> <method_credential user='root' group='root' /> </method_context> <exec_method type='method' name='start' exec='/lib/svc/method/%s start' timeout_seconds="60" /> <exec_method type='method' name='stop' exec='/lib/svc/method/%s stop' timeout_seconds="60" /> <exec_method type='method' name='refresh' exec='/lib/svc/method/%s refresh' timeout_seconds="60" /> <stability value='Unstable' /> <template> <common_name> <loctext xml:lang='C'>Dummy</loctext> </common_name> <documentation> <manpage title='tstapp' section='1m' manpath='/usr/share/man' /> </documentation> </template> </service> </service_bundle> ] % ([o[:service]] * 4) on agent, "svccfg -v validate /var/smf-%s.xml" % o[:service] on agent, "echo > /var/svc/log/application-%s:default.log" % o[:service] return ("/var/smf-%s.xml" % o[:service]), ("/lib/svc/method/%s" % o[:service]) 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/acceptance/lib/puppet/acceptance/rpm_util.rb
acceptance/lib/puppet/acceptance/rpm_util.rb
module Puppet module Acceptance module RpmUtils # Utilities for creating a basic rpm package and using it in tests @@defaults = {:repo => '/tmp/rpmrepo', :pkg => 'mypkg', :publisher => 'tstpub.lan', :version => '1.0'} @@setup_packages = {} def rpm_provider(agent) has_dnf = on(agent, 'which dnf', :acceptable_exit_codes => [0,1]).exit_code has_dnf == 0 ? 'dnf' : 'yum' end def setup(agent) @@setup_packages[agent] ||= {} cmd = rpm_provider(agent) required_packages = %w[createrepo curl rpm-build] required_packages.each do |pkg| pkg_installed = (on agent, "#{cmd} list installed #{pkg}", :acceptable_exit_codes => (0..255)).exit_code == 0 # We need a newer OpenSSH for the newer OpenSSL that curl installs # RE-16677 on(agent, 'dnf upgrade -y openssh') if (agent.platform.start_with?('el-9') && pkg == 'curl') # package not present, so perform a new install if !pkg_installed on agent, "#{cmd} install -y #{pkg}" # package is present, but has not yet attempted an upgrade # note that this may influence YUM cache behavior elsif !@@setup_packages[agent].has_key?(pkg) # first pass, always attempt an upgrade to latest version # fixes Fedora 25 curl compat with python-pycurl for instance on agent, "#{cmd} upgrade -y #{pkg}" end @@setup_packages[agent][pkg] = true end end def clean_rpm(agent, o={}) cmd = rpm_provider(agent) o = @@defaults.merge(o) on agent, "rm -rf #{o[:repo]}", :acceptable_exit_codes => (0..255) on agent, "#{cmd} remove -y #{o[:pkg]}", :acceptable_exit_codes => (0..255) on agent, "rm -f /etc/yum.repos.d/#{o[:publisher]}.repo", :acceptable_exit_codes => (0..255) end def setup_rpm(agent, o={}) setup(agent) o = @@defaults.merge(o) on agent, "mkdir -p #{o[:repo]}/{RPMS,SRPMS,BUILD,SOURCES,SPECS}" on agent, "echo '%_topdir #{o[:repo]}' > ~/.rpmmacros" on agent, "createrepo #{o[:repo]}" on agent, "cat <<EOF > /etc/yum.repos.d/#{o[:publisher]}.repo [#{o[:publisher]}] name=#{o[:publisher]} baseurl=file://#{o[:repo]}/ enabled=1 gpgcheck=0 EOF " end def send_rpm(agent, o={}) setup(agent) o = @@defaults.merge(o) on agent, "mkdir -p #{o[:repo]}/#{o[:pkg]}-#{o[:version]}/usr/bin" on agent, "cat <<EOF > #{o[:repo]}/#{o[:pkg]} #!/bin/bash echo Hello World EOF " pkg_name = "#{o[:pkg]}-#{o[:version]}" on agent, "install -m 755 #{o[:repo]}/#{o[:pkg]} #{o[:repo]}/#{pkg_name}/usr/bin" on agent, "tar -zcvf #{o[:repo]}/SOURCES/#{pkg_name}.tar.gz -C #{o[:repo]} #{pkg_name}" on agent, "cat <<EOF > #{o[:repo]}/SPECS/#{o[:pkg]}.spec # Don't try fancy stuff like debuginfo, which is useless on binary-only packages. Don't strip binary too # Be sure buildpolicy set to do nothing %define __spec_install_post %{nil} %define debug_package %{nil} %define __os_install_post %{_dbpath}/brp-compress Summary: A very simple toy bin rpm package Name: #{o[:pkg]} Version: #{o[:version]} Release: 1 Epoch: #{o[:epoch] || 0} BuildArch: noarch License: GPL+ Group: Development/Tools SOURCE0 : %{name}-%{version}.tar.gz URL: https://www.puppetlabs.com/ BuildRoot: %{_topdir}/BUILD/%{name}-%{version}-%{release}-root %description %{summary} %prep %setup -q %build # Empty section. %install rm -rf %{buildroot} mkdir -p %{buildroot} # in builddir cp -a * %{buildroot} %clean rm -rf %{buildroot} %files %defattr(-,root,root,-) %{_bindir}/* %changelog * Mon Dec 01 2014 Michael Smith <michael.smith@puppetlabs.com> #{o[:version]}-1 - First Build EOF " on agent, "rpmbuild -ba #{o[:repo]}/SPECS/#{o[:pkg]}.spec" on agent, "createrepo --update #{o[:repo]}" cmd = rpm_provider(agent) # DNF requires a cache reset to make local repositories accessible. if cmd == 'dnf' on agent, "dnf clean metadata" 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/acceptance/lib/puppet/acceptance/module_utils.rb
acceptance/lib/puppet/acceptance/module_utils.rb
module Puppet module Acceptance module ModuleUtils # Return an array of module paths for a given host. # # Example return value: # # [ # "/etc/puppetlabs/code/environments/production/modules", # "/etc/puppetlabs/code/modules", # "/opt/puppet/share/puppet/modules", # ] # # @param host [String] hostname # @return [Array] paths for found modulepath def get_modulepaths_for_host(host) environment = on(host, puppet("config print environment")).stdout.chomp on(host, puppet("config print modulepath --environment #{environment}")).stdout.chomp.split(host['pathseparator']) end # Return a string of the default (first) path in modulepath for a given host. # # Example return value: # # "/etc/puppetlabs/code/environments/production/modules" # # @param host [String] hostname # @return [String] first path for found modulepath def get_default_modulepath_for_host(host) get_modulepaths_for_host(host)[0] end # Return an array of paths to installed modules for a given host. # # Example return value: # # [ # "/opt/puppet/share/puppet/modules/apt", # "/opt/puppet/share/puppet/modules/auth_conf", # "/opt/puppet/share/puppet/modules/concat", # ] # # @param host [String] hostname # @return [Array] paths for found modules def get_installed_modules_for_host(host) on(host, puppet('module list --render-as json')) do |result| str = result.stdout.lines.to_a.last pat = /\(([^()]+)\)/ mods = str.scan(pat).flatten return mods end end # Return a hash of array of paths to installed modules for a hosts. # The individual hostnames are the keys of the hash. The only value # for a given key is an array of paths for the found modules. # # Example return value: # # { # "my_master" => # [ # "/opt/puppet/share/puppet/modules/apt", # "/opt/puppet/share/puppet/modules/auth_conf", # "/opt/puppet/share/puppet/modules/concat", # ], # "my_agent01" => # [ # "/opt/puppet/share/puppet/modules/apt", # "/opt/puppet/share/puppet/modules/auth_conf", # "/opt/puppet/share/puppet/modules/concat", # ], # } # # @param hosts [Array] hostnames # @return [Hash] paths for found modules indexed by hostname def get_installed_modules_for_hosts(hosts) mods = {} hosts.each do |host| mods[host] = get_installed_modules_for_host host end return mods end # Compare the module paths in given hashes and remove paths that # are were not present in the first hash. The use case for this # method is to remove any modules that were installed during the # course of a test run. # # Installed module hashes would be gathered using the # `get_+installed_module_for_hosts` command in the setup stage # and teardown stages of a test. These hashes would be passed into # this method in order to find modules installed during the test # and delete them in order to return the SUT environments to their # initial state. # # TODO: Enhance to take versions into account, so that upgrade/ # downgrade events during a test does not persist in the SUT # environment. # # @param beginning_hash [Hash] paths for found modules indexed # by hostname. Taken in the setup stage of a test. # @param ending_hash [Hash] paths for found modules indexed # by hostname. Taken in the teardown stage of a test. def rm_installed_modules_from_hosts(beginning_hash, ending_hash) ending_hash.each do |host, mod_array| mod_array.each do |mod| if ! beginning_hash[host].include? mod on host, "rm -rf '#{mod}'" end end end end # Convert a semantic version number string to an integer. # # Example return value given an input of '1.2.42': # # 10242 # # @param semver [String] semantic version number def semver_to_i( semver ) # semver assumed to be in format <major>.<minor>.<patch> # calculation assumes that each segment is < 100 tmp = semver.split('.') tmp[0].to_i * 10000 + tmp[1].to_i * 100 + tmp[2].to_i end # Compare two given semantic version numbers. # # Returns an integer indicating the relationship between the two: # 0 indicates that both are equal # a value greater than 0 indicates that the semver1 is greater than semver2 # a value less than 0 indicates that the semver1 is less than semver2 # def semver_cmp( semver1, semver2 ) semver_to_i(semver1) - semver_to_i(semver2) end # Assert that a module was installed according to the UI.. # # This is a wrapper to centralize the validation about how # the UI responded that a module was installed. # It is called after a call # to `on ( host )` and inspects # STDOUT for specific content. # # @param stdout [String] # @param module_author [String] the author portion of a module name # @param module_name [String] the name portion of a module name # @param module_verion [String] the version of the module to compare to # installed version # @param compare_op [String] the operator for comparing the verions of # the installed module def assert_module_installed_ui( stdout, module_author, module_name, module_version = nil, compare_op = nil ) valid_compare_ops = {'==' => 'equal to', '>' => 'greater than', '<' => 'less than'} assert_match(/#{module_author}-#{module_name}/, stdout, "Notice that module '#{module_author}-#{module_name}' was installed was not displayed") if version /#{module_author}-#{module_name} \(.*v(\d+\.\d+\.\d+)/ =~ stdout installed_version = Regexp.last_match[1] if valid_compare_ops.include? compare_op assert_equal( true, semver_cmp(installed_version, module_version).send(compare_op, 0), "Installed version '#{installed_version}' of '#{module_name}' was not #{valid_compare_ops[compare_op]} '#{module_version}'") end end end # Assert that a module is installed on disk. # # @param host [HOST] the host object to make the remote call on # @param module_name [String] the name portion of a module name # @param optional moduledir [String, Array] the path where the module should be, will # iterate over components of the modulepath by default. def assert_module_installed_on_disk(host, module_name, moduledir=nil) moduledir ||= get_modulepaths_for_host(host) modulepath = moduledir.is_a?(Array) ? moduledir : [moduledir] moduledir= nil modulepath.each do |i| # module directory should exist if on(host, %Q{[ -d "#{i}/#{module_name}" ]}, :acceptable_exit_codes => (0..255)).exit_code == 0 moduledir = i end end fail_test('module directory not found') unless moduledir owner = '' group = '' on host, %Q{ls -ld "#{moduledir}"} do listing = stdout.split(' ') owner = listing[2] group = listing[3] end # A module's files should have: # * a mode of 644 (755, if they're a directory) # * owner == owner of moduledir # * group == group of moduledir on host, %Q{ls -alR "#{moduledir}/#{module_name}"} do listings = stdout.split("\n") listings = listings.grep(/^[bcdlsp-]/) listings = listings.reject { |l| l =~ /\.\.$/ } listings.each do |line| fileinfo = parse_ls(line) assert_equal owner, fileinfo[:owner] assert_equal group, fileinfo[:group] if fileinfo[:filetype] == 'd' assert_equal 'rwx', fileinfo[:perms][:user] assert_equal 'r-x', fileinfo[:perms][:group] assert_equal 'r-x', fileinfo[:perms][:other] else assert_equal 'rw-', fileinfo[:perms][:user] assert_equal 'r--', fileinfo[:perms][:group] assert_equal 'r--', fileinfo[:perms][:other] end end end end LS_REGEX = %r[(.)(...)(...)(...).?[[:space:]]+\d+[[:space:]]+([[:word:]]+)[[:space:]]+([[:word:]]+).*[[:space:]]+([[:graph:]]+)$] def parse_ls(line) match = line.match(LS_REGEX) if match.nil? fail_test "#{line.inspect} doesn't match ls output regular expression" end captures = match.captures { :filetype => captures[0], :perms => { :user => captures[1], :group => captures[2], :other => captures[3], }, :owner => captures[4], :group => captures[5], :file => captures[6] } end private :parse_ls # Assert that a module is not installed on disk. # # @param host [HOST] the host object to make the remote call on # @param module_name [String] the name portion of a module name # @param optional moduledir [String, Array] the path where the module should be, will # iterate over components of the modulepath by default. def assert_module_not_installed_on_disk(host, module_name, moduledir=nil) moduledir ||= get_modulepaths_for_host(host) modulepath = moduledir.is_a?(Array) ? moduledir : [moduledir] moduledir= nil modulepath.each do |i| # module directory should not exist on host, %Q{[ ! -d "#{i}/#{module_name}" ]} end end # Create a simple directory environment and puppet.conf at :tmpdir. # # @note Also registers a teardown block to remove generated files. # # @param tmpdir [String] directory to contain all the # generated environment files # @return [String] path to the new puppet configuration file defining the # environments def generate_base_directory_environments(tmpdir) puppet_conf = "#{tmpdir}/puppet2.conf" dir_envs = "#{tmpdir}/environments" step 'Configure a the direnv directory environment' apply_manifest_on master, %Q{ File { ensure => directory, owner => #{master.puppet['user']}, group => #{master.puppet['group']}, mode => "0750", } file { [ '#{dir_envs}', '#{dir_envs}/direnv', ]: } file { '#{puppet_conf}': ensure => file, content => " [main] environmentpath=#{dir_envs} " } } return puppet_conf 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/acceptance/lib/puppet/acceptance/puppet_type_test_tools_spec.rb
acceptance/lib/puppet/acceptance/puppet_type_test_tools_spec.rb
require File.join(File.dirname(__FILE__),'../../acceptance_spec_helper.rb') require 'puppet/acceptance/puppet_type_test_tools.rb' require 'beaker/dsl/assertions' require 'beaker/result' module Puppet module Acceptance describe 'PuppetTypeTestTools' do include PuppetTypeTestTools include Beaker::DSL::Assertions include Beaker context '#generate_manifest' do it 'takes a single hash' do expect(generate_manifest({:type => 'fake'})).to match(/^fake{"fake_\w{8}":}$/) end it 'takes an array' do expect(generate_manifest([{:type => 'fake'}])).to match(/^fake{"fake_\w{8}":}$/) end it 'generates empty puppet code (assertion-only instance)' do expect(generate_manifest({:fake => 'fake'})).to eql('') end it 'puts a namevar in the right place' do expect(generate_manifest({:type => 'fake', :parameters => {:namevar => 'blah'}})).to match(/^fake{"blah":}$/) end it 'retains puppet code in a namevar' do expect(generate_manifest({:type => 'fake', :parameters => {:namevar => "half_${interpolated}_puppet_namevar"}})). to match(/^fake{"half_\${interpolated}_puppet_namevar":}$/) end it 'places pre_code before the type' do expect(generate_manifest({:type => 'fake', :pre_code => '$some = puppet_code'})). to match(/^\$some = puppet_code\nfake{"fake_\w{8}":}$/m) end it 'places multiple, arbitrary parameters' do expect(generate_manifest({:type => 'fake', :parameters => {:someprop => "function(call)", :namevar => "blah", :someparam => 2}})). to match(/^fake{"blah":someprop => function\(call\),someparam => 2,}$/) end end context '#generate_assertions' do it 'takes a single hash' do expect(generate_assertions({:assertions => {:fake => 'matcher'}})) .to match(/^fake\("matcher", result\.stdout, '"matcher"'\)$/) end it 'takes an array' do expect(generate_assertions([{:assertions => {:fake => 'matcher'}}])) .to match(/^fake\("matcher", result\.stdout, '"matcher"'\)$/) end it 'generates empty assertions (puppet-code only instance)' do expect(generate_assertions({:type => 'no assertions'})).to eql('') end it 'generates arbitrary assertions' do expect(generate_assertions({:assertions => [{:fake => 'matcher'}, {:other => 'othermatch'}]})) .to match(/^fake\("matcher", result\.stdout, '"matcher"'\)\nother\("othermatch", result.stdout, '"othermatch"'\)$/m) end it 'can give a regex to assertions' do expect(generate_assertions({:assertions => {:fake => /matcher/}})) .to match(/^fake\(\/matcher\/, result\.stdout, '\/matcher\/'\)$/) end it 'allows multiple of one assertion type' do expect(generate_assertions({:assertions => {:fake => ['matcher','othermatch']}})) .to match(/^fake\("matcher", result\.stdout, '"matcher"'\)\nfake\("othermatch", result.stdout, '"othermatch"'\)$/) end it 'allows multiple assertion_types with multiple values' do expect(generate_assertions({:assertions => [{:fake => ['matcher','othermatch']}, {:fake2 => ['matcher2','othermatch2']}]})) .to match(/^fake\("matcher", result\.stdout, '"matcher"'\)\nfake\("othermatch", result.stdout, '"othermatch"'\)\nfake2\("matcher2", result.stdout, '"matcher2"'\)\nfake2\("othermatch2", result.stdout, '"othermatch2"'\)\n$/) end context 'expect_failure' do it 'generates arbitrary assertion' do expect(generate_assertions({:assertions => {:expect_failure => {:fake => 'matcher'}}})) .to match(/^expect_failure '' do\nfake\(.*\)\nend$/) end it 'allows multiple of one assertion type' do expect(generate_assertions({:assertions => {:expect_failure => {:fake => ['matcher','othermatch']}}})) .to match(/^expect_failure '' do\nfake\(.*\)\nfake\(.*\)\nend$/) end it 'allows multiple assertion_types' do pending 'ack! requires recursion :-(' #expect(generate_assertions({:assertions => {:expect_failure => [{:fake => 'matcher'},{:fake2 => 'matcher2'}]}})) #.to match(/^expect_failure '' do\nfake\(.*\)\nfake2\(.*\)\nend$/) end it 'allows multiple assertion_types with an expect_failure on one' do expect(generate_assertions({:assertions => [{:expect_failure => {:fake => 'matcher'}}, {:fake2 => 'matcher2'}]})) .to match(/^expect_failure '' do\nfake\(.*\)\nend\nfake2\(.*\)$/) end it 'allows custom expect_failure messages' do expect(generate_assertions({:assertions => {:expect_failure => {:fake => 'matcher', :message => 'oh noes, this should fail but pass'}}})) .to match(/^expect_failure 'oh noes, this should fail but pass' do\nfake\(.*\)\nend$/) end end it 'allow custom assertion messages' end context 'run_assertions' do #def run_assertions(assertions = '', result) it 'takes a string result' do expect(run_assertions('assert_match("yes please", result.stdout)', 'yes please')).to be true end let(:result) {Beaker::Result.new('host','command')} it 'takes a beaker "type" Result' do result.stdout = 'yes please' expect(run_assertions('assert_match("yes please", result.stdout)', result)).to be true end it 'runs a bunch of assertions' do result.stdout = 'yes please' expect(run_assertions("assert_match('yes please', result.stdout)\nrefute_match('blah', result.stdout)", result)).to be false end it 'fails assertions' do pending 'why doesnt this work?' result.stdout = 'yes please' expect(run_assertions('assert_match("blah", result.stdout)', result)).to raise_error end context 'exceptions' do #rescue RuntimeError, SyntaxError => e it 'puts the assertion code, raises error' do pending 'why doesnt this work?' expect(run_assertions('assert_match("blah") }', result)).to raise_error end end end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/lib/puppet/acceptance/puppet_type_test_tools.rb
acceptance/lib/puppet/acceptance/puppet_type_test_tools.rb
require 'puppet/acceptance/environment_utils' module Puppet module Acceptance module PuppetTypeTestTools include Puppet::Acceptance::EnvironmentUtils # for now, just for #random_string # FIXME: yardocs # TODO: create resource class which contains its manifest chunk, and assertions # can be an array or singular, holds the manifest and the assertion_code # has getter for the manifest # has #run_assertions(BeakerResult or string) def generate_manifest(test_resources) manifest = '' test_resources = [test_resources].flatten # ensure it's an array so we enumerate properly test_resources.each do |resource| manifest << resource[:pre_code] + "\n" if resource[:pre_code] namevar = (resource[:parameters][:namevar] if resource[:parameters]) || "#{resource[:type]}_#{random_string}" # ensure these are double quotes around the namevar incase users puppet-interpolate inside it # FIXME: add test ^^ manifest << resource[:type] + '{"' + namevar + '":' if resource[:type] if resource[:parameters] resource[:parameters].each do |key,value| next if key == :namevar manifest << "#{key} => #{value}," end end manifest << "}\n" if resource[:type] end return manifest end def generate_assertions(test_resources) assertion_code = '' test_resources = [test_resources].flatten # ensure it's an array so we enumerate properly test_resources.each do |resource| if resource[:assertions] resource[:assertions] = [resource[:assertions]].flatten # ensure it's an array so we enumerate properly resource[:assertions].each do |assertion_type| expect_failure = false if assertion_type[:expect_failure] expect_failure = true assertion_code << "expect_failure '#{assertion_type[:expect_failure][:message]}' do\n" # delete the message assertion_type[:expect_failure].delete(:message) # promote the hash in expect_failure assertion_type = assertion_type[:expect_failure] assertion_type.delete(:expect_failure) end # ensure all the values are arrays assertion_values = [assertion_type.values].flatten assertion_values.each do |assertion_value| # TODO: non matching asserts? # TODO: non stdout? (support stdout, stderr, exit_code) # TODO: what about checking resource state on host (non agent/apply #on use)? if assertion_type.keys.first =~ /assert_match/ assert_msg = 'found ' elsif assertion_type.keys.first =~ /refute_match/ assert_msg = 'did not find ' else assert_msg = '' end if assertion_value.is_a?(String) matcher = "\"#{assertion_value}\"" elsif assertion_value.is_a?(Regexp) matcher = assertion_value.inspect else matcher = assertion_value end assertion_code << "#{assertion_type.keys.first}(#{matcher}, result.stdout, '#{assert_msg}#{matcher}')\n" end assertion_code << "end\n" if expect_failure end end end return assertion_code end Result = Struct.new(:stdout) def run_assertions(assertions = '', result) result_struct = Result.new if result.respond_to? :stdout result_struct.stdout = result.stdout else # handle results sent in as string result_struct.stdout = result end result = result_struct begin eval(assertions) rescue RuntimeError, SyntaxError => e puts e puts assertions 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/acceptance/lib/puppet/acceptance/aix_util.rb
acceptance/lib/puppet/acceptance/aix_util.rb
module Puppet module Acceptance module AixUtil def to_kv_array(attributes) attributes.map { |attribute, value| "#{attribute}=#{value}" } end def assert_object_attributes_on(host, object_get, object, expected_attributes) host.send(object_get, object) do |result| actual_attrs_kv_pairs = result.stdout.chomp.split(' ')[(1..-1)] actual_attrs = actual_attrs_kv_pairs.map do |kv_pair| attribute, value = kv_pair.split('=') next nil unless value [attribute, value] end.compact.to_h expected_attributes.each do |attribute, value| attribute_str = "attributes[#{object}][#{attribute}]" actual_value = actual_attrs[attribute] assert_match( /\A#{value}\z/, actual_value, "EXPECTED: #{attribute_str} = \"#{value}\", ACTUAL: #{attribute_str} = \"#{actual_value}\"" ) end end end def assert_puppet_changed_object_attributes(result, object_resource, object, changed_attributes) stdout = result.stdout.chomp changed_attributes.each do |attribute, value| prefix = /#{object_resource}\[#{object}\].*attributes changed.*/ attribute_str = "attributes[#{object}][#{attribute}]" assert_match( /#{prefix}#{attribute}=#{value}/, stdout, "Puppet did not indicate that #{attribute_str} changed to #{value}" ) end end def object_resource_manifest(object_resource, object, params) params_str = params.map do |param, value| value_str = value.to_s value_str = "\"#{value_str}\"" if value.is_a?(String) " #{param} => #{value_str}" end.join(",\n") <<-MANIFEST #{object_resource} { '#{object}': #{params_str} } MANIFEST end def run_attribute_management_tests(object_resource, id_property, initial_attributes, changed_attributes) object_get = "#{object_resource}_get".to_sym object_absent = "#{object_resource}_absent".to_sym name = "obj" teardown do agents.each { |agent| agent.send(object_absent, name) } end current_attributes = initial_attributes.dup agents.each do |agent| agent.send(object_absent, name) # We extract the code for this step as a lambda because we will be checking # for this case (1) Before the object has been created and (2) After the # object has been created (towards the end). We do this because in (1), Puppet # does not trigger the property setters after creating the object, while in (2) # it does. These are two different scenarios that we want to check. step_run_errors_when_property_is_passed_as_attribute = lambda do manifest = object_resource_manifest( object_resource, name, attributes: current_attributes.merge({ 'id' => '15' }) ) apply_manifest_on(agent, manifest) do |result| assert_match(/Error:.*'#{id_property}'.*'id'/, result.stderr, "specifying a Puppet property as part of an AIX attribute should have errored, but received #{result.stderr}") end end step "Ensure that Puppet errors if a Puppet property is passed in as an AIX attribute when creating the #{object_resource}" do step_run_errors_when_property_is_passed_as_attribute.call end step "Ensure that the #{object_resource} can be created with the specified attributes" do manifest = object_resource_manifest( object_resource, name, ensure: :present, attributes: to_kv_array(current_attributes) ) apply_manifest_on(agent, manifest) assert_object_attributes_on(agent, object_get, name, current_attributes) end step "Ensure that Puppet noops when the specified attributes are already set" do manifest = object_resource_manifest( object_resource, name, attributes: to_kv_array(current_attributes) ) apply_manifest_on(agent, manifest, catch_changes: true) end # Remember the changed attribute's old values old_attributes = current_attributes.select { |k, _| changed_attributes.keys.include?(k) } step "Ensure that Puppet updates only the specified attributes and nothing else" do current_attributes = current_attributes.merge(changed_attributes) manifest = object_resource_manifest( object_resource, name, attributes: to_kv_array(current_attributes) ) apply_manifest_on(agent, manifest) do |result| assert_puppet_changed_object_attributes( result, object_resource.capitalize, name, changed_attributes ) end assert_object_attributes_on(agent, object_get, name, current_attributes) end step "Ensure that Puppet accepts a hash for the attributes property" do # We want to see if Puppet will do something with the attributes property # when we pass it in as a hash so that it does not just pass validation # and end up noop-ing. Let's set one of our attributes back to its old # value in order to simulate an actual change. attribute = old_attributes.keys.first old_value = old_attributes.delete(attribute) current_attributes[attribute] = old_value manifest = object_resource_manifest( object_resource, name, attributes: current_attributes ) apply_manifest_on(agent, manifest) assert_object_attributes_on(agent, object_get, name, current_attributes) end step "Ensure that `puppet resource #{object_resource}` outputs valid Puppet code" do on(agent, puppet("resource #{object_resource} #{name}")) do |result| manifest = result.stdout.chomp apply_manifest_on(agent, manifest) end end step "Ensure that Puppet errors if a Puppet property is passed in as an AIX attribute after #{object_resource} has been created" do step_run_errors_when_property_is_passed_as_attribute.call end end end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/lib/puppet/acceptance/i18n_utils.rb
acceptance/lib/puppet/acceptance/i18n_utils.rb
module Puppet module Acceptance module I18nUtils # try to enable the locale's for a given language on the agent and return the preferred language name # # @param agent [string] the agent to check the locale configuration on # @param language [string] the language attempt to configure if needed # @return language [string] the language string to use on the agent node, will return nil if not available def enable_locale_language(agent, language) if agent['platform'] =~ /ubuntu/ on(agent, 'locale -a') do |locale_result| if locale_result.stdout !~ /#{language}/ on(agent, "locale-gen --lang #{language}") end end elsif agent['platform'] =~ /debian/ on(agent, 'locale -a') do |locale_result| if locale_result.stdout !~ /#{language}/ on(agent, "cp /etc/locale.gen /etc/locale.gen.orig ; sed -e 's/# #{language}/#{language}/' /etc/locale.gen.orig > /etc/locale.gen") on(agent, 'locale-gen') end end end return language_name(agent, language) end # figure out the preferred language string for the requested language if the language is configured on the system def language_name(agent, language) step "PLATFORM #{agent['platform']}" on(agent, 'locale -a') do |locale_result| ["#{language}.utf8", "#{language}.UTF-8", language].each do |lang| return lang if locale_result.stdout =~ /#{lang}/ end end return 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/acceptance/lib/puppet/acceptance/classifier_utils_spec.rb
acceptance/lib/puppet/acceptance/classifier_utils_spec.rb
require File.join(File.dirname(__FILE__),'../../acceptance_spec_helper.rb') require 'puppet/acceptance/classifier_utils' require 'stringio' require 'beaker' module ClassifierUtilsSpec describe 'ClassifierUtils' do class ATestCase < Beaker::TestCase include Puppet::Acceptance::ClassifierUtils attr_accessor :logger, :hosts def initialize @logger = Logger.new @hosts = [] end def logger @logger end def teardown end class Logger attr_reader :destination def initialize @destination = StringIO.new end def info(log) @destination << (log) end end end let(:testcase) { ATestCase.new } let(:handle) { testcase.classifier_handle( :server => 'foo', :cert => 'cert', :key => 'key', :ca_cert_file => 'file' ) } it "provides a handle to the classifier service" do handle.expects(:perform_request).with(Net::HTTP::Get, '/hi', {}) handle.get('/hi') end it "logs output from the http connection attempt" do TCPSocket.expects(:open).raises('no-connection') OpenSSL::X509::Certificate.expects(:new).with('certkey').returns(stub('cert')) OpenSSL::PKey::RSA.expects(:new).with('certkey', nil).returns(stub('key')) expect { handle.get('/hi') }.to raise_error('no-connection') expect(testcase.logger.destination.string).to match(/opening connection to foo/) end it "creates an agent-specified environment group for a passed set of nodes" do nodes = [ stub_everything('master', :hostname => 'abcmaster', :[] => ['master'] ), stub_everything('agent', :hostname => 'defagent', :[] => ['agent'] ), ] testcase.hosts = nodes uuid = nil handle.expects(:perform_request).with do |method,url,body_hash| expect(method).to eq(Net::HTTP::Put) test_regex = %r{/v1/groups/(\w+-\w+-\w+-\w+-\w+)} md = test_regex.match(url) expect(uuid = md[1]).to_not be_nil expect(body_hash[:body]).to match(/environment[^:]*:[^:]*agent-specified/) end.returns( stub_everything('response', :code => 201)) expect(testcase.classify_nodes_as_agent_specified(nodes).to_s).to eq(uuid) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/lib/puppet/acceptance/windows_utils/package_installer.rb
acceptance/lib/puppet/acceptance/windows_utils/package_installer.rb
module Puppet module Acceptance module WindowsUtils # Sets up a mock installer on the host. def create_mock_package(host, tmpdir, config = {}, installer_file = 'MockInstaller.cs', uninstaller_file = 'MockUninstaller.cs') installer_exe_path = "#{tmpdir}/#{config[:name].gsub(/\s+/, '')}Installer.exe".gsub('/', '\\') uninstaller_exe_path = "#{tmpdir}/#{config[:name].gsub(/\s+/, '')}Uninstaller.exe".gsub('/', '\\') tranformations = { package_display_name: config[:name], uninstaller_location: uninstaller_exe_path, install_commands: config[:install_commands], uninstall_commands: config[:uninstall_commands] } [ { source: installer_file, destination: installer_exe_path }, { source: uninstaller_file, destination: uninstaller_exe_path }, ].each do |exe| fixture_path = File.join( File.dirname(__FILE__), '..', '..', '..', '..', 'fixtures', exe[:source] ) code = File.read(fixture_path) % tranformations build_mock_exe(host, exe[:destination], code) end # If the registry key still exists from a previous package install, then delete it. teardown do if package_installed?(host, config[:name]) on host, powershell("\"Remove-Item HKLM:\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\#{config[:name]}\"") end end # return the installer path for tests to use as the source: attribute installer_exe_path end def build_mock_exe(host, destination, code) # Make a source file containing the code on the SUT, the source file # will be the same location/name as the destination exe but with the .cs # extension source_path_on_host = destination.gsub(/\.exe$/, '.cs') create_remote_file(host, source_path_on_host.gsub('\\', '/'), code) # Create the installer.exe file by compiling the copied over C# code # with PowerShell create_installer_exe = "\"Add-Type"\ " -TypeDefinition (Get-Content #{source_path_on_host} | Out-String)"\ " -Language CSharp"\ " -OutputAssembly #{destination}"\ " -OutputType ConsoleApplication\"" on host, powershell(create_installer_exe) end def package_installed?(host, name) # A successfully installed mock package will have created a registry key under # HKLM:\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall. Simply checking # for that key should suffice as an indicator that the installer completed test_key = "\"Test-Path HKLM:\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\#{name}\"" on(host, powershell(test_key)) do |result| return result.stdout.chomp == 'True' 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/acceptance/lib/puppet/acceptance/windows_utils/service.rb
acceptance/lib/puppet/acceptance/windows_utils/service.rb
module Puppet module Acceptance module WindowsUtils # Sets up a mock service on the host. The methodology here is a simplified # version of what's described in https://msdn.microsoft.com/en-us/magazine/mt703436.aspx def setup_service(host, config = {}, service_file = 'MockService.cs') config[:name] ||= "Mock Service" config[:display_name] ||= "#{config[:name]} (Puppet Acceptance Tests)" config[:description] ||= "Service created solely for acceptance testing the Puppet Windows Service provider" # Create a temporary directory to store the service's C# source code + # its .exe file. tmpdir = host.tmpdir("mock_service") # Copy-over the C# code code_fixture_path = File.join( File.dirname(__FILE__), '..', '..', '..', '..', 'fixtures', service_file ) code = File.read(code_fixture_path) % { service_name: config[:name], start_sleep: config[:start_sleep], pause_sleep: config[:pause_sleep], continue_sleep: config[:continue_sleep], stop_sleep: config[:stop_sleep] } code_path_unix = "#{tmpdir}/source.cs" code_path_win = code_path_unix.gsub('/', '\\') create_remote_file(host, code_path_unix, code) # Create the service.exe file by compiling the copied over C# code # with PowerShell service_exe_path_win = "#{tmpdir}/#{config[:name]}.exe".gsub('/', '\\') create_service_exe = "\"Add-Type"\ " -TypeDefinition (Get-Content #{code_path_win} | Out-String)"\ " -Language CSharp"\ " -OutputAssembly #{service_exe_path_win}"\ " -OutputType ConsoleApplication"\ " -ReferencedAssemblies 'System.ServiceProcess'\"" on host, powershell(create_service_exe) # Now register the service with SCM register_service_with_scm = "\"New-Service"\ " #{config[:name]}"\ " #{service_exe_path_win}"\ " -DisplayName '#{config[:display_name]}'"\ " -Description '#{config[:description]}'"\ " -StartupType Automatic\"" on host, powershell(register_service_with_scm) # Ensure that our service is deleted after the tests teardown { delete_service(host, config[:name]) } end def delete_service(host, name) # Check if our service has already been deleted. If so, then we # have nothing else to do. begin on host, powershell("Get-Service #{name}") rescue Beaker::Host::CommandFailure return end # Ensure that our service process is killed. We cannot do a Stop-Service here # b/c there's a chance that our service could be in a pending state (e.g. # "PausePending", "ContinuePending"). If this is the case, then Stop-Service # will fail. on host, powershell("\"Get-Process #{name} -ErrorAction SilentlyContinue | Stop-Process -Force\" | exit 0") # Now remove our service. We use sc.exe because older versions of PowerShell # may not have the Remove-Service commandlet. on agent, "sc.exe delete #{name}" end # Config should be a hash of <property> => <expected value> def assert_service_properties_on(host, name, properties = {}) properties.each do |property, expected_value| # We need to get the underlying WMI object for the service since that # object contains all of our service properties. The one returned by # Get-Service only has these properties for newer versions of PowerShell. get_property_value = "\"Get-WmiObject -Class Win32_Service"\ " | Where-Object { \\$_.name -eq '#{name}' }"\ " | ForEach-Object { \\$_.#{property} }\"" on(host, powershell(get_property_value)) do |result| actual_value = result.stdout.chomp property_str = "#{name}[#{property}]" assert_match(expected_value, actual_value, "EXPECTED: #{property_str} = #{expected_value}, ACTUAL: #{property_str} = #{actual_value}") end end end def assert_service_startmode_delayed(host, name) get_delayed_service = "\"Get-ChildItem HKLM:\\SYSTEM\\CurrentControlSet\\Services"\ " | Where-Object { \\$_.Property -Contains 'DelayedAutoStart' -And \\$_.PsChildName -Like '#{name}' }"\ " | Select-Object -ExpandProperty PSChildName\"" on(host, powershell(get_delayed_service)) do |result| svc = result.stdout.chomp assert(!svc.empty?, "Service #{name} does not exist or is not a delayed service") 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/acceptance/config/aio/options.rb
acceptance/config/aio/options.rb
{ :type => 'aio', 'is_puppetserver' => true, 'use-service' => true, # use service scripts to start/stop stuff 'puppetservice' => 'puppetserver', 'puppetserver-confdir' => '/etc/puppetlabs/puppetserver/conf.d', 'puppetserver-config' => '/etc/puppetlabs/puppetserver/conf.d/puppetserver.conf', :post_suite => [ 'teardown/common/099_Archive_Logs.rb', ], }
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/config/gem/options.rb
acceptance/config/gem/options.rb
{ # Use `git` so that we have a sane ruby environment :type => 'git', }
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/config/git/options.rb
acceptance/config/git/options.rb
{ :type => 'git', :install => [ 'puppet', ], 'is_puppetserver' => false, 'use-service' => true, # use service scripts to start/stop stuff 'puppetservice' => 'puppetserver', 'puppetserver-confdir' => '/etc/puppetlabs/puppetserver/conf.d', 'puppetserver-config' => '/etc/puppetlabs/puppetserver/conf.d/puppetserver.conf' }
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/pending/ticket_5224_exec_should_unset_user_env_vars.rb
acceptance/pending/ticket_5224_exec_should_unset_user_env_vars.rb
test_name "#5224: exec resources should unset user-related environment variables" ####################################################################################### # NOTE ####################################################################################### # # This test depends on the following pull requests: # # https://github.com/puppetlabs/puppet-acceptance/pull/123 # # because it needs to be able to set some environment variables for the duration of # the puppet commands. Shouldn't be moved out of 'pending' until after that has been # merged. # ####################################################################################### temp_file_name = "/tmp/5224_exec_should_unset_user_env_vars.txt" sentinel_string = "Abracadabra" # these should match up with the value of Puppet::Util::POSIX_USER_ENV_VARS, # but I don't have access to that from here, so this is unfortunately hard-coded # (cprice 2012-01-27) POSIX_USER_ENV_VARS = ['HOME', 'USER', 'LOGNAME'] step "Check value of user-related environment variables" # in this step we are going to run some "exec" blocks that writes the value of the # user-related environment variables to a file. We need to verify that exec's are # unsetting these vars. test_printenv_manifest = <<HERE exec {"print %s environment variable": command => "/usr/bin/printenv %s > #{temp_file_name}", } HERE # loop over the vars that we care about; these should match up with the value of Puppet::Util::POSIX_USER_ENV_VARS, # but I don't have access to that from here, so this is unfortunately hard-coded (cprice 2012-01-27) POSIX_USER_ENV_VARS.each do |var| # apply the manifest. # # note that we are passing in an extra :environment argument, which will cause the # framework to temporarily set this variable before executing the puppet command. # this lets us know what value we should be looking for as the output of the exec. apply_manifest_on agents, test_printenv_manifest % [var, var], :environment => {var => sentinel_string} # cat the temp file and make sure it contained the correct value. on(agents, "cat #{temp_file_name}").each do |result| assert_equal("", "#{result.stdout.chomp}", "Unexpected result for host '#{result.host}', environment var '#{var}'") end end step "Check value of user-related environment variables when they are provided as part of the exec resource" # in this step we are going to run some "exec" blocks that write the value of the # user-related environment variables to a file. However, this time, the manifest # explicitly overrides these variables in the "environment" section, so we need to # be sure that we are respecting these overrides. test_printenv_with_env_overrides_manifest = <<HERE exec {"print %s environment variable": command => "/usr/bin/printenv %s > #{temp_file_name}", environment => ["%s=#{sentinel_string}", "FOO=bar"] } HERE # loop over the vars that we care about; POSIX_USER_ENV_VARS.each do |var| # apply the manifest. # # note that we are passing in an extra :environment argument, which will cause the # framework to temporarily set this variable before executing the puppet command. # this lets us know what value we should be looking for as the output of the exec. apply_manifest_on agents, test_printenv_with_env_overrides_manifest % [var, var, var], :environment => {var => sentinel_string} # cat the temp file and make sure it contained the correct value. on(agents, "cat #{temp_file_name}").each do |result| assert_equal(sentinel_string, "#{result.stdout.chomp}", "Unexpected result for host '#{result.host}', environment var '#{var}'") end end step "cleanup" # remove the temp file on agents, "rm -f #{temp_file_name}"
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/pending/ticket_4151_defined_function_should_not_return_true_for_unrealized_virtual_resources.rb
acceptance/pending/ticket_4151_defined_function_should_not_return_true_for_unrealized_virtual_resources.rb
test_name "#4151: defined function should not return true for unrealized virtual resources" # Jeff McCune <jeff@puppetlabs.com> # 2010-07-06 # # This script is expected to exit non-zero if ticket 4151 has not been # fixed. # # The expected behavior is for defined() to only return true if a virtual # resource has been realized. # # This test creates a virtual resource, does NOT realize it, then calls # the defined() function against it. If defined returns true, there will # be an error since Notify["goodbye"] will require a resource which has # not been realized. manifest1 = %q{ @notify { "hello": } if (defined(Notify["hello"])) { $requires = [ Notify["hello"] ] } notify { "goodbye": require => $requires } } apply_manifest_on(agents, manifest1)
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/pending/ticket_6928_puppet_master_parse_fails.rb
acceptance/pending/ticket_6928_puppet_master_parse_fails.rb
test_name "#6928: Puppet --parseonly should return deprication message" # Create good and bad formatted manifests step "Master: create valid, invalid formatted manifests" create_remote_file(master, '/tmp/good.pp', %w{notify{good:}} ) create_remote_file(master, '/tmp/bad.pp', 'notify{bad:') step "Master: use --parseonly on an invalid manifest, should return 1 and issue deprecation warning" on master, puppet_master( %w{--parseonly /tmp/bad.pp} ), :acceptable_exit_codes => [ 1 ] fail_test "Deprecation warning not issued for --parseonly" unless stdout.include? '--parseonly has been removed. Please use \'puppet parser validate <manifest>\'' step "Agents: create valid, invalid formatted manifests" agents.each do |host| create_remote_file(host, '/tmp/good.pp', %w{notify{good:}} ) create_remote_file(host, '/tmp/bad.pp', 'notify{bad:') end step "Agents: use --parseonly on an invalid manifest, should return 1 and issue deprecation warning" agents.each do |host| on(host, "puppet --parseonly /tmp/bad.pp}", :acceptable_exit_codes => [ 1 ]) do fail_test "Deprecation warning not issued for --parseonly" unless stdout.include? '--parseonly has been removed. Please use \'puppet parser validate <manifest>\'' end end step "Test Face for ‘parser validate’ with good manifest -- should pass" agents.each do |host| on(host, "puppet parser validate /tmp/good.pp", :acceptable_exit_codes => [ 0 ]) end step "Test Face for ‘parser validate’ with bad manifest -- should fail" agents.each do |host| on(host, "puppet parser validate /tmp/bad.pp", :acceptable_exit_codes => [ 1 ]) do fail_test "Bad manifest detection failed" unless stderr.include? 'Could not run: Could not parse for environment production' end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/pending/ticket_11860_exec_should_not_override_locale.rb
acceptance/pending/ticket_11860_exec_should_not_override_locale.rb
test_name "#11860: exec resources should not override system locale" ####################################################################################### # NOTE ####################################################################################### # # This test won't run properly until the test agent nodes have the Spanish language # pack installed on them. On an ubuntu system, this can be done with the following: # # apt-get install language-pack-es-base # # Also, this test depends on the following pull requests: # # https://github.com/puppetlabs/puppet-acceptance/pull/123 # https://github.com/puppetlabs/facter/pull/159 # ####################################################################################### temp_file_name = "/tmp/11860_exec_should_not_override_locale.txt" locale_string = "es_ES.UTF-8" step "Check value of LANG environment variable" # in this step we are going to run an "exec" block that writes the value of the LANG # environment variable to a file. We need to verify that exec's are no longer # forcefully setting this var to 'C'. test_LANG_manifest = <<HERE exec {"es_ES locale print LANG environment variable": command => "/usr/bin/printenv LANG > #{temp_file_name}", } HERE # apply the manifest. # # note that we are passing in an extra :environment argument, which will cause the # framework to temporarily set this variable before executing the puppet command. # this lets us know what value we should be looking for as the output of the exec. apply_manifest_on agents, test_LANG_manifest, :environment => {:LANG => locale_string} # cat the temp file and make sure it contained the correct value. on(agents, "cat #{temp_file_name}").each do |result| assert_equal(locale_string, "#{result.stdout.chomp}", "Unexpected result for host '#{result.host}'") end step "Check for locale-specific output of cat command" # in this step we are going to run an "exec" block that runs the "cat" command. The command # is intentionally invalid, because we are going to run it using a non-standard locale and # we want to confirm that the error message is in the correct language. test_cat_manifest = <<HERE exec {"es_ES locale invalid cat command": command => "/bin/cat SOME_FILE_THAT_DOESNT_EXIST > #{temp_file_name} 2>&1", returns => 1, } HERE # apply the manifest, again passing in the extra :environment argument to set our locale. apply_manifest_on agents, test_cat_manifest, :environment => {:LANG => locale_string} # cat the output file and ensure that the error message is in spanish on(agents, "cat #{temp_file_name}").each do |result| assert_equal("/bin/cat: SOME_FILE_THAT_DOESNT_EXIST: No existe el fichero o el directorio", "#{result.stdout.chomp}", "Unexpected result for host '#{result.host}'") end step "cleanup" # remove the temp file on agents, "rm -f #{temp_file_name}"
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/pending/ticket_5027_warn_on_dynamic_scope.rb
acceptance/pending/ticket_5027_warn_on_dynamic_scope.rb
test_name "#5027: Issue warnings when using dynamic scope" step "Apply dynamic scoping manifest on agents" apply_manifest_on agents, %q{ $foo = 'foo_value' class a { $bar = 'bar_value' include b } class b inherits c { notify { $baz: } # should not generate a warning -- inherited from class c notify { $bar: } # should generate a warning -- uses dynamic scoping notify { $foo: } # should not generate a warning -- comes from top scope } class c { $baz = 'baz_value' } include a } step "Verify deprecation warning" fail_test "Deprecation warning not issued" unless stdout.include? 'warning: Dynamic lookup of $bar will not be supported in future versions. Use a fully-qualified variable name or parameterized classes.'
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/pending/ticket_4149_parseonly_should_not_fail.rb
acceptance/pending/ticket_4149_parseonly_should_not_fail.rb
test_name "#4149: parseonly should do the right thing" step "test with a manifest with syntax errors" manifest = 'class someclass { notify { "hello, world" } }' apply_manifest_on(agents, manifest, :parseonly => true, :acceptable_exit_codes => [1]) { stdout =~ /Could not parse for .*: Syntax error/ or fail_test("didn't get a reported systax error") } step "test with a manifest with correct syntax" apply_manifest_on agents,'class someclass { notify("hello, world") }', :parseonly => true # REVISIT: This tests the current behaviour, which is IMO not actually the # correct behaviour. On the other hand, if we change this we might # unexpectedly break things out in the wild, so better to be warned than to be # surprised by it. --daniel 2010-12-22 step "test with a class with an invalid attribute" apply_manifest_on agents, 'file { "/tmp/whatever": fooble => 1 }', :parseonly => true
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/ext/windows/service/daemon.rb
ext/windows/service/daemon.rb
#!/usr/bin/env ruby # frozen_string_literal: true require 'fileutils' require 'puppet/util/windows/daemon' # This file defines utilities for logging to eventlog. While it lives inside # Puppet, it is completely independent and loads no other parts of Puppet, so we # can safely require *just* it. require 'puppet/util/windows/eventlog' # monkey patches ruby Process to add .create method require 'puppet/util/windows/monkey_patches/process' class WindowsDaemon < Puppet::Util::Windows::Daemon CREATE_NEW_CONSOLE = 0x00000010 @run_thread = nil @LOG_TO_FILE = false @loglevel = 0 LOG_FILE = File.expand_path(File.join(ENV.fetch('ALLUSERSPROFILE', nil), 'PuppetLabs', 'puppet', 'var', 'log', 'windows.log')) LEVELS = [:debug, :info, :notice, :warning, :err, :alert, :emerg, :crit] LEVELS.each do |level| define_method("log_#{level}") do |msg| log(msg, level) end end def service_init end def service_main(*argsv) argsv = (argsv << ARGV).flatten.compact args = argsv.join(' ') @loglevel = LEVELS.index(argsv.index('--debug') ? :debug : :notice) @LOG_TO_FILE = (argsv.index('--logtofile') ? true : false) if @LOG_TO_FILE FileUtils.mkdir_p(File.dirname(LOG_FILE)) args = args.gsub("--logtofile", "") end base_dir = File.expand_path(File.join(File.dirname(__FILE__), '..')) load_env(base_dir) # The puppet installer registers a 'Puppet' event source. For the moment events will be logged with this key, but # it may be a good idea to split the Service and Puppet events later so it's easier to read in the windows Event Log. # # Example code to register an event source; # eventlogdll = File.expand_path(File.join(basedir, 'puppet', 'ext', 'windows', 'eventlog', 'puppetres.dll')) # if (File.exist?(eventlogdll)) # Win32::EventLog.add_event_source( # 'source' => "Application", # 'key_name' => "Puppet Agent", # 'category_count' => 3, # 'event_message_file' => eventlogdll, # 'category_message_file' => eventlogdll # ) # end puppet = File.join(base_dir, 'puppet', 'bin', 'puppet') ruby = File.join(base_dir, 'puppet', 'bin', 'ruby.exe') ruby_puppet_cmd = "\"#{ruby}\" \"#{puppet}\"" unless File.exist?(puppet) log_err("File not found: '#{puppet}'") return end log_debug("Using '#{puppet}'") cmdline_debug = argsv.index('--debug') ? :debug : nil @loglevel = parse_log_level(ruby_puppet_cmd, cmdline_debug) log_notice('Service started') service = self @run_thread = Thread.new do while service.running? runinterval = service.parse_runinterval(ruby_puppet_cmd) if service.state == RUNNING or service.state == IDLE service.log_notice("Executing agent with arguments: #{args}") pid = Process.create(:command_line => "#{ruby_puppet_cmd} agent --onetime #{args}", :creation_flags => CREATE_NEW_CONSOLE).process_id service.log_debug("Process created: #{pid}") else service.log_debug("Service is paused. Not invoking Puppet agent") end service.log_debug("Service worker thread waiting for #{runinterval} seconds") sleep(runinterval) service.log_debug('Service worker thread woken up') end rescue Exception => e service.log_exception(e) end @run_thread.join rescue Exception => e log_exception(e) ensure log_notice('Service stopped') end def service_stop log_notice('Service stopping / killing worker thread') @run_thread.kill if @run_thread end def service_pause log_notice('Service pausing') end def service_resume log_notice('Service resuming') end def service_shutdown log_notice('Host shutting down') end # Interrogation handler is just for debug. Can be commented out or removed entirely. # def service_interrogate # log_debug('Service is being interrogated') # end def log_exception(e) log_err(e.message) log_err(e.backtrace.join("\n")) end def log(msg, level) if LEVELS.index(level) >= @loglevel if @LOG_TO_FILE # without this change its possible that we get Encoding errors trying to write UTF-8 messages in current codepage File.open(LOG_FILE, 'a:UTF-8') { |f| f.puts("#{Time.now} Puppet (#{level}): #{msg}") } end native_type, native_id = Puppet::Util::Windows::EventLog.to_native(level) report_windows_event(native_type, native_id, msg.to_s) end end def report_windows_event(type, id, message) eventlog = nil eventlog = Puppet::Util::Windows::EventLog.open("Puppet") eventlog.report_event( :event_type => type, # EVENTLOG_ERROR_TYPE, etc :event_id => id, # 0x01 or 0x02, 0x03 etc. :data => message # "the message" ) rescue Exception # Ignore all errors ensure unless eventlog.nil? eventlog.close end end # Parses runinterval. # # @param puppet_path [String] The file path for the Puppet executable. # @return runinterval [Integer] How often to do a Puppet run, in seconds. def parse_runinterval(puppet_path) begin runinterval = %x(#{puppet_path} config --section agent --log_level notice print runinterval).chomp if runinterval == '' runinterval = 1800 log_err("Failed to determine runinterval, defaulting to #{runinterval} seconds") else # Use Kernel#Integer because to_i will return 0 with non-numeric strings. runinterval = Integer(runinterval) end rescue Exception => e log_exception(e) runinterval = 1800 end runinterval end def parse_log_level(puppet_path, cmdline_debug) begin loglevel = "notice" unless loglevel && respond_to?("log_#{loglevel}") loglevel = :notice log_err("Failed to determine loglevel, defaulting to #{loglevel}") end rescue Exception => e log_exception(e) loglevel = :notice end LEVELS.index(cmdline_debug || loglevel.to_sym) end private def load_env(base_dir) # ENV that uses backward slashes ENV['FACTER_env_windows_installdir'] = base_dir.tr('/', '\\') ENV['PL_BASEDIR'] = base_dir.tr('/', '\\') ENV['PUPPET_DIR'] = File.join(base_dir, 'puppet').tr('/', '\\') ENV['OPENSSL_CONF'] = File.join(base_dir, 'puppet', 'ssl', 'openssl.cnf').tr('/', '\\') ENV['SSL_CERT_DIR'] = File.join(base_dir, 'puppet', 'ssl', 'certs').tr('/', '\\') ENV['SSL_CERT_FILE'] = File.join(base_dir, 'puppet', 'ssl', 'cert.pem').tr('/', '\\') ENV['Path'] = [ File.join(base_dir, 'puppet', 'bin'), File.join(base_dir, 'bin') ].join(';').tr('/', '\\') + ';' + ENV.fetch('Path', nil) # ENV that uses forward slashes ENV['RUBYLIB'] = "#{File.join(base_dir, 'puppet', 'lib')};#{ENV.fetch('RUBYLIB', nil)}" rescue => e log_exception(e) end end if __FILE__ == $PROGRAM_NAME WindowsDaemon.mainloop end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/spec_helper.rb
spec/spec_helper.rb
# NOTE: a lot of the stuff in this file is duplicated in the "puppet_spec_helper" in the project # puppetlabs_spec_helper. We should probably eat our own dog food and get rid of most of this from here, # and have the puppet core itself use puppetlabs_spec_helper dir = File.expand_path(File.dirname(__FILE__)) $LOAD_PATH.unshift File.join(dir, 'lib') # Don't want puppet getting the command line arguments for rake ARGV.clear begin require 'rubygems' rescue LoadError end require 'puppet' # Stub out gettext's `_` and `n_()` methods, which attempt to load translations. # Several of our mocks (mostly around file system interaction) are broken by # FastGettext's implementation of these methods. require 'puppet/gettext/stubs' require 'rspec' require 'rspec/its' # So everyone else doesn't have to include this base constant. module PuppetSpec FIXTURE_DIR = File.join(File.expand_path(File.dirname(__FILE__)), "fixtures") unless defined?(FIXTURE_DIR) end require 'pathname' require 'tmpdir' require 'fileutils' require 'puppet_spec/verbose' require 'puppet_spec/files' require 'puppet_spec/settings' require 'puppet_spec/fixtures' require 'puppet_spec/matchers' require 'puppet_spec/unindent' require 'puppet/test/test_helper' Pathname.glob("#{dir}/shared_contexts/*.rb") do |file| require file.relative_path_from(Pathname.new(dir)) end Pathname.glob("#{dir}/shared_behaviours/**/*.rb") do |behaviour| require behaviour.relative_path_from(Pathname.new(dir)) end Pathname.glob("#{dir}/shared_examples/**/*.rb") do |behaviour| require behaviour.relative_path_from(Pathname.new(dir)) end require 'webmock/rspec' require 'vcr' VCR.configure do |vcr| vcr.cassette_library_dir = File.expand_path('vcr/cassettes', PuppetSpec::FIXTURE_DIR) vcr.hook_into :webmock vcr.configure_rspec_metadata! # Uncomment next line to debug vcr # vcr.debug_logger = $stderr end # Disable VCR by default VCR.turn_off! RSpec.configure do |config| include PuppetSpec::Fixtures exclude_filters = {} exclude_filters[:benchmark] = true unless ENV['BENCHMARK'] config.filter_run_excluding exclude_filters config.filter_run_when_matching :focus config.mock_with :rspec do |mocks| mocks.verify_partial_doubles = true end tmpdir = Puppet::FileSystem.expand_path(Dir.mktmpdir("rspecrun")) oldtmpdir = Puppet::FileSystem.expand_path(Dir.tmpdir()) ENV['TMPDIR'] = tmpdir Puppet::Test::TestHelper.initialize config.before :all do Puppet::Test::TestHelper.before_all_tests() if ENV['PROFILE'] == 'all' require 'ruby-prof' RubyProf.start end end config.after :all do if ENV['PROFILE'] == 'all' require 'ruby-prof' result = RubyProf.stop printer = RubyProf::CallTreePrinter.new(result) open(File.join(ENV['PROFILEOUT'],"callgrind.all.#{Time.now.to_i}.trace"), "w") do |f| printer.print(f) end end Puppet::Test::TestHelper.after_all_tests() end config.before :each do |test| # Disabling garbage collection inside each test, and only running it at # the end of each block, gives us an ~ 15 percent speedup, and more on # some platforms *cough* windows *cough* that are a little slower. GC.disable # TODO: in a more sane world, we'd move this logging redirection into our TestHelper class. # Without doing so, external projects will all have to roll their own solution for # redirecting logging, and for validating expected log messages. However, because the # current implementation of this involves creating an instance variable "@logs" on # EVERY SINGLE TEST CLASS, and because there are over 1300 tests that are written to expect # this instance variable to be available--we can't easily solve this problem right now. # # redirecting logging away from console, because otherwise the test output will be # obscured by all of the log output @logs = [] Puppet::Util::Log.close_all if ENV["PUPPET_TEST_LOG_LEVEL"] Puppet::Util::Log.level = ENV["PUPPET_TEST_LOG_LEVEL"].intern end if ENV["PUPPET_TEST_LOG"] Puppet::Util::Log.newdestination(ENV["PUPPET_TEST_LOG"]) m = test.metadata Puppet.notice("*** BEGIN TEST #{m[:file_path]}:#{m[:line_number]}") end Puppet::Util::Log.newdestination(Puppet::Test::LogCollector.new(@logs)) @log_level = Puppet::Util::Log.level base = PuppetSpec::Files.tmpdir('tmp_settings') Puppet[:vardir] = File.join(base, 'var') Puppet[:publicdir] = File.join(base, 'public') Puppet[:confdir] = File.join(base, 'etc') Puppet[:codedir] = File.join(base, 'code') Puppet[:logdir] = "$vardir/log" Puppet[:rundir] = "$vardir/run" Puppet[:hiera_config] = File.join(base, 'hiera') FileUtils.mkdir_p Puppet[:statedir] FileUtils.mkdir_p Puppet[:publicdir] Puppet::Test::TestHelper.before_each_test() end # Facter 2 uses two versions of the GCE API, so match using regex PUPPET_FACTER_2_GCE_URL = %r{^http://metadata/computeMetadata/v1(beta1)?}.freeze PUPPET_FACTER_3_GCE_URL = "http://metadata.google.internal/computeMetadata/v1/?recursive=true&alt=json".freeze # Facter azure metadata endpoint PUPPET_FACTER_AZ_URL = "http://169.254.169.254/metadata/instance?api-version=2020-09-01" # Facter EC2 endpoint PUPPET_FACTER_EC2_METADATA = 'http://169.254.169.254/latest/meta-data/' PUPPET_FACTER_EC2_USERDATA = 'http://169.254.169.254/latest/user-data/' config.around :each do |example| # Ignore requests from Facter to external services stub_request(:get, PUPPET_FACTER_2_GCE_URL) stub_request(:get, PUPPET_FACTER_3_GCE_URL) stub_request(:get, PUPPET_FACTER_AZ_URL) stub_request(:get, PUPPET_FACTER_EC2_METADATA) stub_request(:get, PUPPET_FACTER_EC2_USERDATA) # Enable VCR if the example is tagged with `:vcr` metadata. if example.metadata[:vcr] VCR.turn_on! begin example.run ensure VCR.turn_off! end else example.run end end config.after :each do Puppet::Test::TestHelper.after_each_test() # TODO: would like to move this into puppetlabs_spec_helper, but there are namespace issues at the moment. allow(Dir).to receive(:entries).and_call_original PuppetSpec::Files.cleanup # TODO: this should be abstracted in the future--see comments above the '@logs' block in the # "before" code above. # # clean up after the logging changes that we made before each test. @logs.clear Puppet::Util::Log.close_all Puppet::Util::Log.level = @log_level # This will perform a GC between tests, but only if actually required. We # experimented with forcing a GC run, and that was less efficient than # just letting it run all the time. GC.enable end config.after :suite do # Log the spec order to a file, but only if the LOG_SPEC_ORDER environment variable is # set. This should be enabled on Jenkins runs, as it can be used with Nick L.'s bisect # script to help identify and debug order-dependent spec failures. if ENV['LOG_SPEC_ORDER'] File.open("./spec_order.txt", "w") do |logfile| config.instance_variable_get(:@files_to_run).each { |f| logfile.puts f } end end # return to original tmpdir ENV['TMPDIR'] = oldtmpdir FileUtils.rm_rf(tmpdir) end if ENV['PROFILE'] require 'ruby-prof' def profile result = RubyProf.profile { yield } name = RSpec.current_example.metadata[:full_description].downcase.gsub(/[^a-z0-9_-]/, "-").gsub(/-+/, "-") printer = RubyProf::CallTreePrinter.new(result) open(File.join(ENV['PROFILEOUT'],"callgrind.#{name}.#{Time.now.to_i}.trace"), "w") do |f| printer.print(f) end end config.around(:each) do |example| if ENV['PROFILE'] == 'each' or (example.metadata[:profile] and ENV['PROFILE']) profile { example.run } else example.run end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/integration/directory_environments_spec.rb
spec/integration/directory_environments_spec.rb
require 'spec_helper' describe "directory environments" do let(:args) { ['--configprint', 'modulepath', '--environment', 'direnv'] } let(:puppet) { Puppet::Application[:apply] } context "with a single directory environmentpath" do before(:each) do environmentdir = PuppetSpec::Files.tmpdir('envpath') Puppet[:environmentpath] = environmentdir FileUtils.mkdir_p(environmentdir + "/direnv/modules") end it "config prints the environments modulepath" do Puppet.settings.initialize_global_settings(args) expect { puppet.run }.to exit_with(0) .and output(%r{/direnv/modules}).to_stdout end it "config prints the cli --modulepath despite environment" do args << '--modulepath' << '/completely/different' Puppet.settings.initialize_global_settings(args) expect { puppet.run }.to exit_with(0) .and output(%r{/completely/different}).to_stdout end it 'given an 8.3 style path on Windows, will config print an expanded path', :if => Puppet::Util::Platform.windows? do pending("GH runners seem to have disabled 8.3 support") # ensure an 8.3 style path is set for environmentpath shortened = Puppet::Util::Windows::File.get_short_pathname(Puppet[:environmentpath]) expanded = Puppet::FileSystem.expand_path(shortened) Puppet[:environmentpath] = shortened expect(Puppet[:environmentpath]).to match(/~/) Puppet.settings.initialize_global_settings(args) expect { puppet.run }.to exit_with(0) .and output(a_string_matching(expanded)).to_stdout end end context "with an environmentpath having multiple directories" do let(:args) { ['--configprint', 'modulepath', '--environment', 'otherdirenv'] } before(:each) do envdir1 = File.join(Puppet[:confdir], 'env1') envdir2 = File.join(Puppet[:confdir], 'env2') Puppet[:environmentpath] = [envdir1, envdir2].join(File::PATH_SEPARATOR) FileUtils.mkdir_p(envdir2 + "/otherdirenv/modules") end it "config prints a directory environment modulepath" do Puppet.settings.initialize_global_settings(args) expect { puppet.run }.to exit_with(0) .and output(%r{otherdirenv/modules}).to_stdout end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/integration/type_spec.rb
spec/integration/type_spec.rb
require 'spec_helper' require 'puppet/type' describe Puppet::Type do it "should not lose its provider list when it is reloaded" do type = Puppet::Type.newtype(:integration_test) do newparam(:name) {} end provider = type.provide(:myprovider) {} # reload it type = Puppet::Type.newtype(:integration_test) do newparam(:name) {} end expect(type.provider(:myprovider)).to equal(provider) end it "should not lose its provider parameter when it is reloaded" do type = Puppet::Type.newtype(:reload_test_type) type.provide(:test_provider) # reload it type = Puppet::Type.newtype(:reload_test_type) expect(type.parameters).to include(:provider) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/integration/configurer_spec.rb
spec/integration/configurer_spec.rb
require 'spec_helper' require 'puppet_spec/network' require 'puppet/configurer' describe Puppet::Configurer do include PuppetSpec::Files include PuppetSpec::Network describe "when running" do before(:each) do @catalog = Puppet::Resource::Catalog.new("testing", Puppet.lookup(:environments).get(Puppet[:environment])) @catalog.add_resource(Puppet::Type.type(:notify).new(:title => "testing")) # Make sure we don't try to persist the local state after the transaction ran, # because it will fail during test (the state file is in a not-existing directory) # and we need the transaction to be successful to be able to produce a summary report @catalog.host_config = false @configurer = Puppet::Configurer.new end it "should send a transaction report with valid data" do allow(@configurer).to receive(:save_last_run_summary) expect(Puppet::Transaction::Report.indirection).to receive(:save) do |report, x| expect(report.time).to be_a(Time) expect(report.logs.length).to be > 0 end.twice Puppet[:report] = true @configurer.run :catalog => @catalog end it "should save a correct last run summary" do report = Puppet::Transaction::Report.new allow(Puppet::Transaction::Report.indirection).to receive(:save) Puppet[:lastrunfile] = tmpfile("lastrunfile") Puppet.settings.setting(:lastrunfile).mode = 0666 Puppet[:report] = true # We only record integer seconds in the timestamp, and truncate # backwards, so don't use a more accurate timestamp in the test. # --daniel 2011-03-07 t1 = Time.now.tv_sec @configurer.run :catalog => @catalog, :report => report t2 = Time.now.tv_sec # sticky bit only applies to directories in windows file_mode = Puppet::Util::Platform.windows? ? '666' : '100666' expect(Puppet::FileSystem.stat(Puppet[:lastrunfile]).mode.to_s(8)).to eq(file_mode) summary = Puppet::Util::Yaml.safe_load_file(Puppet[:lastrunfile]) expect(summary).to be_a(Hash) %w{time changes events resources}.each do |key| expect(summary).to be_key(key) end expect(summary["time"]).to be_key("notify") expect(summary["time"]["last_run"]).to be_between(t1, t2) end it "applies a cached catalog if pluginsync fails when usecacheonfailure is true and environment is valid" do expect(@configurer).to receive(:valid_server_environment?).and_return(true) Puppet[:ignore_plugin_errors] = false Puppet[:use_cached_catalog] = false Puppet[:usecacheonfailure] = true report = Puppet::Transaction::Report.new expect_any_instance_of(Puppet::Configurer::Downloader).to receive(:evaluate).and_raise(Puppet::Error, 'Failed to retrieve: some file') expect(Puppet::Resource::Catalog.indirection).to receive(:find).and_return(@catalog) @configurer.run(pluginsync: true, report: report) expect(report.cached_catalog_status).to eq('on_failure') end it "applies a cached catalog if pluginsync fails when usecacheonfailure is true and environment is invalid" do expect(@configurer).to receive(:valid_server_environment?).and_return(false) Puppet[:ignore_plugin_errors] = false Puppet[:use_cached_catalog] = false Puppet[:usecacheonfailure] = true report = Puppet::Transaction::Report.new expect(Puppet::Resource::Catalog.indirection).to receive(:find).and_raise(Puppet::Error, 'Cannot compile remote catalog') expect(Puppet::Resource::Catalog.indirection).to receive(:find).and_return(@catalog) @configurer.run(pluginsync: true, report: report) expect(report.cached_catalog_status).to eq('on_failure') end describe 'resubmitting facts' do context 'when resubmit_facts is set to false' do it 'should not send data' do expect(@configurer).to receive(:resubmit_facts).never @configurer.run(catalog: @catalog) end end context 'when resubmit_facts is set to true' do let(:test_facts) { Puppet::Node::Facts.new('configurer.test', {test_fact: 'test value'}) } before(:each) do Puppet[:resubmit_facts] = true allow(@configurer).to receive(:find_facts).and_return(test_facts) end it 'uploads facts as application/json' do stub_request(:put, "https://puppet:8140/puppet/v3/facts/configurer.test?environment=production"). with( body: hash_including( { "name" => "configurer.test", "values" => {"test_fact" => 'test value',}, }), headers: { 'Accept'=>acceptable_content_types_string, 'Content-Type'=>'application/json', }) @configurer.run(catalog: @catalog) end it 'logs errors that occur during fact generation' do allow(@configurer).to receive(:find_facts).and_raise('error generating facts') expect(Puppet).to receive(:log_exception).with(instance_of(RuntimeError), /^Failed to submit facts/) @configurer.run(catalog: @catalog) end it 'logs errors that occur during fact submission' do stub_request(:put, "https://puppet:8140/puppet/v3/facts/configurer.test?environment=production").to_return(status: 502) expect(Puppet).to receive(:log_exception).with(Puppet::HTTP::ResponseError, /^Failed to submit facts/) @configurer.run(catalog: @catalog) end it 'records time spent resubmitting facts' do report = Puppet::Transaction::Report.new stub_request(:put, "https://puppet:8140/puppet/v3/facts/configurer.test?environment=production"). with( body: hash_including({ "name" => "configurer.test", "values" => {"test_fact": "test value"}, }), headers: { 'Accept'=>acceptable_content_types_string, 'Content-Type'=>'application/json', }).to_return(status: 200) @configurer.run(catalog: @catalog, report: report) expect(report.metrics['time'].values).to include(["resubmit_facts", anything, Numeric]) end end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/integration/util_spec.rb
spec/integration/util_spec.rb
# coding: utf-8 require 'spec_helper' describe Puppet::Util do include PuppetSpec::Files describe "#replace_file on Windows", :if => Puppet::Util::Platform.windows? do it "replace_file should preserve original ACEs from existing replaced file on Windows" do file = tmpfile("somefile") FileUtils.touch(file) admins = 'S-1-5-32-544' dacl = Puppet::Util::Windows::AccessControlList.new dacl.allow(admins, Puppet::Util::Windows::File::FILE_ALL_ACCESS) protect = true expected_sd = Puppet::Util::Windows::SecurityDescriptor.new(admins, admins, dacl, protect) Puppet::Util::Windows::Security.set_security_descriptor(file, expected_sd) ignored_mode = 0644 Puppet::Util.replace_file(file, ignored_mode) do |temp_file| ignored_sd = Puppet::Util::Windows::Security.get_security_descriptor(temp_file.path) users = 'S-1-5-11' ignored_sd.dacl.allow(users, Puppet::Util::Windows::File::FILE_GENERIC_READ) Puppet::Util::Windows::Security.set_security_descriptor(temp_file.path, ignored_sd) end replaced_sd = Puppet::Util::Windows::Security.get_security_descriptor(file) expect(replaced_sd.dacl).to eq(expected_sd.dacl) end it "replace_file should use reasonable default ACEs on a new file on Windows" do dir = tmpdir('DACL_playground') protected_sd = Puppet::Util::Windows::Security.get_security_descriptor(dir) protected_sd.protect = true Puppet::Util::Windows::Security.set_security_descriptor(dir, protected_sd) sibling_path = File.join(dir, 'sibling_file') FileUtils.touch(sibling_path) expected_sd = Puppet::Util::Windows::Security.get_security_descriptor(sibling_path) new_file_path = File.join(dir, 'new_file') ignored_mode = nil Puppet::Util.replace_file(new_file_path, ignored_mode) { |tmp_file| } new_sd = Puppet::Util::Windows::Security.get_security_descriptor(new_file_path) expect(new_sd.dacl).to eq(expected_sd.dacl) end it "replace_file should work with filenames that include - and . (PUP-1389)" do expected_content = 'some content' dir = tmpdir('ReplaceFile_playground') destination_file = File.join(dir, 'some-file.xml') Puppet::Util.replace_file(destination_file, nil) do |temp_file| temp_file.open temp_file.write(expected_content) end actual_content = File.read(destination_file) expect(actual_content).to eq(expected_content) end it "replace_file should work with filenames that include special characters (PUP-1389)" do expected_content = 'some content' dir = tmpdir('ReplaceFile_playground') # http://www.fileformat.info/info/unicode/char/00e8/index.htm # dest_name = "somèfile.xml" dest_name = "som\u00E8file.xml" destination_file = File.join(dir, dest_name) Puppet::Util.replace_file(destination_file, nil) do |temp_file| temp_file.open temp_file.write(expected_content) end actual_content = File.read(destination_file) expect(actual_content).to eq(expected_content) end end describe "#which on Windows", :if => Puppet::Util::Platform.windows? do let (:rune_utf8) { "\u16A0\u16C7\u16BB\u16EB\u16D2\u16E6\u16A6\u16EB\u16A0\u16B1\u16A9\u16A0\u16A2\u16B1\u16EB\u16A0\u16C1\u16B1\u16AA\u16EB\u16B7\u16D6\u16BB\u16B9\u16E6\u16DA\u16B3\u16A2\u16D7" } let (:filename) { 'foo.exe' } it "should be able to use UTF8 characters in the path" do utf8 = tmpdir(rune_utf8) Puppet::FileSystem.mkpath(utf8) filepath = File.join(utf8, filename) Puppet::FileSystem.touch(filepath) path = [utf8, "c:\\windows\\system32", "c:\\windows"].join(File::PATH_SEPARATOR) Puppet::Util.withenv("PATH" => path) do expect(Puppet::Util.which(filename)).to eq(filepath) end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/integration/data_binding_spec.rb
spec/integration/data_binding_spec.rb
require 'spec_helper' require 'puppet/indirector/hiera' require 'puppet_spec/compiler' require 'puppet/indirector/data_binding/hiera' describe "Data binding" do include PuppetSpec::Files include PuppetSpec::Compiler let(:dir) { tmpdir("puppetdir") } let(:data) {{ 'global' => { 'testing::binding::value' => 'the value', 'testing::binding::calling_class' => '%{calling_class}', 'testing::binding::calling_class_path' => '%{calling_class_path}' } }} let(:hash_data) {{ 'global' => { 'testing::hash::options' => { 'key' => 'value', 'port' => '80', 'bind' => 'localhost' } }, 'agent.example.com' => { 'testing::hash::options' => { 'key' => 'new value', 'port' => '443' } } }} let(:hash_data_with_lopts) {{ 'global' => { 'testing::hash::options' => { 'key' => 'value', 'port' => '80', 'bind' => 'localhost' } }, 'agent.example.com' => { 'lookup_options' => { 'testing::hash::options' => { 'merge' => 'deep' } }, 'testing::hash::options' => { 'key' => 'new value', 'port' => '443' } } }} before do # Drop all occurances of cached hiera instances. This will reset @hiera in Puppet::Indirector::Hiera, Testing::DataBinding::Hiera, # and Puppet::DataBinding::Hiera. Different classes are active as indirection depending on configuration ObjectSpace.each_object(Class).select {|klass| klass <= Puppet::Indirector::Hiera }.each { |klass| klass.instance_variable_set(:@hiera, nil) } Puppet[:data_binding_terminus] = 'hiera' Puppet[:modulepath] = dir end context "with testing::binding and global data only" do it "looks up global data from hiera" do configure_hiera_for_one_tier(data) create_manifest_in_module("testing", "binding.pp", <<-MANIFEST) class testing::binding($value, $calling_class, $calling_class_path, $calling_module = $module_name) {} MANIFEST catalog = compile_to_catalog("include testing::binding") resource = catalog.resource('Class[testing::binding]') expect(resource[:value]).to eq("the value") expect(resource[:calling_class]).to eq("testing::binding") expect(resource[:calling_class_path]).to eq("testing/binding") expect(resource[:calling_module]).to eq("testing") end end context "with testing::hash and global data only" do it "looks up global data from hiera" do configure_hiera_for_one_tier(hash_data) create_manifest_in_module("testing", "hash.pp", <<-MANIFEST) class testing::hash($options) {} MANIFEST catalog = compile_to_catalog("include testing::hash") resource = catalog.resource('Class[testing::hash]') expect(resource[:options]).to eq({ 'key' => 'value', 'port' => '80', 'bind' => 'localhost' }) end end context "with custom clientcert" do it "merges global data with agent.example.com data from hiera" do configure_hiera_for_two_tier(hash_data) create_manifest_in_module("testing", "hash.pp", <<-MANIFEST) class testing::hash($options) {} MANIFEST catalog = compile_to_catalog("include testing::hash") resource = catalog.resource('Class[testing::hash]') expect(resource[:options]).to eq({ 'key' => 'new value', 'port' => '443', }) end end context "with custom clientcert and with lookup_options" do it "merges global data with agent.example.com data from hiera" do configure_hiera_for_two_tier(hash_data_with_lopts) create_manifest_in_module("testing", "hash.pp", <<-MANIFEST) class testing::hash($options) {} MANIFEST catalog = compile_to_catalog("include testing::hash") resource = catalog.resource('Class[testing::hash]') expect(resource[:options]).to eq({ 'key' => 'new value', 'port' => '443', 'bind' => 'localhost', }) end end context "with plan_hierarchy key" do context "using Hiera 5" do let(:hiera_config) { <<~CONF } --- version: 5 plan_hierarchy: - path: global name: Common CONF it "ignores plan_hierarchy outside of a Bolt plan" do configure_hiera_for_plan_hierarchy(data, hiera_config) create_manifest_in_module("testing", "binding.pp", <<-MANIFEST) class testing::binding($value) {} MANIFEST expect { compile_to_catalog("include testing::binding") } .to raise_error(/Class\[Testing::Binding\]: expects a value for parameter 'value'/) end end context "with invalid data" do let(:hiera_config) { <<~CONF } --- version: 5 plan_hierarchy: - pop: the question CONF it "raises a validation error" do configure_hiera_for_plan_hierarchy(data, hiera_config) create_manifest_in_module("testing", "binding.pp", <<-MANIFEST) class testing::binding($value) {} MANIFEST expect { compile_to_catalog("include testing::binding") } .to raise_error(/entry 'plan_hierarchy' index 0 unrecognized key 'pop'/) end end context "with Hiera 3" do let(:hiera_config) { <<~CONF } --- plan_hierarchy: ['global'] CONF it "errors with plan_hierarchy key" do configure_hiera_for_plan_hierarchy(data, hiera_config) create_manifest_in_module("testing", "binding.pp", <<-MANIFEST) class testing::binding($value) {} MANIFEST expect { compile_to_catalog("include testing::binding") } .to raise_error(/unrecognized key 'plan_hierarchy'/) end end end def configure_hiera_for_one_tier(data) hiera_config_file = tmpfile("hiera.yaml") File.open(hiera_config_file, 'w:UTF-8') do |f| f.write("--- :yaml: :datadir: #{dir} :hierarchy: ['global'] :logger: 'noop' :backends: ['yaml'] ") end data.each do | file, contents | File.open(File.join(dir, "#{file}.yaml"), 'w:UTF-8') do |f| f.write(YAML.dump(contents)) end end Puppet[:hiera_config] = hiera_config_file end def configure_hiera_for_plan_hierarchy(data, config) hiera_config_file = tmpfile("hiera.yaml") File.open(hiera_config_file, 'w:UTF-8') do |f| f.write(config) end data.each do | file, contents | File.open(File.join(dir, "#{file}.yaml"), 'w:UTF-8') do |f| f.write(YAML.dump(contents)) end end Puppet[:hiera_config] = hiera_config_file end def configure_hiera_for_two_tier(data) hiera_config_file = tmpfile("hiera.yaml") File.open(hiera_config_file, 'w:UTF-8') do |f| f.write("--- :yaml: :datadir: #{dir} :hierarchy: ['agent.example.com', 'global'] :logger: 'noop' :backends: ['yaml'] ") end data.each do | file, contents | File.open(File.join(dir, "#{file}.yaml"), 'w:UTF-8') do |f| f.write(YAML.dump(contents)) end end Puppet[:hiera_config] = hiera_config_file end def create_manifest_in_module(module_name, name, manifest) module_dir = File.join(dir, module_name, 'manifests') FileUtils.mkdir_p(module_dir) File.open(File.join(module_dir, name), 'w:UTF-8') do |f| f.write(manifest) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/integration/transaction_spec.rb
spec/integration/transaction_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'puppet/transaction' Puppet::Type.newtype(:devicetype) do apply_to_device newparam(:name) end describe Puppet::Transaction do include PuppetSpec::Files include PuppetSpec::Compiler before do allow(Puppet::Util::Storage).to receive(:store) end def mk_catalog(*resources) catalog = Puppet::Resource::Catalog.new(Puppet::Node.new("mynode")) resources.each { |res| catalog.add_resource res } catalog end def touch_path Puppet.features.microsoft_windows? ? "#{ENV['windir']}\\system32" : "/usr/bin:/bin" end def usr_bin_touch(path) Puppet.features.microsoft_windows? ? "#{ENV['windir']}\\system32\\cmd.exe /c \"type NUL >> \"#{path}\"\"" : "/usr/bin/touch #{path}" end def touch(path) Puppet.features.microsoft_windows? ? "cmd.exe /c \"type NUL >> \"#{path}\"\"" : "touch #{path}" end it "should not apply generated resources if the parent resource fails" do catalog = Puppet::Resource::Catalog.new resource = Puppet::Type.type(:file).new :path => make_absolute("/foo/bar"), :backup => false catalog.add_resource resource child_resource = Puppet::Type.type(:file).new :path => make_absolute("/foo/bar/baz"), :backup => false expect(resource).to receive(:eval_generate).and_return([child_resource]) transaction = Puppet::Transaction.new(catalog, nil, Puppet::Graph::SequentialPrioritizer.new) expect(resource).to receive(:retrieve).and_raise("this is a failure") allow(resource).to receive(:err) expect(child_resource).not_to receive(:retrieve) transaction.evaluate end it "should not apply virtual resources" do catalog = Puppet::Resource::Catalog.new resource = Puppet::Type.type(:file).new :path => make_absolute("/foo/bar"), :backup => false resource.virtual = true catalog.add_resource resource transaction = Puppet::Transaction.new(catalog, nil, Puppet::Graph::SequentialPrioritizer.new) expect(resource).not_to receive(:retrieve) transaction.evaluate end it "should apply exported resources" do catalog = Puppet::Resource::Catalog.new path = tmpfile("exported_files") resource = Puppet::Type.type(:file).new :path => path, :backup => false, :ensure => :file resource.exported = true catalog.add_resource resource catalog.apply expect(Puppet::FileSystem.exist?(path)).to be_truthy end it "should not apply virtual exported resources" do catalog = Puppet::Resource::Catalog.new resource = Puppet::Type.type(:file).new :path => make_absolute("/foo/bar"), :backup => false resource.exported = true resource.virtual = true catalog.add_resource resource transaction = Puppet::Transaction.new(catalog, nil, Puppet::Graph::SequentialPrioritizer.new) expect(resource).not_to receive(:retrieve) transaction.evaluate end it "should not apply device resources on normal host" do catalog = Puppet::Resource::Catalog.new resource = Puppet::Type.type(:devicetype).new :name => "FastEthernet 0/1" catalog.add_resource resource transaction = Puppet::Transaction.new(catalog, nil, Puppet::Graph::SequentialPrioritizer.new) transaction.for_network_device = false expect(transaction).not_to receive(:apply).with(resource, nil) transaction.evaluate expect(transaction.resource_status(resource)).to be_skipped end it "should not apply host resources on device" do catalog = Puppet::Resource::Catalog.new resource = Puppet::Type.type(:file).new :path => make_absolute("/foo/bar"), :backup => false catalog.add_resource resource transaction = Puppet::Transaction.new(catalog, nil, Puppet::Graph::SequentialPrioritizer.new) transaction.for_network_device = true expect(transaction).not_to receive(:apply).with(resource, nil) transaction.evaluate expect(transaction.resource_status(resource)).to be_skipped end it "should apply device resources on device" do catalog = Puppet::Resource::Catalog.new resource = Puppet::Type.type(:devicetype).new :name => "FastEthernet 0/1" catalog.add_resource resource transaction = Puppet::Transaction.new(catalog, nil, Puppet::Graph::SequentialPrioritizer.new) transaction.for_network_device = true expect(transaction).to receive(:apply).with(resource, nil) transaction.evaluate expect(transaction.resource_status(resource)).not_to be_skipped end it "should apply resources appliable on host and device on a device" do catalog = Puppet::Resource::Catalog.new resource = Puppet::Type.type(:schedule).new :name => "test" catalog.add_resource resource transaction = Puppet::Transaction.new(catalog, nil, Puppet::Graph::SequentialPrioritizer.new) transaction.for_network_device = true expect(transaction).to receive(:apply).with(resource, nil) transaction.evaluate expect(transaction.resource_status(resource)).not_to be_skipped end # Verify that one component requiring another causes the contained # resources in the requiring component to get refreshed. it "should propagate events from a contained resource through its container to its dependent container's contained resources" do file = Puppet::Type.type(:file).new :path => tmpfile("event_propagation"), :ensure => :present execfile = File.join(tmpdir("exec_event"), "exectestingness2") exec = Puppet::Type.type(:exec).new :command => touch(execfile), :path => ENV['PATH'] catalog = mk_catalog(file) fcomp = Puppet::Type.type(:component).new(:name => "Foo[file]") catalog.add_resource fcomp catalog.add_edge(fcomp, file) ecomp = Puppet::Type.type(:component).new(:name => "Foo[exec]") catalog.add_resource ecomp catalog.add_resource exec catalog.add_edge(ecomp, exec) ecomp[:subscribe] = Puppet::Resource.new(:foo, "file") exec[:refreshonly] = true expect(exec).to receive(:refresh) catalog.apply end # Make sure that multiple subscriptions get triggered. it "should propagate events to all dependent resources", :unless => RUBY_PLATFORM == 'java' do path = tmpfile("path") file1 = tmpfile("file1") file2 = tmpfile("file2") file = Puppet::Type.type(:file).new( :path => path, :ensure => "file" ) exec1 = Puppet::Type.type(:exec).new( :path => ENV["PATH"], :command => touch(file1), :refreshonly => true, :subscribe => Puppet::Resource.new(:file, path) ) exec2 = Puppet::Type.type(:exec).new( :path => ENV["PATH"], :command => touch(file2), :refreshonly => true, :subscribe => Puppet::Resource.new(:file, path) ) catalog = mk_catalog(file, exec1, exec2) catalog.apply expect(Puppet::FileSystem.exist?(file1)).to be_truthy expect(Puppet::FileSystem.exist?(file2)).to be_truthy end it "does not refresh resources that have 'noop => true'" do path = tmpfile("path") notify = Puppet::Type.type(:notify).new( :name => "trigger", :notify => Puppet::Resource.new(:exec, "noop exec") ) noop_exec = Puppet::Type.type(:exec).new( :name => "noop exec", :path => ENV["PATH"], :command => touch(path), :noop => true ) catalog = mk_catalog(notify, noop_exec) catalog.apply expect(Puppet::FileSystem.exist?(path)).to be_falsey end it "should apply no resources whatsoever if a pre_run_check fails" do path = tmpfile("path") file = Puppet::Type.type(:file).new( :path => path, :ensure => "file" ) notify = Puppet::Type.type(:notify).new( :title => "foo" ) expect(notify).to receive(:pre_run_check).and_raise(Puppet::Error, "fail for testing") catalog = mk_catalog(file, notify) expect { catalog.apply }.to raise_error(Puppet::Error, /Some pre-run checks failed/) expect(Puppet::FileSystem.exist?(path)).not_to be_truthy end it "one failed refresh should propagate its failure to dependent refreshes", :unless => RUBY_PLATFORM == 'java' do path = tmpfile("path") newfile = tmpfile("file") file = Puppet::Type.type(:file).new( :path => path, :ensure => "file" ) exec1 = Puppet::Type.type(:exec).new( :path => ENV["PATH"], :command => touch(File.expand_path("/this/cannot/possibly/exist")), :logoutput => true, :refreshonly => true, :subscribe => file, :title => "one" ) exec2 = Puppet::Type.type(:exec).new( :path => ENV["PATH"], :command => touch(newfile), :logoutput => true, :refreshonly => true, :subscribe => [file, exec1], :title => "two" ) allow(exec1).to receive(:err) catalog = mk_catalog(file, exec1, exec2) catalog.apply expect(Puppet::FileSystem.exist?(newfile)).to be_falsey end # Ensure when resources have been generated with eval_generate that event # propagation still works when filtering with tags context "when filtering with tags", :unless => RUBY_PLATFORM == 'java' do context "when resources are dependent on dynamically generated resources" do it "should trigger (only) appropriately tagged dependent resources" do source = dir_containing('sourcedir', {'foo' => 'bar'}) target = tmpdir('targetdir') file1 = tmpfile("file1") file2 = tmpfile("file2") file = Puppet::Type.type(:file).new( :path => target, :source => source, :ensure => :present, :recurse => true, :tag => "foo_tag", ) exec1 = Puppet::Type.type(:exec).new( :path => ENV["PATH"], :command => touch(file1), :refreshonly => true, :subscribe => file, :tag => "foo_tag", ) exec2 = Puppet::Type.type(:exec).new( :path => ENV["PATH"], :command => touch(file2), :refreshonly => true, :subscribe => file, ) Puppet[:tags] = "foo_tag" catalog = mk_catalog(file, exec1, exec2) catalog.apply expect(Puppet::FileSystem.exist?(file1)).to be_truthy expect(Puppet::FileSystem.exist?(file2)).to be_falsey end it "should trigger implicitly tagged dependent resources, ie via type name" do file1 = tmpfile("file1") file2 = tmpfile("file2") expect(Puppet::FileSystem).to_not be_exist(file2) exec1 = Puppet::Type.type(:exec).new( :name => "exec1", :path => ENV["PATH"], :command => touch(file1), ) exec2 = Puppet::Type.type(:exec).new( :name => "exec2", :path => ENV["PATH"], :command => touch(file2), :refreshonly => true, :subscribe => exec1, ) Puppet[:tags] = "exec" catalog = mk_catalog(exec1, exec2) catalog.apply expect(Puppet::FileSystem.exist?(file1)).to be_truthy expect(Puppet::FileSystem.exist?(file2)).to be_truthy end end it "should propagate events correctly from a tagged container when running with tags" do file1 = tmpfile("original_tag") file2 = tmpfile("tag_propagation") command1 = usr_bin_touch(file1) command2 = usr_bin_touch(file2) manifest = <<-"MANIFEST" class foo { exec { 'notify test': command => '#{command1}', refreshonly => true, } } class test { include foo exec { 'test': command => '#{command2}', notify => Class['foo'], } } include test MANIFEST Puppet[:tags] = 'test' apply_compiled_manifest(manifest) expect(Puppet::FileSystem.exist?(file1)).to be_truthy expect(Puppet::FileSystem.exist?(file2)).to be_truthy end end describe "skipping resources" do let(:fname) { tmpfile("exec") } let(:file) do Puppet::Type.type(:file).new( :name => tmpfile("file"), :ensure => "file", :backup => false ) end let(:exec) do Puppet::Type.type(:exec).new( :name => touch(fname), :path => touch_path, :subscribe => Puppet::Resource.new("file", file.name) ) end it "does not trigger unscheduled resources", :unless => RUBY_PLATFORM == 'java' do catalog = mk_catalog catalog.add_resource(*Puppet::Type.type(:schedule).mkdefaultschedules) Puppet[:ignoreschedules] = false exec[:schedule] = "monthly" catalog.add_resource(file, exec) # Run it once so further runs don't schedule the resource catalog.apply expect(Puppet::FileSystem.exist?(fname)).to be_truthy # Now remove it, so it can get created again Puppet::FileSystem.unlink(fname) file[:content] = "some content" catalog.apply expect(Puppet::FileSystem.exist?(fname)).to be_falsey end it "does not trigger untagged resources" do catalog = mk_catalog Puppet[:tags] = "runonly" file.tag("runonly") catalog.add_resource(file, exec) catalog.apply expect(Puppet::FileSystem.exist?(fname)).to be_falsey end it "does not trigger skip-tagged resources" do catalog = mk_catalog Puppet[:skip_tags] = "skipme" exec.tag("skipme") catalog.add_resource(file, exec) catalog.apply expect(Puppet::FileSystem.exist?(fname)).to be_falsey end it "does not trigger resources with failed dependencies" do catalog = mk_catalog file[:path] = make_absolute("/foo/bar/baz") catalog.add_resource(file, exec) catalog.apply expect(Puppet::FileSystem.exist?(fname)).to be_falsey end end it "should not attempt to evaluate resources with failed dependencies", :unless => RUBY_PLATFORM == 'java' do exec = Puppet::Type.type(:exec).new( :command => "#{File.expand_path('/bin/mkdir')} /this/path/cannot/possibly/exist", :title => "mkdir" ) file1 = Puppet::Type.type(:file).new( :title => "file1", :path => tmpfile("file1"), :require => exec, :ensure => :file ) file2 = Puppet::Type.type(:file).new( :title => "file2", :path => tmpfile("file2"), :require => file1, :ensure => :file ) catalog = mk_catalog(exec, file1, file2) transaction = catalog.apply expect(Puppet::FileSystem.exist?(file1[:path])).to be_falsey expect(Puppet::FileSystem.exist?(file2[:path])).to be_falsey expect(transaction.resource_status(file1).skipped).to be_truthy expect(transaction.resource_status(file2).skipped).to be_truthy expect(transaction.resource_status(file1).failed_dependencies).to eq([exec]) expect(transaction.resource_status(file2).failed_dependencies).to eq([exec]) end it "on failure, skips dynamically-generated dependents", :unless => RUBY_PLATFORM == 'java' do exec = Puppet::Type.type(:exec).new( :command => "#{File.expand_path('/bin/mkdir')} /this/path/cannot/possibly/exist", :title => "mkdir" ) tmp = tmpfile("dir1") FileUtils.mkdir_p(tmp) FileUtils.mkdir_p(File.join(tmp, "foo")) purge_dir = Puppet::Type.type(:file).new( :title => "dir1", :path => tmp, :require => exec, :ensure => :directory, :recurse => true, :purge => true ) catalog = mk_catalog(exec, purge_dir) txn = catalog.apply expect(txn.resource_status(purge_dir).skipped).to be_truthy children = catalog.relationship_graph.direct_dependents_of(purge_dir) children.each do |child| expect(txn.resource_status(child).skipped).to be_truthy end expect(Puppet::FileSystem.exist?(File.join(tmp, "foo"))).to be_truthy end it "should not trigger subscribing resources on failure", :unless => RUBY_PLATFORM == 'java' do file1 = tmpfile("file1") file2 = tmpfile("file2") create_file1 = Puppet::Type.type(:exec).new( :command => usr_bin_touch(file1) ) exec = Puppet::Type.type(:exec).new( :command => "#{File.expand_path('/bin/mkdir')} /this/path/cannot/possibly/exist", :title => "mkdir", :notify => create_file1 ) create_file2 = Puppet::Type.type(:exec).new( :command => usr_bin_touch(file2), :subscribe => exec ) catalog = mk_catalog(exec, create_file1, create_file2) catalog.apply expect(Puppet::FileSystem.exist?(file1)).to be_falsey expect(Puppet::FileSystem.exist?(file2)).to be_falsey end # #801 -- resources only checked in noop should be rescheduled immediately. it "should immediately reschedule noop resources" do Puppet::Type.type(:schedule).mkdefaultschedules resource = Puppet::Type.type(:notify).new(:name => "mymessage", :noop => true) catalog = Puppet::Resource::Catalog.new catalog.add_resource resource trans = catalog.apply expect(trans.resource_harness).to be_scheduled(resource) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/integration/defaults_spec.rb
spec/integration/defaults_spec.rb
require 'spec_helper' require 'puppet/defaults' describe "Puppet defaults" do describe "when default_manifest is set" do it "returns ./manifests by default" do expect(Puppet[:default_manifest]).to eq('./manifests') end end describe "when disable_per_environment_manifest is set" do it "returns false by default" do expect(Puppet[:disable_per_environment_manifest]).to eq(false) end it "errors when set to true and default_manifest is not an absolute path" do expect { Puppet[:default_manifest] = './some/relative/manifest.pp' Puppet[:disable_per_environment_manifest] = true }.to raise_error Puppet::Settings::ValidationError, /'default_manifest' setting must be.*absolute/ end end describe "when setting the :masterport" do it "should also set :serverport to the same value" do Puppet.settings[:masterport] = 3939 expect(Puppet.settings[:serverport]).to eq(3939) end it "should not overwrite :serverport if explicitly set" do Puppet.settings[:serverport] = 9000 Puppet.settings[:masterport] = 9001 expect(Puppet.settings[:serverport]).to eq(9000) end end describe "when setting the :factpath" do it "should add the :factpath to Facter's search paths" do expect(Facter).to receive(:search).with("/my/fact/path") Puppet.settings[:factpath] = "/my/fact/path" end end describe "when setting the :certname" do it "should fail if the certname is not downcased" do expect { Puppet.settings[:certname] = "Host.Domain.Com" }.to raise_error(ArgumentError) end it 'can set it to a value containing all digits' do Puppet.settings[:certname] = "000000000180" expect(Puppet.settings[:certname]).to eq("000000000180") end end describe "when setting :node_name_value" do it "should default to the value of :certname" do Puppet.settings[:certname] = 'blargle' expect(Puppet.settings[:node_name_value]).to eq('blargle') end end describe "when setting the :node_name_fact" do it "should fail when also setting :node_name_value" do expect do Puppet.settings[:node_name_value] = "some value" Puppet.settings[:node_name_fact] = "some_fact" end.to raise_error("Cannot specify both the node_name_value and node_name_fact settings") end it "should not fail when using the default for :node_name_value" do expect do Puppet.settings[:node_name_fact] = "some_fact" end.not_to raise_error end end it "should have a clientyamldir setting" do expect(Puppet.settings[:clientyamldir]).not_to be_nil end it "should have different values for the yamldir and clientyamldir" do expect(Puppet.settings[:yamldir]).not_to eq(Puppet.settings[:clientyamldir]) end it "should have a client_datadir setting" do expect(Puppet.settings[:client_datadir]).not_to be_nil end it "should have different values for the server_datadir and client_datadir" do expect(Puppet.settings[:server_datadir]).not_to eq(Puppet.settings[:client_datadir]) end # See #1232 it "should not specify a user or group for the clientyamldir" do expect(Puppet.settings.setting(:clientyamldir).owner).to be_nil expect(Puppet.settings.setting(:clientyamldir).group).to be_nil end it "should use the service user and group for the yamldir" do allow(Puppet.settings).to receive(:service_user_available?).and_return(true) allow(Puppet.settings).to receive(:service_group_available?).and_return(true) expect(Puppet.settings.setting(:yamldir).owner).to eq(Puppet.settings[:user]) expect(Puppet.settings.setting(:yamldir).group).to eq(Puppet.settings[:group]) end it "should specify that the host private key should be owned by the service user" do allow(Puppet.settings).to receive(:service_user_available?).and_return(true) expect(Puppet.settings.setting(:hostprivkey).owner).to eq(Puppet.settings[:user]) end it "should specify that the host certificate should be owned by the service user" do allow(Puppet.settings).to receive(:service_user_available?).and_return(true) expect(Puppet.settings.setting(:hostcert).owner).to eq(Puppet.settings[:user]) end [:modulepath, :factpath].each do |setting| it "should configure '#{setting}' not to be a file setting, so multi-directory settings are acceptable" do expect(Puppet.settings.setting(setting)).to be_instance_of(Puppet::Settings::PathSetting) end end describe "on a Unix-like platform it", :if => Puppet.features.posix? do it "should add /usr/sbin and /sbin to the path if they're not there" do Puppet::Util.withenv("PATH" => "/usr/bin#{File::PATH_SEPARATOR}/usr/local/bin") do Puppet.settings[:path] = "none" # this causes it to ignore the setting expect(ENV["PATH"].split(File::PATH_SEPARATOR)).to be_include("/usr/sbin") expect(ENV["PATH"].split(File::PATH_SEPARATOR)).to be_include("/sbin") end end end describe "on a Windows-like platform it", :if => Puppet::Util::Platform.windows? do let (:rune_utf8) { "\u16A0\u16C7\u16BB\u16EB\u16D2\u16E6\u16A6\u16EB\u16A0\u16B1\u16A9\u16A0\u16A2\u16B1\u16EB\u16A0\u16C1\u16B1\u16AA\u16EB\u16B7\u16D6\u16BB\u16B9\u16E6\u16DA\u16B3\u16A2\u16D7" } it "path should not add anything" do path = "c:\\windows\\system32#{File::PATH_SEPARATOR}c:\\windows" Puppet::Util.withenv("PATH" => path) do Puppet.settings[:path] = "none" # this causes it to ignore the setting expect(ENV["PATH"]).to eq(path) end end it "path should support UTF8 characters" do path = "c:\\windows\\system32#{File::PATH_SEPARATOR}c:\\windows#{File::PATH_SEPARATOR}C:\\" + rune_utf8 Puppet::Util.withenv("PATH" => path) do Puppet.settings[:path] = "none" # this causes it to ignore the setting expect(ENV['Path']).to eq(path) end end end it "should default to json for the preferred serialization format" do expect(Puppet.settings.value(:preferred_serialization_format)).to eq("json") end it "should default to true the disable_i18n setting" do expect(Puppet.settings.value(:disable_i18n)).to eq(true) end it "should have a setting for determining the configuration version and should default to an empty string" do expect(Puppet.settings[:config_version]).to eq("") end describe "when enabling reports" do it "should use the default server value when report server is unspecified" do Puppet.settings[:server] = "server" expect(Puppet.settings[:report_server]).to eq("server") end it "should use the default serverport value when report port is unspecified" do Puppet.settings[:serverport] = "1234" expect(Puppet.settings[:report_port]).to eq(1234) end it "should use the default masterport value when report port is unspecified" do Puppet.settings[:masterport] = "1234" expect(Puppet.settings[:report_port]).to eq(1234) end it "should use report_port when set" do Puppet.settings[:serverport] = "1234" Puppet.settings[:report_port] = "5678" expect(Puppet.settings[:report_port]).to eq(5678) end end it "should have a 'prerun_command' that defaults to the empty string" do expect(Puppet.settings[:prerun_command]).to eq("") end it "should have a 'postrun_command' that defaults to the empty string" do expect(Puppet.settings[:postrun_command]).to eq("") end it "should have a 'certificate_revocation' setting that defaults to true" do expect(Puppet.settings[:certificate_revocation]).to be_truthy end describe "reportdir" do subject { Puppet.settings[:reportdir] } it { is_expected.to eq("#{Puppet[:vardir]}/reports") } end describe "reporturl" do subject { Puppet.settings[:reporturl] } it { is_expected.to eq("http://localhost:3000/reports/upload") } end describe "when configuring color" do subject { Puppet.settings[:color] } it { is_expected.to eq("ansi") } end describe "daemonize" do it "should default to true", :unless => Puppet::Util::Platform.windows? do expect(Puppet.settings[:daemonize]).to eq(true) end describe "on Windows", :if => Puppet::Util::Platform.windows? do it "should default to false" do expect(Puppet.settings[:daemonize]).to eq(false) end it "should raise an error if set to true" do expect { Puppet.settings[:daemonize] = true }.to raise_error(/Cannot daemonize on Windows/) end end end describe "diff" do it "should default to 'diff' on POSIX", :unless => Puppet::Util::Platform.windows? do expect(Puppet.settings[:diff]).to eq('diff') end it "should default to '' on Windows", :if => Puppet::Util::Platform.windows? do expect(Puppet.settings[:diff]).to eq('') end end describe "when configuring hiera" do it "should have a hiera_config setting" do expect(Puppet.settings[:hiera_config]).not_to be_nil end end describe "when configuring the data_binding terminus" do it "should have a data_binding_terminus setting" do expect(Puppet.settings[:data_binding_terminus]).not_to be_nil end it "should be set to hiera by default" do expect(Puppet.settings[:data_binding_terminus]).to eq(:hiera) end it "to be neither 'hiera' nor 'none', a deprecation warning is logged" do expect(@logs).to eql([]) Puppet[:data_binding_terminus] = 'magic' expect(@logs[0].to_s).to match(/Setting 'data_binding_terminus' is deprecated/) end it "to not log a warning if set to 'none' or 'hiera'" do expect(@logs).to eql([]) Puppet[:data_binding_terminus] = 'none' Puppet[:data_binding_terminus] = 'hiera' expect(@logs).to eql([]) end end describe "agent_catalog_run_lockfile" do it "(#2888) is not a file setting so it is absent from the Settings catalog" do expect(Puppet.settings.setting(:agent_catalog_run_lockfile)).not_to be_a_kind_of Puppet::Settings::FileSetting expect(Puppet.settings.setting(:agent_catalog_run_lockfile)).to be_a Puppet::Settings::StringSetting end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/integration/node_spec.rb
spec/integration/node_spec.rb
require 'spec_helper' require 'puppet/node' describe Puppet::Node do describe "when delegating indirection calls" do before do Puppet::Node.indirection.reset_terminus_class Puppet::Node.indirection.cache_class = nil @name = "me" @node = Puppet::Node.new(@name) end it "should be able to use the yaml terminus" do allow(Puppet::Node.indirection).to receive(:terminus_class).and_return(:yaml) # Load now, before we stub the exists? method. terminus = Puppet::Node.indirection.terminus(:yaml) expect(terminus).to receive(:path).with(@name).and_return("/my/yaml/file") expect(Puppet::FileSystem).to receive(:exist?).with("/my/yaml/file").and_return(false) expect(Puppet::Node.indirection.find(@name)).to be_nil end it "should be able to use the plain terminus" do allow(Puppet::Node.indirection).to receive(:terminus_class).and_return(:plain) # Load now, before we stub the exists? method. Puppet::Node.indirection.terminus(:plain) expect(Puppet::Node).to receive(:new).with(@name).and_return(@node) expect(Puppet::Node.indirection.find(@name)).to equal(@node) end describe "and using the memory terminus" do before do @name = "me" @terminus = Puppet::Node.indirection.terminus(:memory) allow(Puppet::Node.indirection).to receive(:terminus).and_return(@terminus) @node = Puppet::Node.new(@name) end after do @terminus.instance_variable_set(:@instances, {}) end it "should find no nodes by default" do expect(Puppet::Node.indirection.find(@name)).to be_nil end it "should be able to find nodes that were previously saved" do Puppet::Node.indirection.save(@node) expect(Puppet::Node.indirection.find(@name)).to equal(@node) end it "should replace existing saved nodes when a new node with the same name is saved" do Puppet::Node.indirection.save(@node) two = Puppet::Node.new(@name) Puppet::Node.indirection.save(two) expect(Puppet::Node.indirection.find(@name)).to equal(two) end it "should be able to remove previously saved nodes" do Puppet::Node.indirection.save(@node) Puppet::Node.indirection.destroy(@node.name) expect(Puppet::Node.indirection.find(@name)).to be_nil end it "should fail when asked to destroy a node that does not exist" do expect { Puppet::Node.indirection.destroy(@node) }.to raise_error(ArgumentError) end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/integration/util/autoload_spec.rb
spec/integration/util/autoload_spec.rb
require 'spec_helper' require 'puppet/util/autoload' require 'fileutils' class AutoloadIntegrator @things = [] def self.newthing(name) @things << name end def self.thing?(name) @things.include? name end def self.clear @things.clear end end require 'puppet_spec/files' describe Puppet::Util::Autoload do include PuppetSpec::Files let(:env) { Puppet::Node::Environment.create(:foo, []) } def with_file(name, *path) path = File.join(*path) # Now create a file to load File.open(path, "w") { |f| f.puts "\nAutoloadIntegrator.newthing(:#{name.to_s})\n" } yield File.delete(path) end def with_loader(name, path) dir = tmpfile(name + path) $LOAD_PATH << dir Dir.mkdir(dir) rbdir = File.join(dir, path.to_s) Dir.mkdir(rbdir) loader = Puppet::Util::Autoload.new(name, path) yield rbdir, loader Dir.rmdir(rbdir) Dir.rmdir(dir) $LOAD_PATH.pop AutoloadIntegrator.clear end it "should not fail when asked to load a missing file" do expect(Puppet::Util::Autoload.new("foo", "bar").load(:eh, env)).to be_falsey end it "should load and return true when it successfully loads a file" do with_loader("foo", "bar") { |dir,loader| with_file(:mything, dir, "mything.rb") { expect(loader.load(:mything, env)).to be_truthy expect(loader.class).to be_loaded("bar/mything") expect(AutoloadIntegrator).to be_thing(:mything) } } end it "should consider a file loaded when asked for the name without an extension" do with_loader("foo", "bar") { |dir,loader| with_file(:noext, dir, "noext.rb") { loader.load(:noext, env) expect(loader.class).to be_loaded("bar/noext") } } end it "should consider a file loaded when asked for the name with an extension" do with_loader("foo", "bar") { |dir,loader| with_file(:noext, dir, "withext.rb") { loader.load(:withext, env) expect(loader.class).to be_loaded("bar/withext.rb") } } end it "should be able to load files directly from modules" do ## modulepath can't be used until after app settings are initialized, so we need to simulate that: expect(Puppet.settings).to receive(:app_defaults_initialized?).and_return(true).at_least(:once) modulepath = tmpfile("autoload_module_testing") libdir = File.join(modulepath, "mymod", "lib", "foo") FileUtils.mkdir_p(libdir) file = File.join(libdir, "plugin.rb") env = Puppet::Node::Environment.create(:production, [modulepath]) Puppet.override(:environments => Puppet::Environments::Static.new(env)) do with_loader("foo", "foo") do |dir, loader| with_file(:plugin, file.split("/")) do loader.load(:plugin, env) expect(loader.class).to be_loaded("foo/plugin.rb") end end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/integration/util/settings_spec.rb
spec/integration/util/settings_spec.rb
require 'spec_helper' require 'puppet_spec/files' describe Puppet::Settings do include PuppetSpec::Files def minimal_default_settings { :noop => {:default => false, :desc => "noop"} } end def define_settings(section, settings_hash) settings.define_settings(section, minimal_default_settings.update(settings_hash)) end let(:settings) { Puppet::Settings.new } it "should be able to make needed directories" do define_settings(:main, :maindir => { :default => tmpfile("main"), :type => :directory, :desc => "a", } ) settings.use(:main) expect(File.directory?(settings[:maindir])).to be_truthy end it "should make its directories with the correct modes" do Puppet[:manage_internal_file_permissions] = true define_settings(:main, :maindir => { :default => tmpfile("main"), :type => :directory, :desc => "a", :mode => 0750 } ) settings.use(:main) expect(Puppet::FileSystem.stat(settings[:maindir]).mode & 007777).to eq(0750) end it "will properly parse a UTF-8 configuration file" do rune_utf8 = "\u16A0\u16C7\u16BB" # ᚠᛇᚻ config = tmpfile("config") define_settings(:main, :config => { :type => :file, :default => config, :desc => "a" }, :environment => { :default => 'dingos', :desc => 'test', } ) File.open(config, 'w') do |file| file.puts <<-EOF [main] environment=#{rune_utf8} EOF end settings.initialize_global_settings expect(settings[:environment]).to eq(rune_utf8) end it "reparses configuration if configuration file is touched", :if => !Puppet::Util::Platform.windows? do config = tmpfile("config") define_settings(:main, :config => { :type => :file, :default => config, :desc => "a" }, :environment => { :default => 'dingos', :desc => 'test', } ) Puppet[:filetimeout] = '1s' File.open(config, 'w') do |file| file.puts <<-EOF [main] environment=toast EOF end settings.initialize_global_settings expect(settings[:environment]).to eq('toast') # First reparse establishes WatchedFiles settings.reparse_config_files sleep 1 File.open(config, 'w') do |file| file.puts <<-EOF [main] environment=bacon EOF end # Second reparse if later than filetimeout, reparses if changed settings.reparse_config_files expect(settings[:environment]).to eq('bacon') end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/integration/util/execution_spec.rb
spec/integration/util/execution_spec.rb
require 'spec_helper' describe Puppet::Util::Execution, unless: Puppet::Util::Platform.jruby? do include PuppetSpec::Files describe "#execpipe" do it "should set LANG to C avoid localized output", :if => !Puppet::Util::Platform.windows? do out = "" Puppet::Util::Execution.execpipe('echo $LANG'){ |line| out << line.read.chomp } expect(out).to eq("C") end it "should set LC_ALL to C avoid localized output", :if => !Puppet::Util::Platform.windows? do out = "" Puppet::Util::Execution.execpipe('echo $LC_ALL'){ |line| out << line.read.chomp } expect(out).to eq("C") end it "should raise an ExecutionFailure with a missing command and :failonfail set to true" do expect { failonfail = true # NOTE: critical to return l in the block for `output` in method to be #<IO:(closed)> Puppet::Util::Execution.execpipe('conan_the_librarion', failonfail) { |l| l } }.to raise_error(Puppet::ExecutionFailure) end end describe "#execute" do if Puppet::Util::Platform.windows? let(:argv) { ["cmd", "/c", "echo", 123] } else let(:argv) { ["echo", 123] } end it 'stringifies sensitive arguments when given an array containing integers' do result = Puppet::Util::Execution.execute(argv, sensitive: true) expect(result.to_s.strip).to eq("123") expect(result.exitstatus).to eq(0) end it 'redacts sensitive arguments when given an array' do Puppet[:log_level] = :debug Puppet::Util::Execution.execute(argv, sensitive: true) expect(@logs).to include(an_object_having_attributes(level: :debug, message: "Executing: '[redacted]'")) end it 'redacts sensitive arguments when given a string' do Puppet[:log_level] = :debug str = argv.map(&:to_s).join(' ') Puppet::Util::Execution.execute(str, sensitive: true) expect(@logs).to include(an_object_having_attributes(level: :debug, message: "Executing: '[redacted]'")) end it "allows stdout and stderr to share a file" do command = "ruby -e '(1..10).each {|i| (i%2==0) ? $stdout.puts(i) : $stderr.puts(i)}'" expect(Puppet::Util::Execution.execute(command, :combine => true).split).to match_array([*'1'..'10']) end it "returns output and set $CHILD_STATUS" do command = "ruby -e 'puts \"foo\"; exit 42'" output = Puppet::Util::Execution.execute(command, {:failonfail => false}) expect(output).to eq("foo\n") expect($CHILD_STATUS.exitstatus).to eq(42) end it "raises an error if non-zero exit status is returned" do command = "ruby -e 'exit 43'" expect { Puppet::Util::Execution.execute(command) }.to raise_error(Puppet::ExecutionFailure, /Execution of '#{command}' returned 43: /) expect($CHILD_STATUS.exitstatus).to eq(43) end end describe "#execute (non-Windows)", :if => !Puppet::Util::Platform.windows? do it "should execute basic shell command" do result = Puppet::Util::Execution.execute("ls /tmp", :failonfail => true) expect(result.exitstatus).to eq(0) expect(result.to_s).to_not be_nil end end describe "#execute (Windows)", :if => Puppet::Util::Platform.windows? do let(:utf8text) do # Japanese Lorem Ipsum snippet "utf8testfile" + [227, 131, 171, 227, 131, 147, 227, 131, 179, 227, 131, 132, 227, 130, 162, 227, 130, 166, 227, 130, 167, 227, 131, 150, 227, 130, 162, 227, 129, 181, 227, 129, 185, 227, 129, 139, 227, 130, 137, 227, 129, 154, 227, 130, 187, 227, 130, 183, 227, 131, 147, 227, 131, 170, 227, 131, 134].pack('c*').force_encoding(Encoding::UTF_8) end let(:temputf8filename) do script_containing(utf8text, :windows => "@ECHO OFF\r\nECHO #{utf8text}\r\nEXIT 100") end it "should execute with non-english characters in command line" do result = Puppet::Util::Execution.execute("cmd /c \"#{temputf8filename}\"", :failonfail => false) expect(temputf8filename.encoding.name).to eq('UTF-8') expect(result.exitstatus).to eq(100) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/integration/util/rdoc/parser_spec.rb
spec/integration/util/rdoc/parser_spec.rb
require 'spec_helper' require 'puppet/util/rdoc' describe "RDoc::Parser", :unless => Puppet::Util::Platform.windows? do require 'puppet_spec/files' include PuppetSpec::Files let(:document_all) { false } let(:tmp_dir) { tmpdir('rdoc_parser_tmp') } let(:doc_dir) { File.join(tmp_dir, 'doc') } let(:manifests_dir) { File.join(tmp_dir, 'manifests') } let(:modules_dir) { File.join(tmp_dir, 'modules') } let(:modules_and_manifests) do { :site => [ File.join(manifests_dir, 'site.pp'), <<-EOF # The test class comment class test { # The virtual resource comment @notify { virtual: } # The a_notify_resource comment notify { a_notify_resource: message => "a_notify_resource message" } } # The includes_another class comment class includes_another { include another } # The requires_another class comment class requires_another { require another } # node comment node foo { include test $a_var = "var_value" realize Notify[virtual] notify { bar: } } EOF ], :module_readme => [ File.join(modules_dir, 'a_module', 'README'), <<-EOF The a_module README docs. EOF ], :module_init => [ File.join(modules_dir, 'a_module', 'manifests', 'init.pp'), <<-EOF # The a_module class comment class a_module {} class another {} EOF ], :module_type => [ File.join(modules_dir, 'a_module', 'manifests', 'a_type.pp'), <<-EOF # The a_type type comment define a_module::a_type() {} EOF ], :module_plugin => [ File.join(modules_dir, 'a_module', 'lib', 'puppet', 'type', 'a_plugin.rb'), <<-EOF # The a_plugin type comment Puppet::Type.newtype(:a_plugin) do @doc = "Not presented" end EOF ], :module_function => [ File.join(modules_dir, 'a_module', 'lib', 'puppet', 'parser', 'a_function.rb'), <<-EOF # The a_function function comment module Puppet::Parser::Functions newfunction(:a_function, :type => :rvalue) do return end end EOF ], :module_fact => [ File.join(modules_dir, 'a_module', 'lib', 'facter', 'a_fact.rb'), <<-EOF # The a_fact fact comment Puppet.runtime[:facter].add("a_fact") do end EOF ], } end def write_file(file, content) FileUtils.mkdir_p(File.dirname(file)) File.open(file, 'w') do |f| f.puts(content) end end def prepare_manifests_and_modules modules_and_manifests.each do |key,array| write_file(*array) end end def file_exists_and_matches_content(file, *content_patterns) expect(Puppet::FileSystem.exist?(file)).to(be_truthy, "Cannot find #{file}") content_patterns.each do |pattern| content = File.read(file) expect(content).to match(pattern) end end def some_file_exists_with_matching_content(glob, *content_patterns) expect(Dir.glob(glob).select do |f| contents = File.read(f) content_patterns.all? { |p| p.match(contents) } end).not_to(be_empty, "Could not match #{content_patterns} in any of the files found in #{glob}") end around(:each) do |example| env = Puppet::Node::Environment.create(:doc_test_env, [modules_dir], manifests_dir) Puppet.override({:environments => Puppet::Environments::Static.new(env), :current_environment => env}) do example.run end end before :each do prepare_manifests_and_modules Puppet.settings[:document_all] = document_all Puppet.settings[:modulepath] = modules_dir Puppet::Util::RDoc.rdoc(doc_dir, [modules_dir, manifests_dir]) end describe "rdoc2 support" do def module_path(module_name) "#{doc_dir}/#{module_name}.html" end def plugin_path(module_name, type, name) "#{doc_dir}/#{module_name}/__#{type}s__.html" end def has_plugin_rdoc(module_name, type, name) file_exists_and_matches_content( plugin_path(module_name, type, name), /The .*?#{name}.*?\s*#{type} comment/m, /Type.*?#{type}/m ) end it "documents the a_module::a_plugin type" do has_plugin_rdoc("a_module", :type, 'a_plugin') end it "documents the a_module::a_function function" do has_plugin_rdoc("a_module", :function, 'a_function') end it "documents the a_module::a_fact fact" do has_plugin_rdoc("a_module", :fact, 'a_fact') end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/integration/util/windows/security_spec.rb
spec/integration/util/windows/security_spec.rb
require 'spec_helper' if Puppet::Util::Platform.windows? class WindowsSecurityTester require 'puppet/util/windows/security' include Puppet::Util::Windows::Security end end describe "Puppet::Util::Windows::Security", :if => Puppet::Util::Platform.windows? do include PuppetSpec::Files before :all do # necessary for localized name of guests guests_name = Puppet::Util::Windows::SID.sid_to_name('S-1-5-32-546') guests = Puppet::Util::Windows::ADSI::Group.new(guests_name) @sids = { :current_user => Puppet::Util::Windows::SID.name_to_sid(Puppet::Util::Windows::ADSI::User.current_user_name), :system => Puppet::Util::Windows::SID::LocalSystem, :administrators => Puppet::Util::Windows::SID::BuiltinAdministrators, :guest => Puppet::Util::Windows::SID.name_to_sid(guests.members[0]), :users => Puppet::Util::Windows::SID::BuiltinUsers, :power_users => Puppet::Util::Windows::SID::PowerUsers, :none => Puppet::Util::Windows::SID::Nobody, :everyone => Puppet::Util::Windows::SID::Everyone } # The TCP/IP NetBIOS Helper service (aka 'lmhosts') has ended up # disabled on some VMs for reasons we couldn't track down. This # condition causes tests which rely on resolving UNC style paths # (like \\localhost) to fail with unhelpful error messages. # Put a check for this upfront to aid debug should this strike again. service = Puppet::Type.type(:service).new(:name => 'lmhosts') expect(service.provider.status).to eq(:running), 'lmhosts service is not running' end let (:sids) { @sids } let (:winsec) { WindowsSecurityTester.new } let (:klass) { Puppet::Util::Windows::File } def set_group_depending_on_current_user(path) if sids[:current_user] == sids[:system] # if the current user is SYSTEM, by setting the group to # guest, SYSTEM is automagically given full control, so instead # override that behavior with SYSTEM as group and a specific mode winsec.set_group(sids[:system], path) mode = winsec.get_mode(path) winsec.set_mode(mode & ~WindowsSecurityTester::S_IRWXG, path) else winsec.set_group(sids[:guest], path) end end def grant_everyone_full_access(path) sd = winsec.get_security_descriptor(path) everyone = 'S-1-1-0' inherit = Puppet::Util::Windows::AccessControlEntry::OBJECT_INHERIT_ACE | Puppet::Util::Windows::AccessControlEntry::CONTAINER_INHERIT_ACE sd.dacl.allow(everyone, klass::FILE_ALL_ACCESS, inherit) winsec.set_security_descriptor(path, sd) end shared_examples_for "only child owner" do it "should allow child owner" do winsec.set_owner(sids[:guest], parent) winsec.set_group(sids[:current_user], parent) winsec.set_mode(0700, parent) check_delete(path) end it "should deny parent owner" do winsec.set_owner(sids[:guest], path) winsec.set_group(sids[:current_user], path) winsec.set_mode(0700, path) expect { check_delete(path) }.to raise_error(Errno::EACCES) end it "should deny group" do winsec.set_owner(sids[:guest], path) winsec.set_group(sids[:current_user], path) winsec.set_mode(0700, path) expect { check_delete(path) }.to raise_error(Errno::EACCES) end it "should deny other" do winsec.set_owner(sids[:guest], path) winsec.set_group(sids[:current_user], path) winsec.set_mode(0700, path) expect { check_delete(path) }.to raise_error(Errno::EACCES) end end shared_examples_for "a securable object" do describe "on a volume that doesn't support ACLs" do [:owner, :group, :mode].each do |p| it "should return nil #{p}" do allow(winsec).to receive(:supports_acl?).and_return(false) expect(winsec.send("get_#{p}", path)).to be_nil end end end describe "on a volume that supports ACLs" do describe "for a normal user" do before :each do allow(Puppet.features).to receive(:root?).and_return(false) end after :each do winsec.set_mode(WindowsSecurityTester::S_IRWXU, parent) begin winsec.set_mode(WindowsSecurityTester::S_IRWXU, path) rescue nil end end describe "#supports_acl?" do %w[c:/ c:\\ c:/windows/system32 \\\\localhost\\C$ \\\\127.0.0.1\\C$\\foo].each do |path| it "should accept #{path}" do expect(winsec).to be_supports_acl(path) end end it "should raise an exception if it cannot get volume information" do expect { winsec.supports_acl?('foobar') }.to raise_error(Puppet::Error, /Failed to get volume information/) end end describe "#owner=" do it "should allow setting to the current user" do winsec.set_owner(sids[:current_user], path) end it "should raise an exception when setting to a different user" do expect { winsec.set_owner(sids[:guest], path) }.to raise_error do |error| expect(error).to be_a(Puppet::Util::Windows::Error) expect(error.code).to eq(1307) # ERROR_INVALID_OWNER end end end describe "#owner" do it "it should not be empty" do expect(winsec.get_owner(path)).not_to be_empty end it "should raise an exception if an invalid path is provided" do expect { winsec.get_owner("c:\\doesnotexist.txt") }.to raise_error do |error| expect(error).to be_a(Puppet::Util::Windows::Error) expect(error.code).to eq(2) # ERROR_FILE_NOT_FOUND end end end describe "#group=" do it "should allow setting to a group the current owner is a member of" do winsec.set_group(sids[:users], path) end # Unlike unix, if the user has permission to WRITE_OWNER, which the file owner has by default, # then they can set the primary group to a group that the user does not belong to. it "should allow setting to a group the current owner is not a member of" do winsec.set_group(sids[:power_users], path) end it "should consider a mode of 7 for group to be FullControl (F)" do winsec.set_group(sids[:power_users], path) winsec.set_mode(0070, path) group_ace = winsec.get_aces_for_path_by_sid(path, sids[:power_users]) # there should only be a single ace for the given group expect(group_ace.count).to eq(1) expect(group_ace[0].mask).to eq(klass::FILE_ALL_ACCESS) # ensure that mode is still read as 070 (written as 70) expect((winsec.get_mode(path) & 0777).to_s(8).rjust(3, '0')).to eq("070") end end describe "#group" do it "should not be empty" do expect(winsec.get_group(path)).not_to be_empty end it "should raise an exception if an invalid path is provided" do expect { winsec.get_group("c:\\doesnotexist.txt") }.to raise_error do |error| expect(error).to be_a(Puppet::Util::Windows::Error) expect(error.code).to eq(2) # ERROR_FILE_NOT_FOUND end end end it "should preserve inherited full control for SYSTEM when setting owner and group" do # new file has SYSTEM system_aces = winsec.get_aces_for_path_by_sid(path, sids[:system]) expect(system_aces).not_to be_empty # when running under SYSTEM account, multiple ACEs come back # so we only care that we have at least one of these expect(system_aces.any? do |ace| ace.mask == klass::FILE_ALL_ACCESS end).to be_truthy # changing the owner/group will no longer make the SD protected winsec.set_group(sids[:power_users], path) winsec.set_owner(sids[:administrators], path) expect(system_aces.find do |ace| ace.mask == klass::FILE_ALL_ACCESS && ace.inherited? end).not_to be_nil end describe "#mode=" do (0000..0700).step(0100) do |mode| it "should enforce mode #{mode.to_s(8)}" do winsec.set_mode(mode, path) check_access(mode, path) end end it "should round-trip all 128 modes that do not require deny ACEs, where owner and group are different" do # windows defaults set Administrators, None when Administrator # or Administrators, SYSTEM when System # but we can guarantee group is different by explicitly setting to Users winsec.set_group(sids[:users], path) 0.upto(1).each do |s| 0.upto(7).each do |u| 0.upto(u).each do |g| 0.upto(g).each do |o| # if user is superset of group, and group superset of other, then # no deny ace is required, and mode can be converted to win32 # access mask, and back to mode without loss of information # (provided the owner and group are not the same) next if ((u & g) != g) or ((g & o) != o) mode = (s << 9 | u << 6 | g << 3 | o << 0) winsec.set_mode(mode, path) expect(winsec.get_mode(path).to_s(8)).to eq(mode.to_s(8)) end end end end end it "should round-trip all 54 modes that do not require deny ACEs, where owner and group are same" do winsec.set_group(winsec.get_owner(path), path) 0.upto(1).each do |s| 0.upto(7).each do |ug| 0.upto(ug).each do |o| # if user and group superset of other, then # no deny ace is required, and mode can be converted to win32 # access mask, and back to mode without loss of information # (provided the owner and group are the same) next if ((ug & o) != o) mode = (s << 9 | ug << 6 | ug << 3 | o << 0) winsec.set_mode(mode, path) expect(winsec.get_mode(path).to_s(8)).to eq(mode.to_s(8)) end end end end # The SYSTEM user is a special case therefore we need to test that we round trip correctly when set it "should round-trip all 128 modes that do not require deny ACEs, when simulating a SYSTEM service" do # The owner and group for files/dirs created, when running as a service under Local System are # Owner = Administrators # Group = SYSTEM winsec.set_owner(sids[:administrators], path) winsec.set_group(sids[:system], path) 0.upto(1).each do |s| 0.upto(7).each do |u| 0.upto(u).each do |g| 0.upto(g).each do |o| # if user is superset of group, and group superset of other, then # no deny ace is required, and mode can be converted to win32 # access mask, and back to mode without loss of information # (provided the owner and group are not the same) next if ((u & g) != g) or ((g & o) != o) applied_mode = (s << 9 | u << 6 | g << 3 | o << 0) # SYSTEM must always be Full Control (7) expected_mode = (s << 9 | u << 6 | 7 << 3 | o << 0) winsec.set_mode(applied_mode, path) expect(winsec.get_mode(path).to_s(8)).to eq(expected_mode.to_s(8)) end end end end end it "should preserve full control for SYSTEM when setting mode" do # new file has SYSTEM system_aces = winsec.get_aces_for_path_by_sid(path, sids[:system]) expect(system_aces).not_to be_empty # when running under SYSTEM account, multiple ACEs come back # so we only care that we have at least one of these expect(system_aces.any? do |ace| ace.mask == klass::FILE_ALL_ACCESS end).to be_truthy # changing the mode will make the SD protected winsec.set_group(sids[:none], path) winsec.set_mode(0600, path) # and should have a non-inherited SYSTEM ACE(s) system_aces = winsec.get_aces_for_path_by_sid(path, sids[:system]) system_aces.each do |ace| expect(ace.mask).to eq(klass::FILE_ALL_ACCESS) expect(ace).not_to be_inherited end if Puppet::FileSystem.directory?(path) system_aces.each do |ace| expect(ace).to be_object_inherit expect(ace).to be_container_inherit end # it's critically important that this file be default created # and that this file not have it's owner / group / mode set by winsec nested_file = File.join(path, 'nested_file') File.new(nested_file, 'w').close system_aces = winsec.get_aces_for_path_by_sid(nested_file, sids[:system]) # even when SYSTEM is the owner (in CI), there should be an inherited SYSTEM expect(system_aces.any? do |ace| ace.mask == klass::FILE_ALL_ACCESS && ace.inherited? end).to be_truthy end end describe "for modes that require deny aces" do it "should map everyone to group and owner" do winsec.set_mode(0426, path) expect(winsec.get_mode(path).to_s(8)).to eq("666") end it "should combine user and group modes when owner and group sids are equal" do winsec.set_group(winsec.get_owner(path), path) winsec.set_mode(0410, path) expect(winsec.get_mode(path).to_s(8)).to eq("550") end end describe "for read-only objects" do before :each do winsec.set_group(sids[:none], path) winsec.set_mode(0600, path) Puppet::Util::Windows::File.add_attributes(path, klass::FILE_ATTRIBUTE_READONLY) expect(Puppet::Util::Windows::File.get_attributes(path) & klass::FILE_ATTRIBUTE_READONLY).to be_nonzero end it "should make them writable if any sid has write permission" do winsec.set_mode(WindowsSecurityTester::S_IWUSR, path) expect(Puppet::Util::Windows::File.get_attributes(path) & klass::FILE_ATTRIBUTE_READONLY).to eq(0) end it "should leave them read-only if no sid has write permission and should allow full access for SYSTEM" do winsec.set_mode(WindowsSecurityTester::S_IRUSR | WindowsSecurityTester::S_IXGRP, path) expect(Puppet::Util::Windows::File.get_attributes(path) & klass::FILE_ATTRIBUTE_READONLY).to be_nonzero system_aces = winsec.get_aces_for_path_by_sid(path, sids[:system]) # when running under SYSTEM account, and set_group / set_owner hasn't been called # SYSTEM full access will be restored expect(system_aces.any? do |ace| ace.mask == klass::FILE_ALL_ACCESS end).to be_truthy end end it "should raise an exception if an invalid path is provided" do expect { winsec.set_mode(sids[:guest], "c:\\doesnotexist.txt") }.to raise_error do |error| expect(error).to be_a(Puppet::Util::Windows::Error) expect(error.code).to eq(2) # ERROR_FILE_NOT_FOUND end end end describe "#mode" do it "should report when extra aces are encounted" do sd = winsec.get_security_descriptor(path) (544..547).each do |rid| sd.dacl.allow("S-1-5-32-#{rid}", klass::STANDARD_RIGHTS_ALL) end winsec.set_security_descriptor(path, sd) mode = winsec.get_mode(path) expect(mode & WindowsSecurityTester::S_IEXTRA).to eq(WindowsSecurityTester::S_IEXTRA) end it "should return deny aces" do sd = winsec.get_security_descriptor(path) sd.dacl.deny(sids[:guest], klass::FILE_GENERIC_WRITE) winsec.set_security_descriptor(path, sd) guest_aces = winsec.get_aces_for_path_by_sid(path, sids[:guest]) expect(guest_aces.find do |ace| ace.type == Puppet::Util::Windows::AccessControlEntry::ACCESS_DENIED_ACE_TYPE end).not_to be_nil end it "should skip inherit-only ace" do sd = winsec.get_security_descriptor(path) dacl = Puppet::Util::Windows::AccessControlList.new dacl.allow( sids[:current_user], klass::STANDARD_RIGHTS_ALL | klass::SPECIFIC_RIGHTS_ALL ) dacl.allow( sids[:everyone], klass::FILE_GENERIC_READ, Puppet::Util::Windows::AccessControlEntry::INHERIT_ONLY_ACE | Puppet::Util::Windows::AccessControlEntry::OBJECT_INHERIT_ACE ) winsec.set_security_descriptor(path, sd) expect(winsec.get_mode(path) & WindowsSecurityTester::S_IRWXO).to eq(0) end it "should raise an exception if an invalid path is provided" do expect { winsec.get_mode("c:\\doesnotexist.txt") }.to raise_error do |error| expect(error).to be_a(Puppet::Util::Windows::Error) expect(error.code).to eq(2) # ERROR_FILE_NOT_FOUND end end end describe "inherited access control entries" do it "should be absent when the access control list is protected, and should not remove SYSTEM" do winsec.set_mode(WindowsSecurityTester::S_IRWXU, path) mode = winsec.get_mode(path) [ WindowsSecurityTester::S_IEXTRA, WindowsSecurityTester::S_ISYSTEM_MISSING ].each do |flag| expect(mode & flag).not_to eq(flag) end end it "should be present when the access control list is unprotected" do # add a bunch of aces to the parent with permission to add children allow = klass::STANDARD_RIGHTS_ALL | klass::SPECIFIC_RIGHTS_ALL inherit = Puppet::Util::Windows::AccessControlEntry::OBJECT_INHERIT_ACE | Puppet::Util::Windows::AccessControlEntry::CONTAINER_INHERIT_ACE sd = winsec.get_security_descriptor(parent) sd.dacl.allow( "S-1-1-0", #everyone allow, inherit ) (544..547).each do |rid| sd.dacl.allow( "S-1-5-32-#{rid}", klass::STANDARD_RIGHTS_ALL, inherit ) end winsec.set_security_descriptor(parent, sd) # unprotect child, it should inherit from parent winsec.set_mode(WindowsSecurityTester::S_IRWXU, path, false) expect(winsec.get_mode(path) & WindowsSecurityTester::S_IEXTRA).to eq(WindowsSecurityTester::S_IEXTRA) end end end describe "for an administrator", :if => (Puppet.features.root? && Puppet::Util::Platform.windows?) do before :each do is_dir = Puppet::FileSystem.directory?(path) winsec.set_mode(WindowsSecurityTester::S_IRWXU | WindowsSecurityTester::S_IRWXG, path) set_group_depending_on_current_user(path) winsec.set_owner(sids[:guest], path) expected_error = is_dir ? Errno::EISDIR : Errno::EACCES expect { File.open(path, 'r') }.to raise_error(expected_error) end after :each do if Puppet::FileSystem.exist?(path) winsec.set_owner(sids[:current_user], path) winsec.set_mode(WindowsSecurityTester::S_IRWXU, path) end end describe "#owner=" do it "should accept the guest sid" do winsec.set_owner(sids[:guest], path) expect(winsec.get_owner(path)).to eq(sids[:guest]) end it "should accept a user sid" do winsec.set_owner(sids[:current_user], path) expect(winsec.get_owner(path)).to eq(sids[:current_user]) end it "should accept a group sid" do winsec.set_owner(sids[:power_users], path) expect(winsec.get_owner(path)).to eq(sids[:power_users]) end it "should raise an exception if an invalid sid is provided" do expect { winsec.set_owner("foobar", path) }.to raise_error(Puppet::Error, /Failed to convert string SID/) end it "should raise an exception if an invalid path is provided" do expect { winsec.set_owner(sids[:guest], "c:\\doesnotexist.txt") }.to raise_error do |error| expect(error).to be_a(Puppet::Util::Windows::Error) expect(error.code).to eq(2) # ERROR_FILE_NOT_FOUND end end end describe "#group=" do it "should accept the test group" do winsec.set_group(sids[:guest], path) expect(winsec.get_group(path)).to eq(sids[:guest]) end it "should accept a group sid" do winsec.set_group(sids[:power_users], path) expect(winsec.get_group(path)).to eq(sids[:power_users]) end it "should accept a user sid" do winsec.set_group(sids[:current_user], path) expect(winsec.get_group(path)).to eq(sids[:current_user]) end it "should combine owner and group rights when they are the same sid" do winsec.set_owner(sids[:power_users], path) winsec.set_group(sids[:power_users], path) winsec.set_mode(0610, path) expect(winsec.get_owner(path)).to eq(sids[:power_users]) expect(winsec.get_group(path)).to eq(sids[:power_users]) # note group execute permission added to user ace, and then group rwx value # reflected to match # Exclude missing system ace, since that's not relevant expect((winsec.get_mode(path) & 0777).to_s(8)).to eq("770") end it "should raise an exception if an invalid sid is provided" do expect { winsec.set_group("foobar", path) }.to raise_error(Puppet::Error, /Failed to convert string SID/) end it "should raise an exception if an invalid path is provided" do expect { winsec.set_group(sids[:guest], "c:\\doesnotexist.txt") }.to raise_error do |error| expect(error).to be_a(Puppet::Util::Windows::Error) expect(error.code).to eq(2) # ERROR_FILE_NOT_FOUND end end end describe "when the sid is NULL" do it "should retrieve an empty owner sid" it "should retrieve an empty group sid" end describe "when the sid refers to a deleted trustee" do it "should retrieve the user sid" do sid = nil user = Puppet::Util::Windows::ADSI::User.create("puppet#{rand(10000)}") user.password = 'PUPPET_RULeZ_123!' user.commit begin sid = Puppet::Util::Windows::ADSI::User.new(user.name).sid.sid winsec.set_owner(sid, path) winsec.set_mode(WindowsSecurityTester::S_IRWXU, path) ensure Puppet::Util::Windows::ADSI::User.delete(user.name) end expect(winsec.get_owner(path)).to eq(sid) expect(winsec.get_mode(path)).to eq(WindowsSecurityTester::S_IRWXU) end it "should retrieve the group sid" do sid = nil group = Puppet::Util::Windows::ADSI::Group.create("puppet#{rand(10000)}") group.commit begin sid = Puppet::Util::Windows::ADSI::Group.new(group.name).sid.sid winsec.set_group(sid, path) winsec.set_mode(WindowsSecurityTester::S_IRWXG, path) ensure Puppet::Util::Windows::ADSI::Group.delete(group.name) end expect(winsec.get_group(path)).to eq(sid) expect(winsec.get_mode(path)).to eq(WindowsSecurityTester::S_IRWXG) end end describe "#mode" do it "should deny all access when the DACL is empty, including SYSTEM" do sd = winsec.get_security_descriptor(path) # don't allow inherited aces to affect the test protect = true new_sd = Puppet::Util::Windows::SecurityDescriptor.new(sd.owner, sd.group, [], protect) winsec.set_security_descriptor(path, new_sd) expect(winsec.get_mode(path)).to eq(WindowsSecurityTester::S_ISYSTEM_MISSING) end # REMIND: ruby crashes when trying to set a NULL DACL # it "should allow all when it is nil" do # winsec.set_owner(sids[:current_user], path) # winsec.open_file(path, WindowsSecurityTester::READ_CONTROL | WindowsSecurityTester::WRITE_DAC) do |handle| # winsec.set_security_info(handle, WindowsSecurityTester::DACL_SECURITY_INFORMATION | WindowsSecurityTester::PROTECTED_DACL_SECURITY_INFORMATION, nil) # end # winsec.get_mode(path).to_s(8).should == "777" # end end describe "#mode=" do # setting owner to SYSTEM requires root it "should round-trip all 54 modes that do not require deny ACEs, when simulating a SYSTEM scheduled task" do # The owner and group for files/dirs created, when running as a Scheduled Task as Local System are # Owner = SYSTEM # Group = SYSTEM winsec.set_group(sids[:system], path) winsec.set_owner(sids[:system], path) 0.upto(1).each do |s| 0.upto(7).each do |ug| 0.upto(ug).each do |o| # if user and group superset of other, then # no deny ace is required, and mode can be converted to win32 # access mask, and back to mode without loss of information # (provided the owner and group are the same) next if ((ug & o) != o) applied_mode = (s << 9 | ug << 6 | ug << 3 | o << 0) # SYSTEM must always be Full Control (7) expected_mode = (s << 9 | 7 << 6 | 7 << 3 | o << 0) winsec.set_mode(applied_mode, path) expect(winsec.get_mode(path).to_s(8)).to eq(expected_mode.to_s(8)) end end end end end describe "when the parent directory" do before :each do winsec.set_owner(sids[:current_user], parent) winsec.set_owner(sids[:current_user], path) winsec.set_mode(0777, path, false) end describe "is writable and executable" do describe "and sticky bit is set" do it "should allow child owner" do winsec.set_owner(sids[:guest], parent) winsec.set_group(sids[:current_user], parent) winsec.set_mode(01700, parent) check_delete(path) end it "should allow parent owner" do winsec.set_owner(sids[:current_user], parent) winsec.set_group(sids[:guest], parent) winsec.set_mode(01700, parent) winsec.set_owner(sids[:current_user], path) winsec.set_group(sids[:guest], path) winsec.set_mode(0700, path) check_delete(path) end it "should deny group" do winsec.set_owner(sids[:guest], parent) winsec.set_group(sids[:current_user], parent) winsec.set_mode(01770, parent) winsec.set_owner(sids[:guest], path) winsec.set_group(sids[:current_user], path) winsec.set_mode(0700, path) expect { check_delete(path) }.to raise_error(Errno::EACCES) end it "should deny other" do winsec.set_owner(sids[:guest], parent) winsec.set_group(sids[:current_user], parent) winsec.set_mode(01777, parent) winsec.set_owner(sids[:guest], path) winsec.set_group(sids[:current_user], path) winsec.set_mode(0700, path) expect { check_delete(path) }.to raise_error(Errno::EACCES) end end describe "and sticky bit is not set" do it "should allow child owner" do winsec.set_owner(sids[:guest], parent) winsec.set_group(sids[:current_user], parent) winsec.set_mode(0700, parent) check_delete(path) end it "should allow parent owner" do winsec.set_owner(sids[:current_user], parent) winsec.set_group(sids[:guest], parent) winsec.set_mode(0700, parent) winsec.set_owner(sids[:current_user], path) winsec.set_group(sids[:guest], path) winsec.set_mode(0700, path) check_delete(path) end it "should allow group" do winsec.set_owner(sids[:guest], parent) winsec.set_group(sids[:current_user], parent) winsec.set_mode(0770, parent) winsec.set_owner(sids[:guest], path) winsec.set_group(sids[:current_user], path) winsec.set_mode(0700, path) check_delete(path) end it "should allow other" do winsec.set_owner(sids[:guest], parent) winsec.set_group(sids[:current_user], parent) winsec.set_mode(0777, parent) winsec.set_owner(sids[:guest], path) winsec.set_group(sids[:current_user], path) winsec.set_mode(0700, path) check_delete(path) end end end describe "is not writable" do before :each do winsec.set_group(sids[:current_user], parent) winsec.set_mode(0555, parent) end it_behaves_like "only child owner" end describe "is not executable" do before :each do winsec.set_group(sids[:current_user], parent) winsec.set_mode(0666, parent) end it_behaves_like "only child owner" end end end end end describe "file" do let (:parent) do tmpdir('win_sec_test_file') end let (:path) do path = File.join(parent, 'childfile') File.new(path, 'w').close path end after :each do # allow temp files to be cleaned up grant_everyone_full_access(parent) end it_behaves_like "a securable object" do def check_access(mode, path) if (mode & WindowsSecurityTester::S_IRUSR).nonzero? check_read(path) else expect { check_read(path) }.to raise_error(Errno::EACCES) end if (mode & WindowsSecurityTester::S_IWUSR).nonzero? check_write(path) else expect { check_write(path) }.to raise_error(Errno::EACCES) end if (mode & WindowsSecurityTester::S_IXUSR).nonzero? expect { check_execute(path) }.to raise_error(Errno::ENOEXEC) else expect { check_execute(path) }.to raise_error(Errno::EACCES) end end def check_read(path) File.open(path, 'r').close end def check_write(path) File.open(path, 'w').close end def check_execute(path) Kernel.exec(path) end def check_delete(path) File.delete(path) end end describe "locked files" do let (:explorer) { File.join(ENV['SystemRoot'], "explorer.exe") }
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
true
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/integration/util/windows/adsi_spec.rb
spec/integration/util/windows/adsi_spec.rb
require 'spec_helper' require 'puppet/util/windows' describe Puppet::Util::Windows::ADSI::User, :if => Puppet::Util::Platform.windows? do describe ".initialize" do it "cannot reference BUILTIN accounts like SYSTEM due to WinNT moniker limitations" do system = Puppet::Util::Windows::ADSI::User.new('SYSTEM') # trying to retrieve COM object should fail to load with a localized version of: # ADSI connection error: failed to parse display name of moniker `WinNT://./SYSTEM,user' # HRESULT error code:0x800708ad # The user name could not be found. # Matching on error code alone is sufficient expect { system.native_object }.to raise_error(/0x800708ad/) end end describe '.each' do it 'should return a list of users with UTF-8 names' do begin original_codepage = Encoding.default_external Encoding.default_external = Encoding::CP850 # Western Europe Puppet::Util::Windows::ADSI::User.each do |user| expect(user.name.encoding).to be(Encoding::UTF_8) end ensure Encoding.default_external = original_codepage end end end describe '.[]' do it 'should return string attributes as UTF-8' do user = Puppet::Util::Windows::ADSI::User.new('Guest') expect(user['Description'].encoding).to eq(Encoding::UTF_8) end end describe '.groups' do it 'should return a list of groups with UTF-8 names' do begin original_codepage = Encoding.default_external Encoding.default_external = Encoding::CP850 # Western Europe # lookup by English name Administrator is OK on localized Windows administrator = Puppet::Util::Windows::ADSI::User.new('Administrator') administrator.groups.each do |name| expect(name.encoding).to be(Encoding::UTF_8) end ensure Encoding.default_external = original_codepage end end end describe '.current_user_name_with_format' do context 'when desired format is NameSamCompatible' do it 'should get the same user name as the current_user_name method but fully qualified' do user_name = Puppet::Util::Windows::ADSI::User.current_user_name fully_qualified_user_name = Puppet::Util::Windows::ADSI::User.current_sam_compatible_user_name expect(fully_qualified_user_name).to match(/^.+\\#{user_name}$/) end it 'should have the same SID as with the current_user_name method' do user_name = Puppet::Util::Windows::ADSI::User.current_user_name fully_qualified_user_name = Puppet::Util::Windows::ADSI::User.current_sam_compatible_user_name expect(Puppet::Util::Windows::SID.name_to_sid(user_name)).to eq(Puppet::Util::Windows::SID.name_to_sid(fully_qualified_user_name)) end end end end describe Puppet::Util::Windows::ADSI::Group, :if => Puppet::Util::Platform.windows? do let (:administrator_bytes) { [1, 2, 0, 0, 0, 0, 0, 5, 32, 0, 0, 0, 32, 2, 0, 0] } let (:administrators_principal) { Puppet::Util::Windows::SID::Principal.lookup_account_sid(administrator_bytes) } describe '.each' do it 'should return a list of groups with UTF-8 names' do begin original_codepage = Encoding.default_external Encoding.default_external = Encoding::CP850 # Western Europe Puppet::Util::Windows::ADSI::Group.each do |group| expect(group.name.encoding).to be(Encoding::UTF_8) end ensure Encoding.default_external = original_codepage end end end describe '.members' do it 'should return a list of members resolvable with Puppet::Util::Windows::ADSI::Group.name_sid_hash' do temp_groupname = "g#{SecureRandom.uuid}" temp_username = "u#{SecureRandom.uuid}"[0..12] # From https://docs.microsoft.com/en-us/windows/security/threat-protection/security-policy-settings/password-must-meet-complexity-requirements specials = "~!@#$%^&*_-+=`|\(){}[]:;\"'<>,.?/" temp_password = "p#{SecureRandom.uuid[0..7]}-#{SecureRandom.uuid.upcase[0..7]}-#{specials[rand(specials.length)]}" # select a virtual account that requires an authority to be able to resolve to SID # the Dhcp service is chosen for no particular reason aside from it's a service available on all Windows versions dhcp_virtualaccount = Puppet::Util::Windows::SID.name_to_principal('NT SERVICE\Dhcp') # adding :SidTypeGroup as a group member will cause error in IAdsUser::Add # adding :SidTypeDomain (such as S-1-5-80 / NT SERVICE or computer name) won't error # but also won't be returned as a group member # uncertain how to obtain :SidTypeComputer (perhaps AD? the local machine is :SidTypeDomain) users = [ # Use sid_to_name to get localized names of SIDs - BUILTIN, SYSTEM, NT AUTHORITY, Everyone are all localized # :SidTypeWellKnownGroup # SYSTEM is prefixed with the NT Authority authority, resolveable with or without authority { :sid => 'S-1-5-18', :name => Puppet::Util::Windows::SID.sid_to_name('S-1-5-18') }, # Everyone is not prefixed with an authority, resolveable with or without NT AUTHORITY authority { :sid => 'S-1-1-0', :name => Puppet::Util::Windows::SID.sid_to_name('S-1-1-0') }, # Dhcp service account is prefixed with NT SERVICE authority, requires authority to resolve SID # behavior is similar to IIS APPPOOL\DefaultAppPool { :sid => dhcp_virtualaccount.sid, :name => dhcp_virtualaccount.domain_account }, # :SidTypeAlias with authority component # Administrators group is prefixed with BUILTIN authority, can be resolved with or without authority { :sid => 'S-1-5-32-544', :name => Puppet::Util::Windows::SID.sid_to_name('S-1-5-32-544') }, ] begin # :SidTypeUser as user on localhost, can be resolved with or without authority prefix user = Puppet::Util::Windows::ADSI::User.create(temp_username) # appveyor sometimes requires a password user.password = temp_password user.commit() users.push({ :sid => user.sid.sid, :name => Puppet::Util::Windows::ADSI.computer_name + '\\' + temp_username }) # create a test group and add above 5 members by SID group = described_class.create(temp_groupname) group.commit() group.set_members(users.map { |u| u[:sid]} ) # most importantly make sure that all name are convertible to SIDs expect { described_class.name_sid_hash(group.members) }.to_not raise_error # also verify the names returned are as expected expected_usernames = users.map { |u| u[:name] } expect(group.members.map(&:domain_account)).to eq(expected_usernames) ensure described_class.delete(temp_groupname) if described_class.exists?(temp_groupname) Puppet::Util::Windows::ADSI::User.delete(temp_username) if Puppet::Util::Windows::ADSI::User.exists?(temp_username) end end it 'should return a list of Principal objects even with unresolvable SIDs' do members = [ # NULL SID is not localized double('WIN32OLE', { :objectSID => [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], :Name => 'NULL SID', :ole_respond_to? => true, }), # unresolvable SID is a different story altogether double('WIN32OLE', { # completely valid SID, but Name is just a stringified version :objectSID => [1, 5, 0, 0, 0, 0, 0, 5, 21, 0, 0, 0, 5, 113, 65, 218, 15, 127, 9, 57, 219, 4, 84, 126, 88, 4, 0, 0], :Name => 'S-1-5-21-3661721861-956923663-2119435483-1112', :ole_respond_to? => true, }) ] admins_name = Puppet::Util::Windows::SID.sid_to_name('S-1-5-32-544') admins = Puppet::Util::Windows::ADSI::Group.new(admins_name) # touch the native_object member to have it lazily loaded, so COM objects can be stubbed admins.native_object without_partial_double_verification do allow(admins.native_object).to receive(:Members).and_return(members) end # well-known NULL SID expect(admins.members[0].sid).to eq('S-1-0-0') expect(admins.members[0].account_type).to eq(:SidTypeWellKnownGroup) # unresolvable SID expect(admins.members[1].sid).to eq('S-1-5-21-3661721861-956923663-2119435483-1112') expect(admins.members[1].account).to eq('S-1-5-21-3661721861-956923663-2119435483-1112') expect(admins.members[1].account_type).to eq(:SidTypeUnknown) end it 'should return a list of members with UTF-8 names' do begin original_codepage = Encoding.default_external Encoding.default_external = Encoding::CP850 # Western Europe # lookup by English name Administrators is not OK on localized Windows admins = Puppet::Util::Windows::ADSI::Group.new(administrators_principal.account) admins.members.map(&:domain_account).each do |name| expect(name.encoding).to be(Encoding::UTF_8) end ensure Encoding.default_external = original_codepage end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/integration/util/windows/principal_spec.rb
spec/integration/util/windows/principal_spec.rb
require 'spec_helper' require 'puppet/util/windows' describe Puppet::Util::Windows::SID::Principal, :if => Puppet::Util::Platform.windows? do let (:current_user_sid) { Puppet::Util::Windows::ADSI::User.current_user_sid } let (:system_bytes) { [1, 1, 0, 0, 0, 0, 0, 5, 18, 0, 0, 0] } let (:null_sid_bytes) { [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] } let (:administrator_bytes) { [1, 2, 0, 0, 0, 0, 0, 5, 32, 0, 0, 0, 32, 2, 0, 0] } let (:all_application_packages_bytes) { [1, 2, 0, 0, 0, 0, 0, 15, 2, 0, 0, 0, 1, 0, 0, 0] } let (:computer_sid) { Puppet::Util::Windows::SID.name_to_principal(Puppet::Util::Windows::ADSI.computer_name) } # BUILTIN is localized on German Windows, but not French # looking this up like this dilutes the values of the tests as we're comparing two mechanisms # for returning the same values, rather than to a known good let (:builtin_localized) { Puppet::Util::Windows::SID.sid_to_name('S-1-5-32') } describe ".lookup_account_name" do it "should create an instance from a well-known account name" do principal = Puppet::Util::Windows::SID::Principal.lookup_account_name('NULL SID') expect(principal.account).to eq('NULL SID') expect(principal.sid_bytes).to eq(null_sid_bytes) expect(principal.sid).to eq('S-1-0-0') expect(principal.domain).to eq('') expect(principal.domain_account).to eq('NULL SID') expect(principal.account_type).to eq(:SidTypeWellKnownGroup) expect(principal.to_s).to eq('NULL SID') end it "should create an instance from a well-known account prefixed with NT AUTHORITY" do # a special case that can be used to lookup an account on a localized Windows principal = Puppet::Util::Windows::SID::Principal.lookup_account_name('NT AUTHORITY\\SYSTEM') expect(principal.sid_bytes).to eq(system_bytes) expect(principal.sid).to eq('S-1-5-18') # guard these 3 checks on a US Windows with 1033 - primary language id of 9 primary_language_id = 9 # even though lookup in English, returned values may be localized # French Windows returns AUTORITE NT\\Syst\u00E8me, German Windows returns NT-AUTORIT\u00C4T\\SYSTEM if (Puppet::Util::Windows::Process.get_system_default_ui_language & primary_language_id == primary_language_id) expect(principal.account).to eq('SYSTEM') expect(principal.domain).to eq('NT AUTHORITY') expect(principal.domain_account).to eq('NT AUTHORITY\\SYSTEM') expect(principal.to_s).to eq('NT AUTHORITY\\SYSTEM') end # Windows API LookupAccountSid behaves differently if current user is SYSTEM if current_user_sid.sid_bytes != system_bytes account_type = :SidTypeWellKnownGroup else account_type = :SidTypeUser end expect(principal.account_type).to eq(account_type) end it "should create an instance from a local account prefixed with hostname" do running_as_system = (current_user_sid.sid_bytes == system_bytes) username = running_as_system ? # need to return localized name of Administrator account Puppet::Util::Windows::SID.sid_to_name(computer_sid.sid + '-500').split('\\').last : current_user_sid.account user_exists = Puppet::Util::Windows::ADSI::User.exists?(".\\#{username}") # when running as SYSTEM (in Jenkins CI), then Administrator should be used # otherwise running in AppVeyor there is no Administrator and a the current local user can be used skip if (running_as_system && !user_exists) hostname = Puppet::Util::Windows::ADSI.computer_name principal = Puppet::Util::Windows::SID::Principal.lookup_account_name("#{hostname}\\#{username}") expect(principal.account).to match(/^#{Regexp.quote(username)}$/i) # skip SID and bytes in this case since the most interesting thing here is domain_account expect(principal.domain).to match(/^#{Regexp.quote(hostname)}$/i) expect(principal.domain_account).to match(/^#{Regexp.quote(hostname)}\\#{Regexp.quote(username)}$/i) expect(principal.account_type).to eq(:SidTypeUser) end it "should create an instance from a well-known BUILTIN alias" do # by looking up the localized name of the account, the test value is diluted # this localizes Administrators AND BUILTIN qualified_name = Puppet::Util::Windows::SID.sid_to_name('S-1-5-32-544') domain, name = qualified_name.split('\\') principal = Puppet::Util::Windows::SID::Principal.lookup_account_name(name) expect(principal.account).to eq(name) expect(principal.sid_bytes).to eq(administrator_bytes) expect(principal.sid).to eq('S-1-5-32-544') expect(principal.domain).to eq(domain) expect(principal.domain_account).to eq(qualified_name) expect(principal.account_type).to eq(:SidTypeAlias) expect(principal.to_s).to eq(qualified_name) end it "should raise an error when trying to lookup an account that doesn't exist" do principal = Puppet::Util::Windows::SID::Principal expect { principal.lookup_account_name('ConanTheBarbarian') }.to raise_error do |error| expect(error).to be_a(Puppet::Util::Windows::Error) expect(error.code).to eq(1332) # ERROR_NONE_MAPPED end end it "should return a BUILTIN domain principal for empty account names" do principal = Puppet::Util::Windows::SID::Principal.lookup_account_name('') expect(principal.account_type).to eq(:SidTypeDomain) expect(principal.sid).to eq('S-1-5-32') expect(principal.account).to eq(builtin_localized) expect(principal.domain).to eq(builtin_localized) expect(principal.domain_account).to eq(builtin_localized) expect(principal.to_s).to eq(builtin_localized) end it "should return a BUILTIN domain principal for BUILTIN account names" do principal = Puppet::Util::Windows::SID::Principal.lookup_account_name(builtin_localized) expect(principal.account_type).to eq(:SidTypeDomain) expect(principal.sid).to eq('S-1-5-32') expect(principal.account).to eq(builtin_localized) expect(principal.domain).to eq(builtin_localized) expect(principal.domain_account).to eq(builtin_localized) expect(principal.to_s).to eq(builtin_localized) end it "should always sanitize the account name first" do expect(Puppet::Util::Windows::SID::Principal).to receive(:sanitize_account_name).with('NT AUTHORITY\\SYSTEM').and_call_original Puppet::Util::Windows::SID::Principal.lookup_account_name('NT AUTHORITY\\SYSTEM') end it "should be able to create an instance from an account name prefixed by APPLICATION PACKAGE AUTHORITY" do principal = Puppet::Util::Windows::SID::Principal.lookup_account_name('APPLICATION PACKAGE AUTHORITY\\ALL APPLICATION PACKAGES') expect(principal.account).to eq('ALL APPLICATION PACKAGES') expect(principal.sid_bytes).to eq(all_application_packages_bytes) expect(principal.sid).to eq('S-1-15-2-1') expect(principal.domain).to eq('APPLICATION PACKAGE AUTHORITY') expect(principal.domain_account).to eq('APPLICATION PACKAGE AUTHORITY\\ALL APPLICATION PACKAGES') expect(principal.account_type).to eq(:SidTypeWellKnownGroup) expect(principal.to_s).to eq('APPLICATION PACKAGE AUTHORITY\\ALL APPLICATION PACKAGES') end it "should fail without proper account name sanitization when it is prefixed by APPLICATION PACKAGE AUTHORITY" do given_account_name = 'APPLICATION PACKAGE AUTHORITY\\ALL APPLICATION PACKAGES' expect { Puppet::Util::Windows::SID::Principal.lookup_account_name(nil, false, given_account_name) }.to raise_error(Puppet::Util::Windows::Error, /No mapping between account names and security IDs was done./) end end describe ".lookup_account_sid" do it "should create an instance from a user SID" do # take the computer account bytes and append the equivalent of -501 for Guest bytes = (computer_sid.sid_bytes + [245, 1, 0, 0]) # computer SID bytes start with [1, 4, ...] but need to be [1, 5, ...] bytes[1] = 5 principal = Puppet::Util::Windows::SID::Principal.lookup_account_sid(bytes) # use the returned SID to lookup localized Guest account name in Windows guest_name = Puppet::Util::Windows::SID.sid_to_name(principal.sid) expect(principal.sid_bytes).to eq(bytes) expect(principal.sid).to eq(computer_sid.sid + '-501') expect(principal.account).to eq(guest_name.split('\\')[1]) expect(principal.domain).to eq(computer_sid.domain) expect(principal.domain_account).to eq(guest_name) expect(principal.account_type).to eq(:SidTypeUser) expect(principal.to_s).to eq(guest_name) end it "should create an instance from a well-known group SID" do principal = Puppet::Util::Windows::SID::Principal.lookup_account_sid(null_sid_bytes) expect(principal.sid_bytes).to eq(null_sid_bytes) expect(principal.sid).to eq('S-1-0-0') expect(principal.account).to eq('NULL SID') expect(principal.domain).to eq('') expect(principal.domain_account).to eq('NULL SID') expect(principal.account_type).to eq(:SidTypeWellKnownGroup) expect(principal.to_s).to eq('NULL SID') end it "should create an instance from a well-known BUILTIN Alias SID" do principal = Puppet::Util::Windows::SID::Principal.lookup_account_sid(administrator_bytes) # by looking up the localized name of the account, the test value is diluted # this localizes Administrators AND BUILTIN qualified_name = Puppet::Util::Windows::SID.sid_to_name('S-1-5-32-544') domain, name = qualified_name.split('\\') expect(principal.account).to eq(name) expect(principal.sid_bytes).to eq(administrator_bytes) expect(principal.sid).to eq('S-1-5-32-544') expect(principal.domain).to eq(domain) expect(principal.domain_account).to eq(qualified_name) expect(principal.account_type).to eq(:SidTypeAlias) expect(principal.to_s).to eq(qualified_name) end it "should raise an error when trying to lookup nil" do principal = Puppet::Util::Windows::SID::Principal expect { principal.lookup_account_sid(nil) }.to raise_error(Puppet::Util::Windows::Error, /must not be nil/) end it "should raise an error when trying to lookup non-byte array" do principal = Puppet::Util::Windows::SID::Principal expect { principal.lookup_account_sid('ConanTheBarbarian') }.to raise_error(Puppet::Util::Windows::Error, /array/) end it "should raise an error when trying to lookup an empty array" do principal = Puppet::Util::Windows::SID::Principal expect { principal.lookup_account_sid([]) }.to raise_error(Puppet::Util::Windows::Error, /at least 1 byte long/) end # https://technet.microsoft.com/en-us/library/cc962011.aspx # "... The structure used in all SIDs created by Windows NT and Windows 2000 is revision level 1. ..." # Therefore a value of zero for the revision, is not a valid SID it "should raise an error when trying to lookup completely invalid SID bytes" do principal = Puppet::Util::Windows::SID::Principal expect { principal.lookup_account_sid([0]) }.to raise_error do |error| expect(error).to be_a(Puppet::Util::Windows::Error) expect(error.code).to eq(87) # ERROR_INVALID_PARAMETER end end it "should raise an error when trying to lookup a valid SID that doesn't have a matching account" do principal = Puppet::Util::Windows::SID::Principal expect { # S-1-1-1 which is not a valid account principal.lookup_account_sid([1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0]) }.to raise_error do |error| expect(error).to be_a(Puppet::Util::Windows::Error) expect(error.code).to eq(1332) # ERROR_NONE_MAPPED end end it "should return a domain principal for BUILTIN SID S-1-5-32" do principal = Puppet::Util::Windows::SID::Principal.lookup_account_sid([1, 1, 0, 0, 0, 0, 0, 5, 32, 0, 0, 0]) expect(principal.account_type).to eq(:SidTypeDomain) expect(principal.sid).to eq('S-1-5-32') expect(principal.account).to eq(builtin_localized) expect(principal.domain).to eq(builtin_localized) expect(principal.domain_account).to eq(builtin_localized) expect(principal.to_s).to eq(builtin_localized) end end describe "it should create matching Principal objects" do let(:builtin_sid) { [1, 1, 0, 0, 0, 0, 0, 5, 32, 0, 0, 0] } let(:sid_principal) { Puppet::Util::Windows::SID::Principal.lookup_account_sid(builtin_sid) } ['.', ''].each do |name| it "when comparing the one looked up via SID S-1-5-32 to one looked up via non-canonical name #{name} for the BUILTIN domain" do name_principal = Puppet::Util::Windows::SID::Principal.lookup_account_name(name) # compares canonical sid expect(sid_principal).to eq(name_principal) # compare all properties that have public accessors sid_principal.public_methods(false).reject { |m| m == :== }.each do |method| expect(sid_principal.send(method)).to eq(name_principal.send(method)) end end end it "when comparing the one looked up via SID S-1-5-32 to one looked up via non-canonical localized name for the BUILTIN domain" do name_principal = Puppet::Util::Windows::SID::Principal.lookup_account_name(builtin_localized) # compares canonical sid expect(sid_principal).to eq(name_principal) # compare all properties that have public accessors sid_principal.public_methods(false).reject { |m| m == :== }.each do |method| expect(sid_principal.send(method)).to eq(name_principal.send(method)) end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/integration/util/windows/registry_spec.rb
spec/integration/util/windows/registry_spec.rb
require 'spec_helper' require 'puppet/util/windows' if Puppet::Util::Platform.windows? describe Puppet::Util::Windows::Registry do subject do class TestRegistry include Puppet::Util::Windows::Registry extend FFI::Library ffi_lib :advapi32 attach_function :RegSetValueExW, [:handle, :pointer, :dword, :dword, :pointer, :dword], :win32_long def write_corrupt_dword(reg, valuename) # Normally DWORDs contain 4 bytes. This bad data only has 2 bad_data = [0, 0] FFI::Pointer.from_string_to_wide_string(valuename) do |name_ptr| FFI::MemoryPointer.new(:uchar, bad_data.length) do |data_ptr| data_ptr.write_array_of_uchar(bad_data) if RegSetValueExW(reg.hkey, name_ptr, 0, Win32::Registry::REG_DWORD, data_ptr, data_ptr.size) != 0 raise Puppet::Util::Windows::Error.new("Failed to write registry value") end end end end end TestRegistry.new end let(:name) { 'HKEY_LOCAL_MACHINE' } let(:path) { 'Software\Microsoft' } context "#root" do it "should lookup the root hkey" do expect(subject.root(name)).to be_instance_of(Win32::Registry::PredefinedKey) end it "should raise for unknown root keys" do expect { subject.root('HKEY_BOGUS') }.to raise_error(Puppet::Error, /Invalid registry key/) end end context "#open" do let(:hkey) { double('hklm') } let(:subkey) { double('subkey') } before :each do allow(subject).to receive(:root).and_return(hkey) end it "should yield the opened the subkey" do expect(hkey).to receive(:open).with(path, anything).and_yield(subkey) yielded = nil subject.open(name, path) {|reg| yielded = reg} expect(yielded).to eq(subkey) end if Puppet::Util::Platform.windows? [described_class::KEY64, described_class::KEY32].each do |access| it "should open the key for read access 0x#{access.to_s(16)}" do mode = described_class::KEY_READ | access expect(hkey).to receive(:open).with(path, mode) subject.open(name, path, mode) {|reg| } end end end it "should default to KEY64" do expect(hkey).to receive(:open).with(path, described_class::KEY_READ | described_class::KEY64) subject.open(hkey, path) {|hkey| } end it "should raise for a path that doesn't exist" do expect(hkey).to receive(:keyname).and_return('HKEY_LOCAL_MACHINE') expect(hkey).to receive(:open).and_raise(Win32::Registry::Error.new(2)) # file not found expect do subject.open(hkey, 'doesnotexist') {|hkey| } end.to raise_error(Puppet::Error, /Failed to open registry key 'HKEY_LOCAL_MACHINE\\doesnotexist'/) end end context "#values" do let(:key) { double('uninstall') } it "should return each value's name and data" do expect(key).not_to receive(:each_value) expect(subject).to receive(:each_value).with(key).and_yield('string', 1, 'foo').and_yield('dword', 4, 0) expect(subject.values(key)).to eq({ 'string' => 'foo', 'dword' => 0 }) end it "should return an empty hash if there are no values" do expect(key).not_to receive(:each_value) expect(subject).to receive(:each_value).with(key) expect(subject.values(key)).to eq({}) end it "passes REG_DWORD through" do expect(key).not_to receive(:each_value) expect(subject).to receive(:each_value).with(key).and_yield('dword', Win32::Registry::REG_DWORD, '1') value = subject.values(key).first[1] expect(Integer(value)).to eq(1) end context "when reading non-ASCII values" do ENDASH_UTF_8 = [0xE2, 0x80, 0x93] ENDASH_UTF_16 = [0x2013] TM_UTF_8 = [0xE2, 0x84, 0xA2] TM_UTF_16 = [0x2122] let(:hklm) { Win32::Registry::HKEY_LOCAL_MACHINE } let(:puppet_key) { "SOFTWARE\\Puppet Labs"} let(:subkey_name) { "PuppetRegistryTest#{SecureRandom.uuid}" } let(:guid) { SecureRandom.uuid } let(:regsam) { Puppet::Util::Windows::Registry::KEY32 } after(:each) do # Ruby 2.1.5 has bugs with deleting registry keys due to using ANSI # character APIs, but passing wide strings to them (facepalm) # https://github.com/ruby/ruby/blob/v2_1_5/ext/win32/lib/win32/registry.rb#L323-L329 # therefore, use our own built-in registry helper code hklm.open(puppet_key, Win32::Registry::KEY_ALL_ACCESS | regsam) do |reg| subject.delete_key(reg, subkey_name, regsam) end end # proof that local encodings (such as IBM437 are no longer relevant) it "will return a UTF-8 string from a REG_SZ registry value (written as UTF-16LE)", :if => Puppet::Util::Platform.windows? do # create a UTF-16LE byte array representing "–™" utf_16_bytes = ENDASH_UTF_16 + TM_UTF_16 utf_16_str = utf_16_bytes.pack('s*').force_encoding(Encoding::UTF_16LE) # and it's UTF-8 equivalent bytes utf_8_bytes = ENDASH_UTF_8 + TM_UTF_8 utf_8_str = utf_8_bytes.pack('c*').force_encoding(Encoding::UTF_8) hklm.create("#{puppet_key}\\#{subkey_name}", Win32::Registry::KEY_ALL_ACCESS | regsam) do |reg| reg.write("#{guid}", Win32::Registry::REG_SZ, utf_16_str) # trigger Puppet::Util::Windows::Registry FFI calls keys = subject.keys(reg) vals = subject.values(reg) expect(keys).to be_empty expect(vals).to have_key(guid) # The UTF-16LE string written should come back as the equivalent UTF-8 written = vals[guid] expect(written).to eq(utf_8_str) expect(written.encoding).to eq(Encoding::UTF_8) end end end context "when reading values" do let(:hklm) { Win32::Registry::HKEY_LOCAL_MACHINE } let(:puppet_key) { "SOFTWARE\\Puppet Labs"} let(:subkey_name) { "PuppetRegistryTest#{SecureRandom.uuid}" } let(:value_name) { SecureRandom.uuid } after(:each) do hklm.open(puppet_key, Win32::Registry::KEY_ALL_ACCESS) do |reg| subject.delete_key(reg, subkey_name) end end [ {:name => 'REG_SZ', :type => Win32::Registry::REG_SZ, :value => 'reg sz string'}, {:name => 'REG_EXPAND_SZ', :type => Win32::Registry::REG_EXPAND_SZ, :value => 'reg expand string'}, {:name => 'REG_MULTI_SZ', :type => Win32::Registry::REG_MULTI_SZ, :value => ['string1', 'string2']}, {:name => 'REG_BINARY', :type => Win32::Registry::REG_BINARY, :value => 'abinarystring'}, {:name => 'REG_DWORD', :type => Win32::Registry::REG_DWORD, :value => 0xFFFFFFFF}, {:name => 'REG_DWORD_BIG_ENDIAN', :type => Win32::Registry::REG_DWORD_BIG_ENDIAN, :value => 0xFFFF}, {:name => 'REG_QWORD', :type => Win32::Registry::REG_QWORD, :value => 0xFFFFFFFFFFFFFFFF}, ].each do |pair| it "should return #{pair[:name]} values" do hklm.create("#{puppet_key}\\#{subkey_name}", Win32::Registry::KEY_ALL_ACCESS) do |reg| reg.write(value_name, pair[:type], pair[:value]) end hklm.open("#{puppet_key}\\#{subkey_name}", Win32::Registry::KEY_READ) do |reg| vals = subject.values(reg) expect(vals).to have_key(value_name) subject.each_value(reg) do |subkey, type, data| expect(type).to eq(pair[:type]) end written = vals[value_name] expect(written).to eq(pair[:value]) end end end end context "when reading corrupt values" do let(:hklm) { Win32::Registry::HKEY_LOCAL_MACHINE } let(:puppet_key) { "SOFTWARE\\Puppet Labs"} let(:subkey_name) { "PuppetRegistryTest#{SecureRandom.uuid}" } let(:value_name) { SecureRandom.uuid } before(:each) do hklm.create("#{puppet_key}\\#{subkey_name}", Win32::Registry::KEY_ALL_ACCESS) do |reg_key| subject.write_corrupt_dword(reg_key, value_name) end end after(:each) do hklm.open(puppet_key, Win32::Registry::KEY_ALL_ACCESS) do |reg_key| subject.delete_key(reg_key, subkey_name) end end it "should return nil for a corrupt DWORD" do hklm.open("#{puppet_key}\\#{subkey_name}", Win32::Registry::KEY_ALL_ACCESS) do |reg_key| vals = subject.values(reg_key) expect(vals).to have_key(value_name) expect(vals[value_name]).to be_nil end end end context 'whean reading null byte' do let(:hklm) { Win32::Registry::HKEY_LOCAL_MACHINE } let(:puppet_key) { 'SOFTWARE\\Puppet Labs' } let(:subkey_name) { "PuppetRegistryTest#{SecureRandom.uuid}" } let(:value_name) { SecureRandom.uuid } after(:each) do hklm.open(puppet_key, Win32::Registry::KEY_ALL_ACCESS) do |reg| subject.delete_key(reg, subkey_name) end end [ { name: 'REG_SZ', type: Win32::Registry::REG_SZ, value: "reg sz\u0000\u0000 string", expected_value: "reg sz" }, { name: 'REG_SZ_2', type: Win32::Registry::REG_SZ, value: "reg sz 2\x00\x00 string", expected_value: "reg sz 2" }, { name: 'REG_EXPAND_SZ', type: Win32::Registry::REG_EXPAND_SZ, value: "\0\0\0reg expand string", expected_value: "" }, { name: 'REG_EXPAND_SZ_2', type: Win32::Registry::REG_EXPAND_SZ, value: "1\x002\x003\x004\x00\x00\x00\x90\xD8UoY".force_encoding("UTF-16LE"), expected_value: "1234" } ].each do |pair| it 'reads up to the first wide null' do hklm.create("#{puppet_key}\\#{subkey_name}", Win32::Registry::KEY_ALL_ACCESS) do |reg| reg.write(value_name, pair[:type], pair[:value]) end hklm.open("#{puppet_key}\\#{subkey_name}", Win32::Registry::KEY_READ) do |reg| vals = subject.values(reg) expect(vals).to have_key(value_name) subject.each_value(reg) do |_subkey, type, _data| expect(type).to eq(pair[:type]) end written = vals[value_name] expect(written).to eq(pair[:expected_value]) end end end end end context "#values_by_name" do let(:hkey) { double('hklm') } let(:subkey) { double('subkey') } before :each do allow(subject).to receive(:root).and_return(hkey) end context "when reading values" do let(:hklm) { Win32::Registry::HKEY_LOCAL_MACHINE } let(:puppet_key) { "SOFTWARE\\Puppet Labs"} let(:subkey_name) { "PuppetRegistryTest#{SecureRandom.uuid}" } before(:each) do hklm.create("#{puppet_key}\\#{subkey_name}", Win32::Registry::KEY_ALL_ACCESS) do |reg| reg.write('valuename1', Win32::Registry::REG_SZ, 'value1') reg.write('valuename2', Win32::Registry::REG_SZ, 'value2') end end after(:each) do hklm.open(puppet_key, Win32::Registry::KEY_ALL_ACCESS) do |reg| subject.delete_key(reg, subkey_name) end end it "should return only the values for the names specified" do hklm.open("#{puppet_key}\\#{subkey_name}", Win32::Registry::KEY_ALL_ACCESS) do |reg_key| vals = subject.values_by_name(reg_key, ['valuename1', 'missingname']) expect(vals).to have_key('valuename1') expect(vals).to_not have_key('valuename2') expect(vals['valuename1']).to eq('value1') expect(vals['missingname']).to be_nil end end end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/integration/util/windows/user_spec.rb
spec/integration/util/windows/user_spec.rb
require 'spec_helper' describe "Puppet::Util::Windows::User", :if => Puppet::Util::Platform.windows? do describe "2003 without UAC" do before :each do allow(Puppet::Util::Windows::Process).to receive(:windows_major_version).and_return(5) allow(Puppet::Util::Windows::Process).to receive(:supports_elevated_security?).and_return(false) end it "should be an admin if user's token contains the Administrators SID" do expect(Puppet::Util::Windows::User).to receive(:check_token_membership).and_return(true) expect(Puppet::Util::Windows::User).to be_admin end it "should not be an admin if user's token doesn't contain the Administrators SID" do expect(Puppet::Util::Windows::User).to receive(:check_token_membership).and_return(false) expect(Puppet::Util::Windows::User).not_to be_admin end it "should raise an exception if we can't check token membership" do expect(Puppet::Util::Windows::User).to receive(:check_token_membership).and_raise(Puppet::Util::Windows::Error, "Access denied.") expect { Puppet::Util::Windows::User.admin? }.to raise_error(Puppet::Util::Windows::Error, /Access denied./) end end context "2008 with UAC" do before :each do allow(Puppet::Util::Windows::Process).to receive(:windows_major_version).and_return(6) allow(Puppet::Util::Windows::Process).to receive(:supports_elevated_security?).and_return(true) end describe "in local administrators group" do before :each do allow(Puppet::Util::Windows::User).to receive(:check_token_membership).and_return(true) end it "should be an admin if user is running with elevated privileges" do allow(Puppet::Util::Windows::Process).to receive(:elevated_security?).and_return(true) expect(Puppet::Util::Windows::User).to be_admin end it "should not be an admin if user is not running with elevated privileges" do allow(Puppet::Util::Windows::Process).to receive(:elevated_security?).and_return(false) expect(Puppet::Util::Windows::User).not_to be_admin end it "should raise an exception if the process fails to open the process token" do allow(Puppet::Util::Windows::Process).to receive(:elevated_security?).and_raise(Puppet::Util::Windows::Error, "Access denied.") expect { Puppet::Util::Windows::User.admin? }.to raise_error(Puppet::Util::Windows::Error, /Access denied./) end end describe "not in local administrators group" do before :each do allow(Puppet::Util::Windows::User).to receive(:check_token_membership).and_return(false) end it "should not be an admin if user is running with elevated privileges" do allow(Puppet::Util::Windows::Process).to receive(:elevated_security?).and_return(true) expect(Puppet::Util::Windows::User).not_to be_admin end it "should not be an admin if user is not running with elevated privileges" do allow(Puppet::Util::Windows::Process).to receive(:elevated_security?).and_return(false) expect(Puppet::Util::Windows::User).not_to be_admin end end end describe "module function" do let(:username) { 'fabio' } let(:bad_password) { 'goldilocks' } let(:logon_fail_msg) { /Failed to logon user "fabio": Logon failure: unknown user name or bad password./ } def expect_logon_failure_error(&block) expect { yield }.to raise_error { |error| expect(error).to be_a(Puppet::Util::Windows::Error) # https://msdn.microsoft.com/en-us/library/windows/desktop/ms681385(v=vs.85).aspx # ERROR_LOGON_FAILURE 1326 expect(error.code).to eq(1326) } end describe "load_profile" do it "should raise an error when provided with an incorrect username and password" do expect_logon_failure_error { Puppet::Util::Windows::User.load_profile(username, bad_password) } end it "should raise an error when provided with an incorrect username and nil password" do expect_logon_failure_error { Puppet::Util::Windows::User.load_profile(username, nil) } end end describe "logon_user" do let(:fLOGON32_PROVIDER_DEFAULT) {0} let(:fLOGON32_LOGON_INTERACTIVE) {2} let(:fLOGON32_LOGON_NETWORK) {3} let(:token) {'test'} let(:user) {'test'} let(:passwd) {'test'} it "should raise an error when provided with an incorrect username and password" do expect_logon_failure_error { Puppet::Util::Windows::User.logon_user(username, bad_password) } end it "should raise an error when provided with an incorrect username and nil password" do expect_logon_failure_error { Puppet::Util::Windows::User.logon_user(username, nil) } end it 'should raise error given that logon returns false' do allow(Puppet::Util::Windows::User).to receive(:logon_user_by_logon_type).with( user, '.', passwd, fLOGON32_LOGON_NETWORK, fLOGON32_PROVIDER_DEFAULT, anything).and_return (0) allow(Puppet::Util::Windows::User).to receive(:logon_user_by_logon_type).with( user, '.', passwd, fLOGON32_LOGON_INTERACTIVE, fLOGON32_PROVIDER_DEFAULT, anything).and_return(0) expect {Puppet::Util::Windows::User.logon_user(user, passwd) {}} .to raise_error(Puppet::Util::Windows::Error, /Failed to logon user/) end end describe "password_is?" do it "should return false given an incorrect username and password" do expect(Puppet::Util::Windows::User.password_is?(username, bad_password)).to be_falsey end it "should return false given a nil username and an incorrect password" do expect(Puppet::Util::Windows::User.password_is?(nil, bad_password)).to be_falsey end context "with a correct password" do it "should return true even if account restrictions are in place " do error = Puppet::Util::Windows::Error.new('', Puppet::Util::Windows::User::ERROR_ACCOUNT_RESTRICTION) allow(Puppet::Util::Windows::User).to receive(:logon_user).and_raise(error) expect(Puppet::Util::Windows::User.password_is?(username, 'p@ssword')).to be(true) end it "should return true even for an account outside of logon hours" do error = Puppet::Util::Windows::Error.new('', Puppet::Util::Windows::User::ERROR_INVALID_LOGON_HOURS) allow(Puppet::Util::Windows::User).to receive(:logon_user).and_raise(error) expect(Puppet::Util::Windows::User.password_is?(username, 'p@ssword')).to be(true) end it "should return true even for an account not allowed to log into this workstation" do error = Puppet::Util::Windows::Error.new('', Puppet::Util::Windows::User::ERROR_INVALID_WORKSTATION) allow(Puppet::Util::Windows::User).to receive(:logon_user).and_raise(error) expect(Puppet::Util::Windows::User.password_is?(username, 'p@ssword')).to be(true) end it "should return true even for a disabled account" do error = Puppet::Util::Windows::Error.new('', Puppet::Util::Windows::User::ERROR_ACCOUNT_DISABLED) allow(Puppet::Util::Windows::User).to receive(:logon_user).and_raise(error) expect(Puppet::Util::Windows::User.password_is?(username, 'p@ssword')).to be(true) end end end describe "check_token_membership" do it "should not raise an error" do # added just to call an FFI code path on all platforms expect { Puppet::Util::Windows::User.check_token_membership }.not_to raise_error end end describe "default_system_account?" do it "should succesfully identify 'SYSTEM' user as a default system account" do allow(Puppet::Util::Windows::SID).to receive(:name_to_sid).with('SYSTEM').and_return(Puppet::Util::Windows::SID::LocalSystem) expect(Puppet::Util::Windows::User.default_system_account?('SYSTEM')).to eq(true) end it "should succesfully identify 'NETWORK SERVICE' user as a default system account" do allow(Puppet::Util::Windows::SID).to receive(:name_to_sid).with('NETWORK SERVICE').and_return(Puppet::Util::Windows::SID::NtNetwork) expect(Puppet::Util::Windows::User.default_system_account?('NETWORK SERVICE')).to eq(true) end it "should succesfully identify 'LOCAL SERVICE' user as a default system account" do allow(Puppet::Util::Windows::SID).to receive(:name_to_sid).with('LOCAL SERVICE').and_return(Puppet::Util::Windows::SID::NtLocal) expect(Puppet::Util::Windows::User.default_system_account?('LOCAL SERVICE')).to eq(true) end it "should not identify user with unknown sid as a default system account" do allow(Puppet::Util::Windows::SID).to receive(:name_to_sid).with('UnknownUser').and_return(Puppet::Util::Windows::SID::Null) expect(Puppet::Util::Windows::User.default_system_account?('UnknownUser')).to eq(false) end end describe "localsystem?" do before do allow(Puppet::Util::Windows::ADSI).to receive(:computer_name).and_return("myPC") end ['LocalSystem', '.\LocalSystem', 'myPC\LocalSystem', 'lOcALsysTem'].each do |input| it "should succesfully identify #{input} as the 'LocalSystem' account" do expect(Puppet::Util::Windows::User.localsystem?(input)).to eq(true) end end it "should not identify any other user as the 'LocalSystem' account" do expect(Puppet::Util::Windows::User.localsystem?('OtherUser')).to eq(false) end end describe "get_rights" do it "should be empty when given user does not exist" do allow(Puppet::Util::Windows::SID).to receive(:name_to_principal).with('NonExistingUser').and_return(nil) expect(Puppet::Util::Windows::User.get_rights('NonExistingUser')).to eq("") end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/integration/util/windows/process_spec.rb
spec/integration/util/windows/process_spec.rb
require 'spec_helper' describe "Puppet::Util::Windows::Process", :if => Puppet::Util::Platform.windows? do describe "as an admin" do it "should have the SeCreateSymbolicLinkPrivilege necessary to create symlinks" do # this is a bit of a lame duck test since it requires running user to be admin # a better integration test would create a new user with the privilege and verify expect(Puppet::Util::Windows::User).to be_admin expect(Puppet::Util::Windows::Process.process_privilege_symlink?).to be_truthy end it "should be able to lookup a standard Windows process privilege" do Puppet::Util::Windows::Process.lookup_privilege_value('SeShutdownPrivilege') do |luid| expect(luid).not_to be_nil expect(luid).to be_instance_of(Puppet::Util::Windows::Process::LUID) end end it "should raise an error for an unknown privilege name" do expect { Puppet::Util::Windows::Process.lookup_privilege_value('foo') }.to raise_error do |error| expect(error).to be_a(Puppet::Util::Windows::Error) expect(error.code).to eq(1313) # ERROR_NO_SUCH_PRIVILEGE end end end describe "when reading environment variables" do it "will ignore only keys or values with corrupt byte sequences" do env_vars = {} # Create a UTF-16LE version of the below null separated environment string # "a=b\x00c=d\x00e=\xDD\xDD\x00f=g\x00\x00" env_var_block = "a=b\x00".encode(Encoding::UTF_16LE) + "c=d\x00".encode(Encoding::UTF_16LE) + 'e='.encode(Encoding::UTF_16LE) + "\xDD\xDD".force_encoding(Encoding::UTF_16LE) + "\x00".encode(Encoding::UTF_16LE) + "f=g\x00\x00".encode(Encoding::UTF_16LE) env_var_block_bytes = env_var_block.bytes.to_a FFI::MemoryPointer.new(:byte, env_var_block_bytes.count) do |ptr| # uchar here is synonymous with byte ptr.put_array_of_uchar(0, env_var_block_bytes) # stub the block of memory that the Win32 API would typically return via pointer allow(Puppet::Util::Windows::Process).to receive(:GetEnvironmentStringsW).and_return(ptr) # stub out the real API call to free memory, else process crashes allow(Puppet::Util::Windows::Process).to receive(:FreeEnvironmentStringsW) env_vars = Puppet::Util::Windows::Process.get_environment_strings end # based on corrupted memory, the e=\xDD\xDD should have been removed from the set expect(env_vars).to eq({'a' => 'b', 'c' => 'd', 'f' => 'g'}) # and Puppet should emit a warning about it expect(@logs.last.level).to eq(:warning) expect(@logs.last.message).to eq("Discarding environment variable e=\uFFFD which contains invalid bytes") end end describe "when setting environment variables" do let(:name) { SecureRandom.uuid } around :each do |example| begin example.run ensure Puppet::Util::Windows::Process.set_environment_variable(name, nil) end end it "sets environment variables containing '='" do value = 'foo=bar' Puppet::Util::Windows::Process.set_environment_variable(name, value) env = Puppet::Util::Windows::Process.get_environment_strings expect(env[name]).to eq(value) end it "sets environment variables contains spaces" do Puppet::Util::Windows::Process.set_environment_variable(name, '') env = Puppet::Util::Windows::Process.get_environment_strings expect(env[name]).to eq('') end it "sets environment variables containing UTF-8" do rune_utf8 = "\u16A0\u16C7\u16BB\u16EB\u16D2\u16E6\u16A6\u16EB\u16A0\u16B1\u16A9\u16A0\u16A2\u16B1\u16EB\u16A0\u16C1\u16B1\u16AA\u16EB\u16B7\u16D6\u16BB\u16B9\u16E6\u16DA\u16B3\u16A2\u16D7" Puppet::Util::Windows::Process.set_environment_variable(name, rune_utf8) env = Puppet::Util::Windows::Process.get_environment_strings expect(env[name]).to eq(rune_utf8) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/integration/util/windows/monkey_patches/process_spec.rb
spec/integration/util/windows/monkey_patches/process_spec.rb
# frozen_string_literal: true require 'spec_helper' describe 'Process', if: Puppet::Util::Platform.windows? do describe '.create' do context 'with common flags' do it do Process.create( app_name: 'cmd.exe /c echo 123', creation_flags: 0x00000008, process_inherit: false, thread_inherit: false, cwd: 'C:\\' ) end context 'when FFI call fails' do before do allow(Process).to receive(:CreateProcessW).and_return(false) end it 'raises SystemCallError' do expect do Process.create( app_name: 'cmd.exe /c echo 123', creation_flags: 0x00000008 ) end.to raise_error(SystemCallError) end end end context 'with logon' do context 'without password' do it 'raises error' do expect do Process.create( app_name: 'cmd.exe /c echo 123', creation_flags: 0x00000008, with_logon: 'test' ) end.to raise_error(ArgumentError, 'password must be specified if with_logon is used') end end context 'with common flags' do before do allow(Process).to receive(:CreateProcessWithLogonW).and_return(true) end it do Process.create( app_name: 'cmd.exe /c echo 123', creation_flags: 0x00000008, process_inherit: false, thread_inherit: false, with_logon: 'test', password: 'password', cwd: 'C:\\' ) end context 'when FFI call fails' do before do allow(Process).to receive(:CreateProcessWithLogonW).and_return(false) end it 'raises SystemCallError' do expect do Process.create( app_name: 'cmd.exe /c echo 123', creation_flags: 0x00000008, with_logon: 'test', password: 'password' ) end.to raise_error(SystemCallError) end end end end describe 'validations' do context 'when args is not a hash' do it 'raises TypeError' do expect do Process.create('test') end.to raise_error(TypeError, 'hash keyword arguments expected') end end context 'when args key is invalid' do it 'raises ArgumentError' do expect do Process.create(invalid_key: 'test') end.to raise_error(ArgumentError, "invalid key 'invalid_key'") end end context 'when startup_info is invalid' do it 'raises ArgumentError' do expect do Process.create(startup_info: { invalid_key: 'test' }) end.to raise_error(ArgumentError, "invalid startup_info key 'invalid_key'") end end context 'when app_name and command_line are missing' do it 'raises ArgumentError' do expect do Process.create(creation_flags: 0) end.to raise_error(ArgumentError, 'command_line or app_name must be specified') end end context 'when executable is not found' do it 'raises Errno::ENOENT' do expect do Process.create(app_name: 'non_existent') end.to raise_error(Errno::ENOENT) end end end context 'when environment is not specified' do it 'passes local environment' do stdout_read, stdout_write = IO.pipe ENV['TEST_ENV'] = 'B' Process.create( app_name: 'cmd.exe /c echo %TEST_ENV%', creation_flags: 0x00000008, startup_info: { stdout: stdout_write } ) stdout_write.close expect(stdout_read.read.chomp).to eql('B') end end context 'when environment is specified' do it 'does not pass local environment' do stdout_read, stdout_write = IO.pipe ENV['TEST_ENV'] = 'B' Process.create( app_name: 'cmd.exe /c echo %TEST_ENV%', creation_flags: 0x00000008, environment: '', startup_info: { stdout: stdout_write } ) stdout_write.close expect(stdout_read.read.chomp).to eql('%TEST_ENV%') end it 'supports :environment as a string' do stdout_read, stdout_write = IO.pipe Process.create( app_name: 'cmd.exe /c echo %A% %B%', creation_flags: 0x00000008, environment: 'A=C;B=D', startup_info: { stdout: stdout_write } ) stdout_write.close expect(stdout_read.read.chomp).to eql('C D') end it 'supports :environment as a string' do stdout_read, stdout_write = IO.pipe Process.create( app_name: 'cmd.exe /c echo %A% %C%', creation_flags: 0x00000008, environment: ['A=B;X;', 'C=;D;Y'], startup_info: { stdout: stdout_write } ) stdout_write.close expect(stdout_read.read.chomp).to eql('B;X; ;D;Y') end end end describe '.setpriority' do let(:priority) { Process::BELOW_NORMAL_PRIORITY_CLASS } context 'when success' do it 'returns 0' do expect(Process.setpriority(0, Process.pid, priority)).to eql(0) end it 'treats an int argument of zero as the current process' do expect(Process.setpriority(0, 0, priority)).to eql(0) end end context 'when invalid arguments are sent' do it 'raises TypeError' do expect { Process.setpriority('test', 0, priority) }.to raise_error(TypeError) end end context 'when process is not found' do before do allow(Process).to receive(:OpenProcess).and_return(0) end it 'raises SystemCallError' do expect { Process.setpriority(0, 0, priority) }.to raise_error(SystemCallError) end end context 'when priority is not set' do before do allow(Process).to receive(:SetPriorityClass).and_return(false) end it 'raises SystemCallError' do expect { Process.setpriority(0, 0, priority) }.to raise_error(SystemCallError) end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/integration/type/file_spec.rb
spec/integration/type/file_spec.rb
# coding: utf-8 require 'spec_helper' require 'puppet_spec/files' if Puppet::Util::Platform.windows? require 'puppet/util/windows' class WindowsSecurity extend Puppet::Util::Windows::Security end end describe Puppet::Type.type(:file), :uses_checksums => true do include PuppetSpec::Files include_context 'with supported checksum types' let(:catalog) { Puppet::Resource::Catalog.new } let(:path) do # we create a directory first so backups of :path that are stored in # the same directory will also be removed after the tests parent = tmpdir('file_spec') File.join(parent, 'file_testing') end let(:path_protected) do # we create a file inside windows protected folders (C:\Windows, C:\Windows\system32, etc) # the file will also be removed after the tests parent = 'C:\Windows' File.join(parent, 'file_testing') end let(:dir) do # we create a directory first so backups of :path that are stored in # the same directory will also be removed after the tests parent = tmpdir('file_spec') File.join(parent, 'dir_testing') end if Puppet.features.posix? def set_mode(mode, file) File.chmod(mode, file) end def get_mode(file) Puppet::FileSystem.lstat(file).mode end def get_owner(file) Puppet::FileSystem.lstat(file).uid end def get_group(file) Puppet::FileSystem.lstat(file).gid end else class SecurityHelper extend Puppet::Util::Windows::Security end def set_mode(mode, file) SecurityHelper.set_mode(mode, file) end def get_mode(file) SecurityHelper.get_mode(file) end def get_owner(file) SecurityHelper.get_owner(file) end def get_group(file) SecurityHelper.get_group(file) end def get_aces_for_path_by_sid(path, sid) SecurityHelper.get_aces_for_path_by_sid(path, sid) end end around :each do |example| Puppet.override(:environments => Puppet::Environments::Static.new) do example.run end end before do # stub this to not try to create state.yaml allow(Puppet::Util::Storage).to receive(:store) allow_any_instance_of(Puppet::Type.type(:file)).to receive(:file).and_return('my/file.pp') allow_any_instance_of(Puppet::Type.type(:file)).to receive(:line).and_return(5) end it "should not attempt to manage files that do not exist if no means of creating the file is specified" do source = tmpfile('source') catalog.add_resource described_class.new :path => source, :mode => '0755' status = catalog.apply.report.resource_statuses["File[#{source}]"] expect(status).not_to be_failed expect(status).not_to be_changed expect(Puppet::FileSystem.exist?(source)).to be_falsey end describe "when ensure is present using an empty file" do before(:each) do catalog.add_resource(described_class.new(:path => path, :ensure => :present, :backup => :false)) end context "file is present" do before(:each) do FileUtils.touch(path) end it "should do nothing" do report = catalog.apply.report expect(report.resource_statuses["File[#{path}]"]).not_to be_failed expect(Puppet::FileSystem.exist?(path)).to be_truthy end it "should log nothing" do logs = catalog.apply.report.logs expect(logs).to be_empty end end context "file is not present" do it "should create the file" do report = catalog.apply.report expect(report.resource_statuses["File[#{path}]"]).not_to be_failed expect(Puppet::FileSystem.exist?(path)).to be_truthy end it "should log that the file was created" do logs = catalog.apply.report.logs expect(logs.first.source).to eq("/File[#{path}]/ensure") expect(logs.first.message).to eq("created") end end end describe "when ensure is absent" do before(:each) do catalog.add_resource(described_class.new(:path => path, :ensure => :absent, :backup => :false)) end context "file is present" do before(:each) do FileUtils.touch(path) end it "should remove the file" do report = catalog.apply.report expect(report.resource_statuses["File[#{path}]"]).not_to be_failed expect(Puppet::FileSystem.exist?(path)).to be_falsey end it "should log that the file was removed" do logs = catalog.apply.report.logs expect(logs.first.source).to eq("/File[#{path}]/ensure") expect(logs.first.message).to eq("removed") end end context "file is not present" do it "should do nothing" do report = catalog.apply.report expect(report.resource_statuses["File[#{path}]"]).not_to be_failed expect(Puppet::FileSystem.exist?(path)).to be_falsey end it "should log nothing" do logs = catalog.apply.report.logs expect(logs).to be_empty end end # issue #14599 it "should not fail if parts of path aren't directories" do FileUtils.touch(path) catalog.add_resource(described_class.new(:path => File.join(path,'no_such_file'), :ensure => :absent, :backup => :false)) report = catalog.apply.report expect(report.resource_statuses["File[#{File.join(path,'no_such_file')}]"]).not_to be_failed end end describe "when setting permissions" do it "should set the owner" do target = tmpfile_with_contents('target', '') owner = get_owner(target) catalog.add_resource described_class.new( :name => target, :owner => owner ) catalog.apply expect(get_owner(target)).to eq(owner) end it "should set the group" do target = tmpfile_with_contents('target', '') group = get_group(target) catalog.add_resource described_class.new( :name => target, :group => group ) catalog.apply expect(get_group(target)).to eq(group) end describe "when setting mode" do describe "for directories" do let(:target) { tmpdir('dir_mode') } it "should set executable bits for newly created directories" do catalog.add_resource described_class.new(:path => target, :ensure => :directory, :mode => '0600') catalog.apply expect(get_mode(target) & 07777).to eq(0700) end it "should set executable bits for existing readable directories" do set_mode(0600, target) catalog.add_resource described_class.new(:path => target, :ensure => :directory, :mode => '0644') catalog.apply expect(get_mode(target) & 07777).to eq(0755) end it "should not set executable bits for unreadable directories" do begin catalog.add_resource described_class.new(:path => target, :ensure => :directory, :mode => '0300') catalog.apply expect(get_mode(target) & 07777).to eq(0300) ensure # so we can cleanup set_mode(0700, target) end end it "should set user, group, and other executable bits" do catalog.add_resource described_class.new(:path => target, :ensure => :directory, :mode => '0664') catalog.apply expect(get_mode(target) & 07777).to eq(0775) end it "should set executable bits when overwriting a non-executable file" do target_path = tmpfile_with_contents('executable', '') set_mode(0444, target_path) catalog.add_resource described_class.new(:path => target_path, :ensure => :directory, :mode => '0666', :backup => false) catalog.apply expect(get_mode(target_path) & 07777).to eq(0777) expect(File).to be_directory(target_path) end end describe "for files" do it "should not set executable bits" do catalog.add_resource described_class.new(:path => path, :ensure => :file, :mode => '0666') catalog.apply expect(get_mode(path) & 07777).to eq(0666) end context "file is in protected windows directory", :if => Puppet.features.microsoft_windows? do after { FileUtils.rm(path_protected) } it "should set and get the correct mode for files inside protected windows folders" do catalog.add_resource described_class.new(:path => path_protected, :ensure => :file, :mode => '0640') catalog.apply expect(get_mode(path_protected) & 07777).to eq(0640) end it "should not change resource's status inside protected windows folders if mode is the same" do FileUtils.touch(path_protected) set_mode(0644, path_protected) catalog.add_resource described_class.new(:path => path_protected, :ensure => :file, :mode => '0644') result = catalog.apply status = result.report.resource_statuses["File[#{path_protected}]"] expect(status).not_to be_failed expect(status).not_to be_changed end end it "should not set executable bits when replacing an executable directory (#10365)" do pending("bug #10365") FileUtils.mkdir(path) set_mode(0777, path) catalog.add_resource described_class.new(:path => path, :ensure => :file, :mode => '0666', :backup => false, :force => true) catalog.apply expect(get_mode(path) & 07777).to eq(0666) end end describe "for links", :if => described_class.defaultprovider.feature?(:manages_symlinks) do let(:link) { tmpfile('link_mode') } describe "when managing links" do let(:link_target) { tmpfile('target') } before :each do FileUtils.touch(link_target) File.chmod(0444, link_target) Puppet::FileSystem.symlink(link_target, link) end it "should not set the executable bit on the link target" do catalog.add_resource described_class.new(:path => link, :ensure => :link, :mode => '0666', :target => link_target, :links => :manage) catalog.apply expected_target_permissions = Puppet::Util::Platform.windows? ? 0700 : 0444 expect(Puppet::FileSystem.stat(link_target).mode & 07777).to eq(expected_target_permissions) end it "should ignore dangling symlinks (#6856)" do File.delete(link_target) catalog.add_resource described_class.new(:path => link, :ensure => :link, :mode => '0666', :target => link_target, :links => :manage) catalog.apply expect(Puppet::FileSystem.exist?(link)).to be_falsey end it "should create a link to the target if ensure is omitted" do FileUtils.touch(link_target) catalog.add_resource described_class.new(:path => link, :target => link_target) catalog.apply expect(Puppet::FileSystem.exist?(link)).to be_truthy expect(Puppet::FileSystem.lstat(link).ftype).to eq('link') expect(Puppet::FileSystem.readlink(link)).to eq(link_target) end end describe "when following links" do it "should ignore dangling symlinks (#6856)" do target = tmpfile('dangling') FileUtils.touch(target) Puppet::FileSystem.symlink(target, link) File.delete(target) catalog.add_resource described_class.new(:path => path, :source => link, :mode => '0600', :links => :follow) catalog.apply end describe "to a directory" do let(:link_target) { tmpdir('dir_target') } before :each do File.chmod(0600, link_target) Puppet::FileSystem.symlink(link_target, link) end after :each do File.chmod(0750, link_target) end describe "that is readable" do it "should set the executable bits when creating the destination (#10315)" do catalog.add_resource described_class.new(:path => path, :source => link, :mode => '0666', :links => :follow) catalog.apply expect(File).to be_directory(path) expect(get_mode(path) & 07777).to eq(0777) end it "should set the executable bits when overwriting the destination (#10315)" do FileUtils.touch(path) catalog.add_resource described_class.new(:path => path, :source => link, :mode => '0666', :links => :follow, :backup => false) catalog.apply expect(File).to be_directory(path) expect(get_mode(path) & 07777).to eq(0777) end end describe "that is not readable" do before :each do set_mode(0300, link_target) end # so we can cleanup after :each do set_mode(0700, link_target) end it "should set executable bits when creating the destination (#10315)" do catalog.add_resource described_class.new(:path => path, :source => link, :mode => '0666', :links => :follow) catalog.apply expect(File).to be_directory(path) expect(get_mode(path) & 07777).to eq(0777) end it "should set executable bits when overwriting the destination" do FileUtils.touch(path) catalog.add_resource described_class.new(:path => path, :source => link, :mode => '0666', :links => :follow, :backup => false) catalog.apply expect(File).to be_directory(path) expect(get_mode(path) & 07777).to eq(0777) end end end describe "to a file" do let(:link_target) { tmpfile('file_target') } before :each do FileUtils.touch(link_target) Puppet::FileSystem.symlink(link_target, link) end it "should create the file, not a symlink (#2817, #10315)" do catalog.add_resource described_class.new(:path => path, :source => link, :mode => '0600', :links => :follow) catalog.apply expect(File).to be_file(path) expect(get_mode(path) & 07777).to eq(0600) end it "should not give a deprecation warning about using a checksum in content when using source to define content" do FileUtils.touch(path) expect(Puppet).not_to receive(:puppet_deprecation_warning) catalog.add_resource described_class.new(:path => path, :source => link, :links => :follow) catalog.apply end context "overwriting a file" do before :each do FileUtils.touch(path) set_mode(0644, path) catalog.add_resource described_class.new(:path => path, :source => link, :mode => '0600', :links => :follow) end it "should overwrite the file" do catalog.apply expect(File).to be_file(path) expect(get_mode(path) & 07777).to eq(0600) end it "should log that the mode changed" do report = catalog.apply.report expect(report.logs.first.message).to eq("mode changed '0644' to '0600'") expect(report.logs.first.source).to eq("/File[#{path}]/mode") end end end describe "to a link to a directory" do let(:real_target) { tmpdir('real_target') } let(:target) { tmpfile('target') } before :each do File.chmod(0666, real_target) # link -> target -> real_target Puppet::FileSystem.symlink(real_target, target) Puppet::FileSystem.symlink(target, link) end after :each do File.chmod(0750, real_target) end describe "when following all links" do it "should create the destination and apply executable bits (#10315)" do catalog.add_resource described_class.new(:path => path, :source => link, :mode => '0600', :links => :follow) catalog.apply expect(File).to be_directory(path) expect(get_mode(path) & 07777).to eq(0700) end it "should overwrite the destination and apply executable bits" do FileUtils.mkdir(path) catalog.add_resource described_class.new(:path => path, :source => link, :mode => '0600', :links => :follow) catalog.apply expect(File).to be_directory(path) expect(get_mode(path) & 0111).to eq(0100) end end end end end end end describe "when writing files" do shared_examples "files are backed up" do |resource_options| it "should backup files to a filebucket when one is configured" do |example| if Puppet::Util::Platform.windows? && ['sha512', 'sha384'].include?(example.metadata[:digest_algorithm]) skip "PUP-8257: Skip file bucket test on windows for #{example.metadata[:digest_algorithm]} due to long path names" end filebucket = Puppet::Type.type(:filebucket).new :path => tmpfile("filebucket"), :name => "mybucket" file = described_class.new({:path => path, :backup => "mybucket", :content => "foo"}.merge(resource_options)) catalog.add_resource file catalog.add_resource filebucket File.open(file[:path], "w") { |f| f.write("bar") } d = filebucket_digest.call(IO.binread(file[:path])) catalog.apply expect(filebucket.bucket.getfile(d)).to eq("bar") end it "should backup files in the local directory when a backup string is provided" do file = described_class.new({:path => path, :backup => ".bak", :content => "foo"}.merge(resource_options)) catalog.add_resource file File.open(file[:path], "w") { |f| f.puts "bar" } catalog.apply backup = file[:path] + ".bak" expect(Puppet::FileSystem.exist?(backup)).to be_truthy expect(File.read(backup)).to eq("bar\n") end it "should fail if no backup can be performed" do dir = tmpdir("backups") file = described_class.new({:path => File.join(dir, "testfile"), :backup => ".bak", :content => "foo"}.merge(resource_options)) catalog.add_resource file File.open(file[:path], 'w') { |f| f.puts "bar" } # Create a directory where the backup should be so that writing to it fails Dir.mkdir(File.join(dir, "testfile.bak")) allow(Puppet::Util::Log).to receive(:newmessage) catalog.apply expect(File.read(file[:path])).to eq("bar\n") end it "should not backup symlinks", :if => described_class.defaultprovider.feature?(:manages_symlinks) do link = tmpfile("link") dest1 = tmpfile("dest1") dest2 = tmpfile("dest2") bucket = Puppet::Type.type(:filebucket).new :path => tmpfile("filebucket"), :name => "mybucket" file = described_class.new({:path => link, :target => dest2, :ensure => :link, :backup => "mybucket"}.merge(resource_options)) catalog.add_resource file catalog.add_resource bucket File.open(dest1, "w") { |f| f.puts "whatever" } Puppet::FileSystem.symlink(dest1, link) catalog.apply expect(Puppet::FileSystem.readlink(link)).to eq(dest2) expect(Puppet::FileSystem.exist?(bucket[:path])).to be_falsey end it "should backup directories to the local filesystem by copying the whole directory" do file = described_class.new({:path => path, :backup => ".bak", :content => "foo", :force => true}.merge(resource_options)) catalog.add_resource file Dir.mkdir(path) otherfile = File.join(path, "foo") File.open(otherfile, "w") { |f| f.print "yay" } catalog.apply backup = "#{path}.bak" expect(FileTest).to be_directory(backup) expect(File.read(File.join(backup, "foo"))).to eq("yay") end it "should backup directories to filebuckets by backing up each file separately" do |example| if Puppet::Util::Platform.windows? && ['sha512', 'sha384'].include?(example.metadata[:digest_algorithm]) skip "PUP-8257: Skip file bucket test on windows for #{example.metadata[:digest_algorithm]} due to long path names" end bucket = Puppet::Type.type(:filebucket).new :path => tmpfile("filebucket"), :name => "mybucket" file = described_class.new({:path => tmpfile("bucket_backs"), :backup => "mybucket", :content => "foo", :force => true}.merge(resource_options)) catalog.add_resource file catalog.add_resource bucket Dir.mkdir(file[:path]) foofile = File.join(file[:path], "foo") barfile = File.join(file[:path], "bar") File.open(foofile, "w") { |f| f.print "fooyay" } File.open(barfile, "w") { |f| f.print "baryay" } food = filebucket_digest.call(File.read(foofile)) bard = filebucket_digest.call(File.read(barfile)) catalog.apply expect(bucket.bucket.getfile(food)).to eq("fooyay") expect(bucket.bucket.getfile(bard)).to eq("baryay") end end it "should not give a checksum deprecation warning when given actual content" do expect(Puppet).not_to receive(:puppet_deprecation_warning) catalog.add_resource described_class.new(:path => path, :content => 'this is content') catalog.apply end with_digest_algorithms do it_should_behave_like "files are backed up", {} do let(:filebucket_digest) { method(:digest) } end it "should give a checksum deprecation warning" do expect(Puppet).to receive(:puppet_deprecation_warning).with('Using a checksum in a file\'s "content" property is deprecated. The ability to use a checksum to retrieve content from the filebucket using the "content" property will be removed in a future release. The literal value of the "content" property will be written to the file. The checksum retrieval functionality is being replaced by the use of static catalogs. See https://puppet.com/docs/puppet/latest/static_catalogs.html for more information.', {:file => 'my/file.pp', :line => 5}) d = digest("this is some content") catalog.add_resource described_class.new(:path => path, :content => "{#{digest_algorithm}}#{d}") catalog.apply end it "should not give a checksum deprecation warning when no content is specified while checksum and checksum value are used" do expect(Puppet).not_to receive(:puppet_deprecation_warning) d = digest("this is some content") catalog.add_resource described_class.new(:path => path, :checksum => digest_algorithm, :checksum_value => d) catalog.apply end end CHECKSUM_TYPES_TO_TRY.each do |checksum_type, checksum| describe "when checksum_type is #{checksum_type}" do # FileBucket uses the globally configured default for lookup by digest, which right now is SHA256. it_should_behave_like "files are backed up", {:checksum => checksum_type} do let(:filebucket_digest) { Proc.new {|x| Puppet::Util::Checksums.sha256(x)} } end end end end describe "when recursing" do def build_path(dir) Dir.mkdir(dir) File.chmod(0750, dir) @dirs = [dir] @files = [] %w{one two}.each do |subdir| fdir = File.join(dir, subdir) Dir.mkdir(fdir) File.chmod(0750, fdir) @dirs << fdir %w{three}.each do |file| ffile = File.join(fdir, file) @files << ffile File.open(ffile, "w") { |f| f.puts "test #{file}" } File.chmod(0640, ffile) end end end it "should be able to recurse over a nonexistent file" do @file = described_class.new( :name => path, :mode => '0644', :recurse => true, :backup => false ) catalog.add_resource @file expect { @file.eval_generate }.not_to raise_error end it "should be able to recursively set properties on existing files" do path = tmpfile("file_integration_tests") build_path(path) file = described_class.new( :name => path, :mode => '0644', :recurse => true, :backup => false ) catalog.add_resource file catalog.apply expect(@dirs).not_to be_empty @dirs.each do |dir| expect(get_mode(dir) & 007777).to eq(0755) end expect(@files).not_to be_empty @files.each do |dir| expect(get_mode(dir) & 007777).to eq(0644) end end it "should be able to recursively make links to other files", :if => described_class.defaultprovider.feature?(:manages_symlinks) do source = tmpfile("file_link_integration_source") build_path(source) dest = tmpfile("file_link_integration_dest") @file = described_class.new(:name => dest, :target => source, :recurse => true, :ensure => :link, :backup => false) catalog.add_resource @file catalog.apply @dirs.each do |path| link_path = path.sub(source, dest) expect(Puppet::FileSystem.lstat(link_path)).to be_directory end @files.each do |path| link_path = path.sub(source, dest) expect(Puppet::FileSystem.lstat(link_path).ftype).to eq("link") end end it "should be able to recursively copy files" do source = tmpfile("file_source_integration_source") build_path(source) dest = tmpfile("file_source_integration_dest") @file = described_class.new(:name => dest, :source => source, :recurse => true, :backup => false) catalog.add_resource @file catalog.apply @dirs.each do |path| newpath = path.sub(source, dest) expect(Puppet::FileSystem.lstat(newpath)).to be_directory end @files.each do |path| newpath = path.sub(source, dest) expect(Puppet::FileSystem.lstat(newpath).ftype).to eq("file") end end it "should not recursively manage files set to be ignored" do srcdir = tmpfile("ignore_vs_recurse_1") dstdir = tmpfile("ignore_vs_recurse_2") FileUtils.mkdir_p(srcdir) FileUtils.mkdir_p(dstdir) srcfile = File.join(srcdir, "file.src") cpyfile = File.join(dstdir, "file.src") ignfile = File.join(srcdir, "file.ign") File.open(srcfile, "w") { |f| f.puts "don't ignore me" } File.open(ignfile, "w") { |f| f.puts "you better ignore me" } catalog.add_resource described_class.new( :name => srcdir, :ensure => 'directory', :mode => '0755',) catalog.add_resource described_class.new( :name => dstdir, :ensure => 'directory', :mode => "755", :source => srcdir, :recurse => true, :ignore => '*.ign',) catalog.apply expect(Puppet::FileSystem.exist?(srcdir)).to be_truthy expect(Puppet::FileSystem.exist?(dstdir)).to be_truthy expect(File.read(srcfile).strip).to eq("don't ignore me") expect(File.read(cpyfile).strip).to eq("don't ignore me") expect(Puppet::FileSystem.exist?("#{dstdir}/file.ign")).to be_falsey end it "should not recursively manage files managed by a more specific explicit file" do dir = tmpfile("recursion_vs_explicit_1") subdir = File.join(dir, "subdir") file = File.join(subdir, "file") FileUtils.mkdir_p(subdir) File.open(file, "w") { |f| f.puts "" } base = described_class.new(:name => dir, :recurse => true, :backup => false, :mode => "755") sub = described_class.new(:name => subdir, :recurse => true, :backup => false, :mode => "644") catalog.add_resource base catalog.add_resource sub catalog.apply expect(get_mode(file) & 007777).to eq(0644) end it "should recursively manage files even if there is an explicit file whose name is a prefix of the managed file" do managed = File.join(path, "file") generated = File.join(path, "file_with_a_name_starting_with_the_word_file") FileUtils.mkdir_p(path) FileUtils.touch(managed) FileUtils.touch(generated) catalog.add_resource described_class.new(:name => path, :recurse => true, :backup => false, :mode => '0700') catalog.add_resource described_class.new(:name => managed, :recurse => true, :backup => false, :mode => "644") catalog.apply expect(get_mode(generated) & 007777).to eq(0700) end describe "when recursing remote directories" do describe "for the 2nd time" do with_checksum_types "one", "x" do let(:target_file) { File.join(path, 'x') } let(:second_catalog) { Puppet::Resource::Catalog.new } before(:each) do @options = { :path => path, :ensure => :directory, :backup => false, :recurse => true, :checksum => checksum_type, :source => env_path } end it "should not update the target directory" do # Ensure the test believes the source file was written in the past. FileUtils.touch checksum_file, :mtime => Time.now - 20 catalog.add_resource Puppet::Type.send(:newfile, @options) catalog.apply expect(File).to be_directory(path) expect(Puppet::FileSystem.exist?(target_file)).to be_truthy # The 2nd time the resource should not change. second_catalog.add_resource Puppet::Type.send(:newfile, @options) result = second_catalog.apply status = result.report.resource_statuses["File[#{target_file}]"] expect(status).not_to be_failed expect(status).not_to be_changed end it "should update the target directory if contents change" do pending "a way to appropriately mock ctime checks for a particular file" if checksum_type == 'ctime' catalog.add_resource Puppet::Type.send(:newfile, @options) catalog.apply expect(File).to be_directory(path) expect(Puppet::FileSystem.exist?(target_file)).to be_truthy # Change the source file. File.open(checksum_file, "wb") { |f| f.write "some content" } FileUtils.touch target_file, mtime: Time.now - 20 # The 2nd time should update the resource. second_catalog.add_resource Puppet::Type.send(:newfile, @options) result = second_catalog.apply status = result.report.resource_statuses["File[#{target_file}]"] expect(status).not_to be_failed expect(status).to be_changed end end end describe "when sourceselect first" do describe "for a directory" do it "should recursively copy the first directory that exists" do one = File.expand_path('thisdoesnotexist') two = tmpdir('two') FileUtils.mkdir_p(File.join(two, 'three')) FileUtils.touch(File.join(two, 'three', 'four')) catalog.add_resource Puppet::Type.newfile( :path => path, :ensure => :directory, :backup => false, :recurse => true, :sourceselect => :first, :source => [one, two] ) catalog.apply expect(File).to be_directory(path) expect(Puppet::FileSystem.exist?(File.join(path, 'one'))).to be_falsey expect(Puppet::FileSystem.exist?(File.join(path, 'three', 'four'))).to be_truthy end it "should recursively copy an empty directory" do
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
true
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/integration/type/notify_spec.rb
spec/integration/type/notify_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' describe Puppet::Type.type(:notify) do include PuppetSpec::Compiler it "logs the title at notice level" do apply_compiled_manifest(<<-MANIFEST) notify { 'hi': } MANIFEST expect(@logs).to include(an_object_having_attributes(level: :notice, message: 'hi')) end it "logs the message property" do apply_compiled_manifest(<<-MANIFEST) notify { 'title': message => 'hello' } MANIFEST expect(@logs).to include(an_object_having_attributes(level: :notice, message: "defined 'message' as 'hello'")) end it "redacts sensitive message properties" do apply_compiled_manifest(<<-MANIFEST) $message = Sensitive('secret') notify { 'notify1': message => $message } MANIFEST expect(@logs).to include(an_object_having_attributes(level: :notice, message: 'changed [redacted] to [redacted]')) end it "redacts sensitive interpolated message properties" do apply_compiled_manifest(<<-MANIFEST) $message = Sensitive('secret') notify { 'notify2': message => "${message}" } MANIFEST expect(@logs).to include(an_object_having_attributes(level: :notice, message: "defined 'message' as 'Sensitive [value redacted]'")) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/integration/type/package_spec.rb
spec/integration/type/package_spec.rb
require 'spec_helper' describe Puppet::Type.type(:package), "when choosing a default package provider" do before do # the default provider is cached. Puppet::Type.type(:package).defaultprovider = nil end def provider_name(os) case os when 'Solaris' if Puppet::Util::Package.versioncmp(Puppet.runtime[:facter].value(:kernelrelease), '5.11') >= 0 :pkg else :sun end when 'Ubuntu' :apt when 'Debian' :apt when 'Darwin' :pkgdmg when 'RedHat' if ['2.1', '3', '4'].include?(Puppet.runtime[:facter].value('os.distro.release.full')) :up2date else :yum end when 'Fedora' if Puppet::Util::Package.versioncmp(Puppet.runtime[:facter].value('os.release.major'), '22') >= 0 :dnf else :yum end when 'Suse' if Puppet::Util::Package.versioncmp(Puppet.runtime[:facter].value('os.release.major'), '10') >= 0 :zypper else :rug end when 'FreeBSD' :ports when 'OpenBSD' :openbsd when 'DragonFly' :pkgng when 'OpenWrt' :opkg end end it "should have a default provider" do expect(Puppet::Type.type(:package).defaultprovider).not_to be_nil end it "should choose the correct provider each platform" do unless default_provider = provider_name(Puppet.runtime[:facter].value('os.name')) pending("No default provider specified in this test for #{Puppet.runtime[:facter].value('os.name')}") end expect(Puppet::Type.type(:package).defaultprovider.name).to eq(default_provider) end end describe Puppet::Type.type(:package), "when packages with the same name are sourced" do before :each do allow(Process).to receive(:euid).and_return(0) @provider = double( 'provider', :class => Puppet::Type.type(:package).defaultprovider, :clear => nil, :satisfies? => true, :name => :mock, :validate_source => nil ) allow(Puppet::Type.type(:package).defaultprovider).to receive(:new).and_return(@provider) allow(Puppet::Type.type(:package).defaultprovider).to receive(:instances).and_return([]) @package = Puppet::Type.type(:package).new(:name => "yay", :ensure => :present) @catalog = Puppet::Resource::Catalog.new @catalog.add_resource(@package) end describe "with same title" do before { @alt_package = Puppet::Type.type(:package).new(:name => "yay", :ensure => :present) } it "should give an error" do expect { @catalog.add_resource(@alt_package) }.to raise_error Puppet::Resource::Catalog::DuplicateResourceError, 'Duplicate declaration: Package[yay] is already declared; cannot redeclare' end end describe "with different title" do before :each do @alt_package = Puppet::Type.type(:package).new(:name => "yay", :title => "gem-yay", :ensure => :present) end it "should give an error" do provider_name = Puppet::Type.type(:package).defaultprovider.name expect { @catalog.add_resource(@alt_package) }.to raise_error ArgumentError, "Cannot alias Package[gem-yay] to [nil, \"yay\", :#{provider_name}]; resource [\"Package\", nil, \"yay\", :#{provider_name}] already declared" end end describe "from multiple providers", unless: Puppet::Util::Platform.jruby? do provider_class = Puppet::Type.type(:package).provider(:gem) before :each do @alt_provider = provider_class.new @alt_package = Puppet::Type.type(:package).new(:name => "yay", :title => "gem-yay", :provider => @alt_provider, :ensure => :present) @catalog.add_resource(@alt_package) end describe "when it should be present" do [:present, :latest, "1.0"].each do |state| it "should do nothing if it is #{state.to_s}" do expect(@provider).to receive(:properties).and_return(:ensure => state).at_least(:once) expect(@alt_provider).to receive(:properties).and_return(:ensure => state).at_least(:once) @catalog.apply end end [:purged, :absent].each do |state| it "should install if it is #{state.to_s}" do allow(@provider).to receive(:properties).and_return(:ensure => state) expect(@provider).to receive(:install) allow(@alt_provider).to receive(:properties).and_return(:ensure => state) expect(@alt_provider).to receive(:install) @catalog.apply end end end end end describe Puppet::Type.type(:package), 'logging package state transitions' do let(:catalog) { Puppet::Resource::Catalog.new } let(:provider) { double('provider', :class => Puppet::Type.type(:package).defaultprovider, :clear => nil, :validate_source => nil) } before :each do allow(Process).to receive(:euid).and_return(0) allow(provider).to receive(:satisfies?).with([:purgeable]).and_return(true) allow(provider.class).to receive(:instances).and_return([]) allow(provider).to receive(:install).and_return(nil) allow(provider).to receive(:uninstall).and_return(nil) allow(provider).to receive(:purge).and_return(nil) allow(Puppet::Type.type(:package).defaultprovider).to receive(:new).and_return(provider) end after :each do Puppet::Type.type(:package).defaultprovider = nil end # Map of old state -> {new state -> change} states = { # 'installed' transitions to 'removed' or 'purged' :installed => { :installed => nil, :absent => 'removed', :purged => 'purged' }, # 'absent' transitions to 'created' or 'purged' :absent => { :installed => 'created', :absent => nil, :purged => 'purged' }, # 'purged' transitions to 'created' :purged => { :installed => 'created', :absent => nil, :purged => nil } } states.each do |old, new_states| describe "#{old} package" do before :each do allow(provider).to receive(:properties).and_return(:ensure => old) end new_states.each do |new, status| it "ensure => #{new} should log #{status ? status : 'nothing'}" do catalog.add_resource(described_class.new(:name => 'yay', :ensure => new)) catalog.apply logs = catalog.apply.report.logs if status expect(logs.first.source).to eq("/Package[yay]/ensure") expect(logs.first.message).to eq(status) else expect(logs.first).to be_nil end end end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/integration/type/exec_spec.rb
spec/integration/type/exec_spec.rb
require 'spec_helper' require 'puppet_spec/files' describe Puppet::Type.type(:exec), unless: Puppet::Util::Platform.jruby? do include PuppetSpec::Files let(:catalog) { Puppet::Resource::Catalog.new } let(:path) { tmpfile('exec_provider') } before :each do catalog.host_config = false end shared_examples_for 'a valid exec resource' do it "should execute the command" do exec = described_class.new :command => command, :path => ENV['PATH'] catalog.add_resource exec catalog.apply expect(File.read(path)).to eq('foo') end it "should not execute the command if onlyif returns non-zero" do exec = described_class.new( :command => command, :onlyif => "ruby -e 'exit 44'", :path => ENV['PATH'] ) catalog.add_resource exec catalog.apply expect(Puppet::FileSystem.exist?(path)).to be_falsey end it "should execute the command if onlyif returns zero" do exec = described_class.new( :command => command, :onlyif => "ruby -e 'exit 0'", :path => ENV['PATH'] ) catalog.add_resource exec catalog.apply expect(File.read(path)).to eq('foo') end it "should execute the command if unless returns non-zero" do exec = described_class.new( :command => command, :unless => "ruby -e 'exit 45'", :path => ENV['PATH'] ) catalog.add_resource exec catalog.apply expect(File.read(path)).to eq('foo') end it "should not execute the command if unless returns zero" do exec = described_class.new( :command => command, :unless => "ruby -e 'exit 0'", :path => ENV['PATH'] ) catalog.add_resource exec catalog.apply expect(Puppet::FileSystem.exist?(path)).to be_falsey end end context 'when an exec sends an EOF' do let(:command) { ["/bin/bash", "-c", "exec /bin/sleep 1 >/dev/null 2>&1"] } it 'should not take significant user time' do exec = described_class.new :command => command, :path => ENV['PATH'] catalog.add_resource exec timed_apply = Benchmark.measure { catalog.apply } # In testing I found the user time before the patch in 4f35fd262e to be above # 0.3, after the patch it was consistently below 0.1 seconds. expect(timed_apply.utime).to be < 0.3 end end context 'when command is a string' do let(:command) { "ruby -e 'File.open(\"#{path}\", \"w\") { |f| f.print \"foo\" }'" } it_behaves_like 'a valid exec resource' end context 'when command is an array' do let(:command) { ['ruby', '-e', "File.open(\"#{path}\", \"w\") { |f| f.print \"foo\" }"] } it_behaves_like 'a valid exec resource' context 'when is invalid' do let(:command) { [ "ruby -e 'puts 1'" ] } it 'logs error' do exec = described_class.new :command => command, :path => ENV['PATH'] catalog.add_resource exec logs = catalog.apply.report.logs expect(logs[0].message).to eql("Could not find command 'ruby -e 'puts 1''") end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/integration/type/tidy_spec.rb
spec/integration/type/tidy_spec.rb
require 'spec_helper' require 'puppet_spec/compiler' require 'puppet_spec/files' require 'puppet/file_bucket/dipper' describe Puppet::Type.type(:tidy) do include PuppetSpec::Files include PuppetSpec::Compiler before do allow(Puppet::Util::Storage).to receive(:store) end it "should be able to recursively remove directories" do dir = tmpfile("tidy_testing") FileUtils.mkdir_p(File.join(dir, "foo", "bar")) apply_compiled_manifest(<<-MANIFEST) tidy { '#{dir}': recurse => true, rmdirs => true, } MANIFEST expect(Puppet::FileSystem.directory?(dir)).to be_falsey end # Testing #355. it "should be able to remove dead links", :if => Puppet.features.manages_symlinks? do dir = tmpfile("tidy_link_testing") link = File.join(dir, "link") target = tmpfile("no_such_file_tidy_link_testing") Dir.mkdir(dir) Puppet::FileSystem.symlink(target, link) apply_compiled_manifest(<<-MANIFEST) tidy { '#{dir}': recurse => true, } MANIFEST expect(Puppet::FileSystem.symlink?(link)).to be_falsey end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/integration/resource/type_collection_spec.rb
spec/integration/resource/type_collection_spec.rb
require 'spec_helper' require 'puppet_spec/files' require 'puppet/resource/type_collection' describe Puppet::Resource::TypeCollection do describe "when autoloading from modules" do include PuppetSpec::Files before do @dir = tmpfile("autoload_testing") FileUtils.mkdir_p @dir loader = double('loader', load: nil, set_entry: nil) loaders = double('loaders', runtime3_type_loader: loader) expect(Puppet::Pops::Loaders).to receive(:loaders).at_most(:once).and_return(loaders) environment = Puppet::Node::Environment.create(:env, [@dir]) @code = environment.known_resource_types end # Setup a module. def mk_module(name, files = {}) mdir = File.join(@dir, name) mandir = File.join(mdir, "manifests") FileUtils.mkdir_p mandir defs = files.delete(:define) Dir.chdir(mandir) do files.each do |file, classes| File.open("#{file}.pp", "w") do |f| classes.each { |klass| if defs f.puts "define #{klass} {}" else f.puts "class #{klass} {}" end } end end end end it "should return nil when a class can't be found or loaded" do expect(@code.find_hostclass('nosuchclass')).to be_nil end it "should load the module's init file first" do name = "simple" mk_module(name, :init => [name]) expect(@code.find_hostclass(name).name).to eq(name) end it "should be able to load definitions from the module base file" do name = "simpdef" mk_module(name, :define => true, :init => [name]) expect(@code.find_definition(name).name).to eq(name) end it "should be able to load qualified classes from the module base file" do mk_module('both', :init => %w{both both::sub}) expect(@code.find_hostclass("both::sub").name).to eq("both::sub") end it "should be able load classes from a separate file" do mk_module('separate', :init => %w{separate}, :sub => %w{separate::sub}) expect(@code.find_hostclass("separate::sub").name).to eq("separate::sub") end it "should not fail when loading from a separate file if there is no module file" do mk_module('alone', :sub => %w{alone::sub}) expect { @code.find_hostclass("alone::sub") }.not_to raise_error end it "should be able to load definitions from their own file" do name = "mymod" mk_module(name, :define => true, :mydefine => ["mymod::mydefine"]) expect(@code.find_definition("mymod::mydefine").name).to eq("mymod::mydefine") end it 'should be able to load definitions from their own file using uppercased name' do name = 'mymod' mk_module(name, :define => true, :mydefine => ['mymod::mydefine']) expect(@code.find_definition('Mymod::Mydefine')).not_to be_nil end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/integration/resource/catalog_spec.rb
spec/integration/resource/catalog_spec.rb
require 'spec_helper' describe Puppet::Resource::Catalog do describe "when using the indirector" do before do # This is so the tests work w/out networking. allow(Facter).to receive(:to_hash).and_return({"hostname" => "foo.domain.com"}) allow(Facter).to receive(:value).and_return("eh") end it "should be able to delegate to the :yaml terminus" do allow(Puppet::Resource::Catalog.indirection).to receive(:terminus_class).and_return(:yaml) # Load now, before we stub the exists? method. terminus = Puppet::Resource::Catalog.indirection.terminus(:yaml) expect(terminus).to receive(:path).with("me").and_return("/my/yaml/file") expect(Puppet::FileSystem).to receive(:exist?).with("/my/yaml/file").and_return(false) expect(Puppet::Resource::Catalog.indirection.find("me")).to be_nil end it "should be able to delegate to the :compiler terminus" do allow(Puppet::Resource::Catalog.indirection).to receive(:terminus_class).and_return(:compiler) # Load now, before we stub the exists? method. compiler = Puppet::Resource::Catalog.indirection.terminus(:compiler) node = double('node', :add_server_facts => nil, :trusted_data= => nil, :environment => nil) expect(Puppet::Node.indirection).to receive(:find).and_return(node) expect(compiler).to receive(:compile).with(node, anything).and_return(nil) expect(Puppet::Resource::Catalog.indirection.find("me")).to be_nil end it "should pass provided node information directly to the terminus" do node = double('node') terminus = double('terminus') allow(terminus).to receive(:validate) expect(terminus).to receive(:find) { |request| expect(request.options[:use_node]).to eq(node) } allow(Puppet::Resource::Catalog.indirection).to receive(:terminus).and_return(terminus) Puppet::Resource::Catalog.indirection.find("me", :use_node => node) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/integration/node/facts_spec.rb
spec/integration/node/facts_spec.rb
require 'spec_helper' describe Puppet::Node::Facts do describe "when using the indirector" do it "should expire any cached node instances when it is saved" do allow(Puppet::Node::Facts.indirection).to receive(:terminus_class).and_return(:yaml) expect(Puppet::Node::Facts.indirection.terminus(:yaml)).to equal(Puppet::Node::Facts.indirection.terminus(:yaml)) terminus = Puppet::Node::Facts.indirection.terminus(:yaml) allow(terminus).to receive(:save) expect(Puppet::Node.indirection).to receive(:expire).with("me", be_a(Hash).or(be_nil)) facts = Puppet::Node::Facts.new("me") Puppet::Node::Facts.indirection.save(facts) end it "should be able to delegate to the :yaml terminus" do allow(Puppet::Node::Facts.indirection).to receive(:terminus_class).and_return(:yaml) # Load now, before we stub the exists? method. terminus = Puppet::Node::Facts.indirection.terminus(:yaml) expect(terminus).to receive(:path).with("me").and_return("/my/yaml/file") expect(Puppet::FileSystem).to receive(:exist?).with("/my/yaml/file").and_return(false) expect(Puppet::Node::Facts.indirection.find("me")).to be_nil end it "should be able to delegate to the :facter terminus" do allow(Puppet::Node::Facts.indirection).to receive(:terminus_class).and_return(:facter) expect(Facter).to receive(:resolve).and_return({1 => 2}) facts = Puppet::Node::Facts.new("me") expect(Puppet::Node::Facts).to receive(:new).with("me", {1 => 2}).and_return(facts) expect(Puppet::Node::Facts.indirection.find("me")).to equal(facts) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/integration/node/environment_spec.rb
spec/integration/node/environment_spec.rb
require 'spec_helper' require 'puppet_spec/files' require 'puppet_spec/scope' require 'matchers/resource' describe Puppet::Node::Environment do include PuppetSpec::Files include Matchers::Resource def a_module_in(name, dir) Dir.mkdir(dir) moddir = File.join(dir, name) Dir.mkdir(moddir) moddir end it "should be able to return each module from its environment with the environment, name, and path set correctly" do base = tmpfile("env_modules") Dir.mkdir(base) dirs = [] mods = {} %w{1 2}.each do |num| dir = File.join(base, "dir#{num}") dirs << dir mods["mod#{num}"] = a_module_in("mod#{num}", dir) end environment = Puppet::Node::Environment.create(:foo, dirs) environment.modules.each do |mod| expect(mod.environment).to eq(environment) expect(mod.path).to eq(mods[mod.name]) end end it "should expand 8.3 paths on Windows when creating an environment", :if => Puppet::Util::Platform.windows? do pending("GH runners seem to have disabled 8.3 support") # asking for short names only works on paths that exist base = Puppet::Util::Windows::File.get_short_pathname(tmpdir("env_modules")) parent_modules_dir = File.join(base, 'testmoduledir') # make sure the paths have ~ in them, indicating unexpanded 8.3 paths expect(parent_modules_dir).to match(/~/) module_dir = a_module_in('testmodule', parent_modules_dir) # create the environment with unexpanded 8.3 paths environment = Puppet::Node::Environment.create(:foo, [parent_modules_dir]) # and expect fully expanded paths inside the environment # necessary for comparing module paths internally by the parser expect(environment.modulepath).to eq([Puppet::FileSystem.expand_path(parent_modules_dir)]) expect(environment.modules.first.path).to eq(Puppet::FileSystem.expand_path(module_dir)) end it "should not yield the same module from different module paths" do base = tmpfile("env_modules") Dir.mkdir(base) dirs = [] %w{1 2}.each do |num| dir = File.join(base, "dir#{num}") dirs << dir a_module_in("mod", dir) end environment = Puppet::Node::Environment.create(:foo, dirs) mods = environment.modules expect(mods.length).to eq(1) expect(mods[0].path).to eq(File.join(base, "dir1", "mod")) end it "should not yield a module with the same name as a defined Bolt project" do project_path = File.join(tmpfile('project'), 'bolt_project') FileUtils.mkdir_p(project_path) project = Struct.new("Project", :name, :path, :load_as_module?).new('project', project_path, true) Puppet.override(bolt_project: project) do base = tmpfile("base") FileUtils.mkdir_p([File.join(base, 'project'), File.join(base, 'other')]) environment = Puppet::Node::Environment.create(:env, [base]) mods = environment.modules expect(mods.length).to eq(2) expect(mods.map(&:path)).to eq([project_path, File.join(base, 'other')]) end end shared_examples_for "the environment's initial import" do |settings| it "a manifest referring to a directory invokes parsing of all its files in sorted order" do settings.each do |name, value| Puppet[name] = value end # fixture has three files 00_a.pp, 01_b.pp, and 02_c.pp. The 'b' file # depends on 'a' being evaluated first. The 'c' file is empty (to ensure # empty things do not break the directory import). # dirname = my_fixture('sitedir') # Set the manifest to the directory to make it parse and combine them when compiling node = Puppet::Node.new('testnode', :environment => Puppet::Node::Environment.create(:testing, [], dirname)) catalog = Puppet::Parser::Compiler.compile(node) expect(catalog).to have_resource('Class[A]') expect(catalog).to have_resource('Class[B]') expect(catalog).to have_resource('Notify[variables]').with_parameter(:message, "a: 10, b: 10") end end shared_examples_for "the environment's initial import in 4x" do |settings| it "a manifest referring to a directory invokes recursive parsing of all its files in sorted order" do settings.each do |name, value| Puppet[name] = value end # fixture has three files 00_a.pp, 01_b.pp, and 02_c.pp. The 'b' file # depends on 'a' being evaluated first. The 'c' file is empty (to ensure # empty things do not break the directory import). # dirname = my_fixture('sitedir2') # Set the manifest to the directory to make it parse and combine them when compiling node = Puppet::Node.new('testnode', :environment => Puppet::Node::Environment.create(:testing, [], dirname)) catalog = Puppet::Parser::Compiler.compile(node) expect(catalog).to have_resource('Class[A]') expect(catalog).to have_resource('Class[B]') expect(catalog).to have_resource('Notify[variables]').with_parameter(:message, "a: 10, b: 10 c: 20") end end describe 'using 4x parser' do it_behaves_like "the environment's initial import", # fixture uses variables that are set in a particular order (this ensures # that files are parsed and combined in the right order or an error will # be raised if 'b' is evaluated before 'a'). :strict_variables => true end describe 'using 4x parser' do it_behaves_like "the environment's initial import in 4x", # fixture uses variables that are set in a particular order (this ensures # that files are parsed and combined in the right order or an error will # be raised if 'b' is evaluated before 'a'). :strict_variables => true end describe "#extralibs on Windows", :if => Puppet::Util::Platform.windows? do describe "with UTF8 characters in PUPPETLIB" do let(:rune_utf8) { "\u16A0\u16C7\u16BB\u16EB\u16D2\u16E6\u16A6\u16EB\u16A0\u16B1\u16A9\u16A0\u16A2\u16B1\u16EB\u16A0\u16C1\u16B1\u16AA\u16EB\u16B7\u16D6\u16BB\u16B9\u16E6\u16DA\u16B3\u16A2\u16D7" } before { Puppet::Util::Windows::Process.set_environment_variable('PUPPETLIB', rune_utf8) } it "should use UTF8 characters in PUPPETLIB environment variable" do expect(Puppet::Node::Environment.extralibs()).to eq([rune_utf8]) end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/integration/transaction/report_spec.rb
spec/integration/transaction/report_spec.rb
require 'spec_helper' require 'puppet_spec/files' describe Puppet::Transaction::Report do before :each do # Enable persistence during tests allow_any_instance_of(Puppet::Transaction::Persistence).to receive(:enabled?).and_return(true) end describe "when using the indirector" do it "should be able to delegate to the :processor terminus" do allow(Puppet::Transaction::Report.indirection).to receive(:terminus_class).and_return(:processor) terminus = Puppet::Transaction::Report.indirection.terminus(:processor) allow(Facter).to receive(:value).and_return("host.domain.com") report = Puppet::Transaction::Report.new expect(terminus).to receive(:process).with(report) Puppet::Transaction::Report.indirection.save(report) end end describe "when dumping to YAML" do it "should not contain TagSet objects" do resource = Puppet::Resource.new(:notify, "Hello") ral_resource = resource.to_ral status = Puppet::Resource::Status.new(ral_resource) log = Puppet::Util::Log.new(:level => :info, :message => "foo") report = Puppet::Transaction::Report.new report.add_resource_status(status) report << log expect(YAML.dump(report)).to_not match('Puppet::Util::TagSet') end end describe "inference checking" do include PuppetSpec::Files require 'puppet/configurer' def run_catalogs(resources1, resources2, noop1 = false, noop2 = false, &block) last_run_report = nil expect(Puppet::Transaction::Report.indirection).to receive(:save) do |report, x| last_run_report = report true end.exactly(4) Puppet[:report] = true Puppet[:noop] = noop1 configurer = Puppet::Configurer.new configurer.run :catalog => new_catalog(resources1) yield block if block last_report = last_run_report Puppet[:noop] = noop2 configurer = Puppet::Configurer.new configurer.run :catalog => new_catalog(resources2) expect(last_report).not_to eq(last_run_report) return last_run_report end def new_blank_catalog Puppet::Resource::Catalog.new("testing", Puppet.lookup(:environments).get(Puppet[:environment])) end def new_catalog(resources = []) new_cat = new_blank_catalog [resources].flatten.each do |resource| new_cat.add_resource(resource) end new_cat end def get_cc_count(report) report.metrics["resources"].values.each do |v| if v[0] == "corrective_change" return v[2] end end return nil end describe "for agent runs that contain" do it "notifies with catalog change" do report = run_catalogs(Puppet::Type.type(:notify).new(:title => "testing", :message => "foo"), Puppet::Type.type(:notify).new(:title => "testing", :message => "foobar")) expect(report.status).to eq("changed") rs = report.resource_statuses["Notify[testing]"] expect(rs.events.size).to eq(1) expect(rs.events[0].corrective_change).to eq(false) expect(rs.corrective_change).to eq(false) expect(report.corrective_change).to eq(false) expect(get_cc_count(report)).to eq(0) end it "notifies with no catalog change" do report = run_catalogs(Puppet::Type.type(:notify).new(:title => "testing", :message => "foo"), Puppet::Type.type(:notify).new(:title => "testing", :message => "foo")) expect(report.status).to eq("changed") rs = report.resource_statuses["Notify[testing]"] expect(rs.events.size).to eq(1) expect(rs.events[0].corrective_change).to eq(false) expect(rs.corrective_change).to eq(false) expect(report.corrective_change).to eq(false) expect(get_cc_count(report)).to eq(0) end it "new file resource" do file = tmpfile("test_file") report = run_catalogs([], Puppet::Type.type(:file).new(:title => file, :content => "mystuff")) expect(report.status).to eq("changed") rs = report.resource_statuses["File[#{file}]"] expect(rs.events.size).to eq(1) expect(rs.events[0].corrective_change).to eq(false) expect(rs.corrective_change).to eq(false) expect(report.corrective_change).to eq(false) expect(get_cc_count(report)).to eq(0) end it "removal of a file resource" do file = tmpfile("test_file") report = run_catalogs(Puppet::Type.type(:file).new(:title => file, :content => "mystuff"), []) expect(report.status).to eq("unchanged") expect(report.resource_statuses["File[#{file}]"]).to eq(nil) expect(report.corrective_change).to eq(false) expect(get_cc_count(report)).to eq(0) end it "file with a title change" do file1 = tmpfile("test_file") file2 = tmpfile("test_file") report = run_catalogs(Puppet::Type.type(:file).new(:title => file1, :content => "mystuff"), Puppet::Type.type(:file).new(:title => file2, :content => "mystuff")) expect(report.status).to eq("changed") expect(report.resource_statuses["File[#{file1}]"]).to eq(nil) rs = report.resource_statuses["File[#{file2}]"] expect(rs.events.size).to eq(1) expect(rs.events[0].corrective_change).to eq(false) expect(rs.corrective_change).to eq(false) expect(report.corrective_change).to eq(false) expect(get_cc_count(report)).to eq(0) end it "file with no catalog change" do file = tmpfile("test_file") report = run_catalogs(Puppet::Type.type(:file).new(:title => file, :content => "mystuff"), Puppet::Type.type(:file).new(:title => file, :content => "mystuff")) expect(report.status).to eq("unchanged") rs = report.resource_statuses["File[#{file}]"] expect(rs.events.size).to eq(0) expect(rs.corrective_change).to eq(false) expect(report.corrective_change).to eq(false) expect(get_cc_count(report)).to eq(0) end it "file with a new parameter" do file = tmpfile("test_file") report = run_catalogs(Puppet::Type.type(:file).new(:title => file, :content => "mystuff"), Puppet::Type.type(:file).new(:title => file, :content => "mystuff", :loglevel => :debug)) expect(report.status).to eq("unchanged") rs = report.resource_statuses["File[#{file}]"] expect(rs.events.size).to eq(0) expect(rs.corrective_change).to eq(false) expect(report.corrective_change).to eq(false) expect(get_cc_count(report)).to eq(0) end it "file with a removed parameter" do file = tmpfile("test_file") report = run_catalogs(Puppet::Type.type(:file).new(:title => file, :content => "mystuff", :loglevel => :debug), Puppet::Type.type(:file).new(:title => file, :content => "mystuff")) expect(report.status).to eq("unchanged") rs = report.resource_statuses["File[#{file}]"] expect(rs.events.size).to eq(0) expect(rs.corrective_change).to eq(false) expect(report.corrective_change).to eq(false) expect(get_cc_count(report)).to eq(0) end it "file with a property no longer managed" do file = tmpfile("test_file") report = run_catalogs(Puppet::Type.type(:file).new(:title => file, :content => "mystuff"), Puppet::Type.type(:file).new(:title => file)) expect(report.status).to eq("unchanged") rs = report.resource_statuses["File[#{file}]"] expect(rs.events.size).to eq(0) expect(rs.corrective_change).to eq(false) expect(report.corrective_change).to eq(false) expect(get_cc_count(report)).to eq(0) end it "file with no catalog change, but file changed between runs" do file = tmpfile("test_file") report = run_catalogs(Puppet::Type.type(:file).new(:title => file, :content => "mystuff"), Puppet::Type.type(:file).new(:title => file, :content => "mystuff")) do File.open(file, 'w') do |f| f.puts "some content" end end expect(report.status).to eq("changed") rs = report.resource_statuses["File[#{file}]"] expect(rs.events.size).to eq(1) expect(rs.events[0].corrective_change).to eq(true) expect(rs.corrective_change).to eq(true) expect(report.corrective_change).to eq(true) expect(get_cc_count(report)).to eq(1) end it "file with catalog change, but file changed between runs that matched catalog change" do file = tmpfile("test_file") report = run_catalogs(Puppet::Type.type(:file).new(:title => file, :content => "mystuff"), Puppet::Type.type(:file).new(:title => file, :content => "some content")) do File.open(file, 'w') do |f| f.write "some content" end end expect(report.status).to eq("unchanged") rs = report.resource_statuses["File[#{file}]"] expect(rs.events.size).to eq(0) expect(rs.corrective_change).to eq(false) expect(report.corrective_change).to eq(false) expect(get_cc_count(report)).to eq(0) end it "file with catalog change, but file changed between runs that did not match catalog change" do file = tmpfile("test_file") report = run_catalogs(Puppet::Type.type(:file).new(:title => file, :content => "mystuff1"), Puppet::Type.type(:file).new(:title => file, :content => "mystuff2")) do File.open(file, 'w') do |f| f.write "some content" end end expect(report.status).to eq("changed") rs = report.resource_statuses["File[#{file}]"] expect(rs.events.size).to eq(1) expect(rs.events[0].corrective_change).to eq(true) expect(rs.corrective_change).to eq(true) expect(report.corrective_change).to eq(true) expect(get_cc_count(report)).to eq(1) end it "file with catalog change" do file = tmpfile("test_file") report = run_catalogs(Puppet::Type.type(:file).new(:title => file, :content => "mystuff1"), Puppet::Type.type(:file).new(:title => file, :content => "mystuff2")) expect(report.status).to eq("changed") rs = report.resource_statuses["File[#{file}]"] expect(rs.events.size).to eq(1) expect(rs.events[0].corrective_change).to eq(false) expect(rs.corrective_change).to eq(false) expect(report.corrective_change).to eq(false) expect(get_cc_count(report)).to eq(0) end it "file with ensure property set to present" do file = tmpfile("test_file") report = run_catalogs(Puppet::Type.type(:file).new(:title => file, :ensure => :present), Puppet::Type.type(:file).new(:title => file, :ensure => :present)) expect(report.status).to eq("unchanged") rs = report.resource_statuses["File[#{file}]"] expect(rs.events.size).to eq(0) expect(rs.corrective_change).to eq(false) expect(report.corrective_change).to eq(false) expect(get_cc_count(report)).to eq(0) end it "file with ensure property change file => absent" do file = tmpfile("test_file") report = run_catalogs(Puppet::Type.type(:file).new(:title => file, :ensure => :file), Puppet::Type.type(:file).new(:title => file, :ensure => :absent)) expect(report.status).to eq("changed") rs = report.resource_statuses["File[#{file}]"] expect(rs.events.size).to eq(1) expect(rs.events[0].corrective_change).to eq(false) expect(rs.corrective_change).to eq(false) expect(report.corrective_change).to eq(false) expect(get_cc_count(report)).to eq(0) end it "file with ensure property change present => absent" do file = tmpfile("test_file") report = run_catalogs(Puppet::Type.type(:file).new(:title => file, :ensure => :present), Puppet::Type.type(:file).new(:title => file, :ensure => :absent)) expect(report.status).to eq("changed") rs = report.resource_statuses["File[#{file}]"] expect(rs.events.size).to eq(1) expect(rs.events[0].corrective_change).to eq(false) expect(rs.corrective_change).to eq(false) expect(report.corrective_change).to eq(false) expect(get_cc_count(report)).to eq(0) end it "link with ensure property change present => absent", :unless => Puppet::Util::Platform.windows? do file = tmpfile("test_file") FileUtils.symlink(file, tmpfile("test_link")) report = run_catalogs(Puppet::Type.type(:file).new(:title => file, :ensure => :present), Puppet::Type.type(:file).new(:title => file, :ensure => :absent)) expect(report.status).to eq("changed") rs = report.resource_statuses["File[#{file}]"] expect(rs.events.size).to eq(1) expect(rs.events[0].corrective_change).to eq(false) expect(rs.corrective_change).to eq(false) expect(report.corrective_change).to eq(false) expect(get_cc_count(report)).to eq(0) end it "file with ensure property change absent => present" do file = tmpfile("test_file") report = run_catalogs(Puppet::Type.type(:file).new(:title => file, :ensure => :absent), Puppet::Type.type(:file).new(:title => file, :ensure => :present)) expect(report.status).to eq("changed") rs = report.resource_statuses["File[#{file}]"] expect(rs.events.size).to eq(1) expect(rs.events[0].corrective_change).to eq(false) expect(rs.corrective_change).to eq(false) expect(report.corrective_change).to eq(false) expect(get_cc_count(report)).to eq(0) end it "new resource in catalog" do file = tmpfile("test_file") report = run_catalogs([], Puppet::Type.type(:file).new(:title => file, :content => "mystuff asdf")) expect(report.status).to eq("changed") rs = report.resource_statuses["File[#{file}]"] expect(rs.events.size).to eq(1) expect(rs.events[0].corrective_change).to eq(false) expect(rs.corrective_change).to eq(false) expect(report.corrective_change).to eq(false) expect(get_cc_count(report)).to eq(0) end it "exec with idempotence issue", :unless => Puppet::Util::Platform.windows? || RUBY_PLATFORM == 'java' do report = run_catalogs(Puppet::Type.type(:exec).new(:title => "exec1", :command => "/bin/echo foo"), Puppet::Type.type(:exec).new(:title => "exec1", :command => "/bin/echo foo")) expect(report.status).to eq("changed") # Of note here, is that the main idempotence issues lives in 'returns' rs = report.resource_statuses["Exec[exec1]"] expect(rs.events.size).to eq(1) expect(rs.events[0].corrective_change).to eq(true) expect(rs.corrective_change).to eq(true) expect(report.corrective_change).to eq(true) expect(get_cc_count(report)).to eq(1) end it "exec with no idempotence issue", :unless => Puppet::Util::Platform.windows? || RUBY_PLATFORM == 'java' do report = run_catalogs(Puppet::Type.type(:exec).new(:title => "exec1", :command => "echo foo", :path => "/bin", :unless => "ls"), Puppet::Type.type(:exec).new(:title => "exec1", :command => "echo foo", :path => "/bin", :unless => "ls")) expect(report.status).to eq("unchanged") # Of note here, is that the main idempotence issues lives in 'returns' rs = report.resource_statuses["Exec[exec1]"] expect(rs.events.size).to eq(0) expect(rs.corrective_change).to eq(false) expect(report.corrective_change).to eq(false) expect(get_cc_count(report)).to eq(0) end it "noop on second run, file with no catalog change, but file changed between runs" do file = tmpfile("test_file") report = run_catalogs(Puppet::Type.type(:file).new(:title => file, :content => "mystuff"), Puppet::Type.type(:file).new(:title => file, :content => "mystuff"), false, true) do File.open(file, 'w') do |f| f.puts "some content" end end expect(report.status).to eq("unchanged") rs = report.resource_statuses["File[#{file}]"] expect(rs.events[0].corrective_change).to eq(true) expect(rs.events.size).to eq(1) expect(rs.corrective_change).to eq(true) expect(report.corrective_change).to eq(true) expect(get_cc_count(report)).to eq(1) end it "noop on all subsequent runs, file with no catalog change, but file changed between run 1 and 2" do file = tmpfile("test_file") report = run_catalogs(Puppet::Type.type(:file).new(:title => file, :content => "mystuff"), Puppet::Type.type(:file).new(:title => file, :content => "mystuff"), false, true) do File.open(file, 'w') do |f| f.puts "some content" end end expect(report.status).to eq("unchanged") rs = report.resource_statuses["File[#{file}]"] expect(rs.events[0].corrective_change).to eq(true) expect(rs.events.size).to eq(1) expect(rs.corrective_change).to eq(true) expect(report.corrective_change).to eq(true) expect(get_cc_count(report)).to eq(1) # Simply run the catalog twice again, but this time both runs are noop to # test if the corrective field is still set. report = run_catalogs(Puppet::Type.type(:file).new(:title => file, :content => "mystuff"), Puppet::Type.type(:file).new(:title => file, :content => "mystuff"), true, true) expect(report.status).to eq("unchanged") rs = report.resource_statuses["File[#{file}]"] expect(rs.events[0].corrective_change).to eq(true) expect(rs.events.size).to eq(1) expect(rs.corrective_change).to eq(true) expect(report.corrective_change).to eq(true) expect(get_cc_count(report)).to eq(1) end it "noop on first run, file with no catalog change, but file changed between runs" do file = tmpfile("test_file") report = run_catalogs(Puppet::Type.type(:file).new(:title => file, :content => "mystuff"), Puppet::Type.type(:file).new(:title => file, :content => "mystuff"), true, false) do File.open(file, 'w') do |f| f.puts "some content" end end expect(report.status).to eq("changed") rs = report.resource_statuses["File[#{file}]"] expect(rs.events[0].corrective_change).to eq(true) expect(rs.events.size).to eq(1) expect(rs.corrective_change).to eq(true) expect(report.corrective_change).to eq(true) expect(get_cc_count(report)).to eq(1) end it "noop on both runs, file with no catalog change, but file changed between runs" do file = tmpfile("test_file") report = run_catalogs(Puppet::Type.type(:file).new(:title => file, :content => "mystuff"), Puppet::Type.type(:file).new(:title => file, :content => "mystuff"), true, true) do File.open(file, 'w') do |f| f.puts "some content" end end expect(report.status).to eq("unchanged") rs = report.resource_statuses["File[#{file}]"] expect(rs.events.size).to eq(1) expect(rs.events[0].corrective_change).to eq(true) expect(rs.corrective_change).to eq(true) expect(report.corrective_change).to eq(true) expect(get_cc_count(report)).to eq(1) end it "noop on 4 runs, file with no catalog change, but file changed between runs 1 and 2" do file = tmpfile("test_file") report = run_catalogs(Puppet::Type.type(:file).new(:title => file, :content => "mystuff"), Puppet::Type.type(:file).new(:title => file, :content => "mystuff"), true, true) do File.open(file, 'w') do |f| f.puts "some content" end end expect(report.status).to eq("unchanged") rs = report.resource_statuses["File[#{file}]"] expect(rs.events.size).to eq(1) expect(rs.events[0].corrective_change).to eq(true) expect(rs.corrective_change).to eq(true) expect(report.corrective_change).to eq(true) expect(get_cc_count(report)).to eq(1) report = run_catalogs(Puppet::Type.type(:file).new(:title => file, :content => "mystuff"), Puppet::Type.type(:file).new(:title => file, :content => "mystuff"), true, true) expect(report.status).to eq("unchanged") rs = report.resource_statuses["File[#{file}]"] expect(rs.events.size).to eq(1) expect(rs.events[0].corrective_change).to eq(true) expect(rs.corrective_change).to eq(true) expect(report.corrective_change).to eq(true) expect(get_cc_count(report)).to eq(1) end it "noop on both runs, file already exists but with catalog change each time" do file = tmpfile("test_file") File.open(file, 'w') do |f| f.puts "some content" end report = run_catalogs(Puppet::Type.type(:file).new(:title => file, :content => "a"), Puppet::Type.type(:file).new(:title => file, :content => "b"), true, true) expect(report.status).to eq("unchanged") rs = report.resource_statuses["File[#{file}]"] expect(rs.events.size).to eq(1) expect(rs.events[0].corrective_change).to eq(false) expect(rs.corrective_change).to eq(false) expect(report.corrective_change).to eq(false) expect(get_cc_count(report)).to eq(0) end it "file failure should not return corrective_change" do # Making the path a child path (with no parent) forces a failure file = tmpfile("test_file") + "/foo" report = run_catalogs(Puppet::Type.type(:file).new(:title => file, :content => "a"), Puppet::Type.type(:file).new(:title => file, :content => "b"), false, false) expect(report.status).to eq("failed") rs = report.resource_statuses["File[#{file}]"] expect(rs.events.size).to eq(1) expect(rs.events[0].corrective_change).to eq(false) expect(rs.corrective_change).to eq(false) expect(report.corrective_change).to eq(false) expect(get_cc_count(report)).to eq(0) end it "file skipped with file change between runs will not show corrective_change" do # Making the path a child path (with no parent) forces a failure file = tmpfile("test_file") + "/foo" resources1 = [ Puppet::Type.type(:file).new(:title => file, :content => "a", :notify => "Notify['foo']"), Puppet::Type.type(:notify).new(:title => "foo") ] resources2 = [ Puppet::Type.type(:file).new(:title => file, :content => "a", :notify => "Notify[foo]"), Puppet::Type.type(:notify).new(:title => "foo", :message => "foo") ] report = run_catalogs(resources1, resources2, false, false) expect(report.status).to eq("failed") rs = report.resource_statuses["File[#{file}]"] expect(rs.events.size).to eq(1) expect(rs.events[0].corrective_change).to eq(false) expect(rs.corrective_change).to eq(false) rs = report.resource_statuses["Notify[foo]"] expect(rs.events.size).to eq(0) expect(rs.corrective_change).to eq(false) expect(report.corrective_change).to eq(false) expect(get_cc_count(report)).to eq(0) end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/integration/indirector/direct_file_server_spec.rb
spec/integration/indirector/direct_file_server_spec.rb
require 'spec_helper' require 'puppet/indirector/file_content/file' require 'puppet/indirector/file_metadata/file' describe Puppet::Indirector::DirectFileServer, " when interacting with the filesystem and the model" do include PuppetSpec::Files before do # We just test a subclass, since it's close enough. @terminus = Puppet::Indirector::FileContent::File.new end it "should return an instance of the model" do filepath = make_absolute("/path/to/my/file") expect(Puppet::FileSystem).to receive(:exist?).with(filepath).and_return(true) expect(@terminus.find(@terminus.indirection.request(:find, Puppet::Util.path_to_uri(filepath).to_s, nil))).to be_instance_of(Puppet::FileServing::Content) end it "should return an instance capable of returning its content" do filename = file_containing("testfile", "my content") instance = @terminus.find(@terminus.indirection.request(:find, Puppet::Util.path_to_uri(filename).to_s, nil)) expect(instance.content).to eq("my content") end end describe Puppet::Indirector::DirectFileServer, " when interacting with FileServing::Fileset and the model" do include PuppetSpec::Files matcher :file_with_content do |name, content| match do |actual| actual.full_path == name && actual.content == content end end matcher :directory_named do |name| match do |actual| actual.full_path == name end end it "should return an instance for every file in the fileset" do path = tmpdir('direct_file_server_testing') File.open(File.join(path, "one"), "w") { |f| f.print "one content" } File.open(File.join(path, "two"), "w") { |f| f.print "two content" } terminus = Puppet::Indirector::FileContent::File.new request = terminus.indirection.request(:search, Puppet::Util.path_to_uri(path).to_s, nil, :recurse => true) expect(terminus.search(request)).to contain_exactly( file_with_content(File.join(path, "one"), "one content"), file_with_content(File.join(path, "two"), "two content"), directory_named(path)) end end describe Puppet::Indirector::DirectFileServer, " when interacting with filesystem metadata" do include PuppetSpec::Files include_context 'with supported checksum types' before do @terminus = Puppet::Indirector::FileMetadata::File.new end with_checksum_types("file_metadata", "testfile") do it "should return the correct metadata" do request = @terminus.indirection.request(:find, Puppet::Util.path_to_uri(checksum_file).to_s, nil, :checksum_type => checksum_type) result = @terminus.find(request) expect_correct_checksum(result, checksum_type, checksum, Puppet::FileServing::Metadata) end end with_checksum_types("direct_file_server_testing", "testfile") do it "search of FileServing::Fileset should return the correct metadata" do request = @terminus.indirection.request(:search, Puppet::Util.path_to_uri(env_path).to_s, nil, :recurse => true, :checksum_type => checksum_type) result = @terminus.search(request) expect(result).to_not be_nil expect(result.length).to eq(2) file, dir = result.partition {|x| x.relative_path == 'testfile'} expect(file.length).to eq(1) expect(dir.length).to eq(1) expect_correct_checksum(dir[0], 'ctime', "#{CHECKSUM_STAT_TIME}", Puppet::FileServing::Metadata) expect_correct_checksum(file[0], checksum_type, checksum, Puppet::FileServing::Metadata) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/integration/indirector/catalog/compiler_spec.rb
spec/integration/indirector/catalog/compiler_spec.rb
require 'spec_helper' require 'puppet/resource/catalog' Puppet::Resource::Catalog.indirection.terminus(:compiler) describe Puppet::Resource::Catalog::Compiler do before do allow(Facter).to receive(:value).and_return("something") @catalog = Puppet::Resource::Catalog.new("testing", Puppet::Node::Environment::NONE) @catalog.add_resource(@one = Puppet::Resource.new(:file, "/one")) @catalog.add_resource(@two = Puppet::Resource.new(:file, "/two")) end it "should remove virtual resources when filtering" do @one.virtual = true expect(Puppet::Resource::Catalog.indirection.terminus.filter(@catalog).resource_refs).to eq([ @two.ref ]) end it "should not remove exported resources when filtering" do @one.exported = true expect(Puppet::Resource::Catalog.indirection.terminus.filter(@catalog).resource_refs.sort).to eq([ @one.ref, @two.ref ]) end it "should remove virtual exported resources when filtering" do @one.exported = true @one.virtual = true expect(Puppet::Resource::Catalog.indirection.terminus.filter(@catalog).resource_refs).to eq([ @two.ref ]) end it "should filter out virtual resources when finding a catalog" do Puppet[:node_terminus] = :memory Puppet::Node.indirection.save(Puppet::Node.new("mynode")) allow(Puppet::Resource::Catalog.indirection.terminus).to receive(:extract_facts_from_request) allow(Puppet::Resource::Catalog.indirection.terminus).to receive(:compile).and_return(@catalog) @one.virtual = true expect(Puppet::Resource::Catalog.indirection.find("mynode").resource_refs).to eq([ @two.ref ]) end it "should not filter out exported resources when finding a catalog" do Puppet[:node_terminus] = :memory Puppet::Node.indirection.save(Puppet::Node.new("mynode")) allow(Puppet::Resource::Catalog.indirection.terminus).to receive(:extract_facts_from_request) allow(Puppet::Resource::Catalog.indirection.terminus).to receive(:compile).and_return(@catalog) @one.exported = true expect(Puppet::Resource::Catalog.indirection.find("mynode").resource_refs.sort).to eq([ @one.ref, @two.ref ]) end it "should filter out virtual exported resources when finding a catalog" do Puppet[:node_terminus] = :memory Puppet::Node.indirection.save(Puppet::Node.new("mynode")) allow(Puppet::Resource::Catalog.indirection.terminus).to receive(:extract_facts_from_request) allow(Puppet::Resource::Catalog.indirection.terminus).to receive(:compile).and_return(@catalog) @one.exported = true @one.virtual = true expect(Puppet::Resource::Catalog.indirection.find("mynode").resource_refs).to eq([ @two.ref ]) end it "filters out virtual exported resources using the agent's production environment" do Puppet[:node_terminus] = :memory Puppet::Node.indirection.save(Puppet::Node.new("mynode")) catalog_environment = nil expect_any_instance_of(Puppet::Parser::Resource::Catalog).to receive(:to_resource) {catalog_environment = Puppet.lookup(:current_environment).name} Puppet::Resource::Catalog.indirection.find("mynode") expect(catalog_environment).to eq(:production) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/integration/indirector/file_content/file_server_spec.rb
spec/integration/indirector/file_content/file_server_spec.rb
require 'spec_helper' require 'puppet/indirector/file_content/file_server' require 'shared_behaviours/file_server_terminus' require 'puppet_spec/files' describe Puppet::Indirector::FileContent::FileServer, " when finding files" do it_should_behave_like "Puppet::Indirector::FileServerTerminus" include PuppetSpec::Files before do @terminus = Puppet::Indirector::FileContent::FileServer.new @test_class = Puppet::FileServing::Content Puppet::FileServing::Configuration.instance_variable_set(:@configuration, nil) end it "should find plugin file content in the environment specified in the request" do path = tmpfile("file_content_with_env") Dir.mkdir(path) modpath = File.join(path, "mod") FileUtils.mkdir_p(File.join(modpath, "lib")) file = File.join(modpath, "lib", "file.rb") File.open(file, "wb") { |f| f.write "1\r\n" } Puppet.settings[:modulepath] = "/no/such/file" env = Puppet::Node::Environment.create(:foo, [path]) result = Puppet::FileServing::Content.indirection.search("plugins", :environment => env, :recurse => true) expect(result).not_to be_nil expect(result.length).to eq(2) result.map {|x| expect(x).to be_instance_of(Puppet::FileServing::Content) } expect(result.find {|x| x.relative_path == 'file.rb' }.content).to eq("1\r\n") end it "should find file content in modules" do path = tmpfile("file_content") Dir.mkdir(path) modpath = File.join(path, "mymod") FileUtils.mkdir_p(File.join(modpath, "files")) file = File.join(modpath, "files", "myfile") File.open(file, "wb") { |f| f.write "1\r\n" } env = Puppet::Node::Environment.create(:foo, [path]) result = Puppet::FileServing::Content.indirection.find("modules/mymod/myfile", :environment => env) expect(result).not_to be_nil expect(result).to be_instance_of(Puppet::FileServing::Content) expect(result.content).to eq("1\r\n") end it "should find file content of tasks in modules" do path = tmpfile("task_file_content") Dir.mkdir(path) modpath = File.join(path, "myothermod") FileUtils.mkdir_p(File.join(modpath, "tasks")) file = File.join(modpath, "tasks", "mytask") File.open(file, "wb") { |f| f.write "I'm a task" } env = Puppet::Node::Environment.create(:foo, [path]) result = Puppet::FileServing::Content.indirection.find("tasks/myothermod/mytask", :environment => env) expect(result).not_to be_nil expect(result).to be_instance_of(Puppet::FileServing::Content) expect(result.content).to eq("I'm a task") end it "should find file content in files when node name expansions are used" do allow(Puppet::FileSystem).to receive(:exist?).and_return(true) allow(Puppet::FileSystem).to receive(:exist?).with(Puppet[:fileserverconfig]).and_return(true) path = tmpfile("file_server_testing") Dir.mkdir(path) subdir = File.join(path, "mynode") Dir.mkdir(subdir) File.open(File.join(subdir, "myfile"), "wb") { |f| f.write "1\r\n" } # Use a real mount, so the integration is a bit deeper. mount1 = Puppet::FileServing::Configuration::Mount::File.new("one") mount1.path = File.join(path, "%h") parser = double('parser', :changed? => false) allow(parser).to receive(:parse).and_return("one" => mount1) allow(Puppet::FileServing::Configuration::Parser).to receive(:new).and_return(parser) path = File.join(path, "myfile") env = Puppet::Node::Environment.create(:foo, []) result = Puppet::FileServing::Content.indirection.find("one/myfile", :environment => env, :node => "mynode") expect(result).not_to be_nil expect(result).to be_instance_of(Puppet::FileServing::Content) expect(result.content).to eq("1\r\n") end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/integration/indirector/file_metadata/file_server_spec.rb
spec/integration/indirector/file_metadata/file_server_spec.rb
require 'spec_helper' require 'puppet/indirector/file_metadata/file_server' require 'shared_behaviours/file_server_terminus' require 'puppet_spec/files' describe Puppet::Indirector::FileMetadata::FileServer, " when finding files" do it_should_behave_like "Puppet::Indirector::FileServerTerminus" include PuppetSpec::Files include_context 'with supported checksum types' before do @terminus = Puppet::Indirector::FileMetadata::FileServer.new @test_class = Puppet::FileServing::Metadata Puppet::FileServing::Configuration.instance_variable_set(:@configuration, nil) end describe "with a plugin environment specified in the request" do with_checksum_types("file_content_with_env", "mod/lib/file.rb") do it "should return the correct metadata" do Puppet.settings[:modulepath] = "/no/such/file" env = Puppet::Node::Environment.create(:foo, [env_path]) result = Puppet::FileServing::Metadata.indirection.search("plugins", :environment => env, :checksum_type => checksum_type, :recurse => true) expect(result).to_not be_nil expect(result.length).to eq(2) result.map {|x| expect(x).to be_instance_of(Puppet::FileServing::Metadata)} expect_correct_checksum(result.find {|x| x.relative_path == 'file.rb'}, checksum_type, checksum, Puppet::FileServing::Metadata) end end end describe "in modules" do with_checksum_types("file_content", "mymod/files/myfile") do it "should return the correct metadata" do env = Puppet::Node::Environment.create(:foo, [env_path]) result = Puppet::FileServing::Metadata.indirection.find("modules/mymod/myfile", :environment => env, :checksum_type => checksum_type) expect_correct_checksum(result, checksum_type, checksum, Puppet::FileServing::Metadata) end end end describe "that are tasks in modules" do with_checksum_types("task_file_content", "mymod/tasks/mytask") do it "should return the correct metadata" do env = Puppet::Node::Environment.create(:foo, [env_path]) result = Puppet::FileServing::Metadata.indirection.find("tasks/mymod/mytask", :environment => env, :checksum_type => checksum_type) expect_correct_checksum(result, checksum_type, checksum, Puppet::FileServing::Metadata) end end end describe "when node name expansions are used" do with_checksum_types("file_server_testing", "mynode/myfile") do it "should return the correct metadata" do allow(Puppet::FileSystem).to receive(:exist?).with(checksum_file).and_return(true) allow(Puppet::FileSystem).to receive(:exist?).with(Puppet[:fileserverconfig]).and_return(true) # Use a real mount, so the integration is a bit deeper. mount1 = Puppet::FileServing::Configuration::Mount::File.new("one") mount1.path = File.join(env_path, "%h") parser = double('parser', :changed? => false) allow(parser).to receive(:parse).and_return("one" => mount1) allow(Puppet::FileServing::Configuration::Parser).to receive(:new).and_return(parser) env = Puppet::Node::Environment.create(:foo, []) result = Puppet::FileServing::Metadata.indirection.find("one/myfile", :environment => env, :node => "mynode", :checksum_type => checksum_type) expect_correct_checksum(result, checksum_type, checksum, Puppet::FileServing::Metadata) end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/integration/indirector/facts/facter_spec.rb
spec/integration/indirector/facts/facter_spec.rb
require 'spec_helper' require 'puppet_spec/files' require 'puppet_spec/compiler' require 'puppet/indirector/facts/facter' describe Puppet::Node::Facts::Facter do include PuppetSpec::Files include PuppetSpec::Compiler include PuppetSpec::Settings before :each do Puppet::Node::Facts.indirection.terminus_class = :facter end it "preserves case in fact values" do Puppet.runtime[:facter].add(:downcase_test) do setcode do "AaBbCc" end end allow(Facter).to receive(:reset) cat = compile_to_catalog('notify { $downcase_test: }', Puppet::Node.indirection.find('foo')) expect(cat.resource("Notify[AaBbCc]")).to be end context "resolving file based facts" do let(:factdir) { tmpdir('factdir') } it "should resolve custom facts" do test_module = File.join(factdir, 'module', 'lib', 'facter') FileUtils.mkdir_p(test_module) File.open(File.join(test_module, 'custom.rb'), 'wb') { |file| file.write(<<-EOF)} Puppet.runtime[:facter].add(:custom) do setcode do Puppet.runtime[:facter].value('puppetversion') end end EOF Puppet.initialize_settings(['--modulepath', factdir]) apply = Puppet::Application.find(:apply).new(double('command_line', :subcommand_name => :apply, :args => ['--modulepath', factdir, '-e', 'notify { $custom: }'])) expect { apply.run }.to exit_with(0) .and output(/defined 'message' as '#{Puppet.version}'/).to_stdout end it "should resolve external facts" do external_fact = File.join(factdir, 'external.json') File.open(external_fact, 'wb') { |file| file.write(<<-EOF)} {"foo": "bar"} EOF Puppet.initialize_settings(['--pluginfactdest', factdir]) apply = Puppet::Application.find(:apply).new(double('command_line', :subcommand_name => :apply, :args => ['--pluginfactdest', factdir, '-e', 'notify { $foo: }'])) expect { apply.run }.to exit_with(0) .and output(/defined 'message' as 'bar'/).to_stdout end end context "adding facts" do it "adds the puppetversion fact" do allow(Facter).to receive(:reset) cat = compile_to_catalog('notify { $::puppetversion: }', Puppet::Node.indirection.find('foo')) expect(cat.resource("Notify[#{Puppet.version.to_s}]")).to be end context "when adding the agent_specified_environment fact" do it "does not add the fact if the agent environment is not set" do expect do compile_to_catalog('notify { $::agent_specified_environment: }', Puppet::Node.indirection.find('foo')) end.to raise_error(Puppet::PreformattedError) end it "does not add the fact if the agent environment is set in sections other than agent or main" do set_puppet_conf(Puppet[:confdir], <<~CONF) [user] environment=bar CONF Puppet.initialize_settings expect do compile_to_catalog('notify { $::agent_specified_environment: }', Puppet::Node.indirection.find('foo')) end.to raise_error(Puppet::PreformattedError) end it "adds the agent_specified_environment fact when set in the agent section in puppet.conf" do set_puppet_conf(Puppet[:confdir], <<~CONF) [agent] environment=bar CONF Puppet.initialize_settings cat = compile_to_catalog('notify { $::agent_specified_environment: }', Puppet::Node.indirection.find('foo')) expect(cat.resource("Notify[bar]")).to be end it "prefers agent_specified_environment from main if set in section other than agent" do set_puppet_conf(Puppet[:confdir], <<~CONF) [main] environment=baz [user] environment=bar CONF Puppet.initialize_settings cat = compile_to_catalog('notify { $::agent_specified_environment: }', Puppet::Node.indirection.find('foo')) expect(cat.resource("Notify[baz]")).to be end it "prefers agent_specified_environment from agent if set in multiple sections" do set_puppet_conf(Puppet[:confdir], <<~CONF) [main] environment=baz [agent] environment=bar CONF Puppet.initialize_settings cat = compile_to_catalog('notify { $::agent_specified_environment: }', Puppet::Node.indirection.find('foo')) expect(cat.resource("Notify[bar]")).to be end it "adds the agent_specified_environment fact when set in puppet.conf" do set_puppet_conf(Puppet[:confdir], 'environment=bar') Puppet.initialize_settings cat = compile_to_catalog('notify { $::agent_specified_environment: }', Puppet::Node.indirection.find('foo')) expect(cat.resource("Notify[bar]")).to be end it "adds the agent_specified_environment fact when set via command-line" do Puppet.initialize_settings(['--environment', 'bar']) cat = compile_to_catalog('notify { $::agent_specified_environment: }', Puppet::Node.indirection.find('foo')) expect(cat.resource("Notify[bar]")).to be end it "adds the agent_specified_environment fact, preferring cli, when set in puppet.conf and via command-line" do set_puppet_conf(Puppet[:confdir], 'environment=bar') Puppet.initialize_settings(['--environment', 'baz']) cat = compile_to_catalog('notify { $::agent_specified_environment: }', Puppet::Node.indirection.find('foo')) expect(cat.resource("Notify[baz]")).to be end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/integration/application/agent_spec.rb
spec/integration/application/agent_spec.rb
require 'spec_helper' require 'puppet_spec/files' require 'puppet_spec/puppetserver' require 'puppet_spec/compiler' require 'puppet_spec/https' require 'puppet/application/agent' describe "puppet agent", unless: Puppet::Util::Platform.jruby? do include PuppetSpec::Files include PuppetSpec::Compiler include_context "https client" let(:server) { PuppetSpec::Puppetserver.new } let(:agent) { Puppet::Application[:agent] } let(:node) { Puppet::Node.new(Puppet[:certname], environment: 'production')} let(:formatter) { Puppet::Network::FormatHandler.format(:rich_data_json) } # Create temp fixtures since the agent will attempt to refresh the CA/CRL before do Puppet[:localcacert] = ca = tmpfile('ca') Puppet[:hostcrl] = crl = tmpfile('crl') copy_fixtures(%w[ca.pem intermediate.pem], ca) copy_fixtures(%w[crl.pem intermediate-crl.pem], crl) end def copy_fixtures(sources, dest) ssldir = File.join(PuppetSpec::FIXTURE_DIR, 'ssl') File.open(dest, 'w') do |f| sources.each do |s| f.write(File.read(File.join(ssldir, s))) end end end context 'server identification' do it 'emits a notice if the server sends the X-Puppet-Compiler-Name header' do server.start_server do |port| Puppet[:serverport] = port expect { agent.command_line.args << '--test' agent.run }.to exit_with(0) .and output(%r{Notice: Catalog compiled by test-compiler-hostname}).to_stdout end end end context 'server_list' do it "uses the first server in the list" do Puppet[:server_list] = '127.0.0.1' Puppet[:log_level] = 'debug' server.start_server do |port| Puppet[:serverport] = port expect { agent.command_line.args << '--test' agent.run }.to exit_with(0) .and output(%r{HTTP GET https://127.0.0.1:#{port}/status/v1/simple/server returned 200 OK}).to_stdout end end it "falls back, recording the first viable server in the report" do Puppet[:server_list] = "puppet.example.com,#{Puppet[:server]}" server.start_server do |port| Puppet[:serverport] = port expect { agent.command_line.args << '--test' agent.run }.to exit_with(0) .and output(%r{Notice: Applied catalog}).to_stdout .and output(%r{Unable to connect to server from server_list setting: Request to https://puppet.example.com:#{port}/status/v1/simple/server failed}).to_stderr report = Puppet::Transaction::Report.convert_from(:yaml, File.read(Puppet[:lastrunreport])) expect(report.server_used).to eq("127.0.0.1:#{port}") end end it "doesn't write a report if no servers could be contacted" do Puppet[:server_list] = "puppet.example.com" expect { agent.command_line.args << '--test' agent.run }.to exit_with(1) .and output(a_string_matching(%r{Unable to connect to server from server_list setting}) .and matching(/Error: Could not run Puppet configuration client: Could not select a functional puppet server from server_list: 'puppet.example.com'/)).to_stderr # I'd expect puppet to update the last run report even if the server_list was # exhausted, but it doesn't work that way currently, see PUP-6708 expect(File).to_not be_exist(Puppet[:lastrunreport]) end it "omits server_used when not using server_list" do Puppet[:log_level] = 'debug' server.start_server do |port| Puppet[:serverport] = port expect { agent.command_line.args << '--test' agent.run }.to exit_with(0) .and output(%r{Resolved service 'puppet' to https://127.0.0.1:#{port}/puppet/v3}).to_stdout end report = Puppet::Transaction::Report.convert_from(:yaml, File.read(Puppet[:lastrunreport])) expect(report.server_used).to be_nil end it "server_list takes precedence over server" do Puppet[:server] = 'notvalid.example.com' Puppet[:log_level] = 'debug' server.start_server do |port| Puppet[:server_list] = "127.0.0.1:#{port}" expect { agent.command_line.args << '--test' agent.run }.to exit_with(0) .and output(%r{Debug: Resolved service 'puppet' to https://127.0.0.1:#{port}/puppet/v3}).to_stdout report = Puppet::Transaction::Report.convert_from(:yaml, File.read(Puppet[:lastrunreport])) expect(report.server_used).to eq("127.0.0.1:#{port}") end end end context 'rich data' do let(:deferred_file) { tmpfile('deferred') } let(:deferred_manifest) do <<~END file { '#{deferred_file}': ensure => file, content => '123', } -> notify { 'deferred': message => Deferred('binary_file', ['#{deferred_file}']) } END end it "calls a deferred 4x function" do catalog_handler = -> (req, res) { catalog = compile_to_catalog(<<-MANIFEST, node) notify { 'deferred4x': message => Deferred('join', [[1,2,3], ':']) } MANIFEST res.body = formatter.render(catalog) res['Content-Type'] = formatter.mime } server.start_server(mounts: {catalog: catalog_handler}) do |port| Puppet[:serverport] = port expect { agent.command_line.args << '--test' agent.run }.to exit_with(2) .and output(%r{Notice: /Stage\[main\]/Main/Notify\[deferred4x\]/message: defined 'message' as '1:2:3'}).to_stdout end end it "calls a deferred 3x function" do catalog_handler = -> (req, res) { catalog = compile_to_catalog(<<-MANIFEST, node) notify { 'deferred3x': message => Deferred('sprintf', ['%s', 'I am deferred']) } MANIFEST res.body = formatter.render(catalog) res['Content-Type'] = formatter.mime } server.start_server(mounts: {catalog: catalog_handler}) do |port| Puppet[:serverport] = port expect { agent.command_line.args << '--test' agent.run }.to exit_with(2) .and output(%r{Notice: /Stage\[main\]/Main/Notify\[deferred3x\]/message: defined 'message' as 'I am deferred'}).to_stdout end end it "fails to apply a deferred function with an unsatisfied prerequisite" do Puppet[:preprocess_deferred] = true catalog_handler = -> (req, res) { catalog = compile_to_catalog(deferred_manifest, node) res.body = formatter.render(catalog) res['Content-Type'] = formatter.mime } server.start_server(mounts: {catalog: catalog_handler}) do |port| Puppet[:serverport] = port expect { agent.command_line.args << '--test' agent.run }.to exit_with(1) .and output(%r{Using environment}).to_stdout .and output(%r{The given file '#{deferred_file}' does not exist}).to_stderr end end it "applies a deferred function and its prerequisite in the same run" do catalog_handler = -> (req, res) { catalog = compile_to_catalog(deferred_manifest, node) res.body = formatter.render(catalog) res['Content-Type'] = formatter.mime } server.start_server(mounts: {catalog: catalog_handler}) do |port| Puppet[:serverport] = port expect { agent.command_line.args << '--test' agent.run }.to exit_with(2) .and output(%r{defined 'message' as Binary\("MTIz"\)}).to_stdout end end it "re-evaluates a deferred function in a cached catalog" do Puppet[:report] = false Puppet[:use_cached_catalog] = true Puppet[:usecacheonfailure] = false catalog_dir = File.join(Puppet[:client_datadir], 'catalog') Puppet::FileSystem.mkpath(catalog_dir) cached_catalog_path = "#{File.join(catalog_dir, Puppet[:certname])}.json" # our catalog contains a deferred function that calls `binary_file` # to read `source`. The function returns a Binary object, whose # base64 value is printed to stdout source = tmpfile('deferred_source') catalog = File.read(my_fixture('cached_deferred_catalog.json')) catalog.gsub!('__SOURCE_PATH__', source) File.write(cached_catalog_path, catalog) # verify we get a different result each time the deferred function # is evaluated, and reads `source`. { '1234' => 'MTIzNA==', '5678' => 'NTY3OA==' }.each_pair do |content, base64| File.write(source, content) expect { agent.command_line.args << '-t' agent.run }.to exit_with(2) .and output(/Notice: #{base64}/).to_stdout # reset state so we can run again Puppet::Application.clear! end end it "redacts sensitive values" do catalog_handler = -> (req, res) { catalog = compile_to_catalog(<<-MANIFEST, node) notify { 'sensitive': message => Sensitive('supersecret') } MANIFEST res.body = formatter.render(catalog) res['Content-Type'] = formatter.mime } server.start_server(mounts: {catalog: catalog_handler}) do |port| Puppet[:serverport] = port expect { agent.command_line.args << '--test' agent.run }.to exit_with(2) .and output(a_string_matching( /Notice: Sensitive \[value redacted\]/ ).and matching( /Notify\[sensitive\]\/message: changed \[redacted\] to \[redacted\]/ )).to_stdout end end it "applies binary data in a cached catalog" do catalog = compile_to_catalog(<<-MANIFEST, node) notify { 'some title': message => Binary.new('aGk=') } MANIFEST catalog_dir = File.join(Puppet[:client_datadir], 'catalog') Puppet::FileSystem.mkpath(catalog_dir) cached_catalog = "#{File.join(catalog_dir, Puppet[:certname])}.json" File.write(cached_catalog, catalog.render(:rich_data_json)) expect { Puppet[:report] = false Puppet[:use_cached_catalog] = true Puppet[:usecacheonfailure] = false agent.command_line.args << '-t' agent.run }.to exit_with(2) .and output(%r{defined 'message' as 'hi'}).to_stdout end end context 'static catalogs' do let(:path) { tmpfile('file') } let(:metadata) { Puppet::FileServing::Metadata.new(path) } let(:source) { "puppet:///modules/foo/foo.txt" } before :each do Puppet::FileSystem.touch(path) metadata.collect metadata.source = source metadata.content_uri = "puppet:///modules/foo/files/foo.txt" end it 'uses inline file metadata to determine the file is insync' do catalog_handler = -> (req, res) { catalog = compile_to_catalog(<<-MANIFEST, node) file { "#{path}": ensure => file, source => "#{source}" } MANIFEST catalog.metadata = { path => metadata } res.body = formatter.render(catalog) res['Content-Type'] = formatter.mime } server.start_server(mounts: {catalog: catalog_handler}) do |port| Puppet[:serverport] = port expect { expect { agent.command_line.args << '--test' agent.run }.to exit_with(0) }.to_not output(/content changed/).to_stdout end end it 'retrieves file content using the content_uri from the inlined file metadata' do # create file with binary content binary_content = "\xC0\xFF".force_encoding('binary') File.binwrite(path, binary_content) # recollect metadata metadata.collect # overwrite local file so it is no longer in sync File.binwrite(path, "") catalog_handler = -> (req, res) { catalog = compile_to_catalog(<<-MANIFEST, node) file { "#{path}": ensure => file, source => "#{source}", } MANIFEST catalog.metadata = { path => metadata } res.body = formatter.render(catalog) res['Content-Type'] = formatter.mime } static_file_content_handler = -> (req, res) { res.body = binary_content res['Content-Type'] = 'application/octet-stream' } mounts = { catalog: catalog_handler, static_file_content: static_file_content_handler } server.start_server(mounts: mounts) do |port| Puppet[:serverport] = port expect { agent.command_line.args << '--test' agent.run }.to exit_with(2) .and output(/content changed '{sha256}e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855' to '{sha256}3bef83ad320b471d8e3a03c9b9f150749eea610fe266560395d3195cfbd8e6b8'/).to_stdout # verify puppet restored binary content expect(File.binread(path)).to eq(binary_content) end end end context 'https file sources' do let(:path) { tmpfile('https_file_source') } let(:response_body) { "from https server" } let(:digest) { Digest::SHA1.hexdigest(response_body) } it 'rejects HTTPS servers whose root cert is not in the system CA store' do unknown_ca_cert = cert_fixture('unknown-ca.pem') https = PuppetSpec::HTTPSServer.new( ca_cert: unknown_ca_cert, server_cert: cert_fixture('unknown-127.0.0.1.pem'), server_key: key_fixture('unknown-127.0.0.1-key.pem') ) # create a temp cacert bundle ssl_file = tmpfile('systemstore') # add CA cert that is neither the puppet CA nor unknown CA File.write(ssl_file, cert_fixture('netlock-arany-utf8.pem').to_pem) https.start_server do |https_port| catalog_handler = -> (req, res) { catalog = compile_to_catalog(<<-MANIFEST, node) file { "#{path}": ensure => file, backup => false, checksum => sha1, checksum_value => '#{digest}', source => "https://127.0.0.1:#{https_port}/path/to/file" } MANIFEST res.body = formatter.render(catalog) res['Content-Type'] = formatter.mime } server.start_server(mounts: {catalog: catalog_handler}) do |puppetserver_port| Puppet[:serverport] = puppetserver_port # override path to system cacert bundle, this must be done before # the SSLContext is created and the call to X509::Store.set_default_paths Puppet::Util.withenv("SSL_CERT_FILE" => ssl_file) do expect { agent.command_line.args << '--test' agent.run }.to exit_with(4) .and output(/Notice: Applied catalog/).to_stdout .and output(%r{Error: Could not retrieve file metadata for https://127.0.0.1:#{https_port}/path/to/file: certificate verify failed}).to_stderr end expect(File).to_not be_exist(path) end end end it 'accepts HTTPS servers whose cert is in the system CA store' do unknown_ca_cert = cert_fixture('unknown-ca.pem') https = PuppetSpec::HTTPSServer.new( ca_cert: unknown_ca_cert, server_cert: cert_fixture('unknown-127.0.0.1.pem'), server_key: key_fixture('unknown-127.0.0.1-key.pem') ) # create a temp cacert bundle ssl_file = tmpfile('systemstore') File.write(ssl_file, unknown_ca_cert.to_pem) response_proc = -> (req, res) { res.status = 200 res.body = response_body } https.start_server(response_proc: response_proc) do |https_port| catalog_handler = -> (req, res) { catalog = compile_to_catalog(<<-MANIFEST, node) file { "#{path}": ensure => file, backup => false, checksum => sha1, checksum_value => '#{digest}', source => "https://127.0.0.1:#{https_port}/path/to/file" } MANIFEST res.body = formatter.render(catalog) res['Content-Type'] = formatter.mime } server.start_server(mounts: {catalog: catalog_handler}) do |puppetserver_port| Puppet[:serverport] = puppetserver_port # override path to system cacert bundle, this must be done before # the SSLContext is created and the call to X509::Store.set_default_paths Puppet::Util.withenv("SSL_CERT_FILE" => ssl_file) do expect { agent.command_line.args << '--test' agent.run }.to exit_with(2) .and output(%r{https_file_source.*/ensure: created}).to_stdout end expect(File.binread(path)).to eq("from https server") end end end it 'accepts HTTPS servers whose cert is in the external CA store' do unknown_ca_cert = cert_fixture('unknown-ca.pem') https = PuppetSpec::HTTPSServer.new( ca_cert: unknown_ca_cert, server_cert: cert_fixture('unknown-127.0.0.1.pem'), server_key: key_fixture('unknown-127.0.0.1-key.pem') ) # create a temp cacert bundle ssl_file = tmpfile('systemstore') File.write(ssl_file, unknown_ca_cert.to_pem) response_proc = -> (req, res) { res.status = 200 res.body = response_body } https.start_server(response_proc: response_proc) do |https_port| catalog_handler = -> (req, res) { catalog = compile_to_catalog(<<-MANIFEST, node) file { "#{path}": ensure => file, backup => false, checksum => sha1, checksum_value => '#{digest}', source => "https://127.0.0.1:#{https_port}/path/to/file" } MANIFEST res.body = formatter.render(catalog) res['Content-Type'] = formatter.mime } server.start_server(mounts: {catalog: catalog_handler}) do |puppetserver_port| Puppet[:serverport] = puppetserver_port # set path to external cacert bundle, this must be done before # the SSLContext is created Puppet[:ssl_trust_store] = ssl_file expect { agent.command_line.args << '--test' agent.run }.to exit_with(2) .and output(%r{https_file_source.*/ensure: created}).to_stdout end expect(File.binread(path)).to eq("from https server") end end end context 'multiple agents running' do def with_another_agent_running(&block) path = Puppet[:agent_catalog_run_lockfile] th = Thread.new { %x{ruby -e "$0 = 'puppet'; File.write('#{path}', Process.pid); sleep(5)"} } # ensure file is written before yielding until File.exist?(path) && File.size(path) > 0 do sleep 0.1 end begin yield ensure th.kill # kill thread so we don't wait too much end end it "exits if an agent is already running" do with_another_agent_running do expect { agent.command_line.args << '--test' agent.run }.to exit_with(1).and output(/Run of Puppet configuration client already in progress; skipping/).to_stdout end end it "waits for other agent run to finish before starting" do server.start_server do |port| Puppet[:serverport] = port Puppet[:waitforlock] = 1 with_another_agent_running do expect { agent.command_line.args << '--test' agent.run }.to exit_with(0) .and output(a_string_matching( /Info: Will try again in #{Puppet[:waitforlock]} seconds/ ).and matching( /Applied catalog/ )).to_stdout end end end it "exits if maxwaitforlock is exceeded" do Puppet[:waitforlock] = 1 Puppet[:maxwaitforlock] = 0 with_another_agent_running do expect { agent.command_line.args << '--test' agent.run }.to exit_with(1).and output(/Exiting now because the maxwaitforlock timeout has been exceeded./).to_stdout end end end context 'cached catalogs' do it 'falls back to a cached catalog' do catalog_handler = -> (req, res) { catalog = compile_to_catalog(<<-MANIFEST, node) notify { 'a message': } MANIFEST res.body = formatter.render(catalog) res['Content-Type'] = formatter.mime } server.start_server(mounts: {catalog: catalog_handler}) do |port| Puppet[:serverport] = port expect { agent.command_line.args << '--test' agent.run }.to exit_with(2) .and output(%r{Caching catalog for #{Puppet[:certname]}}).to_stdout end # reset state so we can run again Puppet::Application.clear! # --test above turns off `usecacheonfailure` so re-enable here Puppet[:usecacheonfailure] = true # run agent without server expect { agent.command_line.args << '--no-daemonize' << '--onetime' << '--server' << '127.0.0.1' agent.run }.to exit_with(2) .and output(a_string_matching( /Using cached catalog from environment 'production'/ ).and matching( /Notify\[a message\]\/message:/ )).to_stdout .and output(/No more routes to fileserver/).to_stderr end it 'preserves the old cached catalog if validation fails with the old one' do catalog_handler = -> (req, res) { catalog = compile_to_catalog(<<-MANIFEST, node) exec { 'unqualified_command': } MANIFEST res.body = formatter.render(catalog) res['Content-Type'] = formatter.mime } server.start_server(mounts: {catalog: catalog_handler}) do |port| Puppet[:serverport] = port expect { agent.command_line.args << '--test' agent.run }.to exit_with(1) .and output(%r{Retrieving plugin}).to_stdout .and output(%r{Validation of Exec\[unqualified_command\] failed: 'unqualified_command' is not qualified and no path was specified}).to_stderr end # cached catalog should not be updated cached_catalog = "#{File.join(Puppet[:client_datadir], 'catalog', Puppet[:certname])}.json" expect(File).to_not be_exist(cached_catalog) end end context "reporting" do it "stores a finalized report" do catalog_handler = -> (req, res) { catalog = compile_to_catalog(<<-MANIFEST, node) notify { 'foo': require => Notify['bar'] } notify { 'bar': require => Notify['foo'] } MANIFEST res.body = formatter.render(catalog) res['Content-Type'] = formatter.mime } server.start_server(mounts: {catalog: catalog_handler}) do |port| Puppet[:serverport] = port expect { agent.command_line.args << '--test' agent.run }.to exit_with(1) .and output(%r{Applying configuration}).to_stdout .and output(%r{Found 1 dependency cycle}).to_stderr report = Puppet::Transaction::Report.convert_from(:yaml, File.read(Puppet[:lastrunreport])) expect(report.status).to eq("failed") expect(report.metrics).to_not be_empty end end it "caches a report even if the REST request fails" do server.start_server do |port| Puppet[:serverport] = port Puppet[:report_port] = "-1" expect { agent.command_line.args << '--test' agent.run }.to exit_with(0) .and output(%r{Applied catalog}).to_stdout .and output(%r{Could not send report}).to_stderr report = Puppet::Transaction::Report.convert_from(:yaml, File.read(Puppet[:lastrunreport])) expect(report).to be end end end context "environment convergence" do it "falls back to making a node request if the last server-specified environment cannot be loaded" do mounts = {} mounts[:node] = -> (req, res) { node = Puppet::Node.new('test', environment: Puppet::Node::Environment.remote('doesnotexistonagent')) res.body = formatter.render(node) res['Content-Type'] = formatter.mime } server.start_server(mounts: mounts) do |port| Puppet[:serverport] = port Puppet[:log_level] = 'debug' expect { agent.command_line.args << '--test' agent.run }.to exit_with(0) .and output(a_string_matching(%r{Debug: Requesting environment from the server})).to_stdout Puppet::Application.clear! expect { agent.command_line.args << '--test' agent.run }.to exit_with(0) .and output(a_string_matching(%r{Debug: Successfully loaded last environment from the lastrunfile})).to_stdout end end it "switches to 'newenv' environment and retries the run" do first_run = true libdir = File.join(my_fixture_dir, 'lib') # we have to use the :facter terminus to reliably test that pluginsynced # facts are included in the catalog request Puppet::Node::Facts.indirection.terminus_class = :facter mounts = {} # During the first run, only return metadata for the top-level directory. # During the second run, include metadata for all of the 'lib' fixtures # due to the `recurse` option. mounts[:file_metadatas] = -> (req, res) { request = Puppet::FileServing::Metadata.indirection.request( :search, libdir, nil, recurse: !first_run ) data = Puppet::FileServing::Metadata.indirection.terminus(:file).search(request) res.body = formatter.render(data) res['Content-Type'] = formatter.mime } mounts[:file_content] = -> (req, res) { request = Puppet::FileServing::Content.indirection.request( :find, File.join(libdir, 'facter', 'agent_spec_role.rb'), nil ) content = Puppet::FileServing::Content.indirection.terminus(:file).find(request) res.body = content.content res['Content-Length'] = content.content.length res['Content-Type'] = 'application/octet-stream' } # During the first run, return an empty catalog referring to the newenv. # During the second run, compile a catalog that depends on a fact that # only exists in the second environment. If the fact is missing/empty, # then compilation will fail since resources can't have an empty title. mounts[:catalog] = -> (req, res) { node = Puppet::Node.new('test') code = if first_run first_run = false '' else data = CGI.unescape(req.query['facts']) facts = Puppet::Node::Facts.convert_from('json', data) node.fact_merge(facts) 'notify { $facts["agent_spec_role"]: }' end catalog = compile_to_catalog(code, node) catalog.environment = 'newenv' res.body = formatter.render(catalog) res['Content-Type'] = formatter.mime } server.start_server(mounts: mounts) do |port| Puppet[:serverport] = port expect { agent.command_line.args << '--test' agent.run }.to exit_with(2) .and output(a_string_matching(%r{Notice: Local environment: 'production' doesn't match server specified environment 'newenv', restarting agent run with environment 'newenv'}) .and matching(%r{defined 'message' as 'web'})).to_stdout end end end context "ssl" do context "bootstrapping" do before :each do # reconfigure ssl to non-existent dir and files to force bootstrapping dir = tmpdir('ssl') Puppet[:ssldir] = dir Puppet[:localcacert] = File.join(dir, 'ca.pem') Puppet[:hostcrl] = File.join(dir, 'crl.pem') Puppet[:hostprivkey] = File.join(dir, 'cert.pem') Puppet[:hostcert] = File.join(dir, 'key.pem') Puppet[:daemonize] = false Puppet[:logdest] = 'console' Puppet[:log_level] = 'info' end it "exits if the agent is not allowed to wait" do Puppet[:waitforcert] = 0 server.start_server do |port| Puppet[:serverport] = port expect { agent.run }.to exit_with(1) .and output(%r{Exiting now because the waitforcert setting is set to 0}).to_stdout .and output(%r{Failed to submit the CSR, HTTP response was 404}).to_stderr end end it "exits if the maxwaitforcert time is exceeded" do Puppet[:waitforcert] = 1 Puppet[:maxwaitforcert] = 1 server.start_server do |port| Puppet[:serverport] = port expect { agent.run }.to exit_with(1) .and output(%r{Couldn't fetch certificate from CA server; you might still need to sign this agent's certificate \(127.0.0.1\). Exiting now because the maxwaitforcert timeout has been exceeded.}).to_stdout .and output(%r{Failed to submit the CSR, HTTP response was 404}).to_stderr end end end it "reloads the CRL between runs" do Puppet[:hostcert] = cert = tmpfile('cert') Puppet[:hostprivkey] = key = tmpfile('key') copy_fixtures(%w[127.0.0.1.pem], cert) copy_fixtures(%w[127.0.0.1-key.pem], key) revoked = cert_fixture('revoked.pem') revoked_key = key_fixture('revoked-key.pem') mounts = {} mounts[:catalog] = -> (req, res) { catalog = compile_to_catalog(<<~MANIFEST, node) file { '#{cert}': ensure => file, content => '#{revoked}' } file { '#{key}': ensure => file, content => '#{revoked_key}' } MANIFEST res.body = formatter.render(catalog) res['Content-Type'] = formatter.mime } server.start_server(mounts: mounts) do |port| Puppet[:serverport] = port Puppet[:daemonize] = false Puppet[:runinterval] = 1 Puppet[:waitforcert] = 1 Puppet[:maxwaitforcert] = 1 # simulate two runs of the agent, then return so we don't infinite loop allow_any_instance_of(Puppet::Daemon).to receive(:run_event_loop) do |instance| instance.agent.run(splay: false) instance.agent.run(splay: false) end agent.command_line.args << '--verbose' expect { agent.run }.to exit_with(1) .and output(%r{Exiting now because the maxwaitforcert timeout has been exceeded}).to_stdout .and output(%r{Certificate 'CN=revoked' is revoked}).to_stderr end end it "refreshes the CA and CRL" do now = Time.now yesterday = now - (60 * 60 * 24) Puppet::FileSystem.touch(Puppet[:localcacert], mtime: yesterday) Puppet::FileSystem.touch(Puppet[:hostcrl], mtime: yesterday) server.start_server do |port| Puppet[:serverport] = port Puppet[:ca_refresh_interval] = 1 expect { agent.command_line.args << '--test' agent.run }.to exit_with(0) .and output(/Info: Refreshed CA certificate: /).to_stdout end # If the CA is updated, then the CRL must be updated too expect(Puppet::FileSystem.stat(Puppet[:localcacert]).mtime).to be >= now expect(Puppet::FileSystem.stat(Puppet[:hostcrl]).mtime).to be >= now end it "refreshes only the CRL" do now = Time.now tomorrow = now + (60 * 60 * 24) Puppet::FileSystem.touch(Puppet[:localcacert], mtime: tomorrow) yesterday = now - (60 * 60 * 24) Puppet::FileSystem.touch(Puppet[:hostcrl], mtime: yesterday) server.start_server do |port| Puppet[:serverport] = port Puppet[:crl_refresh_interval] = 1 expect { agent.command_line.args << '--test' agent.run }.to exit_with(0) .and output(/Info: Refreshed CRL: /).to_stdout end expect(Puppet::FileSystem.stat(Puppet[:hostcrl]).mtime).to be >= now end end context "legacy facts" do let(:mod_dir) { tmpdir('module_dir') } let(:custom_dir) { File.join(mod_dir, 'lib') } let(:external_dir) { File.join(mod_dir, 'facts.d') } before(:each) do # don't stub facter behavior, since we're relying on
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
true
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/integration/application/apply_spec.rb
spec/integration/application/apply_spec.rb
require 'spec_helper' require 'puppet_spec/files' require 'puppet_spec/compiler' require 'puppet_spec/https' describe "apply", unless: Puppet::Util::Platform.jruby? do include PuppetSpec::Files let(:apply) { Puppet::Application[:apply] } before :each do Puppet[:reports] = "none" # Let exceptions be raised instead of exiting allow_any_instance_of(Puppet::Application).to receive(:exit_on_fail).and_yield end describe "when applying provided catalogs" do it "can apply catalogs provided in a file in json" do file_to_create = tmpfile("json_catalog") catalog = Puppet::Resource::Catalog.new('mine', Puppet.lookup(:environments).get(Puppet[:environment])) resource = Puppet::Resource.new(:file, file_to_create, :parameters => {:content => "my stuff"}) catalog.add_resource resource apply.command_line.args = ['--catalog', file_containing("manifest", catalog.to_json)] expect { apply.run }.to output(/ensure: defined content as/).to_stdout expect(Puppet::FileSystem.exist?(file_to_create)).to be_truthy expect(File.read(file_to_create)).to eq("my stuff") end context 'and pcore types are available' do let(:envdir) { my_fixture('environments') } let(:env_name) { 'spec' } before(:each) do Puppet[:environmentpath] = envdir Puppet[:environment] = env_name end it 'does not load the pcore type' do apply = Puppet::Application[:apply] apply.command_line.args = [ '-e', "Applytest { message => 'the default'} applytest { 'applytest was here': }" ] expect { apply.run }.to exit_with(0) .and output(a_string_matching( /the Puppet::Type says hello/ ).and matching( /applytest was here/ )).to_stdout end end context 'from environment with a pcore defined resource type' do include PuppetSpec::Compiler let(:envdir) { my_fixture('environments') } let(:env_name) { 'spec' } let(:environments) { Puppet::Environments::Directories.new(envdir, []) } let(:env) { Puppet::Node::Environment.create(:'spec', [File.join(envdir, 'spec', 'modules')]) } let(:node) { Puppet::Node.new('test', :environment => env) } around(:each) do |example| Puppet::Type.rmtype(:applytest) Puppet[:environment] = env_name Puppet.override(:environments => environments, :current_environment => env) do example.run end end it 'does not load the pcore type' do catalog = compile_to_catalog('applytest { "applytest was here":}', node) apply.command_line.args = ['--catalog', file_containing('manifest', catalog.to_json)] Puppet[:environmentpath] = envdir expect_any_instance_of(Puppet::Pops::Loader::Runtime3TypeLoader).not_to receive(:find) expect { apply.run }.to output(/the Puppet::Type says hello.*applytest was here/m).to_stdout end # Test just to verify that the Pcore Resource Type and not the Ruby one is produced when the catalog is produced it 'loads pcore resource type instead of ruby resource type during compile' do Puppet[:code] = 'applytest { "applytest was here": }' compiler = Puppet::Parser::Compiler.new(node) tn = Puppet::Pops::Loader::TypedName.new(:resource_type_pp, 'applytest') rt = Puppet::Pops::Resource::ResourceTypeImpl.new('applytest', [Puppet::Pops::Resource::Param.new(String, 'message')], [Puppet::Pops::Resource::Param.new(String, 'name', true)]) expect(compiler.loaders.runtime3_type_loader.instance_variable_get(:@resource_3x_loader)).to receive(:set_entry).once.with(tn, rt, instance_of(String)) .and_return(Puppet::Pops::Loader::Loader::NamedEntry.new(tn, rt, nil)) expect { compiler.compile }.not_to output(/the Puppet::Type says hello/).to_stdout end it "does not fail when pcore type is loaded twice" do Puppet[:code] = 'applytest { xyz: alias => aptest }; Resource[applytest]' compiler = Puppet::Parser::Compiler.new(node) expect { compiler.compile }.not_to raise_error end it "does not load the ruby type when using function 'defined()' on a loaded resource that is missing from the catalog" do # Ensure that the Resource[applytest,foo] is loaded' eval_and_collect_notices('applytest { xyz: }', node) # Ensure that: # a) The catalog contains aliases (using a name for the abc resource ensures this) # b) That Resource[applytest,xyz] is not defined in the catalog (although it's loaded) # c) That this doesn't trigger a load of the Puppet::Type notices = eval_and_collect_notices('applytest { abc: name => some_alias }; notice(defined(Resource[applytest,xyz]))', node) expect(notices).to include('false') expect(notices).not_to include('the Puppet::Type says hello') end it 'does not load the ruby type when when referenced from collector during compile' do notices = eval_and_collect_notices("@applytest { 'applytest was here': }\nApplytest<| title == 'applytest was here' |>", node) expect(notices).not_to include('the Puppet::Type says hello') end it 'does not load the ruby type when when referenced from exported collector during compile' do notices = eval_and_collect_notices("@@applytest { 'applytest was here': }\nApplytest<<| |>>", node) expect(notices).not_to include('the Puppet::Type says hello') end end end context 'from environment with pcore object types' do include PuppetSpec::Compiler let!(:envdir) { Puppet[:environmentpath] } let(:env_name) { 'spec' } let(:dir_structure) { { 'environment.conf' => <<-CONF, rich_data = true CONF 'modules' => { 'mod' => { 'types' => { 'streetaddress.pp' => <<-PUPPET, type Mod::StreetAddress = Object[{ attributes => { 'street' => String, 'zipcode' => String, 'city' => String, } }] PUPPET 'address.pp' => <<-PUPPET, type Mod::Address = Object[{ parent => Mod::StreetAddress, attributes => { 'state' => String } }] PUPPET 'contact.pp' => <<-PUPPET, type Mod::Contact = Object[{ attributes => { 'address' => Mod::Address, 'email' => String } }] PUPPET }, 'manifests' => { 'init.pp' => <<-PUPPET, define mod::person(Mod::Contact $contact) { notify { $title: } notify { $contact.address.street: } notify { $contact.address.zipcode: } notify { $contact.address.city: } notify { $contact.address.state: } } class mod { mod::person { 'Test Person': contact => Mod::Contact( Mod::Address('The Street 23', '12345', 'Some City', 'A State'), 'test@example.com') } } PUPPET } } } } } let(:env) { Puppet::Node::Environment.create(env_name.to_sym, [File.join(envdir, env_name, 'modules')]) } let(:node) { Puppet::Node.new('test', :environment => env) } before(:each) do dir_contained_in(envdir, env_name => dir_structure) PuppetSpec::Files.record_tmp(File.join(envdir, env_name)) end it 'can compile the catalog' do compile_to_catalog('include mod', node) end it 'can apply the catalog with no warning' do logs = [] Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do catalog = compile_to_catalog('include mod', node) Puppet[:environment] = env_name handler = Puppet::Network::FormatHandler.format(:rich_data_json) apply.command_line.args = ['--catalog', file_containing('manifest', handler.render(catalog))] expect { apply.run }.to output(%r{Notify\[The Street 23\]/message: defined 'message' as 'The Street 23'}).to_stdout end # expected to have no warnings expect(logs.select { |log| log.level == :warning }.map { |log| log.message }).to be_empty end end it "raises if the environment directory does not exist" do manifest = file_containing("manifest.pp", "notice('it was applied')") apply.command_line.args = [manifest] special = Puppet::Node::Environment.create(:special, []) Puppet.override(:current_environment => special) do Puppet[:environment] = 'special' expect { apply.run }.to raise_error(Puppet::Environments::EnvironmentNotFound, /Could not find a directory environment named 'special' anywhere in the path/) end end it "adds environment to the $server_facts variable" do manifest = file_containing("manifest.pp", "notice(\"$server_facts\")") apply.command_line.args = [manifest] expect { apply.run }.to exit_with(0) .and output(/{environment => production}/).to_stdout end it "applies a given file even when an ENC is configured", :unless => Puppet::Util::Platform.windows? || Puppet::Util::Platform.jruby? do manifest = file_containing("manifest.pp", "notice('specific manifest applied')") enc = script_containing('enc_script', :windows => '@echo classes: []' + "\n" + '@echo environment: special', :posix => '#!/bin/sh' + "\n" + 'echo "classes: []"' + "\n" + 'echo "environment: special"') Dir.mkdir(File.join(Puppet[:environmentpath], "special"), 0755) special = Puppet::Node::Environment.create(:special, []) Puppet.override(:current_environment => special) do Puppet[:environment] = 'special' Puppet[:node_terminus] = 'exec' Puppet[:external_nodes] = enc apply.command_line.args = [manifest] expect { apply.run }.to exit_with(0) .and output(/Notice: Scope\(Class\[main\]\): specific manifest applied/).to_stdout end end context "handles errors" do it "logs compile errors once" do apply.command_line.args = ['-e', '08'] expect { apply.run }.to exit_with(1) .and output(/Not a valid octal number/).to_stderr end it "logs compile post processing errors once" do path = File.expand_path('/tmp/content_file_test.Q634Dlmtime') apply.command_line.args = ['-e', "file { '#{path}': content => 'This is the test file content', ensure => present, checksum => mtime }"] expect { apply.run }.to exit_with(1) .and output(/Compiled catalog/).to_stdout .and output(/You cannot specify content when using checksum/).to_stderr end end context "with a module in an environment" do let(:envdir) { tmpdir('environments') } let(:modulepath) { File.join(envdir, 'spec', 'modules') } let(:execute) { 'include amod' } before(:each) do dir_contained_in(envdir, { "spec" => { "modules" => { "amod" => { "manifests" => { "init.pp" => "class amod{ notice('amod class included') }" } } } } }) Puppet[:environmentpath] = envdir end context "given a modulepath" do let(:args) { ['-e', execute] } before :each do Puppet[:modulepath] = modulepath apply.command_line.args = args end it "looks in modulepath even when the default directory environment exists" do expect { apply.run }.to exit_with(0) .and output(/amod class included/).to_stdout end it "looks in modulepath even when given a specific directory --environment" do apply.command_line.args = args << '--environment' << 'production' expect { apply.run }.to exit_with(0) .and output(/amod class included/).to_stdout end it "looks in modulepath when given multiple paths in modulepath" do Puppet[:modulepath] = [tmpdir('notmodulepath'), modulepath].join(File::PATH_SEPARATOR) expect { apply.run }.to exit_with(0) .and output(/amod class included/).to_stdout end end context "with an ENC" do let(:enc) do script_containing('enc_script', :windows => '@echo environment: spec', :posix => '#!/bin/sh' + "\n" + 'echo "environment: spec"') end before :each do Puppet[:node_terminus] = 'exec' Puppet[:external_nodes] = enc end it "should use the environment that the ENC mandates" do apply.command_line.args = ['-e', execute] expect { apply.run }.to exit_with(0) .and output(a_string_matching(/amod class included/) .and matching(/Compiled catalog for .* in environment spec/)).to_stdout end it "should prefer the ENC environment over the configured one and emit a warning" do apply.command_line.args = ['-e', execute, '--environment', 'production'] expect { apply.run }.to exit_with(0) .and output(a_string_matching('amod class included') .and matching(/doesn't match server specified environment/)).to_stdout end end end context 'when applying from file' do include PuppetSpec::Compiler let(:env_dir) { tmpdir('environments') } let(:execute) { 'include amod' } let(:rich_data) { false } let(:env_name) { 'spec' } let(:populated_env_dir) do dir_contained_in(env_dir, { env_name => { 'modules' => { 'amod' => { 'manifests' => { 'init.pp' => <<-EOF class amod { notify { rx: message => /[Rr]eg[Ee]xp/ } notify { bin: message => Binary('w5ZzdGVuIG1lZCByw7ZzdGVuCg==') } notify { ver: message => SemVer('2.3.1') } notify { vrange: message => SemVerRange('>=2.3.0') } notify { tspan: message => Timespan(3600) } notify { tstamp: message => Timestamp('2012-03-04T18:15:11.001') } } class amod::bad_type { notify { bogus: message => amod::bogus() } } EOF }, 'lib' => { 'puppet' => { 'functions' => { 'amod' => { 'bogus.rb' => <<-RUBY # Function that leaks an object that is not recognized in the catalog Puppet::Functions.create_function(:'amod::bogus') do def bogus() Time.new(2016, 10, 6, 23, 51, 14, '+02:00') end end RUBY } } } } } } } }) env_dir end let(:env) { Puppet::Node::Environment.create(env_name.to_sym, [File.join(populated_env_dir, 'spec', 'modules')]) } let(:node) { Puppet::Node.new('test', :environment => env) } before(:each) do Puppet[:rich_data] = rich_data Puppet.push_context(:loaders => Puppet::Pops::Loaders.new(env)) end after(:each) do Puppet.pop_context() end context 'and the file is not serialized with rich_data' do # do not want to stub out behavior in tests before :each do Puppet[:strict] = :warning end around :each do |test| Puppet.override(rich_data: false) do test.run end end it 'will notify a string that is the result of Regexp#inspect (from Runtime3xConverter)' do catalog = compile_to_catalog(execute, node) apply.command_line.args = ['--catalog', file_containing('manifest', catalog.to_json)] expect(apply).to receive(:apply_catalog) do |cat| expect(cat.resource(:notify, 'rx')['message']).to be_a(String) expect(cat.resource(:notify, 'bin')['message']).to be_a(String) expect(cat.resource(:notify, 'ver')['message']).to be_a(String) expect(cat.resource(:notify, 'vrange')['message']).to be_a(String) expect(cat.resource(:notify, 'tspan')['message']).to be_a(String) expect(cat.resource(:notify, 'tstamp')['message']).to be_a(String) end apply.run end it 'will notify a string that is the result of to_s on uknown data types' do json = compile_to_catalog('include amod::bad_type', node).to_json apply.command_line.args = ['--catalog', file_containing('manifest', json)] expect(apply).to receive(:apply_catalog) do |catalog| expect(catalog.resource(:notify, 'bogus')['message']).to be_a(String) end apply.run end it 'will log a warning that a value of unknown type is converted into a string' do logs = [] Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do compile_to_catalog('include amod::bad_type', node).to_json end logs = logs.select { |log| log.level == :warning }.map { |log| log.message } expect(logs.empty?).to be_falsey expect(logs[0]).to eql("Notify[bogus]['message'] contains a Time value. It will be converted to the String '2016-10-06 23:51:14 +0200'") end end context 'and the file is serialized with rich_data' do it 'will notify a regexp using Regexp#to_s' do catalog = compile_to_catalog(execute, node) serialized_catalog = Puppet.override(rich_data: true) do catalog.to_json end apply.command_line.args = ['--catalog', file_containing('manifest', serialized_catalog)] expect(apply).to receive(:apply_catalog) do |cat| expect(cat.resource(:notify, 'rx')['message']).to be_a(Regexp) # The resource return in this expect is a String, but since it was a Binary type that # was converted with `resolve_and_replace`, we want to make sure that the encoding # of that string is the expected ASCII-8BIT. expect(cat.resource(:notify, 'bin')['message'].encoding.inspect).to include('ASCII-8BIT') expect(cat.resource(:notify, 'ver')['message']).to be_a(SemanticPuppet::Version) expect(cat.resource(:notify, 'vrange')['message']).to be_a(SemanticPuppet::VersionRange) expect(cat.resource(:notify, 'tspan')['message']).to be_a(Puppet::Pops::Time::Timespan) expect(cat.resource(:notify, 'tstamp')['message']).to be_a(Puppet::Pops::Time::Timestamp) end apply.run end end end context 'puppet file sources' do let(:env_name) { 'dev' } let(:env_dir) { File.join(Puppet[:environmentpath], env_name) } let(:env) { Puppet::Node::Environment.create(env_name.to_sym, [File.join(env_dir, 'modules')]) } let(:node) { Puppet::Node.new(Puppet[:certname], environment: environment) } before :each do Puppet[:environment] = env_name Puppet::FileSystem.mkpath(env_dir) end it "recursively copies a directory from a module" do dir = File.join(env.full_modulepath, 'amod', 'files', 'dir1', 'dir2') Puppet::FileSystem.mkpath(dir) File.write(File.join(dir, 'file'), 'content from the module') base_dir = tmpdir('apply_spec_base') manifest = file_containing("manifest.pp", <<-MANIFEST) file { "#{base_dir}/dir1": ensure => file, source => "puppet:///modules/amod/dir1", recurse => true, } MANIFEST expect { apply.command_line.args << manifest apply.run }.to exit_with(0) .and output(a_string_matching( /dir1\]\/ensure: created/ ).and matching( /dir1\/dir2\]\/ensure: created/ ).and matching( /dir1\/dir2\/file\]\/ensure: defined content as '{sha256}b37c1d77e09471b3139b2cdfee449fd8ba72ebf7634d52023aff0c0cd088cf1b'/ )).to_stdout dest_file = File.join(base_dir, 'dir1', 'dir2', 'file') expect(File.read(dest_file)).to eq("content from the module") end end context 'http file sources' do include_context 'https client' it "requires the caller to URL encode special characters in the request path and query" do Puppet[:server] = '127.0.0.1' request = nil response_proc = -> (req, res) { request = req res['Content-Type'] = 'text/plain' res.body = "from the server" } https = PuppetSpec::HTTPSServer.new https.start_server(response_proc: response_proc) do |https_port| dest = tmpfile('http_file_source') # spaces in path are encoded as %20 and '[' in query is encoded as %5B, # but ':', '=', '-' are not encoded manifest = file_containing("manifest.pp", <<~MANIFEST) file { "#{dest}": ensure => file, source => "https://#{Puppet[:server]}:#{https_port}/path%20to%20file?x=b%5Bc&sv=2019-02-02&st=2020-07-28T20:18:53Z&se=2020-07-28T21:03:00Z&sr=b&sp=r&sig=JaZhcqxT4akJcOwUdUGrQB2m1geUoh89iL8WMag8a8c=", } MANIFEST expect { apply.command_line.args << manifest apply.run }.to exit_with(0) .and output(%r{Main/File\[#{dest}\]/ensure: defined content as}).to_stdout expect(request.path).to eq('/path to file') expect(request.query).to include('x' => 'b[c') expect(request.query).to include('sig' => 'JaZhcqxT4akJcOwUdUGrQB2m1geUoh89iL8WMag8a8c=') end end end context 'http report processor' do include_context 'https client' before :each do Puppet[:reports] = 'http' end let(:unknown_server) do unknown_ca_cert = cert_fixture('unknown-ca.pem') PuppetSpec::HTTPSServer.new( ca_cert: unknown_ca_cert, server_cert: cert_fixture('unknown-127.0.0.1.pem'), server_key: key_fixture('unknown-127.0.0.1-key.pem') ) end it 'submits a report via reporturl' do report = nil response_proc = -> (req, res) { report = Puppet::Transaction::Report.convert_from(:yaml, req.body) } https = PuppetSpec::HTTPSServer.new https.start_server(response_proc: response_proc) do |https_port| Puppet[:reporturl] = "https://127.0.0.1:#{https_port}/reports/upload" expect { apply.command_line.args = ['-e', 'notify { "hi": }'] apply.run }.to exit_with(0) .and output(/Applied catalog/).to_stdout expect(report).to be_a(Puppet::Transaction::Report) expect(report.resource_statuses['Notify[hi]']).to be_a(Puppet::Resource::Status) end end it 'rejects an HTTPS report server whose root cert is not the puppet CA' do unknown_server.start_server do |https_port| Puppet[:reporturl] = "https://127.0.0.1:#{https_port}/reports/upload" # processing the report happens after the transaction is finished, # so we expect exit code 0, with a later failure on stderr expect { apply.command_line.args = ['-e', 'notify { "hi": }'] apply.run }.to exit_with(0) .and output(/Applied catalog/).to_stdout .and output(/Report processor failed: certificate verify failed \[self.signed certificate in certificate chain for CN=Unknown CA\]/).to_stderr end end it 'accepts an HTTPS report servers whose cert is in the system CA store' do Puppet[:report_include_system_store] = true report = nil response_proc = -> (req, res) { report = Puppet::Transaction::Report.convert_from(:yaml, req.body) } # create a temp cacert bundle ssl_file = tmpfile('systemstore') File.write(ssl_file, unknown_server.ca_cert.to_pem) unknown_server.start_server(response_proc: response_proc) do |https_port| Puppet[:reporturl] = "https://127.0.0.1:#{https_port}/reports/upload" # override path to system cacert bundle, this must be done before # the SSLContext is created and the call to X509::Store.set_default_paths Puppet::Util.withenv("SSL_CERT_FILE" => ssl_file) do expect { apply.command_line.args = ['-e', 'notify { "hi": }'] apply.run }.to exit_with(0) .and output(/Applied catalog/).to_stdout end expect(report).to be_a(Puppet::Transaction::Report) expect(report.resource_statuses['Notify[hi]']).to be_a(Puppet::Resource::Status) end end end context 'rich data' do let(:deferred_file) { tmpfile('deferred') } let(:deferred_manifest) do <<~END file { '#{deferred_file}': ensure => file, content => '123', } -> notify { 'deferred': message => Deferred('binary_file', ['#{deferred_file}']) } END end it "calls a deferred 4x function" do apply.command_line.args = ['-e', 'notify { "deferred3x": message => Deferred("join", [[1,2,3], ":"]) }'] expect { apply.run }.to exit_with(0) # for some reason apply returns 0 instead of 2 .and output(%r{Notice: /Stage\[main\]/Main/Notify\[deferred3x\]/message: defined 'message' as '1:2:3'}).to_stdout end it "calls a deferred 3x function" do apply.command_line.args = ['-e', 'notify { "deferred4x": message => Deferred("sprintf", ["%s", "I am deferred"]) }'] expect { apply.run }.to exit_with(0) # for some reason apply returns 0 instead of 2 .and output(%r{Notice: /Stage\[main\]/Main/Notify\[deferred4x\]/message: defined 'message' as 'I am deferred'}).to_stdout end it "fails to apply a deferred function with an unsatisfied prerequisite" do Puppet[:preprocess_deferred] = true apply.command_line.args = ['-e', deferred_manifest] expect { apply.run }.to exit_with(1) # for some reason apply returns 0 instead of 2 .and output(/Compiled catalog/).to_stdout .and output(%r{The given file '#{deferred_file}' does not exist}).to_stderr end it "applies a deferred function and its prerequisite in the same run" do apply.command_line.args = ['-e', deferred_manifest] expect { apply.run }.to exit_with(0) # for some reason apply returns 0 instead of 2 .and output(%r{defined 'message' as Binary\("MTIz"\)}).to_stdout end it "validates the deferred resource before applying any resources" do Puppet[:preprocess_deferred] = true undeferred_file = tmpfile('undeferred') manifest = <<~END file { '#{undeferred_file}': ensure => file, } file { '#{deferred_file}': ensure => file, content => Deferred('inline_epp', ['<%= 42 %>']), source => 'http://example.com/content', } END apply.command_line.args = ['-e', manifest] expect { apply.run }.to exit_with(1) .and output(/Compiled catalog/).to_stdout .and output(/Validation of File.* failed: You cannot specify more than one of content, source, target/).to_stderr # validation happens before all resources are applied, so this shouldn't exist expect(File).to_not be_exist(undeferred_file) end it "evaluates resources before validating the deferred resource" do manifest = <<~END notify { 'runs before file': } -> file { '#{deferred_file}': ensure => file, content => Deferred('inline_epp', ['<%= 42 %>']), source => 'http://example.com/content', } END apply.command_line.args = ['-e', manifest] expect { apply.run }.to exit_with(1) .and output(/Notify\[runs before file\]/).to_stdout .and output(/Validation of File.* failed: You cannot specify more than one of content, source, target/).to_stderr end it "applies deferred sensitive file content" do manifest = <<~END file { '#{deferred_file}': ensure => file, content => Deferred('new', [Sensitive, "hello\n"]) } END apply.command_line.args = ['-e', manifest] expect { apply.run }.to exit_with(0) .and output(/ensure: changed \[redacted\] to \[redacted\]/).to_stdout end it "applies nested deferred sensitive file content" do manifest = <<~END $vars = {'token' => Deferred('new', [Sensitive, "hello"])} file { '#{deferred_file}': ensure => file, content => Deferred('inline_epp', ['<%= $token %>', $vars]) } END apply.command_line.args = ['-e', manifest] expect { apply.run }.to exit_with(0) .and output(/ensure: changed \[redacted\] to \[redacted\]/).to_stdout end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/integration/application/filebucket_spec.rb
spec/integration/application/filebucket_spec.rb
require 'spec_helper' require 'puppet/face' require 'puppet_spec/puppetserver' require 'puppet_spec/files' describe "puppet filebucket", unless: Puppet::Util::Platform.jruby? do include PuppetSpec::Files include_context "https client" let(:server) { PuppetSpec::Puppetserver.new } let(:filebucket) { Puppet::Application[:filebucket] } let(:backup_file) { tmpfile('backup_file') } let(:text) { 'some random text' } let(:sha256) { Digest::SHA256.file(backup_file).to_s } before :each do Puppet[:log_level] = 'debug' File.binwrite(backup_file, text) end after :each do # mute debug messages generated during `after :each` blocks Puppet::Util::Log.close_all end it "backs up to and restores from the local filebucket" do filebucket.command_line.args = ['backup', backup_file, '--local'] expect { filebucket.run }.to output(/: #{sha256}/).to_stdout dest = tmpfile('file_bucket_restore') filebucket.command_line.args = ['restore', dest, sha256, '--local'] expect { filebucket.run }.to output(/FileBucket read #{sha256}/).to_stdout expect(FileUtils.compare_file(backup_file, dest)).to eq(true) end it "backs up text files to the filebucket server" do server.start_server do |port| Puppet[:serverport] = port expect { filebucket.command_line.args = ['backup', backup_file] filebucket.run }.to output(a_string_matching( %r{Debug: HTTP HEAD https:\/\/127.0.0.1:#{port}\/puppet\/v3\/file_bucket_file\/sha256\/#{sha256}\/#{File.realpath(backup_file)}\?environment\=production returned 404 Not Found} ).and matching( %r{Debug: HTTP PUT https:\/\/127.0.0.1:#{port}\/puppet\/v3\/file_bucket_file\/sha256\/#{sha256}\/#{File.realpath(backup_file)}\?environment\=production returned 200 OK} ).and matching( %r{#{backup_file}: #{sha256}} )).to_stdout expect(File.binread(File.join(server.upload_directory, 'filebucket'))).to eq(text) end end it "backs up binary files to the filebucket server" do binary = "\xD1\xF2\r\n\x81NuSc\x00".force_encoding(Encoding::ASCII_8BIT) File.binwrite(backup_file, binary) server.start_server do |port| Puppet[:serverport] = port expect { filebucket.command_line.args = ['backup', backup_file] filebucket.run }.to output(a_string_matching( %r{Debug: HTTP HEAD https:\/\/127.0.0.1:#{port}\/puppet\/v3\/file_bucket_file/sha256/f3aee54d781e413862eb068d89661f930385cc81bbafffc68477ff82eb9bea43/} ).and matching( %r{Debug: HTTP PUT https:\/\/127.0.0.1:#{port}\/puppet\/v3\/file_bucket_file/sha256/f3aee54d781e413862eb068d89661f930385cc81bbafffc68477ff82eb9bea43/} )).to_stdout expect(File.binread(File.join(server.upload_directory, 'filebucket'))).to eq(binary) end end it "backs up utf-8 encoded files to the filebucket server" do utf8 = "\u2603".force_encoding(Encoding::UTF_8) File.binwrite(backup_file, utf8) server.start_server do |port| Puppet[:serverport] = port expect { filebucket.command_line.args = ['backup', backup_file] filebucket.run }.to output(a_string_matching( %r{Debug: HTTP HEAD https:\/\/127.0.0.1:#{port}\/puppet\/v3\/file_bucket_file/sha256/51643361c79ecaef25a8de802de24f570ba25d9c2df1d22d94fade11b4f466cc/} ).and matching( %r{Debug: HTTP PUT https:\/\/127.0.0.1:#{port}\/puppet\/v3\/file_bucket_file/sha256/51643361c79ecaef25a8de802de24f570ba25d9c2df1d22d94fade11b4f466cc/} )).to_stdout expect(File.read(File.join(server.upload_directory, 'filebucket'), encoding: 'utf-8')).to eq(utf8) end end it "doesn't attempt to back up file that already exists on the filebucket server" do file_exists_handler = -> (req, res) { res.status = 200 } server.start_server(mounts: {filebucket: file_exists_handler}) do |port| Puppet[:serverport] = port expect { filebucket.command_line.args = ['backup', backup_file] filebucket.run }.to output(a_string_matching( %r{Debug: HTTP HEAD https:\/\/127.0.0.1:#{port}\/puppet\/v3\/file_bucket_file\/sha256\/#{sha256}\/#{File.realpath(backup_file)}\?environment\=production returned 200 OK} ).and matching( %r{#{backup_file}: #{sha256}} )).to_stdout end end it "downloads files from the filebucket server" do get_handler = -> (req, res) { res['Content-Type'] = 'application/octet-stream' res.body = 'something to store' } server.start_server(mounts: {filebucket: get_handler}) do |port| Puppet[:serverport] = port expect { filebucket.command_line.args = ['get', 'fac251367c9e083c6b1f0f3181'] filebucket.run }.to output(a_string_matching( %r{Debug: HTTP GET https:\/\/127.0.0.1:#{port}\/puppet\/v3\/file_bucket_file\/sha256\/fac251367c9e083c6b1f0f3181\?environment\=production returned 200 OK} ).and matching( %r{something to store} )).to_stdout end end it "lists the local filebucket even if the environment doesn't exist locally" do Puppet[:environment] = 'doesnotexist' Puppet::FileSystem.mkpath(Puppet[:clientbucketdir]) filebucket.command_line.args = ['backup', '--local', backup_file] expect { result = filebucket.run expect(result).to eq([backup_file]) }.to output(/Computing checksum on file/).to_stdout end context 'diff', unless: Puppet::Util::Platform.windows? || Puppet::Util::Platform.jruby? do context 'using a remote bucket' do it 'outputs a diff between a local and remote file' do File.binwrite(backup_file, "bar\nbaz") get_handler = -> (req, res) { res['Content-Type'] = 'application/octet-stream' res.body = 'foo' } server.start_server(mounts: {filebucket: get_handler}) do |port| Puppet[:serverport] = port expect { filebucket.command_line.args = ['diff', 'fac251367c9e083c6b1f0f3181', backup_file, '--remote'] filebucket.run }.to output(a_string_matching( /[-<] ?foo/ ).and matching( /[+>] ?bar/ ).and matching( /[+>] ?baz/ )).to_stdout end end it 'outputs a diff between two remote files' do get_handler = -> (req, res) { res['Content-Type'] = 'application/octet-stream' res.body = <<~END --- /opt/puppetlabs/server/data/puppetserver/bucket/d/3/b/0/7/3/8/4/d3b07384d113edec49eaa6238ad5ff00/contents\t2020-04-06 21:25:24.892367570 +0000 +++ /opt/puppetlabs/server/data/puppetserver/bucket/9/9/b/9/9/9/2/0/99b999207e287afffc86c053e5693247/contents\t2020-04-06 21:26:13.603398063 +0000 @@ -1 +1,2 @@ -foo +bar +baz END } server.start_server(mounts: {filebucket: get_handler}) do |port| Puppet[:serverport] = port expect { filebucket.command_line.args = ['diff', 'd3b07384d113edec49eaa6238ad5ff00', "99b999207e287afffc86c053e5693247", '--remote'] filebucket.run }.to output(a_string_matching( /[-<] ?foo/ ).and matching( /[+>] ?bar/ ).and matching( /[+>] ?baz/ )).to_stdout end end end context 'using a local bucket' do let(:filea) { f = tmpfile('filea') File.binwrite(f, 'foo') f } let(:fileb) { f = tmpfile('fileb') File.binwrite(f, "bar\nbaz") f } let(:checksuma) { Digest::SHA256.file(filea).to_s } let(:checksumb) { Digest::SHA256.file(fileb).to_s } it 'compares to files stored in a local bucket' do expect { filebucket.command_line.args = ['backup', filea, '--local'] filebucket.run }.to output(/#{filea}: #{checksuma}/).to_stdout expect{ filebucket.command_line.args = ['backup', fileb, '--local'] filebucket.run }.to output(/#{fileb}: #{checksumb}\n/).to_stdout expect { filebucket.command_line.args = ['diff', checksuma, checksumb, '--local'] filebucket.run }.to output(a_string_matching( /[-<] ?foo/ ).and matching( /[+>] ?bar/ ).and matching( /[+>] ?baz/ )).to_stdout end it 'compares a file on the filesystem and a file stored in a local bucket' do expect { filebucket.command_line.args = ['backup', filea, '--local'] filebucket.run }.to output(/#{filea}: #{checksuma}/).to_stdout expect { filebucket.command_line.args = ['diff', checksuma, fileb, '--local'] filebucket.run }.to output(a_string_matching( /[-<] ?foo/ ).and matching( /[+>] ?bar/ ).and matching( /[+>] ?baz/ )).to_stdout end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/integration/application/module_spec.rb
spec/integration/application/module_spec.rb
# coding: utf-8 require 'spec_helper' require 'puppet/forge' require 'puppet_spec/https' describe 'puppet module', unless: Puppet::Util::Platform.jruby? do include PuppetSpec::Files include_context "https client" let(:app) { Puppet::Application[:module] } let(:wrong_hostname) { 'localhost' } let(:server) { PuppetSpec::HTTPSServer.new } let(:ssl_provider) { Puppet::SSL::SSLProvider.new } let(:release_response) { File.read(fixtures('unit/forge/bacula-releases.json')) } let(:release_tarball) { File.binread(fixtures('unit/forge/bacula.tar.gz')) } let(:target_dir) { tmpdir('bacula') } before :each do SemanticPuppet::Dependency.clear_sources end it 'installs a module' do # create a temp cacert bundle ssl_file = tmpfile('systemstore') File.write(ssl_file, server.ca_cert) response_proc = -> (req, res) { if req.path == '/v3/releases' res['Content-Type'] = 'application/json' res.body = release_response else res['Content-Type'] = 'application/octet-stream' res.body = release_tarball end res.status = 200 } # override path to system cacert bundle, this must be done before # the SSLContext is created and the call to X509::Store.set_default_paths Puppet::Util.withenv("SSL_CERT_FILE" => ssl_file) do server.start_server(response_proc: response_proc) do |port| Puppet[:module_repository] = "https://127.0.0.1:#{port}" # On Windows, CP437 encoded output can't be matched against UTF-8 regexp, # so encode the regexp to the external encoding and match against that. app.command_line.args = ['install', 'puppetlabs-bacula', '--target-dir', target_dir] expect { app.run }.to exit_with(0) .and output(Regexp.new("└── puppetlabs-bacula".encode(Encoding.default_external))).to_stdout end end end it 'returns a valid exception when there is an SSL verification problem' do server.start_server do |port| Puppet[:module_repository] = "https://#{wrong_hostname}:#{port}" expect { app.command_line.args = ['install', 'puppetlabs-bacula', '--target-dir', target_dir] app.run }.to exit_with(1) .and output(%r{Notice: Downloading from https://#{wrong_hostname}:#{port}}).to_stdout .and output(%r{Unable to verify the SSL certificate}).to_stderr end end it 'prints the complete URL it tried to connect to' do response_proc = -> (req, res) { res.status = 404 } # create a temp cacert bundle ssl_file = tmpfile('systemstore') File.write(ssl_file, server.ca_cert) Puppet::Util.withenv("SSL_CERT_FILE" => ssl_file) do server.start_server(response_proc: response_proc) do |port| Puppet[:module_repository] = "https://127.0.0.1:#{port}/bogus_test/puppet" expect { app.command_line.args = ['install', 'puppetlabs-bacula'] app.run }.to exit_with(1) .and output(%r{Notice: Downloading from https://127.0.0.1:#{port}}).to_stdout .and output(%r{https://127.0.0.1:#{port}/bogus_test/puppet/v3/releases}).to_stderr end end end context 'install' do it 'lists a module in a non-default directory environment' do Puppet.initialize_settings(['-E', 'direnv']) Puppet[:color] = false Puppet[:environmentpath] = File.join(my_fixture_dir, 'environments') expect { app.command_line.args = ['list'] app.run }.to exit_with(0) .and output(Regexp.new("└── pmtacceptance-nginx".encode(Encoding.default_external), Regexp::MULTILINE)).to_stdout end end context 'changes' do let(:tmp) { tmpdir('module_changes') } before :each do Puppet.initialize_settings(['-E', 'direnv']) Puppet[:color] = false end def use_local_fixture Puppet[:environmentpath] = File.join(my_fixture_dir, 'environments') end def create_working_copy Puppet[:environmentpath] = File.join(tmp, 'environments') FileUtils.cp_r(File.join(my_fixture_dir, 'environments'), tmp) end it 'reports an error when the install path is invalid' do use_local_fixture pattern = Regexp.new([ %Q{.*Error: Could not find a valid module at "#{tmp}/nginx".*}, %Q{.*Error: Try 'puppet help module changes' for usage.*}, ].join("\n"), Regexp::MULTILINE) expect { app.command_line.args = ['changes', File.join(tmp, 'nginx')] app.run }.to exit_with(1) .and output(pattern).to_stderr end it 'reports when checksums are missing from metadata.json' do create_working_copy # overwrite checksums in metadata.json nginx_dir = File.join(tmp, 'environments', 'direnv', 'modules', 'nginx') File.write(File.join(nginx_dir, 'metadata.json'), <<~END) { "name": "pmtacceptance/nginx", "version": "0.0.1" } END pattern = Regexp.new([ %Q{.*Error: No file containing checksums found.*}, %Q{.*Error: Try 'puppet help module changes' for usage.*}, ].join("\n"), Regexp::MULTILINE) expect { app.command_line.args = ['changes', nginx_dir] app.run }.to exit_with(1) .and output(pattern).to_stderr end it 'reports module not found when metadata.json is missing' do create_working_copy # overwrite checksums in metadata.json nginx_dir = File.join(tmp, 'environments', 'direnv', 'modules', 'nginx') File.unlink(File.join(nginx_dir, 'metadata.json')) pattern = Regexp.new([ %Q{.*Error: Could not find a valid module at.*}, %Q{.*Error: Try 'puppet help module changes' for usage.*}, ].join("\n"), Regexp::MULTILINE) expect { app.command_line.args = ['changes', nginx_dir] app.run }.to exit_with(1) .and output(pattern).to_stderr end it 'reports when a file is modified' do create_working_copy # overwrite README so checksum doesn't match nginx_dir = File.join(tmp, 'environments', 'direnv', 'modules', 'nginx') File.write(File.join(nginx_dir, 'README'), '') pattern = Regexp.new([ %Q{.*Warning: 1 files modified.*}, ].join("\n"), Regexp::MULTILINE) expect { app.command_line.args = ['changes', nginx_dir] app.run }.to exit_with(0) .and output(%r{README}).to_stdout .and output(pattern).to_stderr end it 'reports when a file is missing' do create_working_copy # delete README so checksum doesn't match nginx_dir = File.join(tmp, 'environments', 'direnv', 'modules', 'nginx') File.unlink(File.join(nginx_dir, 'README')) # odd that it says modified pattern = Regexp.new([ %Q{.*Warning: 1 files modified.*}, ].join("\n"), Regexp::MULTILINE) expect { app.command_line.args = ['changes', nginx_dir] app.run }.to exit_with(0) .and output(%r{README}).to_stdout .and output(pattern).to_stderr end it 'reports when there are no changes' do use_local_fixture nginx_dir = File.join(Puppet[:environmentpath], 'direnv', 'modules', 'nginx') expect { app.command_line.args = ['changes', nginx_dir] app.run }.to exit_with(0) .and output(/No modified files/).to_stdout end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/integration/application/plugin_spec.rb
spec/integration/application/plugin_spec.rb
require 'spec_helper' require 'puppet/face' require 'puppet_spec/puppetserver' describe "puppet plugin", unless: Puppet::Util::Platform.jruby? do include_context "https client" let(:server) { PuppetSpec::Puppetserver.new } let(:plugin) { Puppet::Application[:plugin] } let(:response_body) { "[{\"path\":\"/etc/puppetlabs/code/environments/production/modules\",\"relative_path\":\".\",\"links\":\"follow\",\"owner\":0,\"group\":0,\"mode\":493,\"checksum\":{\"type\":\"ctime\",\"value\":\"{ctime}2020-03-06 20:14:25 UTC\"},\"type\":\"directory\",\"destination\":null}]" } it "downloads from plugins, pluginsfacts and locales mounts when i18n is enabled" do Puppet[:disable_i18n] = false current_version_handler = -> (req, res) { res['X-Puppet-Version'] = Puppet.version res['Content-Type'] = 'application/json' res.body = response_body } server.start_server(mounts: {file_metadatas: current_version_handler}) do |port| Puppet[:serverport] = port expect { plugin.command_line.args << 'download' plugin.run }.to exit_with(0) .and output(matching( "Downloaded these plugins: #{Regexp.escape(Puppet[:pluginfactdest])}, #{Regexp.escape(Puppet[:plugindest])}, #{Regexp.escape(Puppet[:localedest])}" )).to_stdout end end it "downloads from plugins, pluginsfacts but no locales mounts when i18n is disabled" do Puppet[:disable_i18n] = true current_version_handler = -> (req, res) { res['X-Puppet-Version'] = Puppet.version res['Content-Type'] = 'application/json' res.body = response_body } server.start_server(mounts: {file_metadatas: current_version_handler}) do |port| Puppet[:serverport] = port expect { plugin.command_line.args << 'download' plugin.run }.to exit_with(0) .and output(matching( "Downloaded these plugins: #{Regexp.escape(Puppet[:pluginfactdest])}, #{Regexp.escape(Puppet[:plugindest])}" )).to_stdout end end it "downloads from plugins and pluginsfacts from older puppetservers" do no_locales_handler = -> (req, res) { res['X-Puppet-Version'] = '5.3.3' # locales mount was added in 5.3.4 res['Content-Type'] = 'application/json' res.body = response_body } server.start_server(mounts: {file_metadatas: no_locales_handler}) do |port| Puppet[:serverport] = port expect { plugin.command_line.args << 'download' plugin.run }.to exit_with(0) .and output(matching( "Downloaded these plugins: #{Regexp.escape(Puppet[:pluginfactdest])}, #{Regexp.escape(Puppet[:plugindest])}" )).to_stdout end end it "downloads from an environment that doesn't exist locally" do requested_environment = nil current_version_handler = -> (req, res) { res['X-Puppet-Version'] = Puppet.version res['Content-Type'] = 'application/json' res.body = response_body requested_environment = req.query['environment'] } server.start_server(mounts: {file_metadatas: current_version_handler}) do |port| Puppet[:environment] = 'doesnotexistontheagent' Puppet[:serverport] = port expect { plugin.command_line.args << 'download' plugin.run }.to exit_with(0) .and output(matching("Downloaded these plugins")).to_stdout expect(requested_environment).to eq('doesnotexistontheagent') end end context "pluginsync for external facts uses source permissions to preserve fact executable-ness" do before :all do WebMock.enable! end after :all do WebMock.disable! end before :each do metadata = "[{\"path\":\"/etc/puppetlabs/code\",\"relative_path\":\".\",\"links\":\"follow\",\"owner\":0,\"group\":0,\"mode\":420,\"checksum\":{\"type\":\"ctime\",\"value\":\"{ctime}2020-07-10 14:00:00 -0700\"},\"type\":\"directory\",\"destination\":null}]" stub_request(:get, %r{/puppet/v3/file_metadatas/(plugins|locales)}).to_return(status: 200, body: metadata, headers: {'Content-Type' => 'application/json'}) # response retains owner/group/mode due to source_permissions => use facts_metadata = "[{\"path\":\"/etc/puppetlabs/code\",\"relative_path\":\".\",\"links\":\"follow\",\"owner\":500,\"group\":500,\"mode\":493,\"checksum\":{\"type\":\"ctime\",\"value\":\"{ctime}2020-07-10 14:00:00 -0700\"},\"type\":\"directory\",\"destination\":null}]" stub_request(:get, %r{/puppet/v3/file_metadatas/pluginfacts}).to_return(status: 200, body: facts_metadata, headers: {'Content-Type' => 'application/json'}) end it "processes a download request resulting in no changes" do # Create these so there are no changes Puppet::FileSystem.mkpath(Puppet[:plugindest]) Puppet::FileSystem.mkpath(Puppet[:localedest]) # /opt/puppetlabs/puppet/cache/facts.d will be created based on our umask. # If the mode on disk is not 0755, then the mode from the metadata response # (493 => 0755) will be applied, resulting in "plugins were downloaded" # message. Enforce a umask so the results are consistent. Puppet::FileSystem.mkpath(Puppet[:pluginfactdest]) Puppet::FileSystem.chmod(0755, Puppet[:pluginfactdest]) app = Puppet::Application[:plugin] app.command_line.args << 'download' expect { app.run }.to exit_with(0) .and output(/No plugins downloaded/).to_stdout end it "updates the facts.d mode", unless: Puppet::Util::Platform.windows? do Puppet::FileSystem.mkpath(Puppet[:pluginfactdest]) Puppet::FileSystem.chmod(0775, Puppet[:pluginfactdest]) app = Puppet::Application[:plugin] app.command_line.args << 'download' expect { app.run }.to exit_with(0) .and output(/Downloaded these plugins: .*facts\.d/).to_stdout end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/integration/application/ssl_spec.rb
spec/integration/application/ssl_spec.rb
require 'spec_helper' describe "puppet ssl", unless: Puppet::Util::Platform.jruby? do context "print" do it 'translates custom oids to their long name' do basedir = File.expand_path("#{__FILE__}/../../../fixtures/ssl") # registering custom oids changes global state, so shell out output = %x{puppet ssl show \ --certname oid \ --localcacert #{basedir}/ca.pem \ --hostcrl #{basedir}/crl.pem \ --hostprivkey #{basedir}/oid-key.pem \ --hostcert #{basedir}/oid.pem \ --trusted_oid_mapping_file #{basedir}/trusted_oid_mapping.yaml 2>&1 } expect(output).to match(/Long name:/) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/integration/application/help_spec.rb
spec/integration/application/help_spec.rb
require 'spec_helper' require 'puppet/application/help' describe "puppet help" do let(:app) { Puppet::Application[:help] } it "generates global help" do expect { app.run }.to exit_with(0) .and output(Regexp.new(Regexp.escape(<<~END), Regexp::MULTILINE)).to_stdout Usage: puppet <subcommand> [options] <action> [options] Available subcommands: END end Puppet::Face.faces.sort.each do |face_name| next if face_name == :key context "for #{face_name}" do it "generates help" do app.command_line.args = ['help', face_name] expect { app.run }.to exit_with(0) .and output(/USAGE: puppet #{face_name} <action>/).to_stdout end Puppet::Face[face_name, :current].actions.sort.each do |action_name| it "for action #{action_name}" do app.command_line.args = ['help', face_name, action_name] expect { app.run }.to exit_with(0) .and output(/USAGE: puppet #{face_name}/).to_stdout end end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/integration/application/lookup_spec.rb
spec/integration/application/lookup_spec.rb
require 'spec_helper' require 'puppet_spec/files' require 'puppet_spec/compiler' require 'deep_merge/core' describe 'lookup' do include PuppetSpec::Files context 'with an environment' do let(:fqdn) { Puppet[:certname] } let(:env_name) { 'spec' } let(:env_dir) { tmpdir('environments') } let(:environment_files) do { env_name => { 'modules' => {}, 'hiera.yaml' => <<-YAML.unindent, --- version: 5 hierarchy: - name: "Common" data_hash: yaml_data path: "common.yaml" YAML 'data' => { 'common.yaml' => <<-YAML.unindent --- a: value a mod_a::a: value mod_a::a (from environment) mod_a::hash_a: a: value mod_a::hash_a.a (from environment) mod_a::hash_b: a: value mod_a::hash_b.a (from environment) lookup_options: mod_a::hash_b: merge: hash YAML } }, 'someother' => { } } end let(:app) { Puppet::Application[:lookup] } let(:facts) { Puppet::Node::Facts.new("facts", {'my_fact' => 'my_fact_value'}) } let(:cert) { pem_content('oid.pem') } let(:node) { Puppet::Node.new('testnode', :facts => facts) } let(:populated_env_dir) do dir_contained_in(env_dir, environment_files) env_dir end before do stub_request(:get, "https://puppet:8140/puppet-ca/v1/certificate/#{fqdn}").to_return(body: cert) allow(Puppet::Node::Facts.indirection).to receive(:find).and_return(facts) Puppet[:environment] = env_name Puppet[:environmentpath] = populated_env_dir http = Puppet::HTTP::Client.new(ssl_context: Puppet::SSL::SSLProvider.new.create_insecure_context) Puppet.runtime[:http] = http end def expect_lookup_with_output(exitcode, out) expect { app.run }.to exit_with(exitcode).and output(out).to_stdout end it 'finds data in the environment' do app.command_line.args << 'a' expect_lookup_with_output(0, /value a/) end it "resolves hiera data using a top-level node parameter" do File.write(File.join(env_dir, env_name, 'hiera.yaml'), <<~YAML) --- version: 5 hierarchy: - name: "Per Node" data_hash: yaml_data path: "%{my_fact}.yaml" YAML File.write(File.join(env_dir, env_name, 'data', "my_fact_value.yaml"), <<~YAML) --- a: value from per node data YAML app.command_line.args << 'a' expect_lookup_with_output(0, /--- value from per node data/) end it "resolves hiera data using a top-level node parameter from enc" do Puppet.settings[:node_terminus] = 'exec' enc = tmpfile('enc.sh') Puppet.settings[:external_nodes] = enc File.write(File.join(env_dir, env_name, 'hiera.yaml'), <<~YAML) --- version: 5 hierarchy: - name: "Node parameters" data_hash: yaml_data path: "%{site}.yaml" YAML File.write(File.join(env_dir, env_name, 'data', "pdx.yaml"), <<~YAML) --- key: value YAML allow(Puppet::Util::Execution).to receive(:execute).with([enc, fqdn], anything).and_return(<<~YAML) parameters: site: pdx YAML app.command_line.args << 'key' << '--compile' Puppet.initialize_settings(['-E', env_name]) expect_lookup_with_output(0, /--- value/) end it "prefers the environment specified on the commandline over the enc environment" do Puppet.settings[:node_terminus] = 'exec' enc = tmpfile('enc.sh') Puppet.settings[:external_nodes] = enc File.write(File.join(env_dir, env_name, 'hiera.yaml'), <<~YAML) --- version: 5 hierarchy: - name: "Node parameters" data_hash: yaml_data path: "%{site}.yaml" YAML File.write(File.join(env_dir, env_name, 'data', "pdx.yaml"), <<~YAML) --- key: value YAML allow(Puppet::Util::Execution).to receive(:execute).with([enc, fqdn], anything).and_return(<<~YAML) --- # return 'someother' environment because it doesn't have any hiera data environment: someother parameters: site: pdx YAML app.command_line.args << 'key' << '--compile' Puppet.initialize_settings(['-E', env_name]) expect_lookup_with_output(0, /--- value/) end it 'loads trusted information from the node certificate' do Puppet.settings[:node_terminus] = 'exec' expect_any_instance_of(Puppet::Node::Exec).to receive(:find) do |args| info = Puppet.lookup(:trusted_information) expect(info.certname).to eq(fqdn) expect(info.extensions).to eq({ "1.3.6.1.4.1.34380.1.2.1.1" => "somevalue" }) end.and_return(node) app.command_line.args << 'a' << '--compile' expect_lookup_with_output(0, /--- value a/) end it 'loads external facts when running without --node' do expect(Puppet::Util).not_to receive(:skip_external_facts) expect(Facter).not_to receive(:load_external) app.command_line.args << 'a' expect_lookup_with_output(0, /--- value a/) end describe 'when using --node' do let(:fqdn) { 'random_node' } it 'skips loading of external facts' do app.command_line.args << 'a' << '--node' << fqdn expect(Puppet::Node::Facts.indirection).to receive(:find).and_return(facts) expect(Facter).to receive(:load_external).twice.with(false) expect(Facter).to receive(:load_external).twice.with(true) expect_lookup_with_output(0, /--- value a/) end end context 'uses node_terminus' do require 'puppet/indirector/node/exec' require 'puppet/indirector/node/plain' let(:node) { Puppet::Node.new('testnode', :facts => facts) } it ':plain without --compile' do Puppet.settings[:node_terminus] = 'exec' expect_any_instance_of(Puppet::Node::Plain).to receive(:find).and_return(node) expect_any_instance_of(Puppet::Node::Exec).not_to receive(:find) app.command_line.args << 'a' expect_lookup_with_output(0, /--- value a/) end it 'configured in Puppet settings with --compile' do Puppet.settings[:node_terminus] = 'exec' expect_any_instance_of(Puppet::Node::Plain).not_to receive(:find) expect_any_instance_of(Puppet::Node::Exec).to receive(:find).and_return(node) app.command_line.args << 'a' << '--compile' expect_lookup_with_output(0, /--- value a/) end end context 'configured with the wrong environment' do it 'does not find data in non-existing environment' do Puppet[:environment] = 'doesntexist' app.command_line.args << 'a' expect { app.run }.to raise_error(Puppet::Environments::EnvironmentNotFound, /Could not find a directory environment named 'doesntexist'/) end end context 'and a module' do let(:mod_a_files) do { 'mod_a' => { 'data' => { 'common.yaml' => <<-YAML.unindent --- mod_a::a: value mod_a::a (from mod_a) mod_a::b: value mod_a::b (from mod_a) mod_a::hash_a: a: value mod_a::hash_a.a (from mod_a) b: value mod_a::hash_a.b (from mod_a) mod_a::hash_b: a: value mod_a::hash_b.a (from mod_a) b: value mod_a::hash_b.b (from mod_a) mod_a::interpolated: "-- %{lookup('mod_a::a')} --" mod_a::a_a: "-- %{lookup('mod_a::hash_a.a')} --" mod_a::a_b: "-- %{lookup('mod_a::hash_a.b')} --" mod_a::b_a: "-- %{lookup('mod_a::hash_b.a')} --" mod_a::b_b: "-- %{lookup('mod_a::hash_b.b')} --" 'mod_a::a.quoted.key': 'value mod_a::a.quoted.key (from mod_a)' YAML }, 'hiera.yaml' => <<-YAML.unindent, --- version: 5 hierarchy: - name: "Common" data_hash: yaml_data path: "common.yaml" YAML } } end let(:populated_env_dir) do dir_contained_in(env_dir, DeepMerge.deep_merge!(environment_files, env_name => { 'modules' => mod_a_files })) env_dir end it 'finds data in the module' do app.command_line.args << 'mod_a::b' expect_lookup_with_output(0, /value mod_a::b \(from mod_a\)/) end it 'finds quoted keys in the module' do app.command_line.args << "'mod_a::a.quoted.key'" expect_lookup_with_output(0, /value mod_a::a.quoted.key \(from mod_a\)/) end it 'merges hashes from environment and module when merge strategy hash is used' do app.command_line.args << 'mod_a::hash_a' << '--merge' << 'hash' expect_lookup_with_output(0, <<~END) --- a: value mod_a::hash_a.a (from environment) b: value mod_a::hash_a.b (from mod_a) END end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/spec/integration/application/doc_spec.rb
spec/integration/application/doc_spec.rb
require 'spec_helper' require 'puppet/application/doc' describe Puppet::Application::Doc do include PuppetSpec::Files let(:app) { Puppet::Application[:doc] } it 'lists references' do app.command_line.args = ['-l'] expect { app.run }.to exit_with(0) .and output(/configuration - A reference for all settings/).to_stdout end { 'configuration' => /# Configuration Reference/, 'function' => /# Function Reference/, 'indirection' => /# Indirection Reference/, 'metaparameter' => /# Metaparameter Reference/, 'providers' => /# Provider Suitability Report/, 'report' => /# Report Reference/, 'type' => /# Type Reference/ }.each_pair do |type, expected| it "generates #{type} reference" do app.command_line.args = ['-r', type] expect { app.run }.to exit_with(0) .and output(expected).to_stdout end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false