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/allow_arbitrary_node_name_fact_for_agent.rb | acceptance/tests/allow_arbitrary_node_name_fact_for_agent.rb | test_name "node_name_fact should be used to determine the node name for puppet agent"
tag 'audit:high',
'audit:integration', # Tests that the server properly overrides certname with node_name fact.
# Testing of passenger master is no longer needed.
'server'
success_message = "node_name_fact setting was correctly used to determine the node name"
testdir = master.tmpdir("nodenamefact")
node_names = []
on agents, facter('kernel') do |result|
node_names << result.stdout.chomp
end
node_names.uniq!
step "Prepare for custom tk-auth rules" do
on master, 'cp /etc/puppetlabs/puppetserver/conf.d/auth.conf /etc/puppetlabs/puppetserver/conf.d/auth.bak'
modify_tk_config(master, options['puppetserver-config'], {'jruby-puppet' => {'use-legacy-auth-conf' => false}})
end
teardown do
modify_tk_config(master, options['puppetserver-config'], {'jruby-puppet' => {'use-legacy-auth-conf' => true}})
on master, 'cp /etc/puppetlabs/puppetserver/conf.d/auth.bak /etc/puppetlabs/puppetserver/conf.d/auth.conf'
on master, "service #{master['puppetservice']} reload"
end
step "Setup tk-auth rules" do
tka_header = <<-HEADER
authorization: {
version: 1
rules: [
{
match-request: {
path: "/puppet/v3/file"
type: path
}
allow: "*"
sort-order: 500
name: "puppetlabs file"
},
HEADER
tka_node_rules = node_names.map do |node_name|
<<-NODE_RULES
{
match-request: {
path: "/puppet/v3/catalog/#{node_name}"
type: path
method: [get, post]
}
allow: "*"
sort-order: 500
name: "puppetlabs catalog #{node_name}"
},
{
match-request: {
path: "/puppet/v3/node/#{node_name}"
type: path
method: get
}
allow: "*"
sort-order: 500
name: "puppetlabs node #{node_name}"
},
{
match-request: {
path: "/puppet/v3/report/#{node_name}"
type: path
method: put
}
allow: "*"
sort-order: 500
name: "puppetlabs report #{node_name}"
},
NODE_RULES
end
tka_footer = <<-FOOTER
{
match-request: {
path: "/"
type: path
}
deny: "*"
sort-order: 999
name: "puppetlabs deny all"
}
]
}
FOOTER
tk_auth = [tka_header, tka_node_rules, tka_footer].flatten.join("\n")
apply_manifest_on(master, <<-MANIFEST, :catch_failures => true)
file { '/etc/puppetlabs/puppetserver/conf.d/auth.conf':
ensure => file,
mode => '0644',
content => '#{tk_auth}',
}
MANIFEST
end
step "Setup site.pp for node name based classification" do
site_manifest = <<-SITE_MANIFEST
node default {
notify { "false": }
}
node #{node_names.map { |name| %Q["#{name}"] }.join(", ")} {
notify { "#{success_message}": }
}
SITE_MANIFEST
apply_manifest_on(master, <<-MANIFEST, :catch_failures => true)
$directories = [
'#{testdir}',
'#{testdir}/environments',
'#{testdir}/environments/production',
'#{testdir}/environments/production/manifests',
]
file { $directories:
ensure => directory,
mode => '0755',
}
file { '#{testdir}/environments/production/manifests/manifest.pp':
ensure => file,
mode => '0644',
content => '#{site_manifest}',
}
MANIFEST
end
step "Ensure nodes are classified based on the node name fact" do
master_opts = {
'main' => {
'environmentpath' => "#{testdir}/environments",
},
'master' => {
'node_terminus' => 'plain',
},
}
with_puppet_running_on(master, master_opts, testdir) do
on(agents, puppet('agent', "--no-daemonize --verbose --onetime --node_name_fact kernel")) do |result|
assert_match(/defined 'message'.*#{success_message}/, result.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/acceptance/tests/ticket_15560_managehome.rb | acceptance/tests/ticket_15560_managehome.rb | test_name "#15560: Manage home directories"
tag 'audit:high',
'audit:refactor', # Use block style `test_namme`
# refactor to be OS agnostic and added to the resource/user
# tests. managehome is currently not covered there.
'audit:acceptance'
confine :to, :platform => 'windows'
username = "pl#{rand(99999).to_i}"
manifest_present = <<-EOM
user { '#{username}':
ensure => present,
managehome => true,
password => 'Password123!!',
}
EOM
manifest_absent = <<-EOM
user { '#{username}':
ensure => absent,
managehome => true,
}
EOM
agents.each do |host|
on(host, puppet_apply, :stdin => manifest_present)
deleteable_profile = true
version = on(host, facter('os.release.full')).stdout.chomp
if version =~ /^5\.[012]|2003/
homedir = "C:/Documents and Settings/#{username}"
deleteable_profile = false
else
homedir = "C:/Users/#{username}"
end
on(host, "test -d '#{homedir}'")
on(host, puppet_apply, :stdin => manifest_absent)
if deleteable_profile
on(host, "test ! -d '#{homedir}'")
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/ticket_6541_invalid_filebucket_files.rb | acceptance/tests/ticket_6541_invalid_filebucket_files.rb | test_name "#6541: file type truncates target when filebucket cannot retrieve hash"
tag 'audit:high',
'audit:integration', # file type and file bucket interop
'audit:refactor' # look into combining with ticket_4622_filebucket_diff_test.rb
# Use block style `test_run`
agents.each do |agent|
target=agent.tmpfile('6541-target')
on(agent, "rm -rf \"#{agent.puppet['vardir']}/*bucket\"")
step "write zero length file"
manifest = "file { '#{target}': content => '' }"
apply_manifest_on(agent, manifest)
step "overwrite file, causing zero-length file to be backed up"
manifest = "file { '#{target}': content => 'some text', backup => 'puppet' }"
apply_manifest_on(agent, manifest)
test_name "verify invalid hashes should not change the file"
manifest = "file { '#{target}': content => '{sha256}notahash' }"
apply_manifest_on(agent, manifest) do |result|
refute_match(/content changed/, result.stdout, "#{agent}: shouldn't have overwrote the file")
end
test_name "verify valid but unbucketed hashes should not change the file"
manifest = "file { '#{target}': content => '{md5}13ad7345d56b566a4408ffdcd877bc78' }"
apply_manifest_on(agent, manifest) do |result|
refute_match(/content changed/, result.stdout, "#{agent}: shouldn't have overwrote the file")
end
test_name "verify that an empty file can be retrieved from the filebucket"
manifest = "file { '#{target}': content => '{sha256}e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855', backup => 'puppet' }"
apply_manifest_on(agent, manifest) do |result|
assert_match(/content changed '\{sha256\}b94f6f125c79e3a5ffaa826f584c10d52ada669e6762051b826b55776d05aed2' to '\{sha256\}e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'/, result.stdout, "#{agent}: shouldn't have overwrote the file")
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/ticket_6907_use_provider_in_same_run_it_becomes_suitable.rb | acceptance/tests/ticket_6907_use_provider_in_same_run_it_becomes_suitable.rb | test_name "providers should be useable in the same run they become suitable"
tag 'audit:high', # autoloader, core puppet agent run functionality
'audit:refactor', # Use block style `test_name`
'audit:integration' # does not require packages, probably implicitly assumed in many other places
agents.each do |agent|
dir = agent.tmpdir('provider-6907')
on agent, "mkdir -p #{dir}/lib/puppet/{type,provider/test6907}"
on agent, "cat > #{dir}/lib/puppet/type/test6907.rb", :stdin => <<TYPE
Puppet::Type.newtype(:test6907) do
newparam(:name, :namevar => true)
newproperty(:file)
end
TYPE
on agent, "cat > #{dir}/lib/puppet/provider/test6907/only.rb", :stdin => <<PROVIDER
Puppet::Type.type(:test6907).provide(:only) do
# The name of the file is chosen to be *.exe so it works on windows and *nix
# because windows inspects the PATHEXT environment variable in 1.9.3 and later.
commands :anything => "#{dir}/must_exist.exe"
require 'fileutils'
def file
'not correct'
end
def file=(value)
FileUtils.touch(value)
end
end
PROVIDER
on agent, puppet_apply("--libdir #{dir}/lib --trace"), :stdin => <<MANIFEST
test6907 { "test-6907":
file => "#{dir}/test_file",
}
# The name of the file is chosen to be *.exe so it works on windows and *nix
# because windows inspects the PATHEXT environment variable in 1.9.3 and later.
file { "#{dir}/must_exist.exe":
ensure => file,
mode => "0755",
}
MANIFEST
on agent, "ls #{dir}/test_file"
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/tests/ticket_1334_clientbucket_corrupted.rb | acceptance/tests/ticket_1334_clientbucket_corrupted.rb | test_name 'C99977 corrupted clientbucket' do
tag 'audit:high',
'audit:integration'
agents.each do |agent|
tmpfile = agent.tmpfile('c99977file')
unmanaged_content = "unmanaged\n"
unmanaged_sha = Digest::SHA256.hexdigest(unmanaged_content)
managed_content = "managed\n"
manifest = "file { '#{tmpfile}': content => '#{managed_content}', backup => 'puppet' }"
step 'create unmanaged file' do
create_remote_file(agent, tmpfile, unmanaged_content)
end
step 'manage file' do
apply_manifest_on(agent, manifest)
end
step 'corrupt clientbucket of file' do
if agent['platform'] =~ /windows/
vardir = 'C:/ProgramData/PuppetLabs/puppet/cache'
else
vardir = '/opt/puppetlabs/puppet/cache'
end
clientbucket_base = "#{vardir}/clientbucket"
sha_array = unmanaged_sha.scan(/\w/)
clientbucket_path = clientbucket_base
(0..7).each do |i|
clientbucket_path = "#{clientbucket_path}/#{sha_array[i]}"
end
clientbucket_path = "#{clientbucket_path}/#{unmanaged_sha}"
contents_path = "#{clientbucket_path}/contents"
paths_path = "#{clientbucket_path}/paths"
create_remote_file(agent, contents_path, "corrupted\n")
create_remote_file(agent, paths_path, "corrupted\n")
end
step 'reset file to pre-managed state' do
create_remote_file(agent, tmpfile, unmanaged_content)
end
step 'manage file again' do
apply_manifest_on(agent, manifest) do |result|
assert_match(/Warning: Existing backup does not match its expected sum, .*Overwriting corrupted backup/, result.stderr) unless agent['locale'] == 'ja'
on(agent, "cat #{tmpfile}") do |r2|
assert_equal(managed_content, r2.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/acceptance/tests/allow_arbitrary_node_name_for_agent.rb | acceptance/tests/allow_arbitrary_node_name_for_agent.rb | test_name "node_name_value should be used as the node name for puppet agent"
tag 'audit:high',
'audit:integration', # Tests that the server properly overrides certname with node_name fact.
# Testing of passenger master is no longer needed.
'server'
success_message = "node_name_value setting was correctly used as the node name"
testdir = master.tmpdir('nodenamevalue')
step "Prepare for custom tk-auth rules" do
on master, 'cp /etc/puppetlabs/puppetserver/conf.d/auth.conf /etc/puppetlabs/puppetserver/conf.d/auth.bak'
modify_tk_config(master, options['puppetserver-config'], {'jruby-puppet' => {'use-legacy-auth-conf' => false}})
end
teardown do
on master, 'cp /etc/puppetlabs/puppetserver/conf.d/auth.bak /etc/puppetlabs/puppetserver/conf.d/auth.conf'
modify_tk_config(master, options['puppetserver-config'], {'jruby-puppet' => {'use-legacy-auth-conf' => true}})
on master, "service #{master['puppetservice']} reload"
end
step "Setup tk-auth rules" do
tk_auth = <<-TK_AUTH
authorization: {
version: 1
rules: [
{
match-request: {
path: "/puppet/v3/file"
type: path
}
allow: "*"
sort-order: 500
name: "puppetlabs file"
},
{
match-request: {
path: "/puppet/v3/catalog/specified_node_name"
type: path
method: [get, post]
}
allow: "*"
sort-order: 500
name: "puppetlabs catalog"
},
{
match-request: {
path: "/puppet/v3/node/specified_node_name"
type: path
method: get
}
allow: "*"
sort-order: 500
name: "puppetlabs node"
},
{
match-request: {
path: "/puppet/v3/report/specified_node_name"
type: path
method: put
}
allow: "*"
sort-order: 500
name: "puppetlabs report"
},
{
match-request: {
path: "/"
type: path
}
deny: "*"
sort-order: 999
name: "puppetlabs deny all"
}
]
}
TK_AUTH
apply_manifest_on(master, <<-MANIFEST, :catch_failures => true)
file { '/etc/puppetlabs/puppetserver/conf.d/auth.conf':
ensure => file,
mode => '0644',
content => '#{tk_auth}',
}
MANIFEST
end
step "Setup site.pp for node name based classification" do
site_manifest = <<-SITE_MANIFEST
node default {
notify { "false": }
}
node specified_node_name {
notify { "#{success_message}": }
}
SITE_MANIFEST
apply_manifest_on(master, <<-MANIFEST, :catch_failures => true)
$directories = [
'#{testdir}',
'#{testdir}/environments',
'#{testdir}/environments/production',
'#{testdir}/environments/production/manifests',
]
file { $directories:
ensure => directory,
mode => '0755',
}
file { '#{testdir}/environments/production/manifests/manifest.pp':
ensure => file,
mode => '0644',
content => '#{site_manifest}',
}
MANIFEST
end
step "Ensure nodes are classified based on the node name fact" do
master_opts = {
'main' => {
'environmentpath' => "#{testdir}/environments",
},
'master' => {
'node_terminus' => 'plain',
},
}
with_puppet_running_on(master, master_opts, testdir) do
on(agents, puppet('agent', "-t --node_name_value specified_node_name"), :acceptable_exit_codes => [0,2]) do |result|
assert_match(/defined 'message'.*#{success_message}/, result.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/acceptance/tests/ticket_2280_refresh_fail_should_fail_run.rb | acceptance/tests/ticket_2280_refresh_fail_should_fail_run.rb | test_name 'C100297 - A resource triggered by a refresh that fails should be reported as a failure when using --detailed-exitcodes' do
tag 'audit:high',
'audit:integration' # Service type interaction with --detailed-exitcodes
manifest =<<EOS
exec{'true':
command => 'true',
path => ['/bin', '/usr/bin'],
}
exec{'false':
command => 'false',
path => ['/bin', '/usr/bin'],
refreshonly => true,
subscribe => Exec['true'],
}
exec{'require_echo':
command => 'echo "This should not happen due to a failed requirement."',
path => ['/bin', '/usr/bin'],
logoutput => true,
require => Exec['false'],
}
EOS
agents.each do |agent|
step 'Apply manifest with fail on refresh. Ensure that this results in a failed dependency' do
apply_manifest_on(agent, manifest, :expect_failures => true) do |res|
refute_match(/require_echo.*returns: executed successfully/, res.stdout)
assert_match(/require_echo.*Skipping because of failed dependencies/, res.stderr) unless agent['locale'] == 'ja'
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/catalog_with_binary_data.rb | acceptance/tests/catalog_with_binary_data.rb | test_name "C100300: Catalog containing binary data is applied correctly" do
require 'puppet/acceptance/common_utils'
require 'puppet/acceptance/environment_utils'
extend Puppet::Acceptance::EnvironmentUtils
require 'puppet/acceptance/agent_fqdn_utils'
extend Puppet::Acceptance::AgentFqdnUtils
tag 'risk:high',
'server'
test_num = 'c100300'
tmp_environment = mk_tmp_environment_with_teardown(master, File.basename(__FILE__, '.*'))
agent_tmp_dirs = {}
agents.each do |agent|
agent_tmp_dirs[agent_to_fqdn(agent)] = agent.tmpdir(tmp_environment)
end
teardown do
step 'remove all test files on agents' do
agents.each {|agent| on(agent, "rm -r '#{agent_tmp_dirs[agent_to_fqdn(agent)]}'", :accept_all_exit_codes => true)}
end
# 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
# note - master teardown is registered by #mk_tmp_environment_with_teardown
end
step "Create module with binary data file on master" do
on(master, "mkdir -p '#{environmentpath}/#{tmp_environment}/modules/#{test_num}'/{manifests,files}")
master_module_manifest = "#{environmentpath}/#{tmp_environment}/modules/#{test_num}/manifests/init.pp"
master_module_binary_file = "#{environmentpath}/#{tmp_environment}/modules/#{test_num}/files/binary_data"
create_remote_file(master, master_module_binary_file, "\xC0\xFF")
on(master, "chmod 644 '#{master_module_binary_file}'")
manifest = <<-MANIFEST
class #{test_num}(
) {
\$test_path = \$facts['networking']['fqdn'] ? #{agent_tmp_dirs}
file { '#{test_num}':
path => "\$test_path/#{test_num}",
content => binary_file('#{test_num}/binary_data'),
ensure => present,
}
}
MANIFEST
create_remote_file(master, master_module_manifest, manifest)
on(master, "chmod 644 '#{master_module_manifest}'")
end
step "Create site.pp to classify nodes to include module" do
site_pp_file = "#{environmentpath}/#{tmp_environment}/manifests/site.pp"
site_pp = <<-SITE_PP
node default {
include #{test_num}
}
SITE_PP
create_remote_file(master, site_pp_file, site_pp)
on(master, "chmod 644 '#{site_pp_file}'")
end
step "start the master" do
with_puppet_running_on(master, {}) do
step "run puppet and ensure that binary data was correctly applied" do
agents.each do |agent|
on(agent, puppet('agent', '--test', "--environment '#{tmp_environment}'"), :acceptable_exit_codes => 2)
on(agent, "#{Puppet::Acceptance::CommandUtils::ruby_command(agent)} -e 'puts File.binread(\"#{agent_tmp_dirs[agent_to_fqdn(agent)]}/#{test_num}\").bytes.map {|b| b.to_s(16)}'") do |res|
assert_match(/c0\nff/, res.stdout, 'Binary file did not contain originally specified data')
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/ticket_9862_puppet_runs_without_service_user_or_group_present.rb | acceptance/tests/ticket_9862_puppet_runs_without_service_user_or_group_present.rb | test_name "#9862: puppet runs without service user or group present"
tag 'audit:high', # startup/configuration, high impact, low risk
'audit:refactor', # Use block style `test_name`
'audit:integration' # could easily be acceptance, not package dependant,
# but changing a person running the tests users and
# groups can be very onerous
# puppet doesn't try to manage ownership on windows.
confine :except, :platform => 'windows'
require 'puppet/acceptance/temp_file_utils'
extend Puppet::Acceptance::TempFileUtils
initialize_temp_dirs
def assert_ownership(agent, location, expected_user, expected_group)
permissions = stat(agent, location)
assert_equal(expected_user, permissions[0], "Owner #{permissions[0]} does not match expected #{expected_user}")
assert_equal(expected_group, permissions[1], "Group #{permissions[1]} does not match expected #{expected_group}")
end
def missing_directory_for(agent, dir)
agent_dir = get_test_file_path(agent, dir)
on(agent, "rm -rf #{agent_dir}")
agent_dir
end
teardown do
agents.each do |agent|
step "ensure puppet resets it's user/group settings"
on(agent, puppet('apply', '-e', '"notify { puppet_run: }"'))
on(agent, "find \"#{agent.puppet['vardir']}\" -user exist_u", {:acceptable_exit_codes => [0, 1]}) do |result|
assert_equal('', result.stdout)
end
on(agent, puppet('resource', 'user', 'exist_u', 'ensure=absent'))
on(agent, puppet('resource', 'group', 'exist_g', 'ensure=absent'))
end
end
step "when the user and group are missing"
agents.each do |agent|
logdir = missing_directory_for(agent, 'log')
on(agent, puppet('apply',
'-e', '"notify { puppet_run: }"',
'--logdir', logdir,
'--user', 'missinguser',
'--group', 'missinggroup')) do |result|
assert_match(/puppet_run/, result.stdout)
assert_ownership(agent, logdir, root_user(agent), root_group(agent))
end
end
step "when the user and group exist"
agents.each do |agent|
logdir = missing_directory_for(agent, 'log')
on(agent, puppet('resource', 'user', 'exist_u', 'ensure=present'))
on(agent, puppet('resource', 'group', 'exist_g', 'ensure=present'))
on(agent, puppet('apply',
'-e', '"notify { puppet_run: }"',
'--logdir', logdir,
'--user', 'exist_u',
'--group', 'exist_g')) do |result|
assert_match(/puppet_run/, result.stdout)
assert_ownership(agent, logdir, 'exist_u', 'exist_g')
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/ticket_5477_master_not_dectect_sitepp.rb | acceptance/tests/ticket_5477_master_not_dectect_sitepp.rb | # In 2.6, compile does not fail when site.pp does not exist.
#
# However, if a catalog is compiled when site.pp does not exist,
# puppetmaster does not detect when site.pp is created. This requires a restart
#
test_name "Ticket 5477, Puppet Master does not detect newly created site.pp file"
tag 'audit:high',
'audit:integration',
'audit:refactor', # Use block style `test_name`
'server'
testdir = master.tmpdir('missing_site_pp')
manifest_file = "#{testdir}/environments/production/manifests/site.pp"
apply_manifest_on(master, <<-PP, :catch_failures => true)
File {
ensure => directory,
mode => "0750",
owner => #{master.puppet['user']},
group => #{master.puppet['group']},
}
file {
'#{testdir}':;
'#{testdir}/environments':;
'#{testdir}/environments/production':;
'#{testdir}/environments/production/manifests':;
}
PP
master_opts = {
'main' => {
'environmentpath' => "#{testdir}/environments",
'filetimeout' => 1,
'environment_timeout' => 0,
}
}
with_puppet_running_on master, master_opts, testdir do
# Run test on Agents
step "Agent: agent --test"
on(agents, puppet('agent', "-t"), :acceptable_exit_codes => [0,2])
# Create a new site.pp
step "Master: create basic site.pp file"
create_remote_file master, manifest_file, "notify{ticket_5477_notify:}"
on master, "chmod 644 #{manifest_file}"
sleep 3
step "Agent: puppet agent --test"
agents.each do |host|
on(host, puppet('agent', "-t"), :acceptable_exit_codes => [2]) do |result|
assert_match(/ticket_5477_notify/, result.stdout, "#{host}: Site.pp not detected on Puppet Master")
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/ticket_6857_password-disclosure-when-changing-a-users-password.rb | acceptance/tests/ticket_6857_password-disclosure-when-changing-a-users-password.rb | test_name "#6857: redact password hashes when applying in noop mode"
tag 'audit:high',
'audit:refactor', # Use block style `test_name`
'audit:integration'
require 'puppet/acceptance/common_utils'
extend Puppet::Acceptance::CommandUtils
hosts_to_test = agents.reject do |agent|
if agent['platform'].match(/(?:ubuntu|centos|debian|el-|fedora)/)
result = on(agent, "#{ruby_command(agent)} -e \"require 'shadow' or raise\"", :acceptable_exit_codes => [0,1])
result.exit_code != 0
else
# Non-linux platforms do not rely on ruby-libshadow for password management
# and so we don't reject them from testing
false
end
end
skip_test "No suitable hosts found" if hosts_to_test.empty?
username = "pl#{rand(99999).to_i}"
teardown do
step "Teardown: Ensure test user is removed"
hosts_to_test.each do |host|
on agent, puppet('resource', 'user', username, 'ensure=absent')
on agent, puppet('resource', 'group', username, 'ensure=absent')
end
end
adduser_manifest = <<MANIFEST
user { '#{username}':
ensure => 'present',
password => 'Apassw0rd!',
}
MANIFEST
changepass_manifest = <<MANIFEST
user { '#{username}':
ensure => 'present',
password => 'Anewpassw0rd!',
noop => true,
}
MANIFEST
hosts_to_test.each do |host|
apply_manifest_on(host, adduser_manifest )
apply_manifest_on(host, changepass_manifest ) do |result|
assert_match( /current_value \[redacted\], should be \[redacted\]/ , "#{result.host}: #{result.stdout}" ) unless host['locale'] == 'ja'
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/modulepath.rb | acceptance/tests/modulepath.rb | test_name 'Supports vendored modules' do
tag 'risk:high'
# beacon custom type emits a message so we can tell where the
# type was loaded from, e.g. vendored, global, and whether the
# type was loaded locally or pluginsynced from the master.
def beacon_type(message)
return <<END
Puppet::Type.newtype(:beacon) do
newparam(:name, :namevar => true)
newproperty(:message) do
def sync; true; end
def retrieve; :absent; end
def insync?(is); false; end
defaultto { "#{message}" }
end
end
END
end
def global_modules(host)
if host.platform =~ /windows/
'/cygdrive/c/ProgramData/PuppetLabs/code/modules'
else
'/etc/puppetlabs/code/modules'
end
end
def vendor_modules(host)
if host.platform =~ /windows/
# escape spaces
"/cygdrive/c/Program\\ Files/Puppet\\ Labs/Puppet/puppet/vendor_modules"
else
'/opt/puppetlabs/puppet/vendor_modules'
end
end
teardown do
hosts.each do |host|
on(host, "rm -rf #{vendor_modules(host)}/beacon")
on(host, "rm -rf #{global_modules(host)}/beacon")
libdir = host.puppet['vardir']
on(host, "rm -rf #{libdir}")
end
on(master, "rm -rf /etc/puppetlabs/code/environments/production/modules/beacon")
on(master, "rm -f /etc/puppetlabs/code/environments/production/manifests/site.pp")
end
step 'delete libdir' do
hosts.each do |host|
on(host, "rm -rf #{host.puppet['libdir']}")
end
end
step 'create vendored module with a custom type' do
hosts.each do |host|
vendor_dir = vendor_modules(host)
on(host, "mkdir -p #{vendor_dir}/beacon/lib/puppet/type")
# unescape, because net-scp escapes
vendor_dir.gsub!(/\\/, '')
create_remote_file(host, "#{vendor_dir}/beacon/lib/puppet/type/beacon.rb", beacon_type("vendored module from #{host}"))
end
end
step 'vendored modules work locally' do
hosts.each do |host|
on(host, puppet("apply -e \"beacon { 'ping': }\"")) do |result|
assert_match(/defined 'message' as 'vendored module from #{host}'/, result.stdout)
end
end
end
step 'vendored modules can be excluded' do
hosts.each do |host|
on(host, puppet("describe --vendormoduledir '' beacon"), accept_all_exit_codes: true) do |result|
assert_match(/Unknown type beacon/, result.stdout)
end
end
end
step 'global modules override vendored modules' do
agents.each do |agent|
# skip the agent on the master, as we don't want to install the
# global module on the master until later
next if agent == master
global_dir = global_modules(agent)
on(agent, "mkdir -p #{global_dir}/beacon/lib/puppet/type")
# global_dir doesn't have spaces, so don't need to escape
create_remote_file(agent, "#{global_dir}/beacon/lib/puppet/type/beacon.rb", beacon_type("global module from #{agent}"))
on(agent, puppet("apply -e \"beacon { 'ping': }\"")) do |result|
assert_match(/defined 'message' as 'global module from #{agent}'/, result.stdout)
end
end
end
step "prepare server" do
create_remote_file(master, "/etc/puppetlabs/code/environments/production/manifests/site.pp", "beacon { 'ping': }")
on(master, "chown -R puppet:puppet /etc/puppetlabs/code/environments/production/manifests/site.pp")
on(master, "chown -R puppet:puppet #{vendor_modules(master)}")
end
with_puppet_running_on(master, {}) do
step "agent doesn't pluginsync the vendored module, instead using its local vendored module" do
agents.each do |agent|
on(agent, puppet("agent -t"), :acceptable_exit_codes => [0,2]) do |result|
assert_match(/defined 'message' as 'vendored module from #{agent}'/, result.stdout)
end
end
end
step "agent downloads and uses newly installed global module from the server" do
global_dir = global_modules(master)
on(master, "mkdir -p #{global_dir}/beacon/lib/puppet/type")
create_remote_file(master, "#{global_dir}/beacon/lib/puppet/type/beacon.rb", beacon_type("server module from #{master}"))
on(master, "chown -R puppet:puppet #{global_dir}")
agents.each do |agent|
on(agent, puppet("agent -t"), :acceptable_exit_codes => [0,2]) do |result|
assert_match(/defined 'message' as 'server module from #{master}'/, result.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/acceptance/tests/ticket_2455_on_solaris_init_provider_should_start_service_in_own_smf_contract.rb | acceptance/tests/ticket_2455_on_solaris_init_provider_should_start_service_in_own_smf_contract.rb | test_name "(PUP-2455) Service provider should start Solaris init service in its own SMF contract"
tag 'audit:high',
'audit:refactor', # Use block style `test_name`
# Use mk_tmp_environment_with_teardown
# Combine with Service resource tests
'audit:acceptance' # Service provider functionality
skip_test unless agents.any? {|agent| agent['platform'] =~ /solaris/ }
teardown do
agents.each do |agent|
on(agent, puppet('config print lastrunfile')) do |command_result|
agent.rm_rf(command_result.stdout)
end
end
end
sleepy_daemon_initscript = <<INITSCRIPT
#!/usr/bin/bash
FIXTURESERVICE="/tmp/sleepy_daemon"
start(){
$FIXTURESERVICE &
}
stop(){
FIXTUREPID=`ps -ef | grep "$FIXTURESERVICE" | grep -v grep | awk '{print $2}'`
if [ "x$FIXTUREPID" != "x" ]; then
kill -9 ${FIXTUREPID}
fi
}
status(){
FIXTUREPID=`ps -ef | grep "$FIXTURESERVICE" | grep -v grep | awk '{print $2}'`
if [ "x$FIXTUREPID" = "x" ]; then
exit 1
else
exit 0
fi
}
case "$1" in
start)
start
;;
stop)
stop
;;
status)
status
;;
esac
INITSCRIPT
step "Setup fixture service manifest on master"
testdir = master.tmpdir('solaris_services_in_own_smf_contract')
test_manifest = <<MANIFEST
File {
ensure => directory,
mode => "0750",
owner => #{master.puppet['user']},
group => #{master.puppet['group']},
}
file { '#{testdir}': }
file { '#{testdir}/environments': }
file { '#{testdir}/environments/production': }
file { '#{testdir}/environments/production/manifests': }
file { '#{testdir}/environments/production/manifests/site.pp':
ensure => file,
content => '
node default {
service { "sleepy_daemon":
provider => "init",
enable => "true",
ensure => "running",
status => "/etc/init.d/sleepy_daemon status",
}
}
',
}
MANIFEST
apply_manifest_on master, test_manifest
step "Start master"
master_opts = {
'main' => {
'environmentpath' => "#{testdir}/environments",
}
}
with_puppet_running_on master, master_opts, testdir do
agents.each do |agent|
fixture_service = 'sleepy_daemon'
fixture_service_stop = '/etc/init.d/sleepy_daemon stop'
next unless agent['platform'] =~ /solaris/
step "Setup fixture service on #{agent}"
sleepy_daemon_script = <<SCRIPT
#!#{agent['privatebindir']}/ruby
while true
sleep (2)
end
SCRIPT
sleepy_daemon_path = "/tmp/sleepy_daemon"
sleepy_daemon_initscript_path = "/etc/init.d/sleepy_daemon"
create_remote_file(agent, sleepy_daemon_path, sleepy_daemon_script)
create_remote_file(agent, sleepy_daemon_initscript_path, sleepy_daemon_initscript)
on(agent, "chmod +x #{sleepy_daemon_path} #{sleepy_daemon_initscript_path}")
step "Start the fixture service on #{agent} "
on(agent, puppet("resource service #{fixture_service} provider=init ensure=stopped"))
on(agent, puppet("resource service #{fixture_service} provider=init ensure=running")) do |result|
assert_match(/ensure changed 'stopped' to 'running'/, result.stdout, "The fixture service #{fixture_service} is not in a testable state on #{agent}.")
end
step "Verify whether the fixture process is alone in its SMF contract on #{agent}"
service_ctid = on(agent, "sleep 10;ps -eo ctid,args | grep #{fixture_service} | grep -v grep | awk '{print $1}'").stdout.chomp.to_i
number_in_contract = on(agent, "pgrep -c #{service_ctid} | wc -l").stdout.chomp.to_i
assert(number_in_contract == 1, "The fixture process #{fixture_service} is not alone in its SMF contract on #{agent}.")
if agent.is_pe?
step "Stop puppet on #{agent}"
on(agent, "svcadm disable pe-puppet;sleep 70;svcadm disable pe-puppet")
step "Stop fixture service on #{agent}"
on(agent, "#{fixture_service_stop}")
step "Enable puppet service on #{agent}"
on(agent, "svcadm enable pe-puppet;sleep 10") do
puppet_ctid = on(agent, "svcs -Ho CTID pe-puppet | awk '{print $1}'").stdout.chomp.to_i
service_ctid = on(agent, "ps -eo ctid,args | grep #{fixture_service} | grep -v grep | awk '{print $1}'").stdout.chomp.to_i
step "Compare SMF contract ids for puppet and #{fixture_service} on #{agent}"
unless ( puppet_ctid != "0" and service_ctid != "0" ) then
fail_test("SMF contract ids should not equal zero.")
end
assert(service_ctid != puppet_ctid, "Service is in the same SMF contract as puppet on #{agent}.")
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/ticket_13948_lib_dir_hook_should_be_called_on_initialization.rb | acceptance/tests/ticket_13948_lib_dir_hook_should_be_called_on_initialization.rb | test_name "the $libdir setting hook is called on startup"
require 'puppet/acceptance/temp_file_utils'
extend Puppet::Acceptance::TempFileUtils
tag 'audit:high', # tests basic custom module/pluginsync handling?
'audit:refactor', # Use block style `test_namme`
'audit:integration',
'server'
initialize_temp_dirs()
all_tests_passed = false
###############################################################################
# BEGIN TEST LOGIC
###############################################################################
# create some vars to point to the directories that we're going to point the master/agents at
master_module_dir = "master_modules"
agent_var_dir = "agent_var"
agent_lib_dir = "#{agent_var_dir}/lib"
app_name = "superbogus"
app_desc = "a simple %1$s for testing %1$s delivery via plugin sync"
app_output = "Hello from the #{app_name} %s"
master_module_face_content = <<-HERE
Puppet::Face.define(:#{app_name}, '0.0.1') do
copyright "Puppet Labs", 2011
license "Apache 2 license; see COPYING"
summary "#{app_desc % "face"}"
action(:foo) do
summary "a test action defined in the test face in the main puppet lib dir"
default
when_invoked do |*args|
puts "#{app_output % "face"}"
end
end
end
HERE
master_module_app_content = <<-HERE
require 'puppet/application/face_base'
class Puppet::Application::#{app_name.capitalize} < Puppet::Application::FaceBase
end
HERE
# this begin block is here for handling temp file cleanup via an "ensure" block
# at the very end of the test.
begin
# here we create a custom app, which basically doesn't do anything except for
# print a hello-world message
agent_module_face_file = "#{agent_lib_dir}/puppet/face/#{app_name}.rb"
master_module_face_file = "#{master_module_dir}/#{app_name}/lib/puppet/face/#{app_name}.rb"
agent_module_app_file = "#{agent_lib_dir}/puppet/application/#{app_name}.rb"
master_module_app_file = "#{master_module_dir}/#{app_name}/lib/puppet/application/#{app_name}.rb"
# copy all the files to the master
step "write our simple module out to the master" do
create_test_file(master, master_module_app_file, master_module_app_content, :mkdirs => true)
create_test_file(master, master_module_face_file, master_module_face_content, :mkdirs => true)
end
step "verify that the app file exists on the master" do
unless test_file_exists?(master, master_module_app_file) then
fail_test("Failed to create app file '#{get_test_file_path(master, master_module_app_file)}' on master")
end
unless test_file_exists?(master, master_module_face_file) then
fail_test("Failed to create face file '#{get_test_file_path(master, master_module_face_file)}' on master")
end
end
step "start the master" do
basemodulepath = "#{get_test_file_path(master, master_module_dir)}"
if master.is_pe?
basemodulepath << ":#{master['sitemoduledir']}"
end
master_opts = {
'main' => {
'basemodulepath' => basemodulepath,
},
'master' => {
'node_terminus' => 'plain',
},
}
with_puppet_running_on master, master_opts do
# the module files shouldn't exist on the agent yet because they haven't been synced
step "verify that the module files don't exist on the agent path" do
agents.each do |agent|
if test_file_exists?(agent, agent_module_app_file) then
fail_test("app file already exists on agent: '#{get_test_file_path(agent, agent_module_app_file)}'")
end
if test_file_exists?(agent, agent_module_face_file) then
fail_test("face file already exists on agent: '#{get_test_file_path(agent, agent_module_face_file)}'")
end
end
end
step "run the agent" do
agents.each do |agent|
step "capture the existing ssldir, in case the default package puppet.conf sets it within vardir (rhel...)"
agent_ssldir = on(agent, puppet('agent --configprint ssldir')).stdout.chomp
on(agent, puppet('agent',
"--vardir=\"#{get_test_file_path(agent, agent_var_dir)}\" ",
"--ssldir=\"#{agent_ssldir}\" ",
"--trace --test")
)
end
end
end
end
step "verify that the module files were synced down to the agent" do
agents.each do |agent|
unless test_file_exists?(agent, agent_module_app_file) then
fail_test("Expected app file not synced to agent: '#{get_test_file_path(agent, agent_module_app_file)}'")
end
unless test_file_exists?(agent, agent_module_face_file) then
fail_test("Expected face file not synced to agent: '#{get_test_file_path(agent, agent_module_face_file)}'")
end
end
end
step "verify that the application shows up in help" do
agents.each do |agent|
on(agent, PuppetCommand.new(:help, "--vardir=\"#{get_test_file_path(agent, agent_var_dir)}\"")) do |result|
assert_match(/^\s+#{app_name}\s+#{app_desc % "face"}/, result.stdout)
end
end
end
step "verify that we can run the application" do
agents.each do |agent|
on(agent, PuppetCommand.new(:"#{app_name}", "--vardir=\"#{get_test_file_path(agent, agent_var_dir)}\"")) do |result|
assert_match(/^#{app_output % "face"}/, result.stdout)
end
end
end
step "clear out the libdir on the agents in preparation for the next test" do
agents.each do |agent|
on(agent, "rm -rf '#{get_test_file_path(agent, agent_lib_dir)}/*'")
end
end
all_tests_passed = true
ensure
##########################################################################################
# Clean up all of the temp files created by this test. It would be nice if this logic
# could be handled outside of the test itself; I envision a stanza like this one appearing
# in a very large number of the tests going forward unless it is handled by the framework.
##########################################################################################
if all_tests_passed then
remove_temp_dirs()
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/ticket_5592_hiera_lookup_when_param_undef.rb | acceptance/tests/ticket_5592_hiera_lookup_when_param_undef.rb | test_name 'Ensure hiera lookup occurs if class param is undef' do
tag 'audit:high',
'audit:unit' # basic auto lookup functionality
agents.each do |agent|
testdir = agent.tmpdir('undef')
step 'Setup - create hiera data file and test module' do
##{{{
manifest =<<-PP
File {
ensure => directory,
mode => "0750",
}
file {
'#{testdir}':;
'#{testdir}/hieradata':;
'#{testdir}/environments':;
'#{testdir}/environments/production':;
'#{testdir}/environments/production/modules':;
}
file { '#{testdir}/hiera.yaml':
ensure => file,
content => '---
:backends:
- "yaml"
:hierarchy:
- "global"
:yaml:
:datadir: "#{testdir}/hieradata"
',
mode => "0640",
}
file { '#{testdir}/hieradata/global.yaml':
ensure => file,
content => "test::my_param: 'hiera lookup value'",
mode => "0640",
}
file {
'#{testdir}/environments/production/modules/test':;
'#{testdir}/environments/production/modules/test/manifests':;
}
file { '#{testdir}/environments/production/modules/test/manifests/init.pp':
ensure => file,
content => '
class test (
$my_param = "class default value",
) {
notice($my_param)
}',
mode => "0640",
}
PP
#}}}
apply_manifest_on(agent, manifest, :catch_failures => true)
end
step 'Invoke class with undef param and verify hiera value was applied' do
on(agent, puppet('apply', "-e 'class {\"test\": my_param => undef }'", "--modulepath=#{testdir}/environments/production/modules", "--hiera_config=#{testdir}/hiera.yaml" ), :acceptable_exit_codes => [0,2]) do |result|
assert_match('hiera lookup value', 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/pluginsync/4420_pluginfacts_should_be_resolvable_on_agent.rb | acceptance/tests/pluginsync/4420_pluginfacts_should_be_resolvable_on_agent.rb | test_name "Pluginsync'ed external facts should be resolvable on the agent" do
tag 'audit:high',
'audit:integration'
#
# This test is intended to ensure that external facts downloaded onto an agent via
# pluginsync are resolvable. In Linux, the external fact should have the same
# permissions as its source on the master.
#
step "Create a codedir with a manifest and test module with external fact"
codedir = master.tmpdir('4420-codedir')
site_manifest_content = <<EOM
node default {
include mymodule
notify { "foo is ${foo}": }
}
EOM
unix_fact = <<EOM
#!/bin/sh
echo "foo=bar"
EOM
win_fact = <<EOM
@echo off
echo foo=bar
EOM
apply_manifest_on(master, <<MANIFEST, :catch_failures => true)
File {
ensure => directory,
mode => "0755",
owner => #{master.puppet['user']},
group => #{master.puppet['group']},
}
file {
'#{codedir}':;
'#{codedir}/environments':;
'#{codedir}/environments/production':;
'#{codedir}/environments/production/manifests':;
'#{codedir}/environments/production/modules':;
'#{codedir}/environments/production/modules/mymodule':;
'#{codedir}/environments/production/modules/mymodule/manifests':;
'#{codedir}/environments/production/modules/mymodule/facts.d':;
}
file { '#{codedir}/environments/production/manifests/site.pp':
ensure => file,
content => '#{site_manifest_content}',
}
file { '#{codedir}/environments/production/modules/mymodule/manifests/init.pp':
ensure => file,
content => 'class mymodule {}',
}
file { '#{codedir}/environments/production/modules/mymodule/facts.d/unix_external_fact.sh':
ensure => file,
mode => '755',
content => '#{unix_fact}',
}
file { '#{codedir}/environments/production/modules/mymodule/facts.d/win_external_fact.bat':
ensure => file,
mode => '644',
content => '#{win_fact}',
}
MANIFEST
master_opts = {
'main' => {
'environmentpath' => "#{codedir}/environments"
}
}
with_puppet_running_on(master, master_opts, codedir) do
agents.each do |agent|
factsd = agent.tmpdir('facts.d')
pluginfactdest = agent.tmpdir('facts.d')
teardown do
on(master, "rm -rf '#{codedir}'")
on(agent, "rm -rf '#{factsd}' '#{pluginfactdest}'")
end
step "Pluginsync the external fact to the agent and ensure it resolves correctly" do
on(agent, puppet('agent', '-t', '--pluginfactdest', factsd), :acceptable_exit_codes => [2]) do |result|
assert_match(/foo is bar/, result.stdout)
end
end
step "Use plugin face to download to the agent" do
on(agent, puppet('plugin', 'download', '--pluginfactdest', pluginfactdest)) do |result|
assert_match(/Downloaded these plugins: .*external_fact/, result.stdout) unless agent['locale'] == 'ja'
end
end
step "Ensure it resolves correctly" do
on(agent, puppet('apply', '--pluginfactdest', pluginfactdest, '-e', "'notify { \"foo is ${foo}\": }'")) do |result|
assert_match(/foo is bar/, result.stdout)
end
end
# Linux specific tests
next if agent['platform'] =~ /windows/
step "In Linux, ensure the pluginsync'ed external fact has the same permissions as its source" do
on(agent, puppet('resource', "file '#{factsd}/unix_external_fact.sh'")) do |result|
assert_match(/0755/, result.stdout)
end
end
step "In Linux, ensure puppet apply uses the correct permissions" do
test_source = File.join('/', 'tmp', 'test')
on(agent, puppet('apply', "-e \"file { '#{test_source}': ensure => file, mode => '0456' }\""))
{ 'source_permissions => use,' => /0456/,
'source_permissions => ignore,' => /0644/,
'' => /0644/
}.each do |source_permissions, mode|
on(agent, puppet('apply', "-e \"file { '/tmp/test_target': ensure => file, #{source_permissions} source => '#{test_source}' }\""))
on(agent, puppet('resource', "file /tmp/test_target")) do |result|
assert_match(mode, result.stdout)
end
on(agent, "rm -f /tmp/test_target")
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/pluginsync/3935_pluginsync_should_follow_symlinks.rb | acceptance/tests/pluginsync/3935_pluginsync_should_follow_symlinks.rb | test_name "pluginsync should not error when modulepath is a symlink and no modules have plugin directories"
tag 'audit:high',
'audit:integration',
'server'
step "Create a modulepath directory which is a symlink and includes a module without facts.d or lib directories"
basedir = master.tmpdir("symlink_modulepath")
target = "#{basedir}/target_dir"
test_module_dir = "#{target}/module1"
link_dest = "#{basedir}/link_dest"
modulepath = "#{link_dest}"
modulepath << "#{master['sitemoduledir']}" if master.is_pe?
apply_manifest_on(master, <<MANIFEST, :catch_failures => true)
File {
ensure => directory,
mode => "0750",
owner => #{master.puppet['user']},
group => #{master.puppet['group']},
}
file {
'#{basedir}':;
'#{target}':;
'#{test_module_dir}':;
}
file { '#{link_dest}':
ensure => link,
target => '#{target}',
}
MANIFEST
master_opts = {
'main' => {
'basemodulepath' => "#{modulepath}"
}
}
with_puppet_running_on master, master_opts, basedir do
agents.each do |agent|
on(agent, puppet('agent', "-t")) do |result|
refute_match(/Could not retrieve information from environment production source\(s\) puppet:\/\/\/pluginfacts/, result.stderr)
refute_match(/Could not retrieve information from environment production source\(s\) puppet:\/\/\/plugins/, result.stderr)
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/pluginsync/4847_pluginfacts_should_be_resolvable_from_applications.rb | acceptance/tests/pluginsync/4847_pluginfacts_should_be_resolvable_from_applications.rb | test_name "Pluginsync'ed custom facts should be resolvable during application runs" do
tag 'audit:high',
'audit:integration'
#
# This test is intended to ensure that custom facts downloaded onto an agent via
# pluginsync are resolvable by puppet applications besides agent/apply.
#
require 'puppet/acceptance/environment_utils'
extend Puppet::Acceptance::EnvironmentUtils
tmp_environment = mk_tmp_environment_with_teardown(master, 'resolve')
master_module_dir = "#{environmentpath}/#{tmp_environment}/modules/module_name"
master_type_dir = "#{master_module_dir}/lib/puppet/type"
master_module_type_file = "#{master_type_dir}/test4847.rb"
master_provider_dir = "#{master_module_dir}/lib/puppet/provider/test4847"
master_provider_file = "#{master_provider_dir}/only.rb"
master_facter_dir = "#{master_module_dir}/lib/facter"
master_facter_file = "#{master_facter_dir}/foo.rb"
on(master, "mkdir -p '#{master_type_dir}' '#{master_provider_dir}' '#{master_facter_dir}'")
teardown do
on(master, "rm -rf '#{master_module_dir}'")
# 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
end
test_type = <<-TYPE
Puppet::Type.newtype(:test4847) do
newparam(:name, :namevar => true)
end
TYPE
create_remote_file(master, master_module_type_file, test_type)
test_provider = <<-PROVIDER
Puppet::Type.type(:test4847).provide(:only) do
def self.instances
warn "fact foo=\#{Facter.value('foo')}"
[]
end
end
PROVIDER
create_remote_file(master, master_provider_file, test_provider)
foo_fact_content = <<-FACT_FOO
Facter.add('foo') do
setcode do
'bar'
end
end
FACT_FOO
create_remote_file(master, master_facter_file, foo_fact_content)
on(master, "chmod 755 '#{master_module_type_file}' '#{master_provider_file}' '#{master_facter_file}'")
with_puppet_running_on(master, {}) do
agents.each do |agent|
on(agent, puppet("agent -t --environment #{tmp_environment}"))
on(agent, puppet('resource test4847')) do |result|
assert_match(/fact foo=bar/, result.stderr)
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/pluginsync/files_earlier_in_modulepath_take_precendence.rb | acceptance/tests/pluginsync/files_earlier_in_modulepath_take_precendence.rb | test_name "earlier modules take precendence over later modules in the modulepath"
tag 'audit:high',
'audit:integration',
'server'
step "Create some modules in the modulepath"
basedir = master.tmpdir("module_precedence")
module_dir1 = "#{basedir}/environments/production/modules1"
module_dir2 = "#{basedir}/modules2"
modulepath = "#{module_dir1}:#{module_dir2}"
modulepath << ":#{master['sitemoduledir']}" if master.is_pe?
apply_manifest_on(master, <<MANIFEST, :catch_failures => true)
File {
ensure => directory,
mode => "0750",
owner => #{master.puppet['user']},
group => #{master.puppet['group']},
}
file {
'#{basedir}':;
'#{module_dir2}':;
'#{module_dir2}/a':;
'#{module_dir2}/a/lib':;
'#{basedir}/environments':;
'#{basedir}/environments/production':;
'#{module_dir1}':;
'#{module_dir1}/a':;
'#{module_dir1}/a/lib':;
}
file { '#{basedir}/environments/production/environment.conf':
ensure => file,
content => "modulepath='#{modulepath}'",
mode => "0640",
}
file { "mod1":
ensure => file,
path => "#{module_dir1}/a/lib/foo.rb",
content => "'from the first module'",
mode => "0640",
}
file { "mod2":
ensure => file,
path => "#{module_dir2}/a/lib/foo.rb",
content => "'from the second module'",
mode => "0640",
}
MANIFEST
master_opts = {
'main' => {
'environmentpath' => "#{basedir}/environments",
}
}
with_puppet_running_on master, master_opts, basedir do
agents.each do |agent|
on(agent, puppet('agent', "-t"))
on(agent, "cat \"#{agent.puppet['vardir']}/lib/foo.rb\"") do |result|
assert_match(/from the first module/, result.stdout, "The synced plugin was not found or the wrong version was synced")
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/pluginsync/7316_apps_should_be_available_via_pluginsync.rb | acceptance/tests/pluginsync/7316_apps_should_be_available_via_pluginsync.rb | test_name 'the pluginsync functionality should sync app definitions, and they should be runnable afterwards' do
tag 'audit:high',
'audit:integration'
#
# This test is intended to ensure that pluginsync syncs app definitions to the agents.
# Further, the apps should be runnable on the agent after the sync has occurred.
#
require 'puppet/acceptance/environment_utils'
extend Puppet::Acceptance::EnvironmentUtils
require 'puppet/acceptance/temp_file_utils'
extend Puppet::Acceptance::TempFileUtils
tmp_environment = mk_tmp_environment_with_teardown(master, 'app')
master_module_dir = "#{environmentpath}/#{tmp_environment}/modules"
on(master, "mkdir -p '#{master_module_dir}'")
teardown do
on(master, "rm -rf '#{master_module_dir}'")
# 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
end
app_name = "superbogus"
app_desc = "a simple application for testing application delivery via plugin sync"
app_output = "Hello from the #{app_name} application"
master_module_file_content = <<-HERE
require 'puppet/application'
class Puppet::Application::#{app_name.capitalize} < Puppet::Application
def help
<<-HELP
puppet-#{app_name}(8) -- #{app_desc}
========
HELP
end
def main()
puts("#{app_output}")
end
end
HERE
# here we create a custom app, which basically doesn't do anything except
# for print a hello-world message
#
master_module_app_path = "#{master_module_dir}/#{app_name}/lib/puppet/application"
master_module_app_file = "#{master_module_app_path}/#{app_name}.rb"
on(master, "mkdir -p '#{master_module_app_path}'")
create_remote_file(master, master_module_app_file, master_module_file_content)
on(master, "chmod 755 '#{master_module_app_file}'")
step "start the master" do
with_puppet_running_on(master, {}) do
agents.each do |agent|
agent_lib_dir = agent.tmpdir('agent_lib_sync')
agent_module_app_file = "#{agent_lib_dir}/puppet/application/#{app_name}.rb"
teardown do
on(agent, "rm -rf '#{agent_lib_dir}'")
end
# the module files shouldn't exist on the agent yet because they haven't been synced
step "verify that the module files don't exist on the agent path" do
if file_exists?(agent, agent_module_app_file)
fail_test("app file already exists on agent: '#{agent_module_app_file}'")
end
end
step "run the agent" do
on(agent, puppet("agent --libdir='#{agent_lib_dir}' --test --environment '#{tmp_environment}'")) do |result|
refute_match(
/The \`source_permissions\` parameter is deprecated/,
result.stderr,
"pluginsync should not get a deprecation warning for source_permissions")
end
end
step "verify that the module files were synced down to the agent" do
unless file_exists?(agent, agent_module_app_file)
fail_test("The app file we expect was not not synced to agent: '#{agent_module_app_file}'")
end
end
step "verify that the application shows up in help" do
on(agent, PuppetCommand.new(:help, "--libdir='#{agent_lib_dir}'")) do |result|
assert_match(/^\s+#{app_name}\s+#{app_desc}/, result.stdout)
end
end
step "verify that we can run the application" do
on(agent, PuppetCommand.new(:"#{app_name}", "--libdir='#{agent_lib_dir}'")) do |result|
assert_match(/^#{app_output}/, result.stdout)
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/pluginsync/7316_faces_with_app_stubs_should_be_available_via_pluginsync.rb | acceptance/tests/pluginsync/7316_faces_with_app_stubs_should_be_available_via_pluginsync.rb | test_name "the pluginsync functionality should sync app definitions, and they should be runnable afterwards"
tag 'audit:high',
'audit:integration',
'server'
#
# This test is intended to ensure that pluginsync syncs face definitions to the agents.
# Further, the face should be runnable on the agent after the sync has occurred.
#
# (NOTE: When this test is passing, it should resolve both #7316 re: verifying that apps/faces can
# be run on the agent node after a plugin sync, and #6753 re: being able to run a face without
# having a placeholder stub file in the "applications" directory.)
#
require 'puppet/acceptance/temp_file_utils'
extend Puppet::Acceptance::TempFileUtils
initialize_temp_dirs()
all_tests_passed = false
###############################################################################
# BEGIN TEST LOGIC
###############################################################################
# create some vars to point to the directories that we're going to point the master/agents at
environments_dir = "environments"
master_module_dir = "#{environments_dir}/production/modules"
agent_lib_dir = "agent_lib"
app_name = "superbogus"
app_desc = "a simple %1$s for testing %1$s delivery via plugin sync"
app_output = "Hello from the #{app_name} %s"
master_module_face_content = <<-HERE
Puppet::Face.define(:#{app_name}, '0.0.1') do
copyright "Puppet Labs", 2011
license "Apache 2 license; see COPYING"
summary "#{app_desc % "face"}"
action(:foo) do
summary "a test action defined in the test face in the main puppet lib dir"
default
when_invoked do |*args|
puts "#{app_output % "face"}"
end
end
end
HERE
master_module_app_content = <<-HERE
require 'puppet/application/face_base'
class Puppet::Application::#{app_name.capitalize} < Puppet::Application::FaceBase
end
HERE
# this begin block is here for handling temp file cleanup via an "ensure" block
# at the very end of the test.
begin
# here we create a custom app, which basically doesn't do anything except for
# print a hello-world message
agent_module_face_file = "#{agent_lib_dir}/puppet/face/#{app_name}.rb"
master_module_face_file = "#{master_module_dir}/#{app_name}/lib/puppet/face/#{app_name}.rb"
agent_module_app_file = "#{agent_lib_dir}/puppet/application/#{app_name}.rb"
master_module_app_file = "#{master_module_dir}/#{app_name}/lib/puppet/application/#{app_name}.rb"
# copy all the files to the master
step "write our simple module out to the master" do
create_test_file(master, master_module_app_file, master_module_app_content, :mkdirs => true)
create_test_file(master, master_module_face_file, master_module_face_content, :mkdirs => true)
end
step "verify that the app file exists on the master" do
unless test_file_exists?(master, master_module_app_file) then
fail_test("Failed to create app file '#{get_test_file_path(master, master_module_app_file)}' on master")
end
unless test_file_exists?(master, master_module_face_file) then
fail_test("Failed to create face file '#{get_test_file_path(master, master_module_face_file)}' on master")
end
end
master_opts = {
'main' => {
'environmentpath' => "#{get_test_file_path(master, environments_dir)}",
}
}
step "start the master" do
with_puppet_running_on master, master_opts do
# the module files shouldn't exist on the agent yet because they haven't been synced
step "verify that the module files don't exist on the agent path" do
agents.each do |agent|
if test_file_exists?(agent, agent_module_app_file) then
fail_test("app file already exists on agent: '#{get_test_file_path(agent, agent_module_app_file)}'")
end
if test_file_exists?(agent, agent_module_app_file) then
fail_test("face file already exists on agent: '#{get_test_file_path(agent, agent_module_face_file)}'")
end
end
end
step "run the agent" do
agents.each do |agent|
on(agent, puppet('agent',
"--libdir=\"#{get_test_file_path(agent, agent_lib_dir)}\" ",
"--trace --test")
)
end
end
end
end
step "verify that the module files were synced down to the agent" do
agents.each do |agent|
unless test_file_exists?(agent, agent_module_app_file) then
fail_test("The app file we expected was not synced to the agent: '#{get_test_file_path(agent, agent_module_app_file)}'")
end
unless test_file_exists?(agent, agent_module_face_file) then
fail_test("The face file we expected was not not synced to the agent: '#{get_test_file_path(agent, agent_module_face_file)}'")
end
end
end
step "verify that the application shows up in help" do
agents.each do |agent|
on(agent, PuppetCommand.new(:help, "--libdir=\"#{get_test_file_path(agent, agent_lib_dir)}\"")) do |result|
assert_match(/^\s+#{app_name}\s+#{app_desc % "face"}/, result.stdout)
end
end
end
step "verify that we can run the application" do
agents.each do |agent|
on(agent, PuppetCommand.new(:"#{app_name}", "--libdir=\"#{get_test_file_path(agent, agent_lib_dir)}\"")) do |result|
assert_match(/^#{app_output % "face"}/, result.stdout)
end
end
end
step "clear out the libdir on the agents in preparation for the next test" do
agents.each do |agent|
on(agent, "rm -rf #{get_test_file_path(agent, agent_lib_dir)}/*")
end
end
all_tests_passed = true
ensure
##########################################################################################
# Clean up all of the temp files created by this test. It would be nice if this logic
# could be handled outside of the test itself; I envision a stanza like this one appearing
# in a very large number of the tests going forward unless it is handled by the framework.
##########################################################################################
if all_tests_passed then
remove_temp_dirs()
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/pluginsync/feature/pluginsync_should_sync_features.rb | acceptance/tests/pluginsync/feature/pluginsync_should_sync_features.rb | test_name "the pluginsync functionality should sync feature and function definitions" do
tag 'audit:high',
'audit:integration'
#
# This test is intended to ensure that pluginsync syncs feature definitions to
# the agents. It checks the feature twice; once to make sure that it gets
# loaded successfully during the run in which it was synced, and once to ensure
# that it still gets loaded successfully during the subsequent run (in which it
# should not be synced because the files haven't changed.)
#
require 'puppet/acceptance/environment_utils'
extend Puppet::Acceptance::EnvironmentUtils
require 'puppet/acceptance/temp_file_utils'
extend Puppet::Acceptance::TempFileUtils
teardown do
agents.each do |agent|
on(agent, puppet('config print lastrunfile')) do |command_result|
agent.rm_rf(command_result.stdout)
end
end
end
module_name = 'superbogus'
tmp_environment = mk_tmp_environment_with_teardown(master, 'sync')
master_module_dir = "#{environmentpath}/#{tmp_environment}/modules"
master_module_type_path = "#{master_module_dir}/#{module_name}/lib/puppet/type/"
master_module_feature_path = "#{master_module_dir}/#{module_name}/lib/puppet/feature"
master_module_function_path = "#{master_module_dir}/#{module_name}/lib/puppet/functions"
master_module_function_path_namespaced = "#{master_module_dir}/#{module_name}/lib/puppet/functions/superbogus"
on(master, "mkdir -p '#{master_module_dir}'")
on(master, "mkdir -p '#{master_module_type_path}' '#{master_module_feature_path}' '#{master_module_function_path}' #{master_module_function_path_namespaced}")
master_module_type_file = "#{master_module_type_path}/#{module_name}.rb"
master_module_type_content = <<-HERE
module Puppet
Type.newtype(:#{module_name}) do
newparam(:name) do
isnamevar
end
newproperty(:testfeature) do
def sync
Puppet.info("The value of the #{module_name} feature is: \#{Puppet.features.#{module_name}?}")
end
def retrieve
:absent
end
def insync?(is)
false
end
end
end
end
HERE
create_remote_file(master, master_module_type_file, master_module_type_content)
master_module_feature_file = "#{master_module_feature_path}/#{module_name}.rb"
master_module_feature_content = <<-HERE
Puppet.features.add(:#{module_name}) do
Puppet.info("#{module_name} feature being queried")
true
end
HERE
create_remote_file(master, master_module_feature_file, master_module_feature_content)
on(master, "chmod 755 '#{master_module_type_file}' '#{master_module_feature_file}'")
master_module_function_file = "#{master_module_function_path}/bogus_function.rb"
master_module_function_content = <<-HERE
Puppet::Functions.create_function(:bogus_function) do
dispatch :bogus_function do
end
def bogus_function()
three = call_function('round', 3.14)
hostname = `facter hostname`
"Three is \#{three}. bogus_function reporting hostname is \#{hostname}"
end
end
HERE
create_remote_file(master, master_module_function_file, master_module_function_content)
on(master, "chmod 755 '#{master_module_function_file}' '#{master_module_function_file}'")
master_module_namespaced_function_file = "#{master_module_function_path_namespaced}/bogus_function2.rb"
master_module_namespaced_function_content = <<-HERE
Puppet::Functions.create_function(:'superbogus::bogus_function2') do
dispatch :bogus_function2 do
end
def bogus_function2()
four = call_function('round', 4.14)
hostname = `facter hostname`
"Four is \#{four}. bogus_function reporting hostname is \#{hostname}"
end
end
HERE
create_remote_file(master, master_module_namespaced_function_file, master_module_namespaced_function_content)
on(master, "chmod 755 '#{master_module_namespaced_function_file}'")
site_pp = <<-HERE
#{module_name} { "This is the title of the #{module_name} type instance in site.pp":
testfeature => "Hi. I'm setting the testfeature property of #{module_name} here in site.pp",
}
notify { module_function:
message => Deferred('bogus_function', [])
}
notify { module_function2:
message => Deferred('superbogus::bogus_function2', [])
}
HERE
create_sitepp(master, tmp_environment, site_pp)
# These master opts should not be necessary whence content negotation for
# Puppet 6.0.0 is completed, and this should just be removed.
master_opts = {
'master' => {
'rich_data' => 'true'
}
}
step 'start the master' do
with_puppet_running_on(master, master_opts) do
agents.each do |agent|
agent_lib_dir = agent.tmpdir('libdir')
agent_module_type_file = "#{agent_lib_dir}/puppet/type/#{module_name}.rb"
agent_module_feature_file = "#{agent_lib_dir}/puppet/feature/#{module_name}.rb"
agent_module_function_file = "#{agent_lib_dir}/puppet/functions/bogus_function.rb"
agent_module_namespaced_function_file = "#{agent_lib_dir}/puppet/functions/superbogus/bogus_function2.rb"
facter_hostname = fact_on(agent, 'hostname')
step "verify that the module files don't exist on the agent path" do
[agent_module_type_file, agent_module_feature_file, agent_module_function_file].each do |file_path|
if file_exists?(agent, file_path)
fail_test("file should not exist on the agent yet: '#{file_path}'")
end
end
end
step 'run the agent and verify that it loaded the feature' do
on(agent, puppet("agent -t --libdir='#{agent_lib_dir}' --rich_data --environment '#{tmp_environment}'"),
:acceptable_exit_codes => [2]) do |result|
assert_match(/The value of the #{module_name} feature is: true/, result.stdout,
"Expected agent stdout to include confirmation that the feature was 'true'")
assert_match(/Three is 3. bogus_function reporting hostname is #{facter_hostname}/, result.stdout,
"Expect the agent stdout to run bogus_function and report hostname")
assert_match(/Four is 4. bogus_function reporting hostname is #{facter_hostname}/, result.stdout,
"Expect the agent stdout to run bogus_function and report hostname")
end
end
step 'verify that the module files were synced down to the agent' do
[agent_module_type_file, agent_module_feature_file, agent_module_function_file, agent_module_namespaced_function_file].each do |file_path|
unless file_exists?(agent, file_path)
fail_test("Expected file to exist on the agent now: '#{file_path}'")
end
end
end
step 'run the agent again with a cached catalog' do
on(agent, puppet("agent -t --libdir='#{agent_lib_dir}' --use_cached_catalog --rich_data --environment '#{tmp_environment}'"), :acceptable_exit_codes => [2]) do |result|
assert_match(/The value of the #{module_name} feature is: true/, result.stdout,
"Expected agent stdout to include confirmation that the feature was 'true'")
assert_match(/Three is 3. bogus_function reporting hostname is #{facter_hostname}/, result.stdout,
"Expect the agent stdout to run bogus_function and report hostname")
assert_match(/Four is 4. bogus_function reporting hostname is #{facter_hostname}/, result.stdout,
"Expect the agent stdout to run bogus_function and report hostname")
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/resource/service/puppet_service_management.rb | acceptance/tests/resource/service/puppet_service_management.rb | test_name "The Puppet service should be manageable with Puppet"
tag 'audit:high',
'audit:refactor', # Use block style `test_name`
'audit:acceptance' # uses services from a running puppet-agent install
#
# This test is intended to ensure that the Puppet service can
# be directly managed by Puppet. See PUP-5053, PUP-5257, and RE-5574 for
# more context around circumstances that this can fail.
#
skip_test 'requires puppet service scripts from AIO agent package' if @options[:type] != 'aio'
require 'puppet/acceptance/service_utils'
extend Puppet::Acceptance::ServiceUtils
# Set service status before running other 'ensure' operations on it
def set_service_initial_status(host, service, status)
step "Establishing precondition: #{service}: ensure => #{status}"
ensure_service_on_host(host, service, {'ensure' => status})
end
# We want to test Puppet in the following conditions:
# 1) Starting, stopping and refreshing while the service is initially stopped
# 2) Starting, stopping and refreshing while the service is initially running
agents.each do |agent|
['puppet'].each do |service|
# --- service management using `puppet apply` --- #
step "#{service} service management using `puppet apply`"
set_service_initial_status(agent, service, 'stopped')
step "Starting the #{service} service: it should be running"
ensure_service_on_host(agent, service, {'ensure' => 'running'})
step "Stopping the #{service} service: it should be stopped"
ensure_service_on_host(agent, service, {'ensure' => 'stopped'})
['stopped', 'running'].each do |status|
step "Refreshing the #{service} service while it is #{status}: it should be #{status}"
set_service_initial_status(agent, service, status)
refresh_service_on_host(agent, service)
assert_service_status_on_host(agent, service, {'ensure' => status}) # Status should not change after refresh
# --- service management using `puppet resource` --- #
step "#{service} service management using `puppet resource`"
step "Starting the #{service} service while it is #{status}: it should be running"
set_service_initial_status(agent, service, status)
on(agent, puppet_resource('service', service, 'ensure=running'))
assert_service_status_on_host(agent, service, {'ensure' => 'running'}) # Status should always be 'running' after starting
step "Stopping the #{service} service while it is #{status}: it should be stopped"
set_service_initial_status(agent, service, status)
on(agent, puppet_resource('service', service, 'ensure=stopped'))
assert_service_status_on_host(agent, service, {'ensure' => 'stopped'}) # Status should always be 'stopped' after stopping
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/resource/service/should_not_change_the_system.rb | acceptance/tests/resource/service/should_not_change_the_system.rb | test_name "`puppet resource service` should list running services without calling dangerous init scripts"
tag 'audit:high',
'audit:refactor', # Use block style `test_name`
'audit:integration' # Doesn't change the system it runs on
confine :except, :platform => 'windows'
confine :except, :platform => 'solaris'
# For each script in /etc/init.d, the init service provider will call
# the script with the `status` argument, except for blacklisted
# scripts that are known to be dangerous, e.g. /etc/init.d/reboot.sh
# The first execution of `puppet resource service` will enumerate
# all services, and we want to check that puppet enumerates at
# least one service. We use ssh because our tests run over ssh, so it
# must be present.
agents.each do |agent|
service_name = case agent['platform']
when /osx/
"com.openssh.sshd"
else
"ssh[^']*"
end
step "list running services and make sure ssh reports running"
on(agent, puppet('resource service')) do |result|
assert_match(/service { '#{service_name}':\n\s*ensure\s*=>\s*'(?:true|running)'/, result.stdout, "ssh is not running")
end
step "list running services again and make sure ssh is still running"
on(agent, puppet('resource service')) do |result|
assert_match(/service { '#{service_name}':\n\s*ensure\s*=>\s*'(?:true|running)'/, result.stdout, "ssh is no longer running")
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/resource/service/AIX_service_provider.rb | acceptance/tests/resource/service/AIX_service_provider.rb | test_name 'AIX Service Provider Testing'
tag 'audit:high',
'audit:refactor', # Use block style `test_name`
'audit:acceptance' # Could be done at the integration (or unit) layer though
# actual changing of resources could irreparably damage a
# host running this, or require special permissions.
confine :to, :platform => 'aix'
require 'puppet/acceptance/service_utils'
extend Puppet::Acceptance::ServiceUtils
sloth_daemon_script = <<SCRIPT
#!/usr/bin/env sh
while true; do sleep 1; done
SCRIPT
def lsitab_assert_enable(host, service, expected_status)
case expected_status
when true
expected_output = service
when false
expected_output = ''
else
raise "This test doesn't know what to do with an expected enable status of #{expected_status}"
end
on(host, "lsitab #{service} | cut -f 1 -d :") do |result|
actual_output = result.stdout.chomp
assert_equal(expected_output, actual_output,
"Service doesn't actually have enabled = #{expected_status}")
end
end
def lssrc_assert_status(host, service, expected_status)
case expected_status
when true
expected_output = 'active'
when false
expected_output = 'inoperative'
else
raise "This test doesn't know what to do with an expected status of #{expected_status}"
end
# sometimes there's no group or PID which messes up the condense to a single
# delimiter
on(host, "lssrc -s #{service} | tr -s ' ' ':' | tail -1 | cut -f 3- -d :") do |result|
actual_output = result.stdout.chomp
assert_match(/#{expected_output}\Z/, actual_output,
"Service is not actually #{expected_status}")
end
end
teardown do
agents.each do |agent|
on(agent, "rmssys -s sloth_daemon", :allowable_exit_codes => [0,1])
end
end
agents.each do |agent|
run_nonexistent_service_tests('nonexistent_service')
step "Setup on #{agent}"
sloth_daemon_path = agent.tmpfile("sloth_daemon.sh")
create_remote_file(agent, sloth_daemon_path, sloth_daemon_script)
on(agent, "chmod +x #{sloth_daemon_path}")
on(agent, "mkssys -s sloth_daemon -p #{sloth_daemon_path} -u 0 -S -n 15 -f 9")
# Creating the service may also start it. Stop service before beginning the test.
on(agent, puppet_resource('service', 'sloth_daemon', 'ensure=stopped', 'enable=false'))
## Query
step "Verify the service exists on #{agent}"
on(agent, puppet_resource('service', 'sloth_daemon')) do |result|
assert_match(/sloth_daemon/, result.stdout, "Couldn't find service sloth_daemon")
end
## Start the service
step "Start the service on #{agent}"
ensure_service_on_host(agent, 'sloth_daemon', {:ensure => 'running'}) do
lssrc_assert_status(agent, 'sloth_daemon', true)
end
## Stop the service
step "Stop the service on #{agent}"
ensure_service_on_host(agent, 'sloth_daemon', {:ensure => 'stopped'}) do
lssrc_assert_status(agent, 'sloth_daemon', false)
end
## Enable the service
step "Enable the service on #{agent}"
ensure_service_on_host(agent, 'sloth_daemon', {:enable => 'true'}) do
lsitab_assert_enable(agent, 'sloth_daemon', true)
end
## Disable the service
step "Disable the service on #{agent}"
ensure_service_on_host(agent, 'sloth_daemon', {:enable => 'false'}) do
lsitab_assert_enable(agent, 'sloth_daemon', false)
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/resource/service/puppet_service_runs_puppet.rb | acceptance/tests/resource/service/puppet_service_runs_puppet.rb | require 'puppet/acceptance/service_utils'
extend Puppet::Acceptance::ServiceUtils
test_name 'Starting the puppet service should successfully run puppet' do
tag 'audit:high',
'audit:acceptance'
skip_test 'requires a server node to run puppet agent -t' unless master
agents.each do |agent|
statedir = on(agent, puppet('config', 'print', 'statedir')).stdout.chomp
last_run_report = "#{statedir}/last_run_report.yaml"
teardown do
on(agent, puppet_resource('file', last_run_report, 'ensure=absent'))
end
step 'Ensure last_run_report.yaml is absent' do
on(agent, puppet_resource('file', last_run_report, 'ensure=absent'))
end
step 'Ensure stop puppet service' do
on(agent, puppet_resource('service', 'puppet', 'ensure=stopped'))
assert_service_status_on_host(agent, 'puppet', {'ensure' => 'stopped'})
end
step 'Ensure start puppet service' do
on(agent, puppet_resource('service', 'puppet', 'ensure=running'))
assert_service_status_on_host(agent, 'puppet', {'ensure' => 'running'})
end
retry_params = {:max_retries => 30,
:retry_interval => 2}
step 'Ensure last_run_report.yaml is created' do
retry_on(agent, "test -e #{last_run_report}", retry_params)
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/resource/service/service_enable_linux.rb | acceptance/tests/resource/service/service_enable_linux.rb | test_name 'SysV and Systemd Service Provider Validation'
tag 'audit:high',
'audit:refactor', # Investigate merging with init_on_systemd.rb
# Use block style `test_name`
'audit:acceptance' # Could be done at the integration (or unit) layer though
# actual changing of resources could irreparably damage a
# host running this, or require special permissions.
confine :to, :platform => /el-|centos|fedora|debian|sles|ubuntu-v/
# osx covered by launchd_provider.rb
# ubuntu-[a-u] upstart covered by ticket_14297_handle_upstart.rb
package_name = {'el' => 'httpd',
'centos' => 'httpd',
'fedora' => 'httpd',
'debian' => 'apache2',
'sles' => 'apache2',
'ubuntu' => 'cron', # See https://bugs.launchpad.net/ubuntu/+source/systemd/+bug/1447807
}
agents.each do |agent|
platform = agent.platform.variant
osname = on(agent, facter('os.name')).stdout.chomp
majrelease = on(agent, facter('os.release.major')).stdout.chomp.to_i
init_script_systemd = "/usr/lib/systemd/system/#{package_name[platform]}.service"
symlink_systemd = "/etc/systemd/system/multi-user.target.wants/#{package_name[platform]}.service"
start_runlevels = ["2", "3", "4", "5"]
kill_runlevels = ["0", "1", "6"]
if platform == 'sles'
start_runlevels = ["3", "5"]
kill_runlevels = ["3", "5"]
elsif platform == 'ubuntu'
start_runlevels = ["2", "3", "4", "5"]
kill_runlevels = ["2", "3", "4", "5"]
end
manifest_uninstall_package = %Q{
package { '#{package_name[platform]}':
ensure => absent,
}
}
manifest_install_package = %Q{
package { '#{package_name[platform]}':
ensure => present,
}
}
manifest_service_enabled = %Q{
service { '#{package_name[platform]}':
enable => true,
}
}
manifest_service_disabled = %Q{
service { '#{package_name[platform]}':
enable => false,
}
}
teardown do
apply_manifest_on(agent, manifest_uninstall_package)
end
step "installing #{package_name[platform]}"
apply_manifest_on(agent, manifest_install_package, :catch_failures => true)
step "ensure enabling service creates the start & kill symlinks"
# amazon linux is based on el: v1 uses a 4-digit year for its majrelease
# and is based on el-6 (sysV). v2 returns a single-digit version for its
# majrelease and is based on el-7 (systemd).
is_sysV = ((platform == 'centos' || platform == 'el') && osname != 'Amazon' && majrelease < 7) ||
(osname == 'Amazon' && majrelease > 2010) ||
platform == 'debian' || platform == 'ubuntu' ||
(platform == 'sles' && majrelease < 12)
apply_manifest_on(agent, manifest_service_disabled, :catch_failures => true)
apply_manifest_on(agent, manifest_service_enabled, :catch_failures => true) do
if is_sysV
# debian platforms using sysV put rc runlevels directly in /etc/
on agent, "ln -s /etc/ /etc/rc.d", :accept_all_exit_codes => true
rc_symlinks = on(agent, "find /etc/ -name *#{package_name[platform]}", :accept_all_exit_codes => true).stdout
start_runlevels.each do |runlevel|
assert_match(/rc#{runlevel}\.d\/S\d\d#{package_name[platform]}/, rc_symlinks, "did not find start symlink for #{package_name[platform]} in runlevel #{runlevel}")
assert_match(/\/etc(\/rc\.d)?\/init\.d\/#{package_name[platform]}/, rc_symlinks, "did not find #{package_name[platform]} init script")
end
# Temporary measure until the Ubuntu SysV bugs are fixed. The cron service doesn't keep kill symlinks around while
# the service is enabled, unlike Apache2.
unless platform == 'ubuntu'
kill_runlevels.each do |runlevel|
assert_match(/rc#{runlevel}\.d\/K\d\d#{package_name[platform]}/, rc_symlinks, "did not find kill symlink for #{package_name[platform]} in runlevel #{runlevel}")
end
end
else
rc_symlinks = on(agent, "ls #{symlink_systemd} #{init_script_systemd}", :accept_all_exit_codes => true).stdout
assert_match("#{symlink_systemd}", rc_symlinks, "did not find #{symlink_systemd}")
assert_match("#{init_script_systemd}", rc_symlinks, "did not find #{init_script_systemd}")
end
end
step "ensure disabling service removes start symlinks"
apply_manifest_on(agent, manifest_service_disabled, :catch_failures => true) do
if is_sysV
rc_symlinks = on(agent, "find /etc/ -name *#{package_name[platform]}", :accept_all_exit_codes => true).stdout
# sles removes rc.d symlinks
if platform != 'sles'
(start_runlevels + kill_runlevels).each do |runlevel|
assert_match(/rc#{runlevel}\.d\/K\d\d#{package_name[platform]}/, rc_symlinks, "did not find kill symlink for #{package_name[platform]} in runlevel #{runlevel}")
end
end
else
rc_symlinks = on(agent, "ls #{symlink_systemd}", :accept_all_exit_codes => true).stdout
refute_match("#{symlink_systemd}", rc_symlinks, "should not have found #{symlink_systemd}")
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/resource/service/windows_mixed_utf8.rb | acceptance/tests/resource/service/windows_mixed_utf8.rb | # coding: utf-8
test_name "Windows Service Provider With Mixed UTF-8 Service Names" do
confine :to, :platform => 'windows'
tag 'audit:high',
'audit:acceptance'
require 'puppet/acceptance/windows_utils'
extend Puppet::Acceptance::WindowsUtils
def service_manifest(name, 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
service { '#{name}':
#{params_str}
}
MANIFEST
end
[
# different UTF-8 widths
# 1-byte A
# 2-byte ۿ - http://www.fileformat.info/info/unicode/char/06ff/index.htm - 0xDB 0xBF / 219 191
# 3-byte ᚠ - http://www.fileformat.info/info/unicode/char/16A0/index.htm - 0xE1 0x9A 0xA0 / 225 154 160
# 4-byte - http://www.fileformat.info/info/unicode/char/2070E/index.htm - 0xF0 0xA0 0x9C 0x8E / 240 160 156 142
{
:name => "A\u06FF\u16A0\u{2070E}",
:start_sleep => 0,
:pause_sleep => 0,
:continue_sleep => 0,
:stop_sleep => 0,
}
].each do |mock_service|
agents.each do |agent|
setup_service(agent, mock_service, 'MockService.cs')
step 'Verify that enable = false disables the service' do
apply_manifest_on(agent, service_manifest(mock_service[:name], enable: false))
assert_service_properties_on(agent, mock_service[:name], StartMode: 'Disabled')
end
step 'Verify that enable = manual indicates that the service can be started on demand' do
apply_manifest_on(agent, service_manifest(mock_service[:name], enable: :manual))
assert_service_properties_on(agent, mock_service[:name], StartMode: 'Manual')
end
step 'Verify that enable = delayed indicates that the service start mode is correctly set' do
apply_manifest_on(agent, service_manifest(mock_service[:name], enable: :delayed))
assert_service_startmode_delayed(agent, mock_service[:name])
end
step 'Verify that enable = true indicates that the service is started automatically upon reboot' do
apply_manifest_on(agent, service_manifest(mock_service[:name], enable: true))
assert_service_properties_on(agent, mock_service[:name], StartMode: 'Auto')
end
step 'Verify that we can start the service' do
apply_manifest_on(agent, service_manifest(mock_service[:name], ensure: :running))
assert_service_properties_on(agent, mock_service[:name], State: 'Running')
end
step 'Verify idempotence' do
apply_manifest_on(agent, service_manifest(mock_service[:name], ensure: :running))
assert_service_properties_on(agent, mock_service[:name], State: 'Running')
end
step 'Verify that we can stop the service' do
apply_manifest_on(agent, service_manifest(mock_service[:name], ensure: :stopped))
assert_service_properties_on(agent, mock_service[:name], State: 'Stopped')
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/resource/service/ticket_5024_systemd_enabling_masked_service.rb | acceptance/tests/resource/service/ticket_5024_systemd_enabling_masked_service.rb | require 'puppet/acceptance/service_utils'
extend Puppet::Acceptance::ServiceUtils
test_name 'Systemd masked services are unmasked before attempting to start'
tag 'audit:high',
'audit:refactor', # Use block style `test_run`
'audit:acceptance' # Could be done at the integration (or unit) layer though
# actual changing of resources could irreparably damage a
# host running this, or require special permissions.
skip_test "requires AIO install to require 'puppet'" if @options[:type] != 'aio'
# This test in intended to ensure that a service which was previously marked
# as masked and then set to enabled will first be unmasked.
confine :to, {}, agents.select { |agent| supports_systemd?(agent) }
package_name = {'el' => 'httpd',
'centos' => 'httpd',
'fedora' => 'httpd',
'amazon' => 'httpd',
'sles' => 'apache2',
'debian' => 'cron', # apache2 does not create systemd service symlinks in Debian
'ubuntu' => 'cron', # See https://bugs.launchpad.net/ubuntu/+source/systemd/+bug/1447807
}
agents.each do |agent|
platform = agent.platform.variant
init_script_systemd = "/usr/lib/systemd/system/#{package_name[platform]}.service"
if agent['platform'] =~ /(ubuntu)/
version = on(agent, facter('os.release.full')).stdout.chomp.to_i
if version < 24
init_script_systemd = "/lib/systemd/system/#{package_name[platform]}.service"
end
elsif agent['platform'] =~ /debian/
init_script_systemd = "/lib/systemd/system/#{package_name[platform]}.service"
end
symlink_systemd = "/etc/systemd/system/multi-user.target.wants/#{package_name[platform]}.service"
masked_symlink_systemd = "/etc/systemd/system/#{package_name[platform]}.service"
manifest_uninstall_package = %Q{
package { '#{package_name[platform]}':
ensure => absent,
}
}
manifest_install_package = %Q{
package { '#{package_name[platform]}':
ensure => present,
}
}
manifest_service_masked = %Q{
service { '#{package_name[platform]}':
enable => mask,
ensure => stopped,
}
}
manifest_service_enabled = %Q{
service { '#{package_name[platform]}':
enable => true,
ensure => running,
}
}
teardown do
if platform == 'sles'
on agent, 'zypper remove -y apache2 apache2-prefork libapr1 libapr-util1'
else
apply_manifest_on(agent, manifest_uninstall_package)
end
end
step "Installing #{package_name[platform]}"
apply_manifest_on(agent, manifest_install_package, :catch_failures => true)
step "Masking the #{package_name[platform]} service"
apply_manifest_on(agent, manifest_service_masked, :catch_failures => true)
on(agent, puppet_resource('service', package_name[platform])) do |result|
assert_match(/ensure.+=> 'stopped'/, result.stdout, "Expected #{package_name[platform]} service to be stopped")
assert_match(/enable.+=> 'false'/, result.stdout, "Expected #{package_name[platform]} service to be masked")
on(agent, "readlink #{masked_symlink_systemd}") do |readlink_result|
assert_equal('/dev/null', readlink_result.stdout.chomp, "Expected service symlink to point to /dev/null")
end
end
step "Enabling the #{package_name[platform]} service"
apply_manifest_on(agent, manifest_service_enabled, :catch_failures => true)
on(agent, puppet_resource('service', package_name[platform])) do |result|
assert_match(/ensure.+=> 'running'/, result.stdout, "Expected #{package_name[platform]} service to be running")
assert_match(/enable.+=> 'true'/, result.stdout, "Expected #{package_name[platform]} service to be enabled")
on(agent, "readlink #{symlink_systemd}") do |readlink_result|
assert_equal(init_script_systemd, readlink_result.stdout.chomp, "Expected service symlink to point to systemd init script")
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/resource/service/launchd_provider.rb | acceptance/tests/resource/service/launchd_provider.rb | test_name 'Mac OS X launchd Provider Testing'
tag 'audit:high',
'audit:refactor', # Use block style `test_name`
'audit:acceptance' # Could be done at the integration (or unit) layer though
# actual changing of resources could irreparably damage a
# host running this, or require special permissions.
confine :to, {:platform => /osx/}, agents
require 'puppet/acceptance/service_utils'
extend Puppet::Acceptance::ServiceUtils
sloth_daemon_script = <<SCRIPT
#!/usr/bin/env sh
while true; do sleep 1; done
SCRIPT
svc = 'com.puppetlabs.sloth'
launchd_script_path = "/Library/LaunchDaemons/#{svc}.plist"
def launchctl_assert_status(host, service, expect_running)
on(host, 'launchctl list') do |result|
if expect_running
assert_match(/#{service}/, result.stdout, 'Service was not found in launchctl list')
else
refute_match(/#{service}/, result.stdout, 'Service was not expected in launchctl list')
end
end
end
agents.each do |agent|
step "Setup on #{agent}"
sloth_daemon_path = agent.tmpfile("sloth_daemon.sh")
create_remote_file(agent, sloth_daemon_path, sloth_daemon_script)
launchd_script = <<SCRIPT
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>#{svc}</string>
<key>Program</key>
<string>#{sloth_daemon_path}</string>
<key>RunAtLoad</key>
<true/>
</dict>
</plist>
SCRIPT
create_remote_file(agent, launchd_script_path, launchd_script)
teardown do
on agent, puppet_resource('service', 'com.puppetlabs.sloth', 'ensure=stopped', 'enable=true')
on agent, "rm #{sloth_daemon_path} #{launchd_script_path}"
end
step "Verify the service exists on #{agent}"
assert_service_status_on_host(agent, svc, {:ensure => 'stopped', :enable => 'true'}) do
launchctl_assert_status(agent, svc, false)
end
step "Start the service on #{agent}"
ensure_service_on_host(agent, svc, {:ensure => 'running'}) do
launchctl_assert_status(agent, svc, true)
end
step "Disable the service on #{agent}"
ensure_service_on_host(agent, svc, {:enable => 'false'}) do
launchctl_assert_status(agent, svc, true)
end
step "Stop the service on #{agent}"
ensure_service_on_host(agent, svc, {:ensure => 'stopped'}) do
launchctl_assert_status(agent, svc, false)
end
step "Enable the service on #{agent}"
ensure_service_on_host(agent, svc, {:enable => 'true'}) do
launchctl_assert_status(agent, svc, false)
end
# switching from stopped to running should output the correct status of the service and not 'absent'
step "Start the service on #{agent} when service is stopped, and check output" do
on agent, puppet_resource('service', svc, 'ensure=stopped')
on agent, puppet_resource('service', svc, 'ensure=running')
assert_service_status_on_host(agent, svc, {:ensure => 'running'})
end
# switching from running to stopped should output the correct status of the service and not 'absent'
step "Stop the service on #{agent} when service is running, and check output" do
on agent, puppet_resource('service', svc, 'ensure=running')
on agent, puppet_resource('service', svc, 'ensure=stopped')
assert_service_status_on_host(agent, svc, {:ensure => 'stopped'})
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/resource/service/should_query_all.rb | acceptance/tests/resource/service/should_query_all.rb | test_name "should query all services"
tag 'audit:high',
'audit:refactor', # Investigate combining with should_not_change_the_system.rb
# Use block style `test_name`
'audit:integration' # Doesn't change the system it runs on
agents.each do |agent|
step "query with puppet"
on(agent, puppet_resource('service'), :accept_all_exit_codes => true) do |result|
assert_equal(result.exit_code, 0, "'puppet resource service' should have an exit code of 0")
assert(/^service/ =~ result.stdout, "'puppet resource service' should present service details")
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/resource/service/init_on_systemd.rb | acceptance/tests/resource/service/init_on_systemd.rb | test_name 'SysV on default Systemd Service Provider Validation' do
confine :to, :platform => /el-[6-8]|centos|fedora-(2[0-9])/ do |h|
result = on(h, 'which systemctl', :acceptable_exit_codes => [0, 1])
result.stdout =~ /systemctl/
end
tag 'audit:high',
'audit:acceptance' # Could be done at the integration (or unit) layer though
# actual changing of resources could irreparably damage a
# host running this, or require special permissions.
require 'puppet/acceptance/service_utils'
extend Puppet::Acceptance::ServiceUtils
svc = 'puppetize'
initd_location = "/etc/init.d/#{svc}"
pidfile = "/var/run/#{svc}.pid"
# Some scripts don't have status command.
def initd_file(svc, pidfile, initd_location, status)
<<INITD
#!/bin/bash
# #{svc} daemon
# chkconfig: 2345 20 80
# description: #{svc} daemon
DESC="#{svc} daemon"
PIDFILE=#{pidfile}
SCRIPTNAME=#{initd_location}
case "$1" in
start)
PID=`/usr/bin/#{svc} 120 > /dev/null 2>&1 & echo $!`
if [ -z $PID ]; then
echo "Failed to start"
else
echo $PID > $PIDFILE
echo "Started"
fi
;;
#{if status then "status)" else "status-ignored)" end}
if [ -f $PIDFILE ]; then
PID=`cat $PIDFILE`
if [ -z "`ps axf | grep ${PID} | grep -v grep `" ]; then
printf "Process dead but pidfile exists"
exit 2
else
echo "Running"
fi
else
echo "Service not running"
exit 3
fi
;;
stop)
PID=`cat $PIDFILE`
if [ -f $PIDFILE ]; then
kill -TERM $PID
rm -f $PIDFILE
else
echo "pidfile not found"
fi
;;
restart)
$0 stop
$0 start
;;
*)
echo "Usage: $0 (start|stop|restart)"
exit 1
esac
exit 0
INITD
end
def assert_service_status(agent, pidfile, expected_running)
on(agent, "ps -p `cat #{pidfile}`", :acceptable_exit_codes => (expected_running ? [0] : [1]))
end
agents.each do |agent|
sleep_bin = on(agent, 'which sleep').stdout.chomp
step "Create initd script with status command" do
create_remote_file agent, initd_location, initd_file(svc, pidfile, initd_location, true)
apply_manifest_on agent, <<MANIFEST
file {'/usr/bin/#{svc}': ensure => link, target => '#{sleep_bin}', }
file {'#{initd_location}': ensure => file, mode => '0755', }
MANIFEST
on(agent, "chkconfig --add #{svc}")
on(agent, "chkconfig #{svc}", :acceptable_exit_codes => [0])
on(agent, "service #{svc} status", :acceptable_exit_codes => [3])
end
step "Verify the service exists on #{agent}" do
assert_service_status_on_host(agent, svc, {:ensure => 'stopped', :enable => 'true'}) do
assert_service_status(agent, pidfile, false)
end
end
step "Start the service on #{agent}" do
ensure_service_on_host(agent, svc, {:ensure => 'running'}) do
assert_service_status(agent, pidfile, true)
end
end
step "Disable the service on #{agent}" do
ensure_service_on_host(agent, svc, {:enable => 'false'}) do
assert_service_status(agent, pidfile, true)
end
end
step "Stop the service on #{agent}" do
ensure_service_on_host(agent, svc, {:ensure => 'stopped'}) do
assert_service_status(agent, pidfile, false)
end
end
step "Enable the service on #{agent}" do
ensure_service_on_host(agent, svc, {:enable => 'true'}) do
assert_service_status(agent, pidfile, false)
end
end
step "Create initd script without status command" do
create_remote_file agent, initd_location, initd_file(svc, pidfile, initd_location, false)
apply_manifest_on agent, <<MANIFEST
file {'/usr/bin/#{svc}': ensure => link, target => '#{sleep_bin}', }
file {'#{initd_location}': ensure => file, mode => '0755', }
MANIFEST
on(agent, "chkconfig --add #{svc}")
on(agent, "chkconfig #{svc}", :acceptable_exit_codes => [0])
on(agent, "service #{svc} status", :acceptable_exit_codes => [1])
end
step "Verify the service exists on #{agent}" do
assert_service_status_on_host(agent, svc, {:ensure => 'stopped', :enable => 'true'}) do
assert_service_status(agent, pidfile, false)
end
end
# The following are implemented differently because currently the Redhat provider can't tell when
# a service is running if it doesn't implement the status command. However it can still manage it.
step "Start the service on #{agent}" do
ensure_service_change_on_host(agent, svc, {:ensure => 'running'})
assert_service_status(agent, pidfile, true)
ensure_service_idempotent_on_host(agent, svc, {:ensure => 'running'})
assert_service_status(agent, pidfile, true)
end
step "Disable the service on #{agent}" do
ensure_service_change_on_host(agent, svc, {:enable => 'false'})
assert_service_status(agent, pidfile, true)
ensure_service_idempotent_on_host(agent, svc, {:enable => 'false'})
assert_service_status(agent, pidfile, true)
end
step "Stop the service on #{agent}" do
ensure_service_change_on_host(agent, svc, {:ensure => 'stopped'})
assert_service_status(agent, pidfile, false)
ensure_service_idempotent_on_host(agent, svc, {:ensure => 'stopped'})
assert_service_status(agent, pidfile, false)
end
step "Enable the service on #{agent}" do
ensure_service_change_on_host(agent, svc, {:enable => 'true'})
assert_service_status(agent, pidfile, false)
ensure_service_idempotent_on_host(agent, svc, {:enable => 'true'})
assert_service_status(agent, pidfile, false)
end
teardown do
on(agent, "service #{svc} stop", :accept_any_exit_code => true)
on(agent, "chkconfig --del #{svc}")
on(agent, "rm /usr/bin/#{svc} #{initd_location}")
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/tests/resource/service/systemd_resource_shows_correct_output.rb | acceptance/tests/resource/service/systemd_resource_shows_correct_output.rb | require 'puppet/acceptance/service_utils'
extend Puppet::Acceptance::ServiceUtils
test_name 'systemd service shows correct output when queried with "puppet resource"' do
tag 'audit:high'
skip_test 'requires puppet service script from AIO agent package' if @options[:type] != 'aio'
package_name = 'puppet'
# This test ensures that 'puppet resource' output matches the system state
confine :to, {}, agents.select { |agent| supports_systemd?(agent) }
agents.each do |agent|
initial_state = on(agent, puppet_resource('service', package_name)).stdout
teardown do
apply_manifest_on(agent, initial_state)
end
step "Setting ensure=stopped and enable=true" do
on(agent, puppet_resource('service', package_name, 'ensure=stopped', 'enable=true'))
end
step "Expect reported status to match system state" do
on(agent, puppet_resource('service', package_name, 'ensure=stopped', 'enable=true')) do |result|
assert_match(/ensure\s*=>\s*'stopped'/, result.stdout, "Expected '#{package_name}' service to appear as stopped")
assert_match(/enable\s*=>\s*'true'/, result.stdout, "Expected '#{package_name}' service to appear as enabled")
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/resource/service/windows.rb | acceptance/tests/resource/service/windows.rb | test_name "Windows Service Provider" do
confine :to, :platform => 'windows'
tag 'audit:high',
'audit:acceptance'
require 'puppet/acceptance/windows_utils'
extend Puppet::Acceptance::WindowsUtils
require 'puppet/acceptance/service_utils'
extend Puppet::Acceptance::ServiceUtils
def service_manifest(name, 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
service { '#{name}':
#{params_str}
}
MANIFEST
end
mock_service_nofail = {
:name => "mock_service_nofail",
:start_sleep => 0,
:pause_sleep => 0,
:continue_sleep => 0,
:stop_sleep => 0,
}
# Since the default timeout for service operations is
# 30 seconds, waiting for 40 should ensure that the service
# operation will fail with a default timeout.
mock_service_long_start_stop = {
:name => "mock_service_long_start_stop",
:start_sleep => 40,
:pause_sleep => 0,
:continue_sleep => 0,
:stop_sleep => 40,
}
new_user = "tempUser#{rand(999999).to_i}"
fresh_user = "freshUser#{rand(999999).to_i}"
fresh_user_manifest = <<-MANIFEST
user { '#{fresh_user}':
ensure => present,
password => 'freshUserPassword#123',
roles => 'SeServiceLogonRight'
}
service { '#{mock_service_nofail[:name]}':
logonaccount => '#{fresh_user}',
logonpassword => 'freshUserPassword#123',
require => User['#{fresh_user}']
}
MANIFEST
teardown do
delete_service(agent, mock_service_nofail[:name])
delete_service(agent, mock_service_long_start_stop[:name])
on(agent, puppet("resource user #{new_user} ensure=absent"))
on(agent, puppet("resource user #{fresh_user} ensure=absent"))
end
agents.each do |agent|
local_service_locale_name = agent['locale'] == 'fr' ? 'AUTORITE NT\SERVICE LOCAL' : 'NT AUTHORITY\LOCAL SERVICE'
run_nonexistent_service_tests(mock_service_nofail[:name])
setup_service(agent, mock_service_nofail, 'MockService.cs')
step 'Verify that enable = false disables the service' do
apply_manifest_on(agent, service_manifest(mock_service_nofail[:name], enable: false))
assert_service_properties_on(agent, mock_service_nofail[:name], StartMode: 'Disabled')
end
step 'Verify that enable = manual indicates that the service can be started on demand' do
apply_manifest_on(agent, service_manifest(mock_service_nofail[:name], enable: :manual))
assert_service_properties_on(agent, mock_service_nofail[:name], StartMode: 'Manual')
end
step 'Verify that enable = delayed indicates that the service start mode is correctly set' do
apply_manifest_on(agent, service_manifest(mock_service_nofail[:name], enable: :delayed))
assert_service_startmode_delayed(agent, mock_service_nofail[:name])
end
step 'Verify that enable = true indicates that the service is started automatically upon reboot' do
apply_manifest_on(agent, service_manifest(mock_service_nofail[:name], enable: true))
assert_service_properties_on(agent, mock_service_nofail[:name], StartMode: 'Auto')
end
step 'Verify that enable noops if the enable property is already synced' do
apply_manifest_on(agent, service_manifest(mock_service_nofail[:name], enable: true), catch_changes: true)
assert_service_properties_on(agent, mock_service_nofail[:name], StartMode: 'Auto')
end
step 'Verify that we can start the service' do
apply_manifest_on(agent, service_manifest(mock_service_nofail[:name], ensure: :running))
assert_service_properties_on(agent, mock_service_nofail[:name], State: 'Running')
end
step 'Verify that we can change logonaccount, for an already running service, using user created in the same manifest' do
assert_service_properties_on(agent, mock_service_nofail[:name], StartName: 'LocalSystem')
apply_manifest_on(agent, fresh_user_manifest, expect_changes: true)
assert_service_properties_on(agent, mock_service_nofail[:name], StartName: fresh_user)
end
step 'Verify that running the same manifest twice causes no more changes' do
assert_service_properties_on(agent, mock_service_nofail[:name], StartName: fresh_user)
apply_manifest_on(agent, fresh_user_manifest, catch_changes: true)
assert_service_properties_on(agent, mock_service_nofail[:name], StartName: fresh_user)
end
step 'Verify that we can change logonaccount, for an already running service, using SID' do
assert_service_properties_on(agent, mock_service_nofail[:name], StartName: fresh_user)
on(agent, puppet("resource service #{mock_service_nofail[:name]} logonaccount=S-1-5-19")) do |result|
assert_match(/Service\[#{mock_service_nofail[:name]}\]\/logonaccount: logonaccount changed '.\\#{fresh_user}' to '#{Regexp.escape(local_service_locale_name)}'/, result.stdout)
refute_match(/Transitioning the #{mock_service_nofail[:name]} service from SERVICE_RUNNING to SERVICE_STOPPED/, result.stdout,
"Expected no service restarts since ensure isn't being managed as 'running'.")
refute_match(/Successfully started the #{mock_service_nofail[:name]} service/, result.stdout)
end
assert_service_properties_on(agent, mock_service_nofail[:name], StartName: local_service_locale_name)
end
step 'Verify that logonaccount noops if the logonaccount property is already synced' do
apply_manifest_on(agent, service_manifest(mock_service_nofail[:name], logonaccount: 'S-1-5-19'), catch_changes: true)
assert_service_properties_on(agent, mock_service_nofail[:name], StartName: local_service_locale_name)
end
step 'Verify that setting logonaccount fails if input is invalid' do
apply_manifest_on(agent, service_manifest(mock_service_nofail[:name], logonaccount: 'InvalidUser'), :acceptable_exit_codes => [1]) do |result|
assert_match(/"InvalidUser" is not a valid account/, result.stderr)
end
assert_service_properties_on(agent, mock_service_nofail[:name], StartName: local_service_locale_name)
end
step 'Verify that the service restarts if it is already running, logonaccount is different from last run and ensure is set to running' do
assert_service_properties_on(agent, mock_service_nofail[:name], StartName: local_service_locale_name)
on(agent, puppet("resource service #{mock_service_nofail[:name]} logonaccount=LocalSystem ensure=running --debug")) do |result|
assert_match(/Service\[#{mock_service_nofail[:name]}\]\/logonaccount: logonaccount changed '#{Regexp.escape(local_service_locale_name)}' to 'LocalSystem'/, result.stdout)
assert_match(/Transitioning the #{mock_service_nofail[:name]} service from SERVICE_RUNNING to SERVICE_STOPPED/, result.stdout)
assert_match(/Successfully started the #{mock_service_nofail[:name]} service/, result.stdout)
end
assert_service_properties_on(agent, mock_service_nofail[:name], StartName: 'LocalSystem')
end
step 'Verify that there are no restarts if logonaccount does not change, even though ensure is managed as running' do
assert_service_properties_on(agent, mock_service_nofail[:name], StartName: 'LocalSystem')
on(agent, puppet("resource service #{mock_service_nofail[:name]} logonaccount=LocalSystem ensure=running --debug")) do |result|
refute_match(/Service\[#{mock_service_nofail[:name]}\]\/logonaccount: logonaccount changed/, result.stdout)
refute_match(/Service\[#{mock_service_nofail[:name]}\]\/ensure: ensure changed/, result.stdout)
refute_match(/Transitioning the #{mock_service_nofail[:name]} service from SERVICE_RUNNING to SERVICE_STOPPED/, result.stdout)
refute_match(/Successfully started the #{mock_service_nofail[:name]} service/, result.stdout)
end
assert_service_properties_on(agent, mock_service_nofail[:name], StartName: 'LocalSystem')
end
step "Create a new user named #{new_user}" do
on(agent, puppet("resource user #{new_user} ensure=present password=firstPassword#123")) do |result|
assert_match(/User\[#{new_user}\]\/ensure: created/, result.stdout)
end
end
step 'Verify that a user without the `Logon As A Service` right cannot be managed as the logonaccount of a service' do
apply_manifest_on(agent, service_manifest(mock_service_long_start_stop[:name], logonaccount: new_user), :acceptable_exit_codes => [1]) do |result|
assert_match(/#{new_user}" is missing the 'Log On As A Service' right./, result.stderr)
end
end
step "Grant #{new_user} the `Logon As A Service` right" do
on(agent, puppet("resource user #{new_user} roles='SeServiceLogonRight'")) do |result|
assert_match(/User\[#{new_user}\]\/roles: roles changed to 'SeServiceLogonRight'/, result.stdout)
end
end
step 'Verify that setting logonpassword fails if input is invalid' do
apply_manifest_on(agent, service_manifest(mock_service_nofail[:name], logonaccount: new_user, logonpassword: 'wrongPass'), :acceptable_exit_codes => [1]) do |result|
assert_match(/The given password is invalid for user '\.\\#{new_user}'/, result.stderr)
end
assert_service_properties_on(agent, mock_service_nofail[:name], StartName: 'LocalSystem')
end
step "Verify that #{new_user} can be set as logonaccount and service is still running" do
assert_service_properties_on(agent, mock_service_nofail[:name], StartName: 'LocalSystem')
on(agent, puppet("resource service #{mock_service_nofail[:name]} logonaccount=#{new_user} logonpassword=firstPassword#123 ensure=running --debug")) do |result|
assert_match(/Service\[#{mock_service_nofail[:name]}\]\/logonaccount: logonaccount changed 'LocalSystem' to '.\\#{new_user}'/, result.stdout)
assert_match(/Transitioning the #{mock_service_nofail[:name]} service from SERVICE_RUNNING to SERVICE_STOPPED/, result.stdout)
assert_match(/Successfully started the #{mock_service_nofail[:name]} service/, result.stdout)
end
assert_service_properties_on(agent, mock_service_nofail[:name], StartName: new_user, State: 'Running')
end
step "Change password for #{new_user} and verify that service state isn't yet affected by this" do
on(agent, puppet("resource user #{new_user} ensure=present password=secondPassword#123")) do |result|
assert_match(/User\[#{new_user}\]\/password: changed \[redacted\] to \[redacted\]/, result.stdout)
end
assert_service_properties_on(agent, mock_service_nofail[:name], StartName: new_user, State: 'Running')
end
step 'Verify that setting logonpassword fails when using old password and service remains running' do
apply_manifest_on(agent, service_manifest(mock_service_long_start_stop[:name], logonaccount: new_user, logonpassword: 'firstPassword#123'), :acceptable_exit_codes => [1]) do |result|
assert_match(/The given password is invalid for user/, result.stderr)
end
assert_service_properties_on(agent, mock_service_nofail[:name], StartName: new_user, State: 'Running')
end
step 'Verify that setting the new logonpassword does not report any changes' do
assert_service_properties_on(agent, mock_service_nofail[:name], StartName: new_user, State: 'Running')
apply_manifest_on(agent, service_manifest(mock_service_nofail[:name], logonaccount: new_user, logonpassword: 'secondPassword#123'), catch_changes: true)
assert_service_properties_on(agent, mock_service_nofail[:name], StartName: new_user, State: 'Running')
end
step 'Verify that we can still stop the service' do
assert_service_properties_on(agent, mock_service_nofail[:name], StartName: new_user, State: 'Running')
apply_manifest_on(agent, service_manifest(mock_service_nofail[:name], ensure: :stopped), expect_changes: true)
assert_service_properties_on(agent, mock_service_nofail[:name], StartName: new_user, State: 'Stopped')
end
step 'Verify that the new logonpassword has actually been set by succesfully restarting the service' do
assert_service_properties_on(agent, mock_service_nofail[:name], StartName: new_user, State: 'Stopped')
apply_manifest_on(agent, service_manifest(mock_service_nofail[:name], ensure: :running), expect_changes: true)
assert_service_properties_on(agent, mock_service_nofail[:name], StartName: new_user, State: 'Running')
end
step "Deny #{new_user} the `Logon As A Service` right" do
on(agent, puppet("resource user #{new_user} roles='SeDenyServiceLogonRight'")) do |result|
assert_match(/User\[#{new_user}\]\/roles: roles changed SeServiceLogonRight to 'SeDenyServiceLogonRight,SeServiceLogonRight'/, result.stdout)
end
end
step 'Verify that we can still stop the service' do
assert_service_properties_on(agent, mock_service_nofail[:name], State: 'Running')
apply_manifest_on(agent, service_manifest(mock_service_nofail[:name], ensure: :stopped), expect_changes: true)
assert_service_properties_on(agent, mock_service_nofail[:name], State: 'Stopped')
end
step 'Verify that the service cannot be started anymore because of the denied `Logon As A Service` right' do
apply_manifest_on(agent, service_manifest(mock_service_nofail[:name], ensure: :running), :acceptable_exit_codes => [4], catch_changes: true) do |result|
assert_match(/Failed to start the service/, result.stderr)
end
assert_service_properties_on(agent, mock_service_nofail[:name], StartName: new_user, State: 'Stopped')
end
step 'Verify that a user with `Logon As A Service` right denied will raise error when managing it as logonaccount for a service' do
apply_manifest_on(agent, service_manifest(mock_service_nofail[:name], logonaccount: new_user), :acceptable_exit_codes => [1, 4]) do |result|
assert_match(/#{new_user}\" has the 'Log On As A Service' right set to denied./, result.stderr)
end
assert_service_properties_on(agent, mock_service_nofail[:name], StartName: new_user, State: 'Stopped')
end
step "Grant back #{new_user} the `Logon As A Service` right for our subsequent tests" do
on(agent, puppet("resource user #{new_user} roles='SeServiceLogonRight' role_membership=inclusive")) do |result|
assert_match(/User\[#{new_user}\]\/roles: roles changed SeServiceLogonRight,SeDenyServiceLogonRight to 'SeServiceLogonRight'/, result.stdout)
end
end
step 'Verify that ensure noops if the ensure property is already synced' do
apply_manifest_on(agent, service_manifest(mock_service_nofail[:name], ensure: :stopped), catch_changes: true)
assert_service_properties_on(agent, mock_service_nofail[:name], State: 'Stopped')
end
step 'Verify that we can change logonaccount for a stopped service' do
assert_service_properties_on(agent, mock_service_nofail[:name], State: 'Stopped', StartName: new_user)
apply_manifest_on(agent, service_manifest(mock_service_nofail[:name], logonaccount: local_service_locale_name), expect_changes: true)
assert_service_properties_on(agent, mock_service_nofail[:name], State: 'Stopped', StartName: local_service_locale_name)
end
step 'Verify that logonaccount noops if the logonaccount property is already synced' do
apply_manifest_on(agent, service_manifest(mock_service_nofail[:name], logonaccount: local_service_locale_name), catch_changes: true)
assert_service_properties_on(agent, mock_service_nofail[:name], StartName: local_service_locale_name)
end
step 'Verify that we can query the service with the RAL' do
on(agent, puppet("resource service #{mock_service_nofail[:name]}")) do |result|
assert_match( /enable\s+=>\s+'true'/, result.stdout, "Failed to query the service with the RAL on #{agent}")
end
end
step 'Disable the service and change logonaccount back to `LocalSystem` in preparation for our subsequent tests' do
apply_manifest_on(agent, service_manifest(mock_service_nofail[:name], enable: false, logonaccount: 'LocalSystem'))
assert_service_properties_on(agent, mock_service_nofail[:name], StartName: 'LocalSystem', StartMode: 'Disabled')
end
step 'Verify that starting a disabled service fails if the enable property is not managed' do
apply_manifest_on(agent, service_manifest(mock_service_nofail[:name], ensure: :running)) do |result|
assert_match(/#{mock_service_nofail[:name]}/, result.stderr, 'Windows service provider is able to start a disabled service without managing the enable property')
end
end
step 'Verify that enable = false, ensure = running leaves the service disabled and in the running state' do
apply_manifest_on(agent, service_manifest(mock_service_nofail[:name], enable: false, ensure: :running))
assert_service_properties_on(agent, mock_service_nofail[:name], StartMode: 'Disabled', State: 'Running')
end
step 'Stop the service to prepare for our subsequent tests' do
apply_manifest_on(agent, service_manifest(mock_service_nofail[:name], ensure: :stopped))
assert_service_properties_on(agent, mock_service_nofail[:name], State: 'Stopped')
end
step 'Verify that enable = true, ensure = running leaves the service enabled and in the running state' do
apply_manifest_on(agent, service_manifest(mock_service_nofail[:name], enable: true, ensure: :running))
assert_service_properties_on(agent, mock_service_nofail[:name], StartMode: 'Auto', State: 'Running')
end
step 'Pause the service to prepare for the next test' do
on(agent, powershell("Suspend-Service #{mock_service_nofail[:name]}"))
assert_service_properties_on(agent, mock_service_nofail[:name], State: 'Paused')
end
step 'Verify that Puppet can resume a paused service' do
apply_manifest_on(agent, service_manifest(mock_service_nofail[:name], ensure: :running))
assert_service_properties_on(agent, mock_service_nofail[:name], State: 'Running')
end
step 'Pause the service (again) to prepare for the next test' do
on(agent, powershell("Suspend-Service #{mock_service_nofail[:name]}"))
assert_service_properties_on(agent, mock_service_nofail[:name], State: 'Paused')
end
step 'Verify that Puppet can stop a paused service' do
apply_manifest_on(agent, service_manifest(mock_service_nofail[:name], ensure: :stopped))
assert_service_properties_on(agent, mock_service_nofail[:name], State: 'Stopped')
end
# delete the service so it doesn't interfere with subsequent tests
delete_service(agent, mock_service_nofail[:name])
setup_service(agent, mock_service_long_start_stop, 'MockService.cs')
step 'Verify that starting a service fails if the service does not start by the expiration of the wait hint' do
apply_manifest_on(agent, service_manifest(mock_service_long_start_stop[:name], ensure: :running)) do |result|
assert_match(/#{mock_service_long_start_stop[:name]}/, result.stderr, 'No progress made on service operation and dwWaitHint exceeded')
end
end
# delete and recreate the service so it doesn't interfere with subsequent tests
delete_service(agent, mock_service_long_start_stop[:name])
setup_service(agent, mock_service_long_start_stop, 'MockService.cs')
step 'Verify that starting a service works if the service has a long start and a long timeout' do
apply_manifest_on(agent, service_manifest(mock_service_long_start_stop[:name], ensure: :running, timeout: 45))
assert_service_properties_on(agent, mock_service_long_start_stop[:name], State: 'Running')
end
step 'Start the Service to prepare for subsequent test' do
apply_manifest_on(agent, service_manifest(mock_service_long_start_stop[:name], enable: true, ensure: :running))
end
step 'Verify that stopping a service fails if the service does not stop by the expiration of the wait hint' do
apply_manifest_on(agent, service_manifest(mock_service_long_start_stop[:name], ensure: :stopped)) do |result|
assert_match(/#{mock_service_long_start_stop[:name]}/, result.stderr, 'No progress made on service operation and dwWaitHint exceeded')
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/resource/service/smf_basic_tests.rb | acceptance/tests/resource/service/smf_basic_tests.rb | test_name "SMF: basic tests" do
confine :to, :platform => 'solaris'
tag 'audit:high',
'audit:acceptance' # Could be done at the integration (or unit) layer though
# actual changing of resources could irreparably damage a
# host running this, or require special permissions.
require 'puppet/acceptance/solaris_util'
extend Puppet::Acceptance::SMFUtils
require 'puppet/acceptance/service_utils'
extend Puppet::Acceptance::ServiceUtils
def assert_svcs_info_matches_on(agent, service, info_hash)
info_hash.merge({ 'next_state' => 'none' })
on(agent, "svcs -l #{service}") do |result|
info_hash.each do |key, value|
escaped_key, escaped_value = Regexp.escape(key), Regexp.escape(value)
assert_match(
/^#{escaped_key}.*#{escaped_value}$/,
result.stdout,
"`svcs -l #{service}` does not indicate that #{key} = #{value} on #{agent}"
)
end
end
end
teardown do
agents.each do |agent|
clean agent, :service => 'tstapp'
end
end
agents.each do |agent|
clean agent, :service => 'tstapp'
# Run the tests for a non-existent service first
run_nonexistent_service_tests('tstapp')
manifest, _ = setup agent, :service => 'tstapp'
step "Ensure that the service is created with a manifest" do
apply_manifest_on(agent, 'service {tstapp : enable=>true, manifest=>"%s", ensure=>"running"}' % manifest) do |result|
assert_match( /ensure changed 'stopped' to 'running'/, result.stdout, "Failed to create, enable and start the service on #{agent}")
end
end
step "Ensure that the SMF provider is idempotent -- it does not create services again" do
apply_manifest_on(agent, 'service {tstapp : enable=>true, manifest=>"%s"}' % manifest, :catch_changes => true)
end
step "Ensure you can query the service with the ral" do
on(agent, puppet("resource service tstapp")) do |result|
{ ensure: 'running', enable: true, provider: 'smf' }.each do |property, value|
assert_match(/#{property}.*#{value}.*$/, result.stdout, "Puppet does not report #{property}=#{value} for tstapp service")
end
end
end
step "Verify that ensure can be syncd. without changing the service's enabled? status" do
on(agent, puppet("resource service tstapp ensure=stopped"))
assert_svcs_info_matches_on(agent, 'application/tstapp', { 'enabled' => 'false (temporary)', 'state' => 'disabled' })
end
step "Ensure that when syncing only enable, the service's current status is preserved" do
# Mark the service as maint using svcadm
on(agent, 'svcadm mark -I maintenance tstapp')
on(agent, puppet("resource service tstapp enable=false"))
assert_svcs_info_matches_on(agent, 'application/tstapp', { 'enabled' => 'false', 'state' => 'maintenance' })
end
step "enable == true and ensure == stopped stop the service, but enable it to start again upon reboot" do
on(agent, puppet("resource service tstapp enable=true ensure=stopped"))
assert_svcs_info_matches_on(agent, 'application/tstapp', { 'enabled' => 'false (temporary)', 'state' => 'disabled' })
end
step "enable == false and ensure == running start the service, but disable it upon reboot" do
on(agent, puppet("resource service tstapp enable=false ensure=running"))
assert_svcs_info_matches_on(agent, 'application/tstapp', { 'enabled' => 'true (temporary)', 'state' => 'online' })
end
step "Verify that puppet will noop on the service if enable + ensure are already synced" do
apply_manifest_on(agent, 'service {tstapp : enable=>false, ensure=>"running"}' % manifest, :catch_changes => true)
assert_svcs_info_matches_on(agent, 'application/tstapp', { 'enabled' => 'true (temporary)', 'state' => 'online' })
end
step "Ensure that pupppet fails when multiple instances of the service resource exist" do
# Add a second service instance.
on(agent, 'svccfg -s application/tstapp add second')
apply_manifest_on(agent, 'service {tstapp : enable=>true}') do |result|
assert_match(/Error:.*'tstapp' matches multiple FMRIs/, result.stderr, "Puppet fails to output an error message when multiple FMRIs of a given service exist")
end
on(agent, 'svccfg delete svc:/application/tstapp:second')
end
if agent['platform'] =~ /11/
step "SMF: unset the general/complete property to mark the service as an incomplete service" do
fmri = on(agent, "svcs -H -o fmri tstapp").stdout.chomp
on(agent, "svccfg -s #{fmri} delprop general/complete")
end
step "Verify that an incomplete service is considered stopped and disabled" do
on(agent, puppet_resource('service', 'tstapp')) do |result|
{ enable: false, ensure: :stopped }.each do |property, value|
assert_match(/#{property}.*#{value}.*$/, result.stdout, "Puppet does not report #{property}=#{value} for an incomplete service")
end
end
end
step "Verify that stopping and disabling an incomplete service is a no-op" do
manifest = service_manifest('tstapp', ensure: :stopped, enable: false)
apply_manifest_on(agent, manifest, catch_changes: true)
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/tests/resource/file/should_default_mode.rb | acceptance/tests/resource/file/should_default_mode.rb | test_name "file resource: set default modes"
tag 'audit:high',
'audit:refactor', # Use block style `test_name`
'audit:acceptance'
def regexp_mode(mode)
Regexp.new("mode\s*=>\s*'0?#{mode}'")
end
agents.each do |agent|
step "setup"
parent = agent.tmpdir('default-mode-parent')
on(agent, "rm -rf #{parent}")
step "puppet should set execute bit on readable directories"
on(agent, puppet_resource("file", parent, "ensure=directory", "mode=0644")) do |result|
assert_match(regexp_mode(755), result.stdout)
end
step "include execute bit on newly created directories"
dir = "#{parent}/dir"
on(agent, "mkdir #{dir} && cd #{dir} && cd ..")
step "exclude execute bit from newly created files"
file = "#{parent}/file.txt"
on(agent, "echo foobar > #{file}")
on(agent, "#{file}", :acceptable_exit_codes => (1..255)) do |result|
refute_match(/foobar/, result.stdout)
end
step "set execute bit on file if explicitly specified"
file_750 = "#{parent}/file_750.txt"
on(agent, puppet_resource("file", file_750, "ensure=file", "mode=0750")) do |result|
assert_match(regexp_mode(750), result.stdout)
end
step "don't set execute bit if directory not readable"
dir_600 = "#{parent}/dir_600"
on(agent, puppet_resource("file", dir_600, "ensure=directory", "mode=0600")) do |result|
assert_match(regexp_mode(700), result.stdout) # readable by owner, but not group
end
on(agent, "rm -rf #{parent}")
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/tests/resource/file/content_attribute.rb | acceptance/tests/resource/file/content_attribute.rb | test_name "Content Attribute"
tag 'audit:high',
'audit:refactor', # Use block stype test_name
'audit:acceptance'
agents.each do |agent|
target = agent.tmpfile('content_file_test')
step "Ensure the test environment is clean"
on agent, "rm -f #{target}"
step "Content Attribute: using raw content"
checksums_fips = ['sha256', 'sha256lite']
checksums_no_fips = ['sha256', 'sha256lite', 'md5', 'md5lite']
if on(agent, facter("fips_enabled")).stdout =~ /true/
checksums = checksums_fips
else
checksums = checksums_no_fips
end
manifest = "file { '#{target}': content => 'This is the test file content', ensure => present }"
manifest += checksums.collect {|checksum_type|
"file { '#{target+checksum_type}': content => 'This is the test file content', ensure => present, checksum => #{checksum_type} }"
}.join("\n")
apply_manifest_on(agent, manifest) do |result|
checksums.each do |checksum_type|
refute_match(/content changed/, result.stdout, "#{agent}: shouldn't have overwrote #{target+checksum_type}")
end
end
on(agent, "cat #{target}") do |result|
assert_match(/This is the test file content/, result.stdout, "File content not matched on #{agent}") unless agent['locale'] == 'ja'
end
step "Content Attribute: illegal timesteps"
['mtime', 'ctime'].each do |checksum_type|
manifest = "file { '#{target+checksum_type}': content => 'This is the test file content', ensure => present, checksum => #{checksum_type} }"
apply_manifest_on(agent, manifest, :acceptable_exit_codes => [1]) do |result|
assert_match(/Error: Validation of File\[#{target+checksum_type}\] failed: You cannot specify content when using checksum '#{checksum_type}'/, result.stderr, "#{agent}: expected failure") unless agent['locale'] == 'ja'
end
end
step "Ensure the test environment is clean"
on(agent, "rm -f #{target}")
step "Content Attribute: using a checksum from filebucket"
on(agent, "echo 'This is the checksum file contents' > #{target}")
step "Backup file into the filebucket"
on(agent, puppet_filebucket("backup --local #{target}"))
step "Modify file to force apply to retrieve file from local clientbucket"
on(agent, "echo 'This is the modified file contents' > #{target}")
dir = on(agent, puppet_filebucket("--configprint clientbucketdir")).stdout.chomp
sha256_manifest = %Q|
filebucket { 'local':
path => '#{dir}',
}
file { '#{target}':
ensure => present,
content => '{sha256}3b9238769b033b48073267b8baea00fa51c598dc14081da51f2e510c37c46a28',
backup => local,
}
|
step "Applying Manifest on Agent"
apply_manifest_on agent, sha256_manifest
step "Validate filebucket checksum file contents"
on(agent, "cat #{target}") do |result|
assert_match(/This is the checksum file content/, result.stdout, "File content not matched on #{agent}") unless agent['locale'] == 'ja'
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/resource/file/should_remove_dir.rb | acceptance/tests/resource/file/should_remove_dir.rb | test_name "should remove directory, but force required"
tag 'audit:high',
'audit:refactor', # Use block style `test_name`
'audit:acceptance'
agents.each do |agent|
target = agent.tmpdir("delete-dir")
step "clean up the system before we begin"
on(agent, "rm -rf #{target} ; mkdir -p #{target}")
step "verify we can't remove a directory without 'force'"
on(agent, puppet_resource("file", target, 'ensure=absent')) do |result|
fail_test "didn't tell us that force was required" unless
result.stdout.include? "Not removing directory; use 'force' to override" unless agent['locale'] == 'ja'
end
step "verify the directory still exists"
on(agent, "test -d #{target}")
step "verify we can remove a directory with 'force'"
on(agent, puppet_resource("file", target, 'ensure=absent', 'force=true'))
step "verify that the directory is gone"
on(agent, "test -d #{target}", :acceptable_exit_codes => [1])
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/tests/resource/file/ticket_7680-follow-symlinks.rb | acceptance/tests/resource/file/ticket_7680-follow-symlinks.rb | test_name "#7680: 'links => follow' should use the file source content"
tag 'audit:high',
'audit:refactor', # Use block style `test_name`
'audit:acceptance'
agents.each do |agent|
step "Create file content"
real_source = agent.tmpfile('follow_links_source')
dest = agent.tmpfile('follow_links_dest')
symlink = agent.tmpfile('follow_links_symlink')
on agent, "echo 'This is the real content' > #{real_source}"
if agent['platform'].include?('windows')
# cygwin ln doesn't behave properly, fallback to mklink,
# but that requires backslashes, that need to be escaped,
# and the link cannot exist prior.
on agent, "rm -f #{symlink}"
on agent, "cmd /c mklink #{symlink.gsub('/', '\\\\\\\\')} #{real_source.gsub('/', '\\\\\\\\')}"
else
on agent, "ln -sf #{real_source} #{symlink}"
end
manifest = <<-MANIFEST
file { '#{dest}':
ensure => file,
source => '#{symlink}',
links => follow,
}
MANIFEST
apply_manifest_on(agent, manifest, :trace => true)
on(agent, "cat #{dest}") do |result|
assert_match(/This is the real content/, result.stdout)
end
step "Cleanup"
[real_source, dest, symlink].each do |file|
on agent, "rm -f '#{file}'"
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/resource/file/ascii_diff_output_content_attribute.rb | acceptance/tests/resource/file/ascii_diff_output_content_attribute.rb | test_name "ASCII Diff Output of Content Attribute" do
tag 'audit:high',
'audit:acceptance'
sha256 = Digest::SHA256.new
agents.each do |agent|
step 'When handling ASCII files' do
target = agent.tmpfile('content_ASCII_file_test')
initial_text = 'Initial Text'
initial_text_sha_checksum = sha256.hexdigest(initial_text)
updated_text = 'Updated Text'
updated_text_sha_checksum = sha256.hexdigest(updated_text)
on agent, puppet('config', 'set', 'diff', 'diff')
step 'Ensure the test environment is clean' do
on agent, "rm -f #{target}"
end
teardown do
on agent, "rm -f #{target}"
end
step 'Create ASCII file using content' do
manifest = "file { '#{target}': content => '#{initial_text}', ensure => present , checksum => 'sha256'}"
on(agent, puppet('apply'), :stdin => manifest) do |result|
assert_match(/ensure: defined content as '{sha256}#{initial_text_sha_checksum}'/, result.stdout, "#{agent}: checksum of ASCII file not matched")
end
end
step 'Update existing ASCII file content' do
manifest = "file { '#{target}': content => '#{updated_text}', ensure => present , checksum => 'sha256'}"
on(agent, puppet('apply','--show_diff'), :stdin => manifest) do |result|
assert_match(/content: content changed '{sha256}#{initial_text_sha_checksum}' to '{sha256}#{updated_text_sha_checksum}'/, result.stdout, "#{agent}: checksum of ASCII file not matched after update")
assert_match(/^- ?#{initial_text}$/, result.stdout, "#{agent}: initial text not found in diff")
assert_match(/^\+ ?#{updated_text}$/, result.stdout, "#{agent}: updated text not found in diff")
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/resource/file/symbolic_modes.rb | acceptance/tests/resource/file/symbolic_modes.rb | test_name 'file resource: symbolic modes' do
confine :except, :platform => /^windows/
confine :to, {}, hosts.select {|host| !host[:roles].include?('master')}
tag 'audit:high',
'audit:acceptance'
require 'puppet/acceptance/temp_file_utils'
extend Puppet::Acceptance::TempFileUtils
class FileSymlink
attr_reader :mode, :path, :start_mode, :symbolic_mode
def initialize(base_dir, file_type, symbolic_mode, mode, start_mode=nil)
@base_dir = base_dir
@file_type = file_type
@symbolic_mode = symbolic_mode
@mode = mode
@start_mode = start_mode
if @start_mode.nil?
@path= "#{@base_dir}/#{@file_type}_#{@symbolic_mode}_#{@mode.to_s(8)}"
else
@path= "#{@base_dir}/#{@file_type}_#{@symbolic_mode}_#{@start_mode.to_s(8)}_#{@mode.to_s(8)}"
end
end
# does the mode of the file/directory change from start_mode to puppet apply
def mode_changes?
! @start_mode.nil? && @start_mode != @mode
end
def get_manifest
"file { #{@path.inspect}: ensure => '#{@file_type}', mode => '#{@symbolic_mode}' }"
end
end
class BaseTest
include Beaker::DSL::Assertions
def initialize(testcase, agent, base_dir)
@testcase = testcase
@agent = agent
@base_dir = base_dir
@file_list = []
@directory_list = []
end
def assert_mode(agent, path, expected_mode)
permissions = @testcase.stat(agent, path)
assert_equal(expected_mode, permissions[2], "'#{path}' current mode #{permissions[2].to_s(8)} doesn't match expected mode #{expected_mode.to_s(8)}")
end
def manifest
manifest_array = (@file_list + @directory_list).map {|x| x.get_manifest}
@testcase.step(manifest_array)
manifest_array.join("\n")
end
def puppet_reapply
@testcase.apply_manifest_on(@agent, manifest) do |apply_result|
refute_match(/mode changed/, apply_result.stdout, "reapplied the symbolic mode change")
(@file_list + @directory_list).each do |file|
refute_match(/#{Regexp.escape(file.path)}/, apply_result.stdout, "Expected to not see '#{file.path}' in 'puppet apply' output")
end
end
end
end
class CreateTest < BaseTest
def symlink_file(symbolic_mode, mode)
@file_list << FileSymlink.new(@base_dir, 'file', symbolic_mode, mode)
end
def symlink_directory(symbolic_mode, mode)
@directory_list << FileSymlink.new(@base_dir, 'directory', symbolic_mode, mode)
end
def puppet_apply
apply_result = @testcase.apply_manifest_on(@agent, manifest).stdout
(@file_list + @directory_list).each do |file|
assert_match(/File\[#{Regexp.escape(file.path)}\]\/ensure: created/, apply_result, "Failed to create #{file.path}")
assert_mode(@agent, file.path, file.mode)
end
end
end
class ModifyTest < BaseTest
def symlink_file(symbolic_mode, start_mode, mode)
@file_list << FileSymlink.new(@base_dir, 'file', symbolic_mode, mode, start_mode)
end
def symlink_directory(symbolic_mode, start_mode, mode)
@directory_list << FileSymlink.new(@base_dir, 'directory', symbolic_mode, mode, start_mode)
end
def create_starting_state
files = @file_list.collect {|x| "'#{x.path}'" }
directories = @directory_list.collect {|x| "'#{x.path}'" }
@testcase.on(@agent, "touch #{files.join(' ')}")
@testcase.on(@agent, "mkdir -p #{directories.join(' ')}")
@testcase.on(@agent, "chown symuser:symgroup #{files.join(' ')} #{directories.join(' ')}")
cmd_list = []
(@file_list + @directory_list).each do |file|
cmd_list << "chmod #{file.start_mode.to_s(8)} '#{file.path}'"
end
@testcase.on(@agent, cmd_list.join(' && '))
end
def puppet_apply
@testcase.step(manifest)
apply_result = @testcase.apply_manifest_on(@agent, manifest).stdout
@testcase.step(apply_result)
(@file_list + @directory_list).each do |file|
if file.mode_changes?
assert_match(/File\[#{Regexp.escape(file.path)}.* mode changed '#{'%04o' % file.start_mode}'.* to '#{'%04o' % file.mode}'/,
apply_result, "couldn't set mode to #{file.symbolic_mode}")
else
refute_match(/#{Regexp.escape(file.path)}.*mode changed/, apply_result, "reapplied the symbolic mode change for file #{file.path}")
end
assert_mode(@agent, file.path, file.mode)
end
end
end
# For your reference:
# 4000 the set-user-ID-on-execution bit
# 2000 the set-group-ID-on-execution bit
# 1000 the sticky bit
# 0400 Allow read by owner.
# 0200 Allow write by owner.
# 0100 For files, allow execution by owner. For directories, allow the
# owner to search in the directory.
# 0040 Allow read by group members.
# 0020 Allow write by group members.
# 0010 For files, allow execution by group members. For directories, allow
# group members to search in the directory.
# 0004 Allow read by others.
# 0002 Allow write by others.
# 0001 For files, allow execution by others. For directories allow others
# to search in the directory.
#
# On Solaris 11 (from man chmod):
#
# 20#0 Set group ID on execution if # is 7, 5, 3, or 1.
# Enable mandatory locking if # is 6, 4, 2, or 0.
# ...
# For directories, the set-gid bit can
# only be set or cleared by using symbolic mode.
# From https://www.gnu.org/software/coreutils/manual/html_node/Symbolic-Modes.html#Symbolic-Modes
# Users
# u the user who owns the file;
# g other users who are in the file's group;
# o all other users;
# a all users; the same as 'ugo'.
#
# Operations
# + to add the permissions to whatever permissions the users already have for the file;
# - to remove the permissions from whatever permissions the users already have for the file;
# = to make the permissions the only permissions that the users have for the file.
#
# Permissions
# r the permission the users have to read the file;
# w the permission the users have to write to the file;
# x the permission the users have to execute the file, or search it if it is a directory.
# s the meaning depends on which user (uga) the permission is associated with:
# to set set-user-id-on-execution, use 'u' in the users part of the symbolic mode and 's' in the permissions part.
# to set set-group-id-on-execution, use 'g' in the users part of the symbolic mode and 's' in the permissions part.
# to set both user and group-id-on-execution, omit the users part of the symbolic mode (or use 'a') and use 's' in the permissions part.
# t the restricted deletion flag (sticky bit), omit the users part of the symbolic mode (or use 'a') and use 't' in the permissions part.
# X execute/search permission is affected only if the file is a directory or already had execute permission.
#
# Note we do not currently support the Solaris (l) permission:
# l mandatory file and record locking refers to a file's ability to have its reading or writing
# permissions locked while a program is accessing that file.
#
agents.each do |agent|
is_solaris = agent['platform'].include?('solaris')
on(agent, puppet('resource user symuser ensure=present'))
on(agent, puppet('resource group symgroup ensure=present'))
base_dir_create = agent.tmpdir('symbolic-modes-create_test')
base_dir_modify = agent.tmpdir('symbolic-modes-modify_test')
teardown do
on(agent, puppet('resource user symuser ensure=absent'))
on(agent, puppet('resource group symgroup ensure=absent'))
on(agent, "rm -rf '#{base_dir_create}' '#{base_dir_modify}'")
end
create_test = CreateTest.new(self, agent, base_dir_create)
create_test.symlink_file('u=r', 00444)
create_test.symlink_file('u=w', 00244)
create_test.symlink_file('u=x', 00144)
create_test.symlink_file('u=rw', 00644)
create_test.symlink_file('u=rwx', 00744)
create_test.symlink_file('u=rwxt', 01744)
create_test.symlink_file('u=rwxs', 04744)
create_test.symlink_file('u=rwxts', 05744)
create_test.symlink_file('ug=r', 00444)
create_test.symlink_file('ug=rw', 00664)
create_test.symlink_file('ug=rwx', 00774)
create_test.symlink_file('ug=rwxt', 01774)
create_test.symlink_file('ug=rwxs', 06774)
create_test.symlink_file('ug=rwxts', 07774)
create_test.symlink_file('ugo=r', 00444)
create_test.symlink_file('ugo=rw', 00666)
create_test.symlink_file('ugo=rwx', 00777)
create_test.symlink_file('ugo=rwxt', 01777)
#create_test.symlink_file('ugo=rwxs', 06777) ## BUG, puppet creates 07777
create_test.symlink_file('ugo=rwxts', 07777)
create_test.symlink_file('u=rwx,go=rx', 00755)
create_test.symlink_file('u=rwx,g=rx,o=r', 00754)
create_test.symlink_file('u=rwx,g=rx,o=', 00750)
create_test.symlink_file('a=rwx', 00777)
create_test.symlink_file('u+r', 00644)
create_test.symlink_file('u+w', 00644)
create_test.symlink_file('u+x', 00744)
create_test.symlink_directory('u=r', 00455)
create_test.symlink_directory('u=w', 00255)
create_test.symlink_directory('u=x', 00155)
create_test.symlink_directory('u=rw', 00655)
create_test.symlink_directory('u=rwx', 00755)
create_test.symlink_directory('u=rwxt', 01755)
create_test.symlink_directory('u=rwxs', 04755)
create_test.symlink_directory('u=rwxts', 05755)
create_test.symlink_directory('ug=r', 00445)
create_test.symlink_directory('ug=rw', 00665)
create_test.symlink_directory('ug=rwx', 00775)
create_test.symlink_directory('ug=rwxt', 01775)
create_test.symlink_directory('ug=rwxs', 06775)
create_test.symlink_directory('ug=rwxts', 07775)
create_test.symlink_directory('ugo=r', 00444)
create_test.symlink_directory('ugo=rw', 00666)
create_test.symlink_directory('ugo=rwx', 00777)
create_test.symlink_directory('ugo=rwxt', 01777)
#create_test.symlink_directory('ugo=rwxs', 06777) ## BUG, puppet creates 07777
create_test.symlink_directory('ugo=rwxts', 07777)
create_test.symlink_directory('u=rwx,go=rx', 00755)
create_test.symlink_directory('u=rwx,g=rx,o=r', 00754)
create_test.symlink_directory('u=rwx,g=rx,o=', 00750)
create_test.symlink_directory('a=rwx', 00777)
create_test.symlink_directory('u+r', 00755)
create_test.symlink_directory('u+w', 00755)
create_test.symlink_directory('u+x', 00755)
create_test.puppet_apply()
create_test.puppet_reapply()
modify_test = ModifyTest.new(self, agent, base_dir_modify)
modify_test.symlink_file('u+r', 00200, 00600)
modify_test.symlink_file('u+r', 00600, 00600)
modify_test.symlink_file('u+w', 00500, 00700)
modify_test.symlink_file('u+w', 00400, 00600)
modify_test.symlink_file('u+x', 00700, 00700)
modify_test.symlink_file('u+x', 00600, 00700)
modify_test.symlink_file('u+X', 00100, 00100)
modify_test.symlink_file('u+X', 00200, 00200)
modify_test.symlink_file('u+X', 00410, 00510)
modify_test.symlink_file('a+X', 00600, 00600)
modify_test.symlink_file('a+X', 00700, 00711)
modify_test.symlink_file('u+s', 00744, 04744)
modify_test.symlink_file('g+s', 00744, 02744)
modify_test.symlink_file('u+t', 00744, 01744)
modify_test.symlink_file('u-r', 00200, 00200)
modify_test.symlink_file('u-r', 00600, 00200)
modify_test.symlink_file('u-w', 00500, 00500)
modify_test.symlink_file('u-w', 00600, 00400)
modify_test.symlink_file('u-x', 00700, 00600)
modify_test.symlink_file('u-x', 00600, 00600)
modify_test.symlink_file('u-s', 04744, 00744)
modify_test.symlink_file('g-s', 02744, 00744)
modify_test.symlink_file('u-t', 01744, 00744)
modify_test.symlink_directory('u+r', 00200, 00600)
modify_test.symlink_directory('u+r', 00600, 00600)
modify_test.symlink_directory('u+w', 00500, 00700)
modify_test.symlink_directory('u+w', 00400, 00600)
modify_test.symlink_directory('u+x', 00700, 00700)
modify_test.symlink_directory('u+x', 00600, 00700)
modify_test.symlink_directory('u+X', 00100, 00100)
modify_test.symlink_directory('u+X', 00200, 00300)
modify_test.symlink_directory('u+X', 00410, 00510)
modify_test.symlink_directory('a+X', 00600, 00711)
modify_test.symlink_directory('a+X', 00700, 00711)
modify_test.symlink_directory('u+s', 00744, 04744)
modify_test.symlink_directory('g+s', 00744, 02744)
modify_test.symlink_directory('u+t', 00744, 01744)
modify_test.symlink_directory('u-r', 00200, 00200)
modify_test.symlink_directory('u-r', 00600, 00200)
modify_test.symlink_directory('u-w', 00500, 00500)
modify_test.symlink_directory('u-w', 00600, 00400)
modify_test.symlink_directory('u-x', 00700, 00600)
modify_test.symlink_directory('u-x', 00600, 00600)
modify_test.symlink_directory('u-s', 04744, 00744)
# using chmod 2744 on a directory to set the start_mode fails on Solaris
modify_test.symlink_directory('g-s', 02744, 00744) unless is_solaris
modify_test.symlink_directory('u-t', 01744, 00744)
modify_test.create_starting_state
modify_test.puppet_apply
modify_test.puppet_reapply
# these raise
# test.assert_raises('')
# test.assert_raises(' ')
# test.assert_raises('u=X')
# test.assert_raises('u-X')
# test.assert_raises('+l')
# test.assert_raises('-l')
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/resource/file/ticket_8740_should_not_enumerate_root_directory.rb | acceptance/tests/resource/file/ticket_8740_should_not_enumerate_root_directory.rb | test_name "#8740: should not enumerate root directory"
confine :except, :platform => 'windows'
confine :except, :platform => 'osx'
tag 'audit:high',
'audit:refactor', # Use block style `test_name`
'audit:acceptance'
target = "/test-socket-#{$$}"
require 'puppet/acceptance/common_utils'
extend Puppet::Acceptance::CommandUtils
agents.each do |agent|
step "clean up the system before we begin"
on(agent, "rm -f #{target}")
step "create UNIX domain socket"
on(agent, "#{ruby_command(agent)} -e \"require 'socket'; UNIXServer::new('#{target}').close\"")
step "query for all files, which should return nothing"
on(agent, puppet_resource('file'), :acceptable_exit_codes => [1]) do |result|
assert_match(%r{Listing all file instances is not supported. Please specify a file or directory, e.g. puppet resource file /etc}, result.stderr)
end
["/", "/etc"].each do |file|
step "query '#{file}' directory, which should return single entry"
on(agent, puppet_resource('file', file)) do |result|
files = result.stdout.scan(/^file \{ '([^']+)'/).flatten
assert_equal(1, files.size, "puppet returned multiple files: #{files.join(', ')}")
assert_match(file, files[0], "puppet did not return file")
end
end
step "query file that does not exist, which should report the file is absent"
on(agent, puppet_resource('file', '/this/does/notexist')) do |result|
assert_match(/ensure\s+=>\s+'absent'/, result.stdout)
end
step "remove UNIX domain socket"
on(agent, "rm -f #{target}")
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/tests/resource/file/handle_fifo_files.rb | acceptance/tests/resource/file/handle_fifo_files.rb | test_name "should be able to handle fifo files"
tag 'audit:high',
'audit:acceptance'
confine :except, :platform => /windows/
def ensure_content_to_file_manifest(file_path, ensure_value)
return <<-MANIFEST
file { "#{file_path}":
ensure => #{ensure_value},
content => "Hello World"
}
MANIFEST
end
agents.each do |agent|
tmp_path = agent.tmpdir("tmpdir")
fifo_path = "#{tmp_path}/myfifo"
teardown do
agent.rm_rf(tmp_path)
end
step "create fifo" do
on(agent, "mkfifo #{fifo_path}")
end
step "check that fifo got created" do
on(agent, "ls -l #{fifo_path}") do |result|
assert(result.stdout.start_with?('p'))
end
end
step "puppet ensures given fifo is present" do
apply_manifest_on(agent, ensure_content_to_file_manifest(fifo_path, 'present'), :acceptable_exit_codes => [2]) do |result|
assert_match(/Warning: .+ Ensure set to :present but file type is fifo so no content will be synced/, result.stderr)
end
end
step "check that given file is still a fifo" do
on(agent, "ls -l #{fifo_path}") do |result|
assert(result.stdout.start_with?('p'))
end
end
step "puppet ensures given fifo is a regular file" do
apply_manifest_on(agent, ensure_content_to_file_manifest(fifo_path, 'file'), :acceptable_exit_codes => [0]) do |result|
assert_match(/Notice: .+\/myfifo\]\/ensure: defined content as '{/, result.stdout)
refute_match(/Warning: .+ Ensure set to :present but file type is fifo so no content will be synced/, result.stderr)
end
end
step "check that given fifo is now a regular file" do
on(agent, "ls -l #{fifo_path}") do |result|
assert(result.stdout.start_with?('-'))
end
end
step "check that given file now has desired content" do
on(agent, "cat #{fifo_path}") do |result|
assert_equal('Hello World', result.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/acceptance/tests/resource/file/source_attribute.rb | acceptance/tests/resource/file/source_attribute.rb | test_name "The source attribute" do
require 'puppet/acceptance/module_utils'
extend Puppet::Acceptance::ModuleUtils
tag 'audit:high',
'audit:acceptance',
'server'
@target_file_on_windows = 'C:/windows/temp/source_attr_test'
@target_file_on_nix = '/tmp/source_attr_test'
@target_dir_on_windows = 'C:/windows/temp/source_attr_test_dir'
@target_dir_on_nix = '/tmp/source_attr_test_dir'
# In case any of the hosts happens to be fips enabled we limit to the lowest
# common denominator.
checksums_fips = [nil, 'sha256', 'sha256lite', 'ctime', 'mtime']
checksums_no_fips = [nil, 'sha256', 'sha256lite', 'md5', 'md5lite', 'ctime', 'mtime']
fips_host_present = hosts.any? { |host| on(host, facter("fips_enabled")).stdout =~ /true/ }
if fips_host_present
checksums = checksums_fips
else
checksums = checksums_no_fips
end
orig_installed_modules = get_installed_modules_for_hosts hosts
teardown do
rm_installed_modules_from_hosts orig_installed_modules, (get_installed_modules_for_hosts hosts)
hosts.each do |host|
file_to_rm = host['platform'] =~ /windows/ ? @target_file_on_windows : @target_file_on_nix
dir_to_rm = host['platform'] =~ /windows/ ? @target_dir_on_windows : @target_dir_on_nix
checksums.each do |checksum_type|
on(host, "rm #{file_to_rm}#{checksum_type}", :acceptable_exit_codes => [0,1])
on(host, "rm -r #{dir_to_rm}#{checksum_type}", :acceptable_exit_codes => [0,1])
end
end
end
step "Setup - create environment and test module"
# set directories
testdir = master.tmpdir('file_source_attr')
env_dir = "#{testdir}/environments"
prod_dir = "#{env_dir}/production"
manifest_dir = "#{prod_dir}/manifests"
manifest_file = "#{prod_dir}/manifests/site.pp"
module_dir = "#{prod_dir}/modules"
test_module_dir = "#{module_dir}/source_test_module"
test_module_manifests_dir = "#{test_module_dir}/manifests"
test_module_files_dir = "#{test_module_dir}/files"
mod_manifest_file = "#{test_module_manifests_dir}/init.pp"
mod_source_file = "#{test_module_files_dir}/source_file"
mod_source_dir = "#{test_module_files_dir}/source_dir"
mod_source_dir_file = "#{mod_source_dir}/source_dir_file"
mod_source = ' the content is present'
def mod_manifest_entry(checksum_type = nil)
checksum = if checksum_type then "checksum => #{checksum_type}," else "" end
manifest = <<-EOF
$target_file#{checksum_type} = $::kernel ? {
\\'windows\\' => \\'#{@target_file_on_windows}#{checksum_type}\\',
default => \\'#{@target_file_on_nix}#{checksum_type}\\'
}
file { $target_file#{checksum_type}:
source => \\'puppet:///modules/source_test_module/source_file\\',
#{checksum}
ensure => present
}
$target_dir#{checksum_type} = $::kernel ? {
\\'windows\\' => \\'#{@target_dir_on_windows}#{checksum_type}\\',
default => \\'#{@target_dir_on_nix}#{checksum_type}\\'
}
file { $target_dir#{checksum_type}:
source => \\'puppet:///modules/source_test_module/source_dir\\',
#{checksum}
ensure => directory,
recurse => true
}
EOF
manifest
end
mod_manifest = <<-EOF
class source_test_module {
#{checksums.collect { |checksum_type| mod_manifest_entry(checksum_type) }.join("\n")}
}
EOF
env_manifest = <<-EOF
filebucket { \\'main\\':
server => \\'#{master}\\',
path => false,
}
File { backup => \\'main\\' }
node default {
include source_test_module
}
EOF
# apply manifests to setup environment and modules
apply_manifest_on(master, <<-MANIFEST, :catch_failures => true)
File {
ensure => directory,
mode => '0755',
}
file {
'#{testdir}':;
'#{env_dir}':;
'#{prod_dir}':;
'#{manifest_dir}':;
'#{module_dir}':;
'#{test_module_dir}':;
'#{test_module_manifests_dir}':;
'#{test_module_files_dir}':;
}
file { '#{mod_manifest_file}':
ensure => file,
mode => '0644',
content => '#{mod_manifest}',
}
file { '#{mod_source_file}':
ensure => file,
mode => '0644',
content => '#{mod_source}',
}
file { '#{mod_source_dir}':
ensure => directory,
mode => '0755'
}
file { '#{mod_source_dir_file}':
ensure => file,
mode => '0644',
content => '#{mod_source}',
}
file { '#{manifest_file}':
ensure => file,
mode => '0644',
content => '#{env_manifest}',
}
MANIFEST
step "When using a puppet:/// URI with a master/agent setup"
master_opts = {
'main' => {
'environmentpath' => "#{env_dir}",
},
}
with_puppet_running_on(master, master_opts, testdir) do
agents.each do |agent|
# accept an exit code of 2 which is returned if there are changes
step "create file the first run"
on(agent, puppet('agent', "--test"), :acceptable_exit_codes => [0,2]) do
file_to_check = agent['platform'] =~ /windows/ ? @target_file_on_windows : @target_file_on_nix
dir_to_check = agent['platform'] =~ /windows/ ? @target_dir_on_windows : @target_dir_on_nix
checksums.each do |checksum_type|
on agent, "cat #{file_to_check}#{checksum_type}" do |result|
assert_match(/the content is present/, result.stdout, "Result file not created #{checksum_type}")
end
on agent, "cat #{dir_to_check}#{checksum_type}/source_dir_file" do |result|
assert_match(/the content is present/, result.stdout, "Result file not created #{checksum_type}")
end
end
end
step "second run should not update file"
on(agent, puppet('agent', "--test"), :acceptable_exit_codes => [0,2]) do |result|
refute_match(/content changed.*(md5|sha256)/, result.stdout, "Shouldn't have overwritten any files")
# When using ctime/mtime, the agent compares the values from its
# local file with the values on the master to determine if the
# file is insync or not. If during the first run, the agent
# creates the files, and the resulting ctime/mtime are still
# behind the times on the master, then the 2nd agent run will
# consider the file to not be insync, and will update it
# again. This process will repeat until the agent updates the
# file, and the resulting ctime/mtime are after the values on
# the master, at which point it will have converged.
if result.stdout =~ /content changed.*ctime/
Log.warn "Agent did not converge using ctime"
end
if result.stdout =~ /content changed.*mtime/
Log.warn "Agent did not converge using mtime"
end
end
end
=begin
# Disable flaky test until PUP-4115 is addressed.
step "touch files and verify they're updated with ctime/mtime"
# wait until we're not at the mtime of files on the agents
# this could be done cross-platform using Puppet, but a single puppet query is unlikely to be less than a second,
# and iterating over all agents would be much slower
sleep(1)
on master, "touch #{mod_source_file} #{mod_source_dir_file}"
agents.each do |agent|
on(agent, puppet('agent', "--test"), :acceptable_exit_codes => [0,2]) do
file_to_check = agent['platform'] =~ /windows/ ? @target_file_on_windows : @target_file_on_nix
dir_to_check = agent['platform'] =~ /windows/ ? @target_dir_on_windows : @target_dir_on_nix
['ctime', 'mtime'].each do |time_type|
assert_match(/File\[#{file_to_check}#{time_type}\]\/content: content changed/, stdout, "Should have updated files")
assert_match(/File\[#{dir_to_check}#{time_type}\/source_dir_file\]\/content: content changed/, stdout, "Should have updated files")
end
end
end
=end
end
# TODO: Add tests for puppet:// URIs with multi-master/agent setups.
step "When using puppet apply"
agents.each do |agent|
step "Setup testing local file sources"
# create one larger manifest with all the files so we don't have to run
# puppet apply per each checksum_type
localsource_testdir = agent.tmpdir('local_source_file_test')
source = "#{localsource_testdir}/source_mod/files/source"
on agent, "mkdir -p #{File.dirname(source)}"
# don't put a 'z' in this content
source_content = 'Yay, this is the local file. I have to be bigger than 512 bytes so that my masters. yadda yadda yadda not a nice thing. lorem ipsem. alice bob went to fetch a pail of water. Lorem ipsum dolor sit amet, pede ipsum nam wisi lectus eget, sociis sed, commodo vitae velit eleifend. Vestibulum orci feugiat erat etiam pellentesque sed, imperdiet a integer nulla, mi tincidunt suscipit. Nec sed, mi tortor, in a consequat mattis proin scelerisque eleifend. In lectus magna quam. Magna quam vitae sociosqu. Adipiscing laoreet.'
create_remote_file agent, source, source_content
local_apply_manifest = ""
target = {}
checksums.each do |checksum_type|
target[checksum_type] = "#{localsource_testdir}/target#{checksum_type}"
checksum = if checksum_type then "checksum => #{checksum_type}," else "" end
local_apply_manifest.concat("file { '#{target[checksum_type]}': source => '#{source}', ensure => present, #{checksum} }\n")
end
apply_manifest_on agent, local_apply_manifest
checksums.each do |checksum_type|
step "Using a local file path. #{checksum_type}"
on(agent, "cat #{target[checksum_type]}") do |result|
assert_match(/Yay, this is the local file./, result.stdout, "FIRST: File contents not matched on #{agent}")
end
end
step "second run should not update any files"
apply_manifest_on(agent, local_apply_manifest) do |result|
refute_match(/content changed/, result.stdout, "Shouldn't have overwrote any files")
end
# changes in source file producing updates is tested elsewhere
step "subsequent run should not update file using <checksum>lite if only after byte 512 is changed"
byte_after_md5lite = 513
source_content[byte_after_md5lite] = 'z'
create_remote_file agent, source, source_content
if fips_host_present
apply_manifest_on(agent, "file { '#{localsource_testdir}/targetsha256lite': source => '#{source}', ensure => present, checksum => sha256lite }") do |result|
refute_match(/(content changed|defined content)/, result.stdout, "Shouldn't have overwrote any files")
end
else
apply_manifest_on(agent, "file { '#{localsource_testdir}/targetmd5lite': source => '#{source}', ensure => present, checksum => md5lite } file { '#{localsource_testdir}/targetsha256lite': source => '#{source}', ensure => present, checksum => sha256lite }") do |result|
refute_match(/(content changed|defined content)/, result.stdout, "Shouldn't have overwrote any files")
end
end
local_module_manifest = ""
checksums.each do |checksum_type|
on agent, "rm -rf #{target[checksum_type]}"
checksum = if checksum_type then "checksum => #{checksum_type}," else "" end
local_module_manifest.concat("file { '#{target[checksum_type]}': source => 'puppet:///modules/source_mod/source', ensure => present, #{checksum} }\n")
end
localsource_test_manifest = agent.tmpfile('local_source_test_manifest')
create_remote_file agent, localsource_test_manifest, local_module_manifest
on agent, puppet( %{apply --modulepath=#{localsource_testdir} #{localsource_test_manifest}} )
checksums.each do |checksum_type|
step "Using a puppet:/// URI with checksum type: #{checksum_type}"
on(agent, "cat #{target[checksum_type]}") do |result|
assert_match(/Yay, this is the local file./, result.stdout, "FIRST: File contents not matched on #{agent}")
end
end
step "second run should not update any files using apply with puppet:/// URI source"
on(agent, puppet( %{apply --modulepath=#{localsource_testdir} #{localsource_test_manifest}} )) do |result|
refute_match(/content changed/, result.stdout, "Shouldn't have overwrote any files")
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/resource/file/bin_diff_output_content_attribute.rb | acceptance/tests/resource/file/bin_diff_output_content_attribute.rb | test_name "Binary Diff Output of Content Attribute" do
tag 'audit:high',
'audit:acceptance'
# cannot test binary diff on windows2012r2_ja-64-1
# Error: Could not write report for afire-lien.delivery.puppetlabs.net at C:/ProgramData/PuppetLabs/puppet/cache/reports/afire-lien.delivery.puppetlabs.net/201912041455.yaml: anchor value must contain alphanumerical characters only
# Error: Could not send report: anchor value must contain alphanumerical characters only
confine :except, {}, hosts.select { |host| host[:platform]=~ /windows/ && host[:locale] == 'ja' }
sha256 = Digest::SHA256.new
agents.each do |agent|
step 'When handling binary files' do
target = agent.tmpfile('content_binary_file_test')
initial_bin_data = "\xc7\xd1\xfc\x84"
initial_base64_data = Base64.encode64(initial_bin_data).chomp
initial_sha_checksum = sha256.hexdigest(initial_bin_data)
updated_bin_data = "\xc7\xd1\xfc\x85"
updated_base64_data = Base64.encode64(updated_bin_data).chomp
updated_sha_checksum = sha256.hexdigest(updated_bin_data)
on(agent, puppet('config', 'set', 'diff', 'diff'))
agent_default_external_encoding=nil
on(agent, "#{ruby_command(agent)} -e \"puts Encoding.default_external\"") do |result|
agent_default_external_encoding = result.stdout.chomp
end
if agent_default_external_encoding && agent_default_external_encoding != Encoding.default_external
begin
initial_bin_data=initial_bin_data.force_encoding(agent_default_external_encoding).encode(Encoding.default_external)
updated_bin_data=updated_bin_data.force_encoding(agent_default_external_encoding).encode(Encoding.default_external)
rescue Encoding::InvalidByteSequenceError
#depending on agent_default_external_encoding, the conversion may fail, but this should not be a problem
end
end
teardown do
on agent, "rm -f #{target}"
end
step 'Ensure the test environment is clean' do
on agent, "rm -f #{target}"
end
step 'Create binary file using content' do
manifest = "file { '#{target}': content => Binary('#{initial_base64_data}'), ensure => present , checksum => 'sha256'}"
on(agent, puppet('apply'), :stdin => manifest) do |result|
assert_match(/ensure: defined content as '{sha256}#{initial_sha_checksum}'/, result.stdout, "#{agent}: checksum of binary file not matched")
end
end
step 'Update existing binary file content' do
manifest = "file { '#{target}': content => Binary('#{updated_base64_data}'), ensure => present , checksum => 'sha256'}"
on(agent, puppet('apply','--show_diff'), :stdin => manifest) do |result|
assert_match(/content: content changed '{sha256}#{initial_sha_checksum}' to '{sha256}#{updated_sha_checksum}'/, result.stdout, "#{agent}: checksum of binary file not matched after update")
refute_match(/content: Received a Log attribute with invalid encoding:/, result.stdout, "#{agent}: Received a Log attribute with invalid encoding")
if initial_bin_data.valid_encoding? && updated_bin_data.valid_encoding?
assert_match(/^- ?#{initial_bin_data}$/, result.stdout, "#{agent}: initial utf-8 data not found in binary diff")
assert_match(/^\+ ?#{updated_bin_data}$/, result.stdout, "#{agent}: updated utf-8 data not found in binary diff")
else
assert_match(/Binary files #{target} and .* differ/, result.stdout, "#{agent}: Binary file diff notice not matched")
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/resource/file/handle_fifo_files_when_recursing.rb | acceptance/tests/resource/file/handle_fifo_files_when_recursing.rb | test_name "should be able to handle fifo files when recursing"
tag 'audit:high',
'audit:acceptance'
confine :except, :platform => /windows/
def ensure_owner_recursively_manifest(path, owner_value)
return <<-MANIFEST
file { "#{path}":
ensure => present,
recurse => true,
owner => #{owner_value}
}
MANIFEST
end
agents.each do |agent|
initial_owner = ''
random_user = "pl#{rand(999).to_i}"
tmp_path = agent.tmpdir("tmpdir")
fifo_path = "#{tmp_path}/myfifo"
teardown do
agent.rm_rf(tmp_path)
end
step "create fifo file" do
on(agent, "mkfifo #{fifo_path}")
on(agent, puppet("resource user #{random_user} ensure=absent"))
end
step "check that fifo file got created" do
on(agent, "ls -l #{fifo_path}") do |result|
assert(result.stdout.start_with?('p'))
initial_owner = result.stdout.split[2]
end
end
step "create a new user" do
on(agent, puppet("resource user #{random_user} ensure=present"))
end
step "puppet ensures '#{random_user}' as owner of path" do
apply_manifest_on(agent, ensure_owner_recursively_manifest(tmp_path, random_user), :acceptable_exit_codes => [0]) do |result|
assert_match(/#{tmp_path}\]\/owner: owner changed '#{initial_owner}' to '#{random_user}'/, result.stdout)
refute_match(/Error: .+ Failed to generate additional resources using ‘eval_generate’: Cannot manage files of type fifo/, result.stderr)
end
end
step "check that given file is still a fifo" do
on(agent, "ls -l #{fifo_path}") do |result|
assert(result.stdout.start_with?('p'))
end
end
step "check ownership of fifo file" do
on(agent, "ls -l #{fifo_path}") do |result|
user = result.stdout.split[2]
assert_equal(random_user, user)
end
end
step "check ownership of tmp folder" do
on(agent, "ls -ld #{tmp_path}") do |result|
user = result.stdout.split[2]
assert_equal(random_user, user)
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/resource/file/should_remove_file.rb | acceptance/tests/resource/file/should_remove_file.rb | test_name "should remove file"
tag 'audit:high',
'audit:refactor', # Use block style `test_name`
'audit:acceptance'
agents.each do |agent|
target = agent.tmpfile('delete-file')
step "clean up the system before we begin"
on agent, "rm -rf #{target} && touch #{target}"
step "verify we can remove a file"
on(agent, puppet_resource("file", target, 'ensure=absent'))
step "verify that the file is gone"
on agent, "test -e #{target}", :acceptable_exit_codes => [1]
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/tests/resource/file/should_create_directory.rb | acceptance/tests/resource/file/should_create_directory.rb | test_name "should create directory"
tag 'audit:high',
'audit:refactor', # Use block style `test_name`
'audit:acceptance'
agents.each do |agent|
target = agent.tmpfile("create-dir")
teardown do
step "clean up after the test run" do
on(agent, "rm -rf #{target}")
end
end
step "verify we can create a directory" do
on(agent, puppet_resource("file", target, 'ensure=directory'))
end
step "verify the directory was created" do
on(agent, "test -d #{target}")
end
dir_manifest = agent.tmpfile("dir-resource")
create_remote_file(agent, dir_manifest, <<-PP)
$dir='#{target}'
$same_dir='#{target}/'
file {$dir:
ensure => directory,
}
file { $same_dir:
ensure => directory,
}
PP
step "verify we can't create same dir resource with a trailing slash" do
options = {:acceptable_exit_codes => [1]}
on(agent, puppet_apply("--noop #{dir_manifest}"), options) do |result|
unless agent['locale'] == 'ja'
assert_match('Cannot alias File', result.output,
'duplicate directory resources did not fail properly')
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/resource/file/should_create_empty.rb | acceptance/tests/resource/file/should_create_empty.rb | test_name "should create empty file for 'present'"
tag 'audit:high',
'audit:refactor', # Use block style `test_name`
'audit:acceptance'
agents.each do |agent|
target = agent.tmpfile("empty")
step "clean up the system before we begin"
on(agent, "rm -rf #{target}")
step "verify we can create an empty file"
on(agent, puppet_resource("file", target, 'ensure=present'))
step "verify the target was created"
on(agent, "test -f #{target} && test ! -s #{target}")
step "clean up after the test run"
on(agent, "rm -rf #{target}")
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/tests/resource/file/should_create_symlink.rb | acceptance/tests/resource/file/should_create_symlink.rb | test_name "should create symlink"
tag 'audit:high',
'audit:refactor', # Use block style `test_name`
'audit:acceptance'
def message
'hello world'
end
def reset_link_and_target(agent, link, target)
step "clean up the system before we begin"
on agent, "rm -rf #{target} #{link}"
on agent, "echo '#{message}' > #{target}"
end
def verify_symlink(agent, link, target)
step "verify the symlink was created"
on(agent, "test -L #{link} && test -f #{link}")
step "verify the symlink points to a file"
on(agent, "test -f #{target}")
step "verify the content is identical on both sides"
on(agent, "cat #{link}") do |result|
fail_test "link missing content" unless result.stdout.include?(message)
end
on(agent, "cat #{target}") do |result|
fail_test "target missing content" unless result.stdout.include?(message)
end
end
agents.each do |agent|
if agent.platform.variant == 'windows'
# symlinks are supported only on Vista+ (version 6.0 and higher)
on(agent, facter('kernelmajversion')) do |result|
skip_test "Test not supported on this platform" if result.stdout.chomp.to_f < 6.0
end
end
link_file = agent.tmpfile("symlink-link")
target_file = agent.tmpfile("symlink-target")
link_dir = agent.tmpdir("dir_symlink-link")
target_dir = agent.tmpdir("dir-symlink-target")
reset_link_and_target(agent, link_file, target_file)
reset_link_and_target(agent, link_dir, target_dir)
step "verify we can create a symlink with puppet resource"
on(agent, puppet_resource("file", "#{link_file}", "ensure=#{target_file}"))
verify_symlink(agent, link_file, target_file)
reset_link_and_target(agent, link_file, target_file)
step "verify that 'links => manage' preserves a symlink"
apply_manifest_on(agent, "file { '#{link_file}': ensure => link, target => '#{target_file}', links => manage }")
verify_symlink(agent, link_file, target_file)
reset_link_and_target(agent, link_file, target_file)
step "verify that 'links => manage' and 'recurse => true' preserves links in a directory"
on(agent, puppet_resource("file", target_dir, "ensure=directory"))
reset_link_and_target(agent, link_dir, "#{target_dir}/symlink-target")
apply_manifest_on(agent, "file { '#{link_dir}': ensure => directory, target => '#{target_dir}', links => manage, recurse => true }")
verify_symlink(agent, "#{link_dir}/symlink-target", "#{target_dir}/symlink-target")
step "clean up after the test run"
on agent, "rm -rf #{target_file} #{link_file} #{target_dir} #{link_dir}"
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/tests/resource/file/ticket_6448_file_with_utf8_source.rb | acceptance/tests/resource/file/ticket_6448_file_with_utf8_source.rb | test_name 'Ensure a file resource can have a UTF-8 source attribute, content, and path when served via a module' do
tag 'audit:high',
'broken:images',
'audit:acceptance',
'server'
require 'puppet/acceptance/environment_utils'
extend Puppet::Acceptance::EnvironmentUtils
require 'puppet/acceptance/agent_fqdn_utils'
extend Puppet::Acceptance::AgentFqdnUtils
tmp_environment = mk_tmp_environment_with_teardown(master, File.basename(__FILE__, '.*'))
agent_tmp_dirs = {}
agents.each do |agent|
agent_tmp_dirs[agent_to_fqdn(agent)] = agent.tmpdir(tmp_environment)
end
teardown do
# note - master teardown is registered by #mk_tmp_environment_with_teardown
step 'remove all test files on agents' do
agents.each do |agent|
on(agent, "rm -r '#{agent_tmp_dirs[agent_to_fqdn(agent)]}'", :accept_all_exit_codes => true)
on(agent, puppet('config print lastrunfile')) do |command_result|
agent.rm_rf(command_result.stdout)
end
end
end
end
step 'create unicode source file served via module on master' do
# 静 \u9759 0xE9 0x9D 0x99 http://www.fileformat.info/info/unicode/char/9759/index.htm
# 的 \u7684 0xE7 0x9A 0x84 http://www.fileformat.info/info/unicode/char/7684/index.htm
# ☃ \2603 0xE2 0x98 0x83 http://www.fileformat.info/info/unicode/char/2603/index.htm
setup_module_on_master = <<-MASTER_MANIFEST
File {
ensure => directory,
mode => "0755",
}
file {
'#{environmentpath}/#{tmp_environment}/modules/utf8_file_module':;
'#{environmentpath}/#{tmp_environment}/modules/utf8_file_module/files':;
}
file { '#{environmentpath}/#{tmp_environment}/modules/utf8_file_module/files/\u9759\u7684':
ensure => file,
content => "\u2603"
}
MASTER_MANIFEST
apply_manifest_on(master, setup_module_on_master, :expect_changes => true)
end
step 'create a site.pp on master containing a unicode file resource' do
site_pp_contents = <<-SITE_PP
\$test_path = \$facts['networking']['fqdn'] ? #{agent_tmp_dirs}
file { "\$test_path/\uff72\uff67\u30d5\u30eb":
ensure => present,
source => "puppet:///modules/utf8_file_module/\u9759\u7684",
}
SITE_PP
create_site_pp = <<-CREATE_SITE_PP
file { "#{environmentpath}/#{tmp_environment}/manifests/site.pp":
ensure => file,
content => @(UTF8)
#{site_pp_contents}
| UTF8
}
CREATE_SITE_PP
apply_manifest_on(master, create_site_pp, :expect_changes => true)
end
step 'ensure agent can manage unicode file resource' do
# イ \uff72 0xEF 0xBD 0xB2 http://www.fileformat.info/info/unicode/char/ff72/index.htm
# ァ \uff67 0xEF 0xBD 0xA7 http://www.fileformat.info/info/unicode/char/ff67/index.htm
# フ \u30d5 0xE3 0x83 0x95 http://www.fileformat.info/info/unicode/char/30d5/index.htm
# ル \u30eb 0xE3 0x83 0xAB http://www.fileformat.info/info/unicode/char/30eb/index.htm
with_puppet_running_on(master, {}) do
agents.each do |agent|
on(agent, puppet("agent -t --environment '#{tmp_environment}'"), :acceptable_exit_codes => 2)
on(agent, "cat '#{agent_tmp_dirs[agent_to_fqdn(agent)]}/\uff72\uff67\u30d5\u30eb'") do |result|
assert_match("\u2603", result.stdout, "managed UTF-8 file contents '#{result.stdout}' did not match expected value '\u2603'")
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/resource/user/should_modify_while_managing_home.rb | acceptance/tests/resource/user/should_modify_while_managing_home.rb | test_name "should modify a user without changing home directory (pending #19542)"
tag 'audit:high',
'audit:refactor', # Use block style `test_run`
'audit:acceptance' # Could be done as integration tests, but would
# require changing the system running the test
# in ways that might require special permissions
# or be harmful to the system running the test
require 'puppet/acceptance/windows_utils'
extend Puppet::Acceptance::WindowsUtils
name = "pl#{rand(999999).to_i}"
pw = "Passwrd-#{rand(999999).to_i}"[0..11]
def get_home_dir(host, user_name)
home_dir = nil
on host, puppet_resource('user', user_name) do |result|
home_dir = result.stdout.match(/home\s*=>\s*'([^']+)'/m)[1]
end
home_dir
end
agents.each do |agent|
home_prop = nil
case agent['platform']
when /windows/
home_prop = "home='#{profile_base(agent)}\\#{name}'"
when /solaris/
pending_test("managehome needs work on solaris")
when /osx/
skip_test("OSX doesn't support managehome")
# we don't get here
end
teardown do
step "delete the user"
agent.user_absent(name)
agent.group_absent(name)
end
step "ensure the user is present with managehome"
on agent, puppet_resource('user', name, ["ensure=present", "managehome=true", "password=#{pw}", home_prop].compact)
step "find the current home dir"
home_dir = get_home_dir(agent, name)
step "modify the user"
on agent, puppet_resource('user', name, ["ensure=present", "managehome=true", "home='#{home_dir}_foo'"]) do |result|
# SHOULD: user resource output should contain the new home directory
pending_test "when #19542 is reimplemented correctly"
end
# SHOULD: old home directory should not exist in the filesystem
# SHOULD: new home directory should exist in the filesystem
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/tests/resource/user/should_manage_roles_on_windows.rb | acceptance/tests/resource/user/should_manage_roles_on_windows.rb | test_name "Manage roles for a Windows user" do
confine :to, :platform => 'windows'
tag 'audit:high',
'audit:acceptance'
require 'puppet/acceptance/windows_utils'
extend Puppet::Acceptance::WindowsUtils
def user_manifest(name, 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
user { '#{name}':
#{params_str}
}
MANIFEST
end
newUser = "tempUser#{rand(999999).to_i}"
teardown do
on(agent, puppet("resource user #{newUser} ensure=absent")) do |result|
assert_match(/User\[#{newUser}\]\/ensure: removed/, result.stdout)
end
end
agents.each do |agent|
step "Create a new user named #{newUser}" do
apply_manifest_on(agent, user_manifest(newUser, ensure: :present), expect_changes: true) do |result|
assert_match(/User\[#{newUser}\]\/ensure: created/, result.stdout)
end
end
step "Verify that a new user has no roles" do
on(agent, puppet("resource user #{newUser}")) do |result|
refute_match(/roles\s+=>/, result.stdout)
end
end
step "Verify that puppet can grant #{newUser} a right" do
apply_manifest_on(agent, user_manifest(newUser, roles: ['SeServiceLogonRight']), expect_changes: true) do |result|
assert_match(/User\[#{newUser}\]\/roles: roles changed to 'SeServiceLogonRight'/, result.stdout)
end
end
step "Verify that puppet can grant #{newUser} a privilege also" do
apply_manifest_on(agent, user_manifest(newUser, roles: ['SeBackupPrivilege']), expect_changes: true) do |result|
assert_match(/User\[#{newUser}\]\/roles: roles changed SeServiceLogonRight to 'SeBackupPrivilege,SeServiceLogonRight'/, result.stdout)
end
end
step "Verify that puppet can not grant #{newUser} an invalid role" do
apply_manifest_on(agent, user_manifest(newUser, roles: ['InvalidRoleName']), :acceptable_exit_codes => [4], catch_changes: true) do |result|
assert_match(/Calling `LsaAddAccountRights` returned 'Win32 Error Code 0x00000521'. One or more of the given rights\/privilleges are incorrect./, result.stderr)
end
end
step "Verify that puppet can remove all of #{newUser}'s roles when managing :roles as an empty array and :role_membership as inclusive" do
apply_manifest_on(agent, user_manifest(newUser, roles: [], role_membership: :inclusive), expect_changes: true) do |result|
assert_match(/User\[#{newUser}\]\/roles: roles changed SeBackupPrivilege,SeServiceLogonRight to ''/, result.stdout)
end
end
step "Verify that puppet can grant #{newUser} more than one right at the same time" do
apply_manifest_on(agent, user_manifest(newUser, roles: ['SeDenyServiceLogonRight', 'SeDenyBatchLogonRight']), expect_changes: true) do |result|
assert_match(/User\[#{newUser}\]\/roles: roles changed to 'SeDenyBatchLogonRight,SeDenyServiceLogonRight'/, result.stdout)
end
end
step "Verify that :role_membership managed as minimum just appends given role to existing ones" do
apply_manifest_on(agent, user_manifest(newUser, roles: ['SeBackupPrivilege'], role_membership: :minimum), expect_changes: true) do |result|
assert_match(/User\[#{newUser}\]\/roles: roles changed SeDenyServiceLogonRight,SeDenyBatchLogonRight to 'SeBackupPrivilege,SeDenyBatchLogonRight,SeDenyServiceLogonRight'/, result.stdout)
end
end
step "Verify that :roles noops when #{newUser} already has given role while managing :role_membership as minimum" do
apply_manifest_on(agent, user_manifest(newUser, roles: ['SeBackupPrivilege'], role_membership: :minimum), catch_changes: true) do |result|
refute_match(/User\[#{newUser}\]\/roles: roles changed/, result.stdout)
end
end
step "Verify that while not managing :role_membership, the behaviour remains the same, with noop from :roles when #{newUser} already has the given role" do
apply_manifest_on(agent, user_manifest(newUser, roles: ['SeBackupPrivilege']), catch_changes: true) do |result|
refute_match(/User\[#{newUser}\]\/roles: roles changed/, result.stdout)
end
end
step "Verify that while managing :role_membership as inclusive, #{newUser} remains only with the given roles" do
apply_manifest_on(agent, user_manifest(newUser, roles: ['SeBackupPrivilege', 'SeServiceLogonRight'], role_membership: :inclusive), expect_changes: true) do |result|
assert_match(/User\[#{newUser}\]\/roles: roles changed SeBackupPrivilege,SeDenyServiceLogonRight,SeDenyBatchLogonRight to 'SeBackupPrivilege,SeServiceLogonRight'/, 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/resource/user/should_manage_groups.rb | acceptance/tests/resource/user/should_manage_groups.rb | test_name "should correctly manage the groups property for the User resource" do
# NOTE: These tests run for only some of our supported platforms.
# We should eventually update them to work with all of our
# supported platforms where managing the groups property makes
# sense.
confine :except, :platform => /windows/
tag 'audit:high',
'audit:acceptance' # Could be done as integration tests, but would
# require changing the system running the test
# in ways that might require special permissions
# or be harmful to the system running the test
require 'puppet/acceptance/common_utils'
extend Puppet::Acceptance::BeakerUtils
def random_name
"pl#{rand(999999).to_i}"
end
def user_manifest(user, 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
user { '#{user}':
#{params_str}
}
MANIFEST
end
def groups_of(host, user)
# The setup step should have already set :privatebindir on the
# host. We only include the default here to make this routine
# work for local testing, which sometimes skips the setup step.
privatebindir = host.has_key?(:privatebindir) ? host[:privatebindir] : '/opt/puppetlabs/puppet/bin'
# This bit of code reads the user's groups from the /etc/group file.
result = on(host, "#{privatebindir}/ruby -e \"require 'puppet'; puts(Puppet::Util::POSIX.groups_of('#{user}').to_s)\"")
Kernel.eval(result.stdout.chomp)
end
agents.each do |agent|
groups = 5.times.collect { random_name }
groups.each { |group| agent.group_absent(group) }
# We want to ensure that Beaker destroys the user first before
# the groups. Otherwise the teardown step will fail b/c we will
# be trying to remove the user's primary group before removing
# the user.
user = random_name
agent.user_absent(user)
teardown { agent.user_absent(user) }
step 'Creating the Groups' do
groups.each do |group|
agent.group_present(group)
teardown { agent.group_absent(group) }
end
end
user_groups = [groups[0], groups[1]]
primary_group = groups[2]
step 'Ensure that the user is created with the specified groups' do
# We use inclusive membership to ensure that the user's only a member
# of our groups and no other group.
manifest = user_manifest(user, groups: user_groups, gid: primary_group, membership: :inclusive)
apply_manifest_on(agent, manifest)
assert_matching_arrays(user_groups, groups_of(agent, user), "The user was not successfully created with the specified groups!")
end
step "Verify that Puppet errors when one of the groups does not exist" do
manifest = user_manifest(user, groups: ['nonexistent_group'])
apply_manifest_on(agent, manifest) do |result|
assert_match(/Error:.*#{user}/, result.stderr, "Puppet fails to report an error when one of the groups in the groups property does not exist")
end
end
primary_group = groups[3]
step "Verify that modifying the primary group does not change the user's groups" do
manifest = user_manifest(user, gid: primary_group)
apply_manifest_on(agent, manifest)
assert_matching_arrays(user_groups, groups_of(agent, user), "The user's groups changed after modifying the primary group")
end
step "Verify that Puppet noops when the user's groups are already set" do
manifest = user_manifest(user, groups: user_groups)
apply_manifest_on(agent, manifest, catch_changes: true)
assert_matching_arrays(user_groups, groups_of(agent, user), "The user's groups somehow changed despite Puppet reporting a noop")
end
step "Verify that Puppet enforces minimum group membership" do
new_groups = [groups[2], groups[4]]
manifest = user_manifest(user, groups: new_groups, membership: :minimum)
apply_manifest_on(agent, manifest)
user_groups += new_groups
assert_matching_arrays(user_groups, groups_of(agent, user), "Puppet fails to enforce minimum group membership")
end
if agent['platform'] =~ /osx/
skip_test "User provider on OSX fails to enforce inclusive group membership, so we will skip that test until this is fixed. See PUP-9160."
end
step "Verify that Puppet enforces inclusive group membership" do
user_groups = [groups[0]]
manifest = user_manifest(user, groups: user_groups, membership: :inclusive)
apply_manifest_on(agent, manifest)
assert_matching_arrays(user_groups, groups_of(agent, user), "Puppet fails to enforce inclusive group membership")
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/resource/user/should_modify_gid_forcelocal.rb | acceptance/tests/resource/user/should_modify_gid_forcelocal.rb | test_name "verify that we can modify the gid with forcelocal" do
confine :to, :platform => /el|fedora/ # PUP-5358
require 'puppet/acceptance/common_utils'
extend Puppet::Acceptance::PackageUtils
extend Puppet::Acceptance::ManifestUtils
tag 'audit:high'
user = "u#{rand(99999).to_i}"
group1 = "#{user}o"
group2 = "#{user}n"
agents.each do |host|
teardown do
on(host, puppet_resource('user', user, 'ensure=absent'))
on(host, puppet_resource('group', group1, 'ensure=absent'))
on(host, puppet_resource('group', group2, 'ensure=absent'))
end
step "ensure that the groups both exist" do
on(host, puppet_resource('group', group1, 'ensure=present'))
on(host, puppet_resource('group', group2, 'ensure=present'))
end
step "ensure the user exists and has the old group" do
apply_manifest_on(agent, resource_manifest('user', user, ensure: 'present', gid: group1, forcelocal: true))
end
step "verify that the user has the correct gid" do
group_gid1 = host.group_gid(group1)
host.user_get(user) do |result|
user_gid1 = result.stdout.split(':')[3]
fail_test "didn't have the expected old GID #{group_gid1}, but got: #{user_gid1}" unless group_gid1 == user_gid1
end
end
step "modify the GID of the user" do
apply_manifest_on(agent, resource_manifest('user', user, ensure: 'present', gid: group2, forcelocal: true), expect_changes: true)
end
step "verify that the user has the updated gid" do
group_gid2 = host.group_gid(group2)
host.user_get(user) do |result|
user_gid2 = result.stdout.split(':')[3]
fail_test "didn't have the expected old GID #{group_gid}, but got: #{user_gid2}" unless group_gid2 == user_gid2
end
end
step "run again for idempotency" do
apply_manifest_on(agent, resource_manifest('user', user, ensure: 'present', gid: group2, forcelocal: true), catch_changes: true)
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/tests/resource/user/should_manage_purge_ssh_keys.rb | acceptance/tests/resource/user/should_manage_purge_ssh_keys.rb | test_name 'should manage purge_ssh_keys' do
tag 'audit:high',
'audit:acceptance'
# MODULES-11236
skip_test('This test does not work on Windows nor macOS') if agent['platform'] =~ /windows/ || agent['platform'] =~ /osx/
name = "usr#{rand(9999).to_i}"
agents.each do |agent|
home = agent.tmpdir(name)
authorized_keys_path = "#{home}/.ssh/authorized_keys"
teardown do
agent.rm_rf(home)
on(agent, puppet_resource('user', "#{name}", 'ensure=absent'))
end
step "create user #{name} with ssh keys purged" do
apply_manifest_on(agent, <<-MANIFEST, { :catch_failures => true, :debug => true }) do |result|
user {'#{name}':
ensure => present,
home => '#{home}',
purge_ssh_keys => true
}
MANIFEST
end
on(agent, puppet("resource user #{name} --to_yaml")) do |result|
resource = YAML.load(result.stdout)
assert_match('present', resource['user'][name]['ensure'])
end
end
step "ensure home ownership" do
on(agent, "chown -R #{name} #{home}")
end
step "add ssh keys" do
apply_manifest_on(agent, <<-MANIFEST, { :catch_failures => true, :debug => true }) do |result|
ssh_authorized_key { '#{name}@example.com':
ensure => present,
user => '#{name}',
type => 'ssh-rsa',
key => 'my-key'
}
MANIFEST
end
on(agent, "cat #{authorized_keys_path}") do |result|
assert_match(/ssh-rsa my-key #{name}@example.com/, result.stdout)
end
end
step "purge ssh keys" do
apply_manifest_on(agent, <<-MANIFEST, { :catch_failures => true, :debug => true }) do |result|
user {'#{name}':
purge_ssh_keys => true
}
MANIFEST
end
on(agent, "cat #{authorized_keys_path}") do |result|
refute_match(/ssh-rsa my-key #{name}@example.com/, result.stdout)
end
end
step "add ssh keys" do
apply_manifest_on(agent, <<-MANIFEST, { :catch_failures => true, :debug => true }) do |result|
ssh_authorized_key { '#{name}@example.com':
ensure => present,
user => '#{name}',
type => 'ssh-rsa',
key => 'my-key'
}
MANIFEST
end
on(agent, "cat #{authorized_keys_path}") do |result|
assert_match(/ssh-rsa my-key #{name}@example.com/, result.stdout)
end
end
step "purge ssh keys when purge_ssh_keys has relative path to home" do
apply_manifest_on(agent, <<-MANIFEST, { :catch_failures => true, :debug => true }) do |result|
user {'#{name}':
purge_ssh_keys => '~/.ssh/authorized_keys'
}
MANIFEST
end
on(agent, "cat #{authorized_keys_path}") do |result|
refute_match(/ssh-rsa my-key #{name}@example.com/, result.stdout)
end
end
step "add ssh keys" do
apply_manifest_on(agent, <<-MANIFEST, { :catch_failures => true, :debug => true }) do |result|
ssh_authorized_key { '#{name}@example.com':
ensure => present,
user => '#{name}',
type => 'ssh-rsa',
key => 'my-key'
}
MANIFEST
end
on(agent, "cat #{authorized_keys_path}") do |result|
assert_match(/ssh-rsa my-key #{name}@example.com/, result.stdout)
end
end
step "purge ssh keys when purge_ssh_keys has absolute path" do
apply_manifest_on(agent, <<-MANIFEST, { :catch_failures => true, :debug => true }) do |result|
user {'#{name}':
purge_ssh_keys => '#{authorized_keys_path}'
}
MANIFEST
end
on(agent, "cat #{authorized_keys_path}") do |result|
refute_match(/ssh-rsa my-key #{name}@example.com/, 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/resource/user/should_not_modify_disabled.rb | acceptance/tests/resource/user/should_not_modify_disabled.rb | test_name 'PUP-6586 Ensure puppet does not continually reset password for disabled user' do
confine :to, :platform => 'windows'
tag 'audit:high',
'audit:acceptance' # Could be done as integration tests, but would
# require changing the system running the test
# in ways that might require special permissions
# or be harmful to the system running the test
name = "pl#{rand(99999).to_i}"
teardown do
agents.each do |agent|
on(agent, puppet_resource('user', "#{name}", 'ensure=absent'))
end
end
manifest = <<-MANIFEST
user {'#{name}':
ensure => present,
password => 'P@ssword!',
}
MANIFEST
agents.each do |agent|
step "create user #{name} with puppet" do
apply_manifest_on(agent, manifest, :catch_failures => true)
end
step "disable user #{name}" do
on(agent, "net user #{name} /ACTIVE:NO", :acceptable_exit_codes => 0)
end
step "test that password is not reset by puppet" do
# :catch_changes will fail the test if there were changes during
# run execution
apply_manifest_on(agent, manifest, :catch_changes => true)
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/tests/resource/user/utf8_user_comments.rb | acceptance/tests/resource/user/utf8_user_comments.rb | # Ensure a user can be managed with UTF-8 comment value. The comment value is
# normally used for "Full Name" so this is important in a UTF-8 context.
# We should be able to:
# - create a new user with a UTF-8 comment
# - modify an existing UTF-8 comment to a new UTF-8 comment
# - modify an existing UTF-8 comment to an ASCII comment
# - create a new user with an ASCII comment
# - modify an existing ASCII comment to a UTF-8 one
# Where applicable, we should be able to do this in different locales
test_name 'PUP-6777 Manage users with UTF-8 comments' do
tag 'audit:high',
'audit:acceptance' # Could be done as integration tests, but would
# require changing the system running the test
# in ways that might require special permissions
# or be harmful to the system running the test
# AIX providers are separate from most other platforms,
# and have not been made unicode-aware yet.
confine :except, :platform => /aix/
user0 = "foo#{rand(99999).to_i}"
user1 = "bar#{rand(99999).to_i}"
user2 = "baz#{rand(99999).to_i}"
user3 = "qux#{rand(99999).to_i}"
user4 = "ris#{rand(99999).to_i}"
osx_agents = agents.select { |a| a[:platform] =~ /osx/ } || []
windows_agents = agents.select { |a| a[:platform] =~ /windows/ } || []
# different UTF-8 widths
# 1-byte A
# 2-byte ۿ - http://www.fileformat.info/info/unicode/char/06ff/index.htm - 0xDB 0xBF / 219 191
# 3-byte ᚠ - http://www.fileformat.info/info/unicode/char/16A0/index.htm - 0xE1 0x9A 0xA0 / 225 154 160
# 4-byte 𠜎 - http://www.fileformat.info/info/unicode/char/2070E/index.htm - 0xF0 0xA0 0x9C 0x8E / 240 160 156 142
mixed_utf8_0 = "A\u06FF"
reported_mixed_utf8_0 = '\'A\u{6FF}\''
mixed_utf8_1 = "\u16A0\u{2070E}"
reported_mixed_utf8_1 = '\'\u{16A0}\u{2070E}\''
teardown do
# remove user on all agents
teardown_manifest = <<-EOF
user { ['#{user0}','#{user1}','#{user2}','#{user3}','#{user4}']: ensure => absent }
EOF
apply_manifest_on(agents, teardown_manifest, :environment => {:LANG => "en_US.UTF-8"})
end
step "ensure user can be created with UTF-8 comment (with UTF-8 environment on *nix)" do
create_user = <<-EOF
user { '#{user0}':
ensure => present,
comment => '#{mixed_utf8_0}',
}
EOF
# Note setting LANG='<encoding>' environment like this has no effect on Windows agents.
apply_manifest_on(agents, create_user, :expect_changes => true, :environment => {:LANG => "en_US.UTF-8"})
end
step "ensure UTF-8 comment can be changed (with UTF-8 environment on *nix)" do
set_comment_utf8 = <<-EOF
user { '#{user0}':
comment => '#{mixed_utf8_1}',
}
EOF
# Note setting LANG='<encoding>' environment like this has no effect on Windows agents.
apply_manifest_on(agents, set_comment_utf8, :expect_changes => true, :environment => {:LANG => "en_US.UTF-8"}) do |result|
assert_match(/changed #{reported_mixed_utf8_0} to #{reported_mixed_utf8_1}/, result.stdout, "failed to modify UTF-8 user comment in UTF-8 environment")
end
end
# *NIX and OSX should also work with ISO-8859-1 (at least, let's make sure we don't regress)
step "ensure user can be created with UTF-8 comment (with ISO-8859-1 environment on *nix)" do
create_user = <<-EOF
user { '#{user1}':
ensure => present,
comment => '#{mixed_utf8_0}',
}
EOF
# Since LANG=<'encoding'> has no effect, this test is redundant on Windows - exclude it.
apply_manifest_on(agents - windows_agents, create_user, :expect_changes => true, :environment => {:LANG => "en_US.ISO8859-1"})
end
step "ensure UTF-8 comment can be changed (with ISO-8859-1 environment on *nix)" do
set_comment_utf8 = <<-EOF
user { '#{user1}':
comment => '#{mixed_utf8_1}',
}
EOF
# Since LANG=<'encoding'> has no effect, this test is redundant on Windows - exclude it.
apply_manifest_on(agents - windows_agents, set_comment_utf8, :expect_changes => true, :environment => {:LANG => "en_US.ISO8859-1"}) do |result|
assert_match(/changed #{reported_mixed_utf8_0} to #{reported_mixed_utf8_1}/, result.stdout, "failed to modify UTF-8 user comment in ISO-8859-1 environment")
end
end
step "ensure user can be created with UTF-8 comment (with POSIX locale on *nix)" do
create_user = <<-EOF
user { '#{user2}':
ensure => present,
comment => '#{mixed_utf8_0}',
}
EOF
# OS X is known broken in POSIX locale with UTF-8 chars on OS X, so exclude OS X here.
# Also since LANG=<'encoding'> has no effect, this test is redundant on Windows - exclude it.
apply_manifest_on(agents - osx_agents - windows_agents, create_user, :expect_changes => true, :environment => {:LANG => "POSIX"})
end
step "ensure UTF-8 comment can be modifed (with POSIX locale on *nix)" do
set_comment_utf8 = <<-EOF
user { '#{user2}':
ensure => present,
comment => '#{mixed_utf8_1}',
}
EOF
# OS X is known broken in POSIX locale with UTF-8 chars on OS X, so exclude OS X here.
# Also since LANG=<'encoding'> has no effect, this test is redundant on Windows - exclude it.
apply_manifest_on(agents - osx_agents - windows_agents, set_comment_utf8, :expect_changes => true, :environment => {:LANG => "POSIX"}) do |result|
assert_match(/changed #{reported_mixed_utf8_0} to #{reported_mixed_utf8_1}/, result.stdout, "failed to modify UTF-8 user comment with POSIX environment")
end
end
step "ensure user can be created with ASCII comment (with POSIX locale on *nix)" do
create_user = <<-EOF
user { '#{user3}':
ensure => present,
comment => 'bar',
}
EOF
# While setting LANG='<encoding>' environment like this has no effect on
# Windows agents, we still want to run this and the following tests on Windows
# because we want to ensure we can set create/modify ASCII comments to UTF-8
# and back.
# OS X is known broken in POSIX locale with UTF-8 chars on OS X, so exclude OS X here.
apply_manifest_on(agents - osx_agents, create_user, :expect_changes => true, :environment => {:LANG => "POSIX"})
end
# This test is important because of ruby's Etc.getpwnam behavior which returns
# strings in current locale if compatible - make sure we can get a system
# value in POSIX and compare it to incoming from puppet in UTF-8.
step "ensure ASCII comment can be modified to UTF-8 comment (with POSIX locale on *nix)" do
set_comment_utf8 = <<-EOF
user { '#{user3}':
comment => '#{mixed_utf8_0}',
}
EOF
# While setting LANG='<encoding>' environment like this has no effect on
# Windows agents, we still want to run this and the following tests on Windows
# because we want to ensure we can set create/modify ASCII comments to UTF-8
# and back.
# OS X is known broken in POSIX locale with UTF-8 chars on OS X, so exclude OS X here.
apply_manifest_on(agents - osx_agents, set_comment_utf8, :expect_changes => true, :environment => {:LANG => "POSIX"}) do |result|
assert_match(/changed 'bar' to #{reported_mixed_utf8_0}/, result.stdout, "failed to modify user ASCII comment to UTF-8 comment with POSIX locale")
end
end
step "create another user with UTF-8 comment (with POSIX locale on *nix)" do
create_user = <<-EOF
user { '#{user4}':
ensure => present,
comment => '#{mixed_utf8_0}',
}
EOF
# While setting LANG='<encoding>' environment like this has no effect on
# Windows agents, we still want to run this and the following tests on Windows
# because we want to ensure we can set create/modify ASCII comments to UTF-8
# and back.
# OS X is known broken in POSIX locale with UTF-8 chars on OS X, so exclude OS X here.
apply_manifest_on(agents - osx_agents, create_user, :expect_changes => true, :environment => {:LANG => "POSIX"})
end
step "ensure UTF-8 comment can be modified to ASCII comment (with POSIX locale on *nix)" do
set_comment_ascii = <<-EOF
user { '#{user4}':
comment => 'bar',
}
EOF
# While setting LANG='<encoding>' environment like this has no effect on
# Windows agents, we still want to run this on Windows because we want to
# ensure we can set create/modify ASCII comments to UTF-8 and back.
# OS X is known broken in POSIX locale with UTF-8 chars, so exclude OS X here
apply_manifest_on(agents - osx_agents, set_comment_ascii, :expect_changes => true, :environment => {:LANG => "POSIX"}) do |result|
assert_match(/changed #{reported_mixed_utf8_0} to 'bar'/, result.stdout, "failed to modify user UTF-8 comment to ASCII comment with POSIX locale")
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/resource/user/should_modify.rb | acceptance/tests/resource/user/should_modify.rb | test_name "should modify a user"
tag 'audit:high',
'audit:refactor', # Use block style `test_run`
'audit:acceptance' # Could be done as integration tests, but would
# require changing the system running the test
# in ways that might require special permissions
# or be harmful to the system running the test
name = "pl#{rand(999999).to_i}"
agents.each do |agent|
step "ensure the user is present"
agent.user_present(name)
step "modify the user"
on agent, puppet_resource('user', name, ["ensure=present", "comment=comment#{name}"])
step "verify the user was modified"
agent.user_get(name) do |result|
fail_test "didn't modify the user #{name}" unless result.stdout.include? "comment#{name}"
end
step "delete the user"
agent.user_absent(name)
agent.group_absent(name)
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/tests/resource/user/should_destroy_with_managehome.rb | acceptance/tests/resource/user/should_destroy_with_managehome.rb | test_name "should delete a user with managehome=true" do
confine :except, :platform => /osx/
tag 'audit:high',
'audit:acceptance' # Could be done as integration tests, but would
# require changing the system running the test
# in ways that might require special permissions
# or be harmful to the system running the test
agents.each do |agent|
home = ''
name = "pl#{rand(999999).to_i}"
teardown do
agent.user_absent(name)
end
step "ensure the user is present" do
agent.user_present(name)
end
step "get home directory path" do
on(agent, puppet_resource('user', name)) do |result|
info = result.stdout.match(/home\s+=>\s+'(.+)',/)
home = info[1] if info
end
end
step "delete the user with managehome=true" do
on(agent, puppet_resource('user', name, ['ensure=absent', 'managehome=true']))
end
step "verify the user was deleted" do
fail_test "User '#{name}' was not deleted" if agent.user_list.include?(name)
end
step "verify the home directory was deleted" do
skip_test("managehome parameter on Windows is not behaving as expected. See PUP-11202") if agent['platform'] =~ /windows/
on(agent, "test -d #{home}", :acceptable_exit_codes => [1])
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/tests/resource/user/should_purge.rb | acceptance/tests/resource/user/should_purge.rb | test_name "should purge a user" do
# Until purging works on AIX, Solaris, and OSX. See PUP-9188
confine :except, :platform => /^aix/
confine :except, :platform => /^solaris/
confine :except, :platform => /^osx/
tag 'audit:high',
'audit:acceptance'
agents.each do |agent|
unmanaged = "unmanaged-#{rand(999999).to_i}"
managed = "managed-#{rand(999999).to_i}"
step "ensure that the unmanaged and managed users do not exist" do
agent.user_absent(unmanaged)
agent.user_absent(managed)
end
step "create the unmanaged user" do
on agent, puppet_resource('user', unmanaged, 'ensure=present')
end
step "verify the user exists" do
assert(agent.user_list.include?(unmanaged), "Unmanaged user was not created")
end
step "create the managed user and purge unmanaged users" do
manifest = %Q|
user {'#{managed}':
ensure => present
}
resources { 'user':
purge => true,
unless_system_user => true
}|
apply_manifest_on(agent, manifest)
end
step "verify the unmanaged user is purged" do
assert(!agent.user_list.include?(unmanaged), "Unmanaged user was not purged")
end
step "verify managed user is not purged" do
assert(agent.user_list.include?(managed), "Managed user was purged")
end
step "verify system user is not purged" do
if agent['platform'] =~ /windows/
win_admin_user = agent['locale'] == 'fr' ? "Administrateur" : "Administrator"
assert(agent.user_list.include?(win_admin_user), "System user (Administrator) was purged")
else
assert(agent.user_list.include?("root"), "System user (root) was purged")
end
end
teardown do
agent.user_absent(unmanaged)
agent.user_absent(managed)
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/resource/user/should_allow_managed_macos_users_to_login.rb | acceptance/tests/resource/user/should_allow_managed_macos_users_to_login.rb | test_name "should allow managed macOS users to login" do
confine :to, :platform => /osx/
tag 'audit:high',
'audit:acceptance' # Could be done as integration tests, but would
# require changing the system running the test
# in ways that might require special permissions
# or be harmful to the system running the test
# Two different test cases, with additional environment setup inbetween,
# were added in the same file to save on test run time (managing macOS users
# takes around a minute or so because when retrieving plist data from all users with
# `dscl readall` we also receive thousands of bytes of user avatar image)
agents.each do |agent|
teardown do
on(agent, puppet("resource", "user", 'testuser', "ensure=absent"))
end
# Checking if we can create a user with password, salt and iterations
step "create the test user with password and salt" do
# The password is 'helloworld'
apply_manifest_on(agent, <<-MANIFEST, :catch_failures => true)
user { 'testuser':
ensure => present,
password => '6ce97688468f231845d9d982f1f10832ca0c6c728a77bac51c548af99ebd9b9c62bcba15112a0c7a7e34effbb2e92635650c79c51517d72b083a4eb2a513f51ad1f8ea9556cef22456159c341d8bcd382a91708afaf253c2b727d4c6cd3d29cc26011d5d511154037330ecea0263b1be8c1c13086d029c57344291bd37952b56',
salt => '377e8b60e5fdfe509cad188d5b1b9e40e78b418f8c3f0127620ea69d4c32789c',
iterations => 40000,
}
MANIFEST
end
step "verify the password was set correctly and is able to log in" do
on(agent, "dscl /Local/Default -authonly testuser helloworld", :acceptable_exit_codes => 0)
end
unless agent['platform'] =~ /^osx-1[1-9]/
skip_test "AuthenticationAuthority field fix test is not valid for macOS before Big Sur (11.0)"
end
# Setting up environment to mimic situation on macOS 11 BigSur
# Prior to macOS BigSur, `dscl . -create` was populating more fields with
# default values, including AuthenticationAuthority which contains the
# ShadowHash type
# Withouth this field, login is not allowed
step "remove AuthenticationAuthority field from user" do
on(agent, "dscl /Local/Default -delete Users/testuser AuthenticationAuthority", :acceptable_exit_codes => 0)
end
step "expect user without AuthenticationAuthority to not be able to log in" do
on(agent, "dscl /Local/Default -authonly testuser helloworld", :acceptable_exit_codes => (1..255))
end
# Expecting Puppet to pick up the missing field and add it to
# make the user usable again
step "change password with different salt and expect AuthenticationAuthority field to be readded" do
# The password is still 'helloworld' but with different salt
apply_manifest_on(agent, <<-MANIFEST, { :catch_failures => true, :debug => true }) do |result|
user { 'testuser':
ensure => present,
password => '7e8e82542a0c06595e99bfe10c6bd219d19dede137c5c2f84bf10d98d83b77302d3c9c7f7e3652d420f562613f582ab62b26a52b9b26d0d032efbd486fd865b3ba4fd8a3512137681ce87d190f8fa7848d941c6080c588528dcb682c763c040ff54992dce204c3e5dda973e7b36f7f50a774e55e99fe4c8ed6b6464614838c13',
salt => '8005b8855a187086a3b59eff925a611ec61d2d66d2e786b7598fe0a0b4b8ffba',
iterations => 40000
}
MANIFEST
assert_match(/User 'testuser' is missing the 'SALTED-SHA512-PBKDF2' AuthenticationAuthority key for ShadowHash/, result.stdout)
assert_match(/Adding 'SALTED-SHA512-PBKDF2' AuthenticationAuthority key for ShadowHash to user 'testuser'/, result.stdout)
end
end
step "verify the password was set correctly and is able to log in" do
on(agent, "dscl /Local/Default -authonly testuser helloworld", :acceptable_exit_codes => 0)
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/tests/resource/user/should_manage_attributes_aix.rb | acceptance/tests/resource/user/should_manage_attributes_aix.rb | test_name "should correctly manage the attributes property for the User resource (AIX only)" do
confine :to, :platform => /aix/
tag 'audit:high',
'audit:acceptance' # Could be done as integration tests, but would
# require changing the system running the test
# in ways that might require special permissions
# or be harmful to the system running the test
require 'puppet/acceptance/aix_util'
extend Puppet::Acceptance::AixUtil
initial_attributes = {
'nofiles' => 10000,
'fsize' => 100000,
'data' => 60000,
}
changed_attributes = {
'nofiles' => -1,
'data' => 40000
}
run_attribute_management_tests('user', :uid, initial_attributes, changed_attributes)
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/tests/resource/user/should_modify_gid.rb | acceptance/tests/resource/user/should_modify_gid.rb | test_name "verify that we can modify the gid"
confine :except, :platform => 'windows'
confine :except, :platform => /aix/ # PUP-5358
tag 'audit:high',
'audit:refactor', # Use block style `test_run`
'audit:acceptance' # Could be done as integration tests, but would
# require changing the system running the test
# in ways that might require special permissions
# or be harmful to the system running the test
user = "u#{rand(99999).to_i}"
group1 = "#{user}o"
group2 = "#{user}n"
agents.each do |host|
step "ensure that the groups both exist"
on(host, puppet_resource('group', group1, 'ensure=present'))
on(host, puppet_resource('group', group2, 'ensure=present'))
step "ensure the user exists and has the old group"
on(host, puppet_resource('user', user, 'ensure=present', "gid=#{group1}"))
step "verify that the user has the correct gid"
group_gid1 = host.group_gid(group1)
host.user_get(user) do |result|
user_gid1 = result.stdout.split(':')[3]
fail_test "didn't have the expected old GID #{group_gid1}, but got: #{user_gid1}" unless group_gid1 == user_gid1
end
step "modify the GID of the user"
on(host, puppet_resource('user', user, 'ensure=present', "gid=#{group2}"))
step "verify that the user has the updated gid"
group_gid2 = host.group_gid(group2)
host.user_get(user) do |result|
user_gid2 = result.stdout.split(':')[3]
fail_test "didn't have the expected old GID #{group_gid}, but got: #{user_gid2}" unless group_gid2 == user_gid2
end
step "ensure that we remove the things we made"
on(host, puppet_resource('user', user, 'ensure=absent'))
on(host, puppet_resource('group', group1, 'ensure=absent'))
on(host, puppet_resource('group', group2, 'ensure=absent'))
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/tests/resource/user/should_not_create_existing.rb | acceptance/tests/resource/user/should_not_create_existing.rb | test_name "tests that user resource will not add users that already exist." do
tag 'audit:high',
'audit:acceptance' # Could be done as integration tests, but would
# require changing the system running the test
# in ways that might require special permissions
# or be harmful to the system running the test
user = "u#{rand(999999).to_i}"
group = "g#{rand(999999).to_i}"
teardown do
agents.each do |agent|
agent.user_absent(user)
agent.group_absent(group)
end
end
step "Setup: Create test user and group" do
agents.each do |agent|
agent.user_present(user)
agent.group_present(group)
end
end
step "verify that we don't try to create a user account that already exists" do
agents.each do |agent|
on(agent, puppet_resource('user', user, 'ensure=present')) do |result|
fail_test "tried to create '#{user}' user" if result.stdout.include? 'created'
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/resource/user/should_destroy.rb | acceptance/tests/resource/user/should_destroy.rb | test_name "should delete a user"
tag 'audit:high',
'audit:refactor', # Use block style `test_run`
'audit:acceptance' # Could be done as integration tests, but would
# require changing the system running the test
# in ways that might require special permissions
# or be harmful to the system running the test
name = "pl#{rand(999999).to_i}"
agents.each do |agent|
step "ensure the user is present"
agent.user_present(name)
step "delete the user"
on agent, puppet_resource('user', name, 'ensure=absent')
step "verify the user was deleted"
fail_test "User #{name} was not deleted" if agent.user_list.include? name
step "delete the user, if any"
agent.user_absent(name)
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/tests/resource/user/should_not_destroy_unexisting.rb | acceptance/tests/resource/user/should_not_destroy_unexisting.rb | test_name "ensure that puppet does not report removing a user that does not exist"
tag 'audit:high',
'audit:refactor', # Use block style `test_run`
'audit:acceptance' # Could be done as integration tests, but would
# require changing the system running the test
# in ways that might require special permissions
# or be harmful to the system running the test
name = "pl#{rand(999999).to_i}"
step "verify that user #{name} does not exist"
agents.each do |agent|
agent.user_absent(name)
end
step "ensure absent doesn't try and do anything"
on(agents, puppet_resource('user', name, 'ensure=absent')) do |result|
fail_test "tried to remove the user, apparently" if result.stdout.include? 'removed'
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/tests/resource/user/should_query_all.rb | acceptance/tests/resource/user/should_query_all.rb | test_name "should query all users"
tag 'audit:high',
'audit:refactor', # Use block style `test_run`
'audit:integration'
agents.each do |agent|
next if agent == master
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 "query natively"
users = agent.user_list
fail_test("No users found") unless users
step "query with puppet"
on(agent, puppet_resource('user')) do |result|
result.stdout.each_line do |line|
name = ( line.match(/^user \{ '([^']+)'/) or next )[1]
unless users.delete(name)
fail_test "user #{name} found by puppet, not natively"
end
end
end
if users.length > 0 then
fail_test "#{users.length} users found natively, not puppet: #{users.join(', ')}"
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/resource/user/should_create_with_gid.rb | acceptance/tests/resource/user/should_create_with_gid.rb | test_name "verifies that puppet resource creates a user and assigns the correct group"
confine :except, :platform => 'windows'
tag 'audit:high',
'audit:refactor', # Use block style `test_run`
'audit:acceptance' # Could be done as integration tests, but would
# require changing the system running the test
# in ways that might require special permissions
# or be harmful to the system running the test
user = "pl#{rand(999999).to_i}"
group = "gp#{rand(999999).to_i}"
agents.each do |host|
step "user should not exist"
host.user_absent(user)
step "group should exist"
host.group_present(group)
step "create user with group"
on(host, puppet_resource('user', user, 'ensure=present', "gid=#{group}"))
step "verify the group exists and find the gid"
group_gid = host.group_gid(group)
step "verify that the user has that as their gid"
host.user_get(user) do |result|
if host['platform'] =~ /aix/
match = result.stdout.match(/pgrp=([^\s\\]+)/)
user_gid = match ? host.group_gid(match[1]) : nil
else
user_gid = result.stdout.split(':')[3]
end
fail_test "expected gid #{group_gid} but got: #{user_gid}" unless group_gid == user_gid
end
step "clean up after the test is done"
on(host, puppet_resource('user', user, 'ensure=absent'))
on(host, puppet_resource('group', group, 'ensure=absent'))
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/tests/resource/user/should_modify_when_not_managing_home.rb | acceptance/tests/resource/user/should_modify_when_not_managing_home.rb | test_name "should modify a user when no longer managing home (#20726)"
tag 'audit:high',
'audit:refactor', # Use block style `test_run`
'audit:acceptance' # Could be done as integration tests, but would
# require changing the system running the test
# in ways that might require special permissions
# or be harmful to the system running the test
require 'puppet/acceptance/windows_utils'
extend Puppet::Acceptance::WindowsUtils
name = "pl#{rand(999999).to_i}"
pw = "Passwrd-#{rand(999999).to_i}"[0..11]
def get_home_dir(host, user_name)
home_dir = nil
on host, puppet_resource('user', user_name) do |result|
home_dir = result.stdout.match(/home\s*=>\s*'([^']+)'/m)[1]
end
home_dir
end
agents.each do |agent|
home_prop = nil
case agent['platform']
when /windows/
# Sadly Windows ADSI won't tell us the default home directory
# for a user. You can get it via WMI Win32_UserProfile, but that
# doesn't exist in a base 2003 install. So we simply specify an
# initial home directory, that matches what the default will be.
# This way we are guaranteed that `puppet resource user name`
# will include the home directory in its output.
home_prop = "home='#{profile_base(agent)}\\#{name}'"
when /solaris/
pending_test("managehome needs work on solaris")
when /osx/
skip_test("OSX doesn't support managehome")
# we don't get here
end
teardown do
step "delete the user"
agent.user_absent(name)
agent.group_absent(name)
end
step "ensure the user is present with managehome"
on agent, puppet_resource('user', name, ["ensure=present", "managehome=true", "password=#{pw}", home_prop].compact)
step "find the current home dir"
home_dir = get_home_dir(agent, name)
on agent, "test -d '#{home_dir}'"
step "modify the user"
new_home_dir = "#{home_dir}_foo"
on agent, puppet_resource('user', name, ["ensure=present", "home='#{new_home_dir}'"]) do |result|
found_home_dir = result.stdout.match(/home\s*=>\s*'([^']+)'/m)[1]
assert_equal new_home_dir, found_home_dir, "Failed to change home property of user"
end
step "verify that home directory still exists since we did not specify managehome"
on agent, "test -d '#{home_dir}'"
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/tests/resource/user/should_create_with_expiry_absent.rb | acceptance/tests/resource/user/should_create_with_expiry_absent.rb | test_name "verifies that puppet resource creates a user and assigns the correct expiry date when absent" do
confine :except, :platform => 'windows'
tag 'audit:high',
'audit:acceptance' # Could be done as integration tests, but would
# require changing the system running the test
# in ways that might require special permissions
# or be harmful to the system running the test
user = "pl#{rand(999999).to_i}"
teardown do
step "cleanup"
agents.each do |host|
on(host, puppet_resource('user', user, 'ensure=absent'))
end
end
agents.each do |host|
step "user should not exist"
on(host, puppet_resource('user', user, 'ensure=absent'), :acceptable_exit_codes => [0])
step "create user with expiry=absent"
on(host, puppet_resource('user', user, 'ensure=present', 'expiry=absent'), :acceptable_exit_codes => [0])
step "verify the user exists and expiry is not set (meaning never expire)"
on(host, puppet_resource('user', user)) do |result|
assert_match(/ensure.*=> 'present'/, result.stdout)
refute_match(/expiry.*=>/, result.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/acceptance/tests/resource/user/osx_10.4_should_fail_when_modify_home.rb | acceptance/tests/resource/user/osx_10.4_should_fail_when_modify_home.rb | test_name "should not modify the home directory of an user on OS X >= 10.14" do
confine :to, :platform => /osx/
tag 'audit:high',
'audit:acceptance' # Could be done as integration tests, but would
# require changing the system running the test
# in ways that might require special permissions
# or be harmful to the system running the test
require 'puppet/acceptance/common_utils'
extend Puppet::Acceptance::BeakerUtils
extend Puppet::Acceptance::ManifestUtils
user = "pl#{rand(999999).to_i}"
agents.each do |agent|
teardown do
agent.user_absent(user)
end
step "ensure the user is present" do
agent.user_present(user)
end
step "verify the error message is correct" do
expected_error = /OS X version [0-9\.]+ does not allow changing home using puppet/
user_manifest = resource_manifest('user', user, ensure: 'present', home: "/opt/#{user}")
apply_manifest_on(agent, user_manifest) do |result|
assert_match(
expected_error,
result.stderr,
"Puppet fails to report an error when changing home directory on OS X >= 10.14"
)
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/resource/user/should_create.rb | acceptance/tests/resource/user/should_create.rb | test_name "should create a user"
tag 'audit:high',
'audit:refactor', # Use block style `test_run`
'audit:acceptance' # Could be done as integration tests, but would
# require changing the system running the test
# in ways that might require special permissions
# or be harmful to the system running the test
name = "pl#{rand(999999).to_i}"
agents.each do |agent|
step "ensure the user and group do not exist"
agent.user_absent(name)
agent.group_absent(name)
step "create the user"
on agent, puppet_resource('user', name, 'ensure=present')
step "verify the user exists"
agent.user_get(name)
case agent['platform']
when /sles/, /solaris/, /windows/, /osx/, /aix/
# no private user groups by default
else
agent.group_get(name)
end
step "delete the user, and group, if any"
agent.user_absent(name)
agent.group_absent(name)
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/tests/resource/user/should_create_modify_with_password.rb | acceptance/tests/resource/user/should_create_modify_with_password.rb | # frozen_string_literal: true
test_name 'should create a user with password and modify the password' do
tag 'audit:high',
'audit:acceptance' # Could be done as integration tests, but would
# require changing the system running the test
# in ways that might require special permissions
# or be harmful to the system running the test
require 'puppet/acceptance/common_utils'
extend Puppet::Acceptance::ManifestUtils
name = "pl#{rand(999_999).to_i}"
initial_password = 'test1'
modified_password = 'test2'
agents.each do |agent|
teardown { agent.user_absent(name) }
step 'ensure the user does not exist' do
user_manifest = resource_manifest('user', name, { ensure: 'absent', provider: 'useradd' } )
apply_manifest_on(agent, user_manifest) do |result|
skip_test 'Useradd provider not present on this host' if result.stderr =~ /Provider useradd is not functional on this host/
end
end
step 'create the user with password' do
apply_manifest_on(agent, <<-MANIFEST, catch_failures: true)
user { '#{name}':
ensure => present,
password => '#{initial_password}',
}
MANIFEST
end
step 'verify the password was set correctly' do
on(agent, puppet('resource', 'user', name), acceptable_exit_codes: 0) do |result|
assert_match(/password\s*=>\s*'#{initial_password}'/, result.stdout, 'Password was not set correctly')
end
end
step 'modify the user with a different password' do
# There is a known issue with SSSD and Red Hat 8, this is a temporary workaround until a permanent fix is
# implemented in our images. See ITHELP-100250
# https://access.redhat.com/solutions/7031304
if agent['platform'] == 'el-8-ppc64le'
on(agent, 'systemctl stop sssd; rm -f /var/lib/sss/db/*; systemctl start sssd', acceptable_exit_codes: 0)
end
apply_manifest_on(agent, <<-MANIFEST, catch_failures: true)
user { '#{name}':
ensure => present,
password => '#{modified_password}',
}
MANIFEST
end
step 'verify the password was set correctly' do
on(agent, "puppet resource user #{name}", acceptable_exit_codes: 0) do |result|
assert_match(/password\s*=>\s*'#{modified_password}'/, result.stdout, 'Password was not changed correctly')
end
end
step 'Verify idempotency when setting the same password' do
apply_manifest_on(agent, <<-MANIFEST, expect_changes: false)
user { '#{name}':
ensure => present,
password => '#{modified_password}',
}
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/resource/user/osx_10.4_should_fail_when_modify_uid.rb | acceptance/tests/resource/user/osx_10.4_should_fail_when_modify_uid.rb | test_name "should not modify the uid of an user on OS X >= 10.14" do
confine :to, :platform => /osx/
tag 'audit:high',
'audit:acceptance' # Could be done as integration tests, but would
# require changing the system running the test
# in ways that might require special permissions
# or be harmful to the system running the test
require 'puppet/acceptance/common_utils'
extend Puppet::Acceptance::BeakerUtils
extend Puppet::Acceptance::ManifestUtils
user = "pl#{rand(999999).to_i}"
agents.each do |agent|
teardown do
agent.user_absent(user)
end
step "ensure the user is present" do
agent.user_present(user)
end
step "verify the error message is correct" do
expected_error = /OS X version [0-9\.]+ does not allow changing uid using puppet/
user_manifest = resource_manifest('user', user, ensure: 'present', uid: rand(999999))
apply_manifest_on(agent, user_manifest) do |result|
assert_match(
expected_error,
result.stderr,
"Puppet fails to report an error when changing uid on OS X >= 10.14"
)
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/resource/user/should_manage_shell.rb | acceptance/tests/resource/user/should_manage_shell.rb | test_name "should manage user shell"
tag 'audit:high',
'audit:refactor', # Use block style `test_run`
'audit:acceptance' # Could be done as integration tests, but would
# require changing the system running the test
# in ways that might require special permissions
# or be harmful to the system running the test
name = "pl#{rand(999999).to_i}"
confine :except, :platform => 'windows'
agents.each do |agent|
step "ensure the user and group do not exist"
agent.user_absent(name)
agent.group_absent(name)
step "create the user with shell"
shell = '/bin/sh'
on agent, puppet_resource('user', name, ["ensure=present", "shell=#{shell}"])
step "verify the user shell matches the managed shell"
agent.user_get(name) do |result|
fail_test "didn't set the user shell for #{name}" unless result.stdout.include? shell
end
step "modify the user with shell"
# We need to use an allowed shell in AIX, as according to `/etc/security/login.cfg`
if agent['platform'] =~ /aix/
shell = '/bin/ksh'
else
shell = '/bin/bash'
end
on agent, puppet_resource('user', name, ["ensure=present", "shell=#{shell}"])
step "verify the user shell matches the managed shell"
agent.user_get(name) do |result|
fail_test "didn't set the user shell for #{name}" unless result.stdout.include? shell
end
step "delete the user, and group, if any"
agent.user_absent(name)
agent.group_absent(name)
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/tests/resource/user/should_query.rb | acceptance/tests/resource/user/should_query.rb | test_name "test that we can query and find a user that exists."
tag 'audit:high',
'audit:refactor', # Use block style `test_run`
'audit:acceptance' # Could be done as integration tests, but would
# require changing the system running the test
# in ways that might require special permissions
# or be harmful to the system running the test
name = "pl#{rand(999999).to_i}"
agents.each do |agent|
step "ensure that our test user exists"
agent.user_present(name)
step "query for the resource and verify it was found"
on(agent, puppet_resource('user', name)) do |result|
fail_test "didn't find the user #{name}" unless result.stdout.include? 'present'
end
step "clean up the user and group we added"
agent.user_absent(name)
agent.group_absent(name)
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/tests/resource/exec/should_run_command_as_user.rb | acceptance/tests/resource/exec/should_run_command_as_user.rb | test_name "The exec resource should be able to run commands as a different user" do
confine :except, :platform => 'windows'
tag 'audit:high',
'audit:acceptance'
require 'puppet/acceptance/common_utils'
extend Puppet::Acceptance::BeakerUtils
def random_username
"pl#{rand(999999).to_i}"
end
def exec_resource_manifest(params = {})
default_params = {
:logoutput => true,
:path => '/usr/bin:/usr/sbin:/bin:/sbin',
:command => 'echo Hello'
}
params = default_params.merge(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
exec { 'run_test_command':
#{params_str}
}
MANIFEST
end
agents.each do |agent|
username = random_username
# Create our user. Ensure that we start with a clean slate.
agent.user_absent(username)
agent.user_present(username)
teardown { agent.user_absent(username) }
tmpdir = agent.tmpdir("forbidden")
on(agent, "chmod 700 #{tmpdir}")
step "Runs the command even when the user doesn't have permissions to access the pwd" do
# Can't use apply_manifest_on here because that does not take the :cwd
# as an option.
tmpfile = agent.tmpfile("exec_user_perms_manifest")
create_remote_file(agent, tmpfile, exec_resource_manifest(user: username))
on(agent, "cd #{tmpdir} && puppet apply #{tmpfile} --detailed-exitcodes", acceptable_exit_codes: [0, 2])
end
step "Runs the command even when the user doesn't have permission to access the specified cwd" do
apply_manifest_on(agent, exec_resource_manifest(user: username, cwd: tmpdir), catch_failures: true)
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/tests/resource/exec/should_run_command.rb | acceptance/tests/resource/exec/should_run_command.rb | test_name "tests that puppet correctly runs an exec."
# original author: Dan Bode --daniel 2010-12-23
tag 'audit:high',
'audit:refactor', # Use block style `test_name`
'audit:acceptance'
def before(agent)
step "file to be touched should not exist."
agent.tmpfile('test-exec')
end
def after(agent, touched)
step "checking the output worked"
on agent, "test -f #{touched}"
step "clean up the system"
on agent, "rm -f #{touched}"
end
agents.each do |agent|
touched = before(agent)
apply_manifest_on(agent, "exec {'test': command=>'#{agent.touch(touched)}'}") do |result|
fail_test "didn't seem to run the command" unless
result.stdout.include? 'executed successfully' unless agent['locale'] == 'ja'
end
after(agent, touched)
touched = before(agent)
on(agent, puppet_resource('-d', 'exec', 'test', "command='#{agent.touch(touched)}'}")) do |result|
fail_test "didn't seem to run the command" unless
result.stdout.include? 'executed successfully' unless agent['locale'] == 'ja'
end
after(agent, touched)
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/tests/resource/exec/accept_array_commands.rb | acceptance/tests/resource/exec/accept_array_commands.rb | test_name "Be able to execute array commands" do
tag 'audit:high',
'audit:acceptance'
agents.each do |agent|
if agent.platform =~ /windows/
cmd = ['C:\Windows\System32\cmd.exe', '/c', 'echo', '*']
else
cmd = ['/bin/echo', '*']
end
exec_manifest = <<~MANIFEST
exec { "test exec":
command => #{cmd},
logoutput => true,
}
MANIFEST
apply_manifest_on(agent, exec_manifest) do |output|
assert_match('Notice: /Stage[main]/Main/Exec[test exec]/returns: *', output.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/acceptance/tests/resource/exec/should_set_environment_variables.rb | acceptance/tests/resource/exec/should_set_environment_variables.rb | test_name "The Exec resource should set user-specified environment variables" do
tag 'audit:high',
'audit:acceptance'
# Would be nice to parse the actual values from puppet_output,
# but that would require some complicated matching since
# puppet_output contains other stuff.
def assert_env_var_values(puppet_output, expected_values)
expected_values.each do |env_var, value|
assert_match(/#{env_var}=#{value}/, puppet_output, "Expected '#{env_var}=#{value}' to be printed as part of the output!")
end
end
agents.each do |agent|
# Calculate some top-level variables/functions we
# will need for our tests.
unless agent.platform =~ /windows/
path = '/usr/bin:/usr/sbin:/bin:/sbin'
print_env_vars = lambda do |*env_vars|
env_vars_str = env_vars.map do |env_var|
"#{env_var}=$#{env_var}"
end.join(" ")
"echo #{env_vars_str}"
end
else
# Powershell's directory is dependent on what version of Powershell is
# installed on the system (e.g. v1.0, v2.0), so we need to programmatically
# calculate the executable's directory to add to our PATH variable.
powershell_path = on(agent, "cmd.exe /c where powershell.exe").stdout.chomp
*powershell_dir, _ = powershell_path.split('\\')
powershell_dir = powershell_dir.join('\\')
path = "C:\Windows\System32;#{powershell_dir}"
print_env_vars = lambda do |*env_vars|
env_vars_str = env_vars.map do |env_var|
"#{env_var}=$env:#{env_var}"
end
"powershell.exe \"Write-Host -NoNewLine #{env_vars_str}\""
end
end
# Easier to read than a def. The def. would require us
# to specify the host as a param. in order to get the path
# and print_cwd command, which is unnecessary clutter.
exec_resource_manifest = lambda do |params = {}|
default_params = {
:logoutput => true,
:path => path
}
params = default_params.merge(params)
params_str = params.map do |param, value|
value_str = value.to_s
# Single quote the strings in case our value is a Windows
# path
value_str = "'#{value_str}'" if value.is_a?(String)
" #{param} => #{value_str}"
end.join(",\n")
<<-MANIFEST
exec { 'run_test_command':
#{params_str}
}
MANIFEST
end
step 'Passes the user-specified environment variables into the command' do
manifest = exec_resource_manifest.call(
command: print_env_vars.call('ENV_VAR_ONE', 'ENV_VAR_TWO'),
environment: ['ENV_VAR_ONE=VALUE_ONE', 'ENV_VAR_TWO=VALUE_TWO']
)
apply_manifest_on(agent, manifest) do |result|
assert_env_var_values(result.stdout, ENV_VAR_ONE: 'VALUE_ONE', ENV_VAR_TWO: 'VALUE_TWO')
end
end
step "Temporarily overrides previously set environment variables" do
manifest = exec_resource_manifest.call(
command: print_env_vars.call('ENV_VAR_ONE'),
environment: ['ENV_VAR_ONE=VALUE_OVERRIDE']
)
apply_manifest_on(agent, manifest, environment: { 'ENV_VAR_ONE' => 'VALUE' }) do |result|
assert_env_var_values(result.stdout, ENV_VAR_ONE: 'VALUE_OVERRIDE')
end
end
step "Temporarily overrides previously set environment variables even if the passed-in value is empty" do
manifest = exec_resource_manifest.call(
command: print_env_vars.call('ENV_VAR_ONE'),
environment: ['ENV_VAR_ONE=']
)
apply_manifest_on(agent, manifest, environment: { 'ENV_VAR_ONE' => 'VALUE' }) do |result|
assert_env_var_values(result.stdout, ENV_VAR_ONE: '')
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/resource/exec/should_run_command_in_cwd.rb | acceptance/tests/resource/exec/should_run_command_in_cwd.rb | test_name "The Exec resource should run commands in the specified cwd" do
tag 'audit:high',
'audit:acceptance'
confine :except, :platform => /debian-12-amd64/ # PUP-12020
require 'puppet/acceptance/windows_utils'
extend Puppet::Acceptance::WindowsUtils
# Useful utility that converts a string literal
# to a regex. We do a lot of assertions on file
# paths here that we need to escape, so this is
# a nice way of making the code more readable.
def to_regex(str)
Regexp.new(Regexp.escape(str))
end
def exec_resource_manifest(command, params = {})
default_params = {
:command => command
}
params = default_params.merge(params)
params_str = params.map do |param, value|
value_str = value.to_s
# Single quote the strings in case our value is a Windows
# path
value_str = "'#{value_str}'" if value.is_a?(String)
" #{param} => #{value_str}"
end.join(",\n")
<<-MANIFEST
exec { 'run_test_command':
#{params_str}
}
MANIFEST
end
def assert_file_on(host, filepath, failure_comment)
if host.platform =~ /windows/
cmd = "cmd.exe /c \"type #{filepath.gsub('/', '\\')}\""
else
cmd = "test -f #{filepath}"
end
on(host, cmd, :acceptable_exit_codes => [0, 1]) do |result|
assert_equal(0, result.exit_code, failure_comment)
end
end
agents.each do |agent|
testdir = agent.tmpdir("mock_testdir")
if agent.platform =~ /windows/
path = 'C:\Windows\System32'
echo_to = 'cmd.exe /c echo testing >'
cat = 'cmd.exe /c type'
non_existant_dir = 'C:\does_not_exist'
origin_working_dir = on(agent, 'cmd.exe /c echo %CD%').stdout.chomp
else
path = '/usr/bin:/usr/sbin:/bin:/sbin'
echo_to = 'echo testing >'
cat = 'cat'
non_existant_dir = '/does_not_exist'
origin_working_dir = on(agent, 'pwd').stdout.chomp
end
step "clean current working directory" do
on(agent, "rm -f cwd_test*")
end
step "Defaults to the current directory if the CWD option is not provided" do
apply_manifest_on(agent, exec_resource_manifest("#{echo_to} cwd_test1", {:path => path}), :catch_failures => true)
assert_file_on(agent, File.join(origin_working_dir, 'cwd_test1'), 'Exec did not create file in origin pwd, exec resource not defaulting to pwd when no :cwd option is given')
end
step "Runs the command in the user specified CWD" do
apply_manifest_on(agent, exec_resource_manifest("#{echo_to} cwd_test2", {:cwd => testdir, :path => path}), :catch_failures => true)
assert_file_on(agent, File.join(testdir, 'cwd_test2'), 'Exec did not create file in test directory, exec resource not using :cwd given')
end
step "Errors if the user specified CWD does not exist" do
apply_manifest_on(agent, exec_resource_manifest("#{echo_to} cwd_test3", {cwd: non_existant_dir, :path => path}), :expect_failures => true) do |result|
assert_equal(4, result.exit_code, "Exec manifest still executed with non-existant :cwd")
end
end
# "onlyif" testing will require some form of runnable test in the testdir for the
# onlyif clause to actually execute. The runnable test we will use is attempting to
# 'cat' an unqualified file that will only exist in the testdir
create_remote_file(agent, File.join(testdir, 'testdir_onlyif.txt'), 'testing')
step 'Runs a "check" command (:onlyif or :unless) in the user specified CWD' do
apply_manifest_on(agent, exec_resource_manifest("#{echo_to} cwd_test4", {cwd: testdir, :path => path, :onlyif => "#{cat} testdir_onlyif.txt"}), :expect_changes => true)
assert_file_on(agent, File.join(testdir, 'cwd_test4'), 'Exec did not create file in test directory, exec resource not using :cwd given')
end
step 'Does not run the exec if the "check" command (:onlyif or :unless) fails' do
apply_manifest_on(agent, exec_resource_manifest("#{echo_to} cwd_test5", {cwd: testdir, :path => path, :onlyif => "foobar"}), :expect_failures => true) do |result|
assert_equal(4, result.exit_code, "Exec manifest still executed with failed :onlyif clause")
end
end
tmpdir_noaccess = agent.tmpdir("mock_dir")
create_remote_file(agent, File.join(tmpdir_noaccess, 'noaccess.txt'), 'foobar')
username = "pl#{rand(999999).to_i}"
# The next two steps set up to test running with a CWD that the user does not have access to.
# The setup for the test creates 1. a new user and 2. a new directory that the new user does
# not have access to.
step "Setup user for 'no access' test" do
agent.user_present(username)
if agent.platform =~ /solaris/
# for some reason applications of 'user_present' on solaris 10 don't manage the homedir correctly, so just
# force a puppet apply to manage the user
on agent, puppet_resource('user', username, "ensure=present managehome=true home=/export/home/#{username}")
# we need to create the user directory ourselves in order for solaris users to successfully login
on(agent, "mkdir /export/home/#{username} && chown -R #{username} /export/home/#{username}")
elsif agent.platform =~ /osx/
# we need to create the user directory ourselves in order for macos users to successfully login
on(agent, "mkdir /Users/#{username} && chown -R #{username}:80 /Users/#{username}")
elsif agent.platform =~ /debian|ubuntu|sles/
# we need to create the user directory ourselves in order for deb users to successfully login
on(agent, "mkdir /home/#{username} && chown -R #{username} /home/#{username}")
end
teardown { agent.user_absent(username) }
end
tmpdir_noaccess = agent.tmpdir("mock_noaccess")
create_remote_file(agent, File.join(tmpdir_noaccess, 'noaccess.txt'), 'foobar')
step "Setup restricted access directory for 'no access' test" do
if agent.platform =~ /windows/
deny_administrator_access_to(agent, tmpdir_noaccess)
deny_administrator_access_to(agent, File.join(tmpdir_noaccess, 'noaccess.txt'))
else
if agent.platform =~ /osx/
# This is a little nuts, but on MacOS the tmpdir returned from agent.tmpdir is located in
# a directory that users other than root can't even access, i.e. other users won't have access
# to either the noaccess dir itself (which we want) _or the tmpdir root it's located in_. This is
# a problem since it will look to puppet like the noacceess dir doesn't exist at all, and so we
# can't count on any reliaable failure since we want a return indicating no access, not a missing directory.
#
# To get around this for MacOS platforms we simply use the new user's homedir as the 'tmpdir' and
# put the noaccess dir there.
on(agent, "mkdir /Users/#{username}/noaccess_test && cp #{tmpdir_noaccess}/noaccess.txt /Users/#{username}/noaccess_test && chmod -R 600 /Users/#{username}/noaccess_test")
tmpdir_noaccess = "/Users/#{username}/noaccess_test"
end
# remove permissions for all other users other than root, which should force puppet to fail when running as another user
on(agent, "chmod -R 600 #{tmpdir_noaccess}")
end
end
step "Errors if the user does not have access to the specified CWD" do
manifest_path = agent.tmpfile('apply_manifest.pp')
create_remote_file(agent, manifest_path, exec_resource_manifest("#{cat} noaccess.txt", {:cwd => tmpdir_noaccess, :path => path}))
if agent.platform =~ /windows/
on(agent, "cmd.exe /c \"puppet apply #{manifest_path} --detailed-exitcodes\"", :acceptable_exit_codes => [4]) do |result|
assert_equal(4, result.exit_code, "Exec manifest still executed inside restricted directory", )
end
elsif agent.platform =~ /osx/
# on MacOS we need to copy the manifest to run to the user's home dir and give the user ownership. otherwise puppet won't run on it.
on(agent, "cp #{manifest_path} /Users/#{username}/noaccess_manifest.pp && chown #{username}:80 /Users/#{username}/noaccess_manifest.pp")
on(agent, "su - #{username} -c \"/opt/puppetlabs/bin/puppet apply /Users/#{username}/noaccess_manifest.pp --detailed-exitcodes\"", :acceptable_exit_codes => [4]) do |result|
assert_equal(4, result.exit_code, "Exec manifest still executed inside restricted directory")
end
else
on(agent, "chown #{username} #{manifest_path}")
if agent.platform =~ /solaris|aix/
on(agent, "su - #{username} -c \"/opt/puppetlabs/bin/puppet apply #{manifest_path} --detailed-exitcodes\"", :acceptable_exit_codes => [4]) do |result|
assert_equal(4, result.exit_code, "Exec manifest still executed inside restricted directory")
end
else
on(agent, "su #{username} -c \"/opt/puppetlabs/bin/puppet apply #{manifest_path} --detailed-exitcodes\"", :acceptable_exit_codes => [4]) do |result|
assert_equal(4, result.exit_code, "Exec manifest still executed inside restricted directory")
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/resource/exec/accept_multi-line_commands.rb | acceptance/tests/resource/exec/accept_multi-line_commands.rb | test_name "Be able to execute multi-line commands (#9996)"
confine :except, :platform => 'windows'
tag 'audit:high',
'audit:refactor', # Use block style `test_name`
'audit:acceptance'
agents.each do |agent|
temp_file_name = agent.tmpfile('9996-multi-line-commands')
test_manifest = <<HERE
exec { "test exec":
command => "/bin/echo '#Test' > #{temp_file_name};
/bin/echo 'bob' >> #{temp_file_name};"
}
HERE
expected_results = <<HERE
#Test
bob
HERE
on(agent, "rm -f #{temp_file_name}")
apply_manifest_on agent, test_manifest
on(agent, "cat #{temp_file_name}") do |result|
assert_equal(expected_results, result.stdout, "Unexpected result for host '#{agent}'")
end
on(agent, "rm -f #{temp_file_name}")
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/tests/resource/exec/should_not_run_command_creates.rb | acceptance/tests/resource/exec/should_not_run_command_creates.rb | test_name "should not run command creates"
tag 'audit:high',
'audit:refactor', # Use block style `test_name`
'audit:acceptance'
agents.each do |agent|
touch = agent.tmpfile('touched')
donottouch = agent.tmpfile('not-touched')
manifest = %Q{
exec { "test#{Time.new.to_i}": command => '#{agent.touch(donottouch)}', creates => "#{touch}"}
}
step "prepare the agents for the test"
on agent, "touch #{touch} && rm -f #{donottouch}"
step "test using puppet apply"
apply_manifest_on(agent, manifest) do |result|
fail_test "looks like the thing executed, which it shouldn't" if
result.stdout.include? 'executed successfully'
end
step "verify the file didn't get created"
on agent, "test -f #{donottouch}", :acceptable_exit_codes => [1]
step "prepare the agents for the second part of the test"
on agent, "touch #{touch} ; rm -f #{donottouch}"
step "test using puppet resource"
on(agent, puppet_resource('exec', "test#{Time.new.to_i}",
"command='#{agent.touch(donottouch)}'",
"creates='#{touch}'")) do |result|
fail_test "looks like the thing executed, which it shouldn't" if
result.stdout.include? 'executed successfully'
end
step "verify the file didn't get created the second time"
on agent, "test -f #{donottouch}", :acceptable_exit_codes => [1]
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/tests/resource/exec/should_run_bad_command.rb | acceptance/tests/resource/exec/should_run_bad_command.rb | test_name "tests that puppet can run badly written scripts that fork and inherit descriptors"
tag 'audit:high',
'audit:refactor', # Use block style `test_name`
'audit:acceptance'
def sleepy_daemon_script(agent)
if agent['platform'] =~ /win/
# Windows uses a shorter sleep, because it's expected to wait until the end.
return <<INITSCRIPT
echo hello
start /b ping.exe 127.0.0.1 -n 1
INITSCRIPT
else
return <<INITSCRIPT
echo hello
/bin/sleep 60 &
INITSCRIPT
end
end
# TODO: taken from pxp-agent, find common home
def stop_sleep_process(targets, accept_no_pid_found = false)
targets = [targets].flatten
targets.each do |target|
case target['platform']
when /osx/
command = "ps -e -o pid,comm | grep sleep | sed 's/^[^0-9]*//g' | cut -d\\ -f1"
when /win/
command = "cmd.exe /C WMIC path win32_process WHERE Name=\\\"PING.EXE\\\" get ProcessId | egrep -o '[0-9]+\\s*$'"
else
command = "ps -ef | grep 'bin/sleep ' | grep -v 'grep' | grep -v 'true' | sed 's/^[^0-9]*//g' | cut -d\\ -f1"
end
# A failed test may leave an orphaned sleep process, handle multiple matches.
pids = nil
on(target, command, accept_all_exit_codes: accept_no_pid_found) do |output|
pids = output.stdout.chomp.split
if pids.empty? && !accept_no_pid_found
raise("Did not find a pid for a sleep process on #{target}")
end
end
pids.each do |pid|
target['platform'] =~ /win/ ?
on(target, "taskkill /F /pid #{pid}") :
on(target, "kill -s TERM #{pid}")
end
end
end
teardown do
# On Windows, Puppet waits until the sleep process exits before exiting
stop_sleep_process(agents.select {|agent| agent['platform'] =~ /win/}, true)
# Requiring a sleep process asserts that Puppet exited before the sleep process.
stop_sleep_process(agents.reject {|agent| agent['platform'] =~ /win/})
end
agents.each do |agent|
ext = if agent['platform'] =~ /win/ then '.bat' else '' end
daemon = agent.tmpfile('sleepy_daemon') + ext
create_remote_file(agent, daemon, sleepy_daemon_script(agent))
on(agent, "chmod +x #{daemon}")
apply_manifest_on(agent, "exec {'#{daemon}': logoutput => true}") do |result|
fail_test "didn't seem to run the command" unless
result.stdout.include? 'executed successfully' unless agent['locale'] == 'ja'
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/resource/exec/should_set_path.rb | acceptance/tests/resource/exec/should_set_path.rb | test_name "the path statement should work to locate commands"
tag 'audit:high',
'audit:refactor', # Use block style `test_name`
'audit:acceptance'
agents.each do |agent|
file = agent.tmpfile('touched-should-set-path')
step "clean up the system for the test"
on agent, "rm -f #{file}"
step "invoke the exec resource with a path set"
on(agent, puppet_resource('exec', 'test',
"command='#{agent.touch(file, false)}'", "path='#{agent.path}'"))
step "verify that the files were created"
on agent, "test -f #{file}"
step "clean up the system after testing"
on agent, "rm -f #{file}"
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/tests/resource/exec/should_accept_large_output.rb | acceptance/tests/resource/exec/should_accept_large_output.rb | test_name "tests that puppet correctly captures large and empty output."
tag 'audit:high',
'audit:refactor', # Use block style `test_name`
'audit:acceptance'
agents.each do |agent|
testfile = agent.tmpfile('should_accept_large_output')
# Generate >64KB file to exceed pipe buffer.
lorem_ipsum = <<EOF
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint
occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
EOF
create_remote_file(agent, testfile, lorem_ipsum*1024)
apply_manifest_on(agent, "exec {'cat #{testfile}': path => ['/bin', '/usr/bin', 'C:/cygwin32/bin', 'C:/cygwin64/bin', 'C:/cygwin/bin'], logoutput => true}") do |result|
fail_test "didn't seem to run the command" unless
result.stdout.include? 'executed successfully' unless agent['locale'] == 'ja'
fail_test "didn't print output correctly" unless
result.stdout.lines.select {|line| line =~ /\/returns:/}.count == 4097
end
apply_manifest_on(agent, "exec {'echo': path => ['/bin', '/usr/bin', 'C:/cygwin32/bin', 'C:/cygwin64/bin', 'C:/cygwin/bin'], logoutput => true}") do |result|
fail_test "didn't seem to run the command" unless
result.stdout.include? 'executed successfully' unless agent['locale'] == 'ja'
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/resource/group/should_manage_attributes_aix.rb | acceptance/tests/resource/group/should_manage_attributes_aix.rb | test_name "should correctly manage the attributes property for the Group (AIX only)" do
confine :to, :platform => /aix/
tag 'audit:high',
'audit:acceptance' # Could be done as integration tests, but would
# require changing the system running the test
# in ways that might require special permissions
# or be harmful to the system running the test
require 'puppet/acceptance/aix_util'
extend Puppet::Acceptance::AixUtil
initial_attributes = {
'admin' => true
}
changed_attributes = {
'admin' => false
}
run_attribute_management_tests('group', :gid, initial_attributes, changed_attributes)
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/tests/resource/group/should_modify_gid.rb | acceptance/tests/resource/group/should_modify_gid.rb | test_name "should modify gid of existing group"
confine :except, :platform => 'windows'
tag 'audit:high',
'audit:refactor', # Use block style `test_name`
'audit:acceptance' # Could be done at the integration (or unit) layer though
# actual changing of resources could irreparably damage a
# host running this, or require special permissions.
name = "pl#{rand(999999).to_i}"
gid1 = (rand(989999).to_i + 10000)
gid2 = (rand(989999).to_i + 10000)
agents.each do |agent|
# AIX group provider returns quoted gids
step "ensure that the group exists with gid #{gid1}"
on(agent, puppet_resource('group', name, 'ensure=present', "gid=#{gid1}")) do |result|
fail_test "missing gid notice" unless result.stdout =~ /gid +=> +'?#{gid1}'?/
end
step "ensure that we can modify the GID of the group to #{gid2}"
on(agent, puppet_resource('group', name, 'ensure=present', "gid=#{gid2}")) do |result|
fail_test "missing gid notice" unless result.stdout =~ /gid +=> +'?#{gid2}'?/
end
step "verify that the GID changed"
gid_output = agent.group_gid(name).to_i
fail_test "gid #{gid_output} does not match expected value of: #{gid2}" unless gid_output == gid2
step "clean up the system after the test run"
on(agent, puppet_resource('group', name, 'ensure=absent'))
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/tests/resource/group/should_not_create_existing.rb | acceptance/tests/resource/group/should_not_create_existing.rb | test_name "group should not create existing group"
tag 'audit:high',
'audit:refactor', # Use block style `test_name`
'audit:acceptance' # Could be done at the integration (or unit) layer though
# actual changing of resources could irreparably damage a
# host running this, or require special permissions.
name = "gr#{rand(999999).to_i}"
agents.each do |agent|
step "ensure the group exists on the target node"
agent.group_present(name)
step "verify that we don't try and create the existing group"
on(agent, puppet_resource('group', name, 'ensure=present')) do |result|
fail_test "looks like we created the group" if
result.stdout.include? "/Group[#{name}]/ensure: created"
end
step "clean up the system after the test run"
agent.group_absent(name)
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/tests/resource/group/should_destroy.rb | acceptance/tests/resource/group/should_destroy.rb | test_name "should destroy a group"
tag 'audit:high',
'audit:refactor', # Use block style `test_name`
'audit:acceptance' # Could be done at the integration (or unit) layer though
# actual changing of resources could irreparably damage a
# host running this, or require special permissions.
name = "pl#{rand(999999).to_i}"
agents.each do |agent|
step "ensure the group is present"
agent.group_present(name)
step "delete the group"
on agent, puppet_resource('group', name, 'ensure=absent')
step "verify the group was deleted"
agent.group_absent(name)
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/tests/resource/group/should_not_destroy_unexisting.rb | acceptance/tests/resource/group/should_not_destroy_unexisting.rb | test_name "should not destroy a group that doesn't exist"
tag 'audit:high',
'audit:refactor', # Use block style `test_name`
'audit:acceptance' # Could be done at the integration (or unit) layer though
# actual changing of resources could irreparably damage a
# host running this, or require special permissions.
name = "test-group-#{Time.new.to_i}"
step "verify the group does not already exist"
agents.each do |agent|
agent.group_absent(name)
end
step "verify that we don't remove the group when it doesn't exist"
on(agents, puppet_resource('group', name, 'ensure=absent')) do |result|
fail_test "it looks like we tried to remove the group" if
result.stdout.include? "/Group[#{name}]/ensure: removed"
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/tests/resource/group/should_query_all.rb | acceptance/tests/resource/group/should_query_all.rb | test_name "should query all groups"
tag 'audit:high',
'audit:refactor', # Use block style `test_name`
'audit:integration' # Does not modify system running test
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 "query natively"
groups = agent.group_list
fail_test("No groups found") unless groups
step "query with puppet"
on(agent, puppet_resource('group')) do |result|
result.stdout.each_line do |line|
name = ( line.match(/^group \{ '([^']+)'/) or next )[1]
unless groups.delete(name)
fail_test "group #{name} found by puppet, not natively"
end
end
end
if groups.length > 0 then
fail_test "#{groups.length} groups found natively, not puppet: #{groups.join(', ')}"
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/resource/group/should_create.rb | acceptance/tests/resource/group/should_create.rb | test_name "should create a group"
tag 'audit:high',
'audit:refactor', # Use block style `test_name`
'audit:acceptance' # Could be done at the integration (or unit) layer though
# actual changing of resources could irreparably damage a
# host running this, or require special permissions.
name = "pl#{rand(999999).to_i}"
agents.each do |agent|
step "ensure the group does not exist"
agent.group_absent(name)
step "create the group"
on agent, puppet_resource('group', name, 'ensure=present')
step "verify the group exists"
agent.group_get(name)
step "delete the group"
agent.group_absent(name)
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/tests/resource/group/should_manage_members.rb | acceptance/tests/resource/group/should_manage_members.rb | test_name "should correctly manage the members property for the Group resource" do
# These are the only platforms whose group providers manage the members
# property
confine :to, :platform => /windows|osx|aix|^el-|fedora/
tag 'audit:high',
'audit:acceptance' # Could be done as integration tests, but would
# require changing the system running the test
# in ways that might require special permissions
# or be harmful to the system running the test
require 'puppet/acceptance/common_utils'
extend Puppet::Acceptance::BeakerUtils
def random_name
"pl#{rand(999999).to_i}"
end
def group_manifest(user, 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
group { '#{user}':
#{params_str}
}
MANIFEST
end
def members_of(host, group)
case host['platform']
when /windows/
# More verbose than 'net localgroup <group>', but more programmatic
# because it does not require us to parse stdout
get_group_members = <<-PS1
# Adapted from https://github.com/RamblingCookieMonster/PowerShell/blob/master/Get-ADGroupMembers.ps1
function Get-Members([string] $group) {
$ErrorActionPreference = 'Stop'
Add-Type -AssemblyName 'System.DirectoryServices.AccountManagement' -ErrorAction Stop
$contextType = [System.DirectoryServices.AccountManagement.ContextType]::Machine
$groupObject = [System.DirectoryServices.AccountManagement.GroupPrincipal]::FindByIdentity(
$contextType,
$group
)
if (-Not $groupObject) {
throw "Could not find the group '$group'!"
}
$members = $groupObject.GetMembers($false) | ForEach-Object { "'$($_.Name)'" }
write-output "[$([string]::join(',', $members))]"
}
Get-Members #{group}
PS1
Kernel.eval(
execute_powershell_script_on(host, get_group_members).stdout.chomp
)
else
# This reads the group members from the /etc/group file
get_group_members = <<-RUBY
require 'etc'
group_struct = nil
Etc.group do |g|
if g.name == '#{group}'
group_struct = g
break
end
end
unless group_struct
raise "Could not find the group '#{group}'!"
end
puts(group_struct.mem.to_s)
RUBY
script_path = "#{host.tmpfile("get_group_members")}.rb"
create_remote_file(host, script_path, get_group_members)
# The setup step should have already set :privatebindir on the
# host. We only include the default here to make this routine
# work for local testing, which sometimes skips the setup step.
privatebindir = host.has_key?(:privatebindir) ? host[:privatebindir] : '/opt/puppetlabs/puppet/bin'
result = on(host, "#{privatebindir}/ruby #{script_path}")
Kernel.eval(result.stdout.chomp)
end
end
agents.each do |agent|
users = 6.times.collect { random_name }
users.each { |user| agent.user_absent(user) }
group = random_name
agent.group_absent(group)
teardown { agent.group_absent(group) }
step 'Creating the Users' do
users.each do |user|
agent.user_present(user)
teardown { agent.user_absent(user) }
end
end
group_members = [users[0], users[1]]
step 'Ensure that the group is created with the specified members' do
manifest = group_manifest(group, members: group_members)
apply_manifest_on(agent, manifest)
assert_matching_arrays(group_members, members_of(agent, group), "The group was not successfully created with the specified members!")
end
step "Verify that Puppet errors when one of the members does not exist" do
manifest = group_manifest(group, members: ['nonexistent_member'])
apply_manifest_on(agent, manifest, :acceptable_exit_codes => [0, 1]) do |result|
assert_match(/Error:.*#{group}/, result.stderr, "Puppet fails to report an error when one of the members in the members property does not exist")
end
end
step "Verify that Puppet noops when the group's members are already set after creating the group" do
manifest = group_manifest(group, members: group_members)
apply_manifest_on(agent, manifest, catch_changes: true)
assert_matching_arrays(group_members, members_of(agent, group), "The group's members somehow changed despite Puppet reporting a noop")
end
step "Verify that Puppet enforces minimum user membership when auth_membership == false" do
new_members = [users[2], users[4]]
manifest = group_manifest(group, members: new_members, auth_membership: false)
apply_manifest_on(agent, manifest)
group_members += new_members
assert_matching_arrays(group_members, members_of(agent, group), "Puppet fails to enforce minimum user membership when auth_membership == false")
end
step "Verify that Puppet noops when the group's members are already set after enforcing minimum user membership" do
manifest = group_manifest(group, members: group_members)
apply_manifest_on(agent, manifest, catch_changes: true)
assert_matching_arrays(group_members, members_of(agent, group), "The group's members somehow changed despite Puppet reporting a noop")
end
# Run some special, platform-specific tests. If these get too large, then
# we should consider placing them in a separate file.
case agent['platform']
when /windows/
domain = on(agent, 'hostname').stdout.chomp.upcase
step "(Windows) Verify that Puppet prints each group member as DOMAIN\\<user>" do
new_members = [users[3]]
manifest = group_manifest(group, members: new_members, auth_membership: false)
apply_manifest_on(agent, manifest) do |result|
group_members += new_members
stdout = result.stdout.chomp
group_members.each do |user|
assert_match(/#{domain}\\#{user}/, stdout, "Puppet fails to print the group member #{user} as #{domain}\\#{user}")
end
end
end
step "(Windows) Verify that `puppet resource` prints each group member as DOMAIN\\<user>" do
on(agent, puppet('resource', 'group', group)) do |result|
stdout = result.stdout.chomp
group_members.each do |user|
assert_match(/#{domain}\\#{user}/, stdout, "`puppet resource` fails to print the group member #{user} as #{domain}\\#{user}")
end
end
end
when /aix/
step "(AIX) Verify that Puppet accepts a comma-separated list of members for backwards compatibility" do
new_members = [users[3], users[5]]
manifest = group_manifest(group, members: new_members.join(','), auth_membership: false)
apply_manifest_on(agent, manifest)
group_members += new_members
assert_matching_arrays(group_members, members_of(agent, group), "Puppet cannot manage the members property when the members are provided as a comma-separated list")
end
end
step "Verify that Puppet enforces inclusive user membership when auth_membership == true" do
group_members = [users[0]]
manifest = group_manifest(group, members: group_members, auth_membership: true)
apply_manifest_on(agent, manifest)
assert_matching_arrays(group_members, members_of(agent, group), "Puppet fails to enforce inclusive group membership when auth_membership == true")
end
step "Verify that Puppet noops when the group's members are already set after enforcing inclusive user membership" do
manifest = group_manifest(group, members: group_members)
apply_manifest_on(agent, manifest, catch_changes: true)
assert_matching_arrays(group_members, members_of(agent, group), "The group's members somehow changed despite Puppet reporting a noop")
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/resource/group/should_query.rb | acceptance/tests/resource/group/should_query.rb | test_name "test that we can query and find a group that exists."
tag 'audit:high',
'audit:refactor', # Use block style `test_name`
'audit:acceptance' # Could be done at the integration (or unit) layer though
# actual changing of resources could irreparably damage a
# host running this, or require special permissions.
name = "pl#{rand(999999).to_i}"
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 "ensure that our test group exists"
agent.group_present(name)
step "query for the resource and verify it was found"
on(agent, puppet_resource('group', name)) do |result|
fail_test "didn't find the group #{name}" unless result.stdout.include? 'present'
end
step "clean up the group we added"
agent.group_absent(name)
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/tests/resource/package/yum.rb | acceptance/tests/resource/package/yum.rb | test_name "test the yum package provider" do
confine :to, {:platform => /(?:centos|el-|fedora)/}, agents
# Skipping tests if facter finds this is an ec2 host, PUP-7774
agents.each do |agent|
skip_test('Skipping EC2 Hosts') if fact_on(agent, 'ec2_metadata')
end
# Upgrade the AlmaLinux release package for newer keys until our image is updated (RE-16096)
agents.each do |agent|
on(agent, 'dnf -y upgrade almalinux-release') if fact_on(agent, 'os.name') == 'AlmaLinux'
end
tag 'audit:high',
'audit:acceptance' # Could be done at the integration (or unit) layer though
# actual changing of resources could irreparably damage a
# host running this, or require special permissions.
require 'puppet/acceptance/rpm_util'
extend Puppet::Acceptance::RpmUtils
epoch_rpm_options = {:pkg => 'epoch', :version => '1.1', :epoch => '1'}
no_epoch_rpm_options = {:pkg => 'guid', :version => '1.0'}
teardown do
step "cleanup"
agents.each do |agent|
clean_rpm agent, epoch_rpm_options
clean_rpm agent, no_epoch_rpm_options
end
end
def verify_state(hosts, pkg, state, match)
hosts.each do |agent|
cmd = rpm_provider(agent)
# Note yum and dnf list packages as <name>.<arch>
on(agent, "#{cmd} list installed") do |result|
method(match).call(/^#{pkg}\./, result.stdout)
end
end
end
def verify_present(hosts, pkg)
verify_state(hosts, pkg, '(?!purged|absent)[^\']+', :assert_match)
end
def verify_absent(hosts, pkg)
verify_state(hosts, pkg, '(?:purged|absent)', :refute_match)
end
step "Managing a package which does not include an epoch in its version" do
step 'Setup repo and package'
agents.each do |agent|
clean_rpm agent, no_epoch_rpm_options
setup_rpm agent, no_epoch_rpm_options
send_rpm agent, no_epoch_rpm_options
end
step 'Installing a known package succeeds' do
verify_absent agents, 'guid'
apply_manifest_on(agents, 'package {"guid": ensure => installed}') do |result|
assert_match('Package[guid]/ensure: created', "#{result.host}: #{result.stdout}")
end
end
step 'Removing a known package succeeds' do
verify_present agents, 'guid'
apply_manifest_on(agents, 'package {"guid": ensure => absent}') do |result|
assert_match('Package[guid]/ensure: removed', "#{result.host}: #{result.stdout}")
end
end
step 'Installing a specific version of a known package succeeds' do
verify_absent agents, 'guid'
apply_manifest_on(agents, 'package {"guid": ensure => "1.0"}') do |result|
assert_match('Package[guid]/ensure: created', "#{result.host}: #{result.stdout}")
end
end
step 'Removing a specific version of a known package succeeds' do
verify_present agents, 'guid'
apply_manifest_on(agents, 'package {"guid": ensure => absent}') do |result|
assert_match('Package[guid]/ensure: removed', "#{result.host}: #{result.stdout}")
end
end
step 'Installing a non-existent version of a known package fails' do
verify_absent agents, 'guid'
apply_manifest_on(agents, 'package {"guid": ensure => "1.1"}') do |result|
refute_match(/Package\[guid\]\/ensure: created/, "#{result.host}: #{result.stdout}")
assert_match("Package[guid]/ensure: change from 'purged' to '1.1' failed", "#{result.host}: #{result.stderr}")
end
verify_absent agents, 'guid'
end
step 'Installing a non-existent package fails' do
verify_absent agents, 'not_a_package'
apply_manifest_on(agents, 'package {"not_a_package": ensure => present}') do |result|
refute_match(/Package\[not_a_package\]\/ensure: created/, "#{result.host}: #{result.stdout}")
assert_match("Package[not_a_package]/ensure: change from 'purged' to 'present' failed", "#{result.host}: #{result.stderr}")
end
verify_absent agents, 'not_a_package'
end
step 'Removing a non-existent package succeeds' do
verify_absent agents, 'not_a_package'
apply_manifest_on(agents, 'package {"not_a_package": ensure => absent}') do |result|
refute_match(/Package\[not_a_package\]\/ensure/, "#{result.host}: #{result.stdout}")
assert_match('Applied catalog', "#{result.host}: #{result.stdout}")
end
verify_absent agents, 'not_a_package'
end
step 'Installing a known package using source succeeds' do
verify_absent agents, 'guid'
apply_manifest_on(agents, "package { 'guid': ensure => installed, install_options => '--nogpgcheck', source=>'/tmp/rpmrepo/RPMS/noarch/guid-1.0-1.noarch.rpm' }") do |result|
assert_match('Package[guid]/ensure: created', "#{result.host}: #{result.stdout}")
end
end
end
### Epoch tests ###
agents.each do |agent|
step "Managing a package which includes an epoch in its version" do
step "Setup repo and package" do
clean_rpm agent, no_epoch_rpm_options
setup_rpm agent, epoch_rpm_options
send_rpm agent, epoch_rpm_options
end
step 'Installing a known package with an epoch succeeds' do
verify_absent [agent], 'epoch'
apply_manifest_on(agent, 'package {"epoch": ensure => installed}') do |result|
assert_match('Package[epoch]/ensure: created', "#{result.host}: #{result.stdout}")
end
end
step 'Removing a known package with an epoch succeeds' do
verify_present [agent], 'epoch'
apply_manifest_on(agent, 'package {"epoch": ensure => absent}') do |result|
assert_match('Package[epoch]/ensure: removed', "#{result.host}: #{result.stdout}")
end
end
step "Installing a specific version of a known package with an epoch succeeds when epoch and arch are specified" do
verify_absent [agent], 'epoch'
apply_manifest_on(agent, "package {'epoch': ensure => '1:1.1-1.noarch'}") do |result|
assert_match('Package[epoch]/ensure: created', "#{result.host}: #{result.stdout}")
end
apply_manifest_on(agent, "package {'epoch': ensure => '1:1.1-1.noarch'}") do |result|
refute_match(/epoch/, result.stdout)
end
end
if rpm_provider(agent) == 'dnf'
# Yum requires the arch to be specified whenever epoch is specified. This step is only
# expected to work in DNF.
step "Installing a specific version of a known package with an epoch succeeds when epoch is specified and arch is not" do
step "Remove the package" do
apply_manifest_on(agent, 'package {"epoch": ensure => absent}')
verify_absent [agent], 'epoch'
end
apply_manifest_on(agent, 'package {"epoch": ensure => "1:1.1-1"}') do |result|
assert_match('Package[epoch]/ensure: created', "#{result.host}: #{result.stdout}")
end
apply_manifest_on(agent, 'package {"epoch": ensure => "1:1.1-1"}') do |result|
refute_match(/epoch/, result.stdout)
end
apply_manifest_on(agent, "package {'epoch': ensure => '1:1.1-1.noarch'}") do |result|
refute_match(/epoch/, result.stdout)
end
end
end
if rpm_provider(agent) == 'yum'
step "Installing a specified version of a known package with an epoch succeeds without epoch or arch provided" do
# Due to a bug in DNF, epoch is required. This step is only expected to work in Yum.
# See https://bugzilla.redhat.com/show_bug.cgi?id=1286877
step "Remove the package" do
apply_manifest_on(agent, 'package {"epoch": ensure => absent}')
verify_absent [agent], 'epoch'
end
apply_manifest_on(agent, 'package {"epoch": ensure => "1.1-1"}') do |result|
assert_match('Package[epoch]/ensure: created', "#{result.host}: #{result.stdout}")
end
apply_manifest_on(agent, 'package {"epoch": ensure => "1.1-1"}') do |result|
refute_match(/epoch/, result.stdout)
end
apply_manifest_on(agent, "package {'epoch': ensure => '1:1.1-1.noarch'}") do |result|
refute_match(/epoch/, result.stdout)
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/resource/package/does_not_exist.rb | acceptance/tests/resource/package/does_not_exist.rb | # Redmine (#22529)
test_name "Puppet returns only resource package declaration when querying an uninstalled package" do
tag 'audit:high',
'audit:acceptance' # Could be done at the integration (or unit) layer though
# actual changing of resources could irreparably damage a
# host running this, or require special permissions.
agents.each do |agent|
step "test puppet resource package" do
on(agent, puppet('resource', 'package', 'not-installed-on-this-host')) do |result|
assert_match(/package.*not-installed-on-this-host.*\n.*ensure.*(?:absent|purged).*\n.*provider/, result.stdout)
end
end
end
# Until #3707 is fixed and purged rpm/yum packages no longer give spurious creation notices
# Also skipping solaris, windows whose providers do not have purgeable implemented.
confine_block(:to, :platform => /debian|ubuntu/) do
agents.each do |agent|
step "test puppet apply" do
on(agent, puppet('apply', '-e', %Q|"package {'not-installed-on-this-host': ensure => purged }"|)) do |result|
refute_match(/warning/i, result.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/acceptance/tests/resource/package/common_package_name_in_different_providers.rb | acceptance/tests/resource/package/common_package_name_in_different_providers.rb | test_name "ticket 1073: common package name in two different providers should be allowed" do
confine :to, {:platform => /(?:centos|el-|fedora)/}, agents
# Skipping tests if facter finds this is an ec2 host, PUP-7774
agents.each do |agent|
skip_test('Skipping EC2 Hosts') if fact_on(agent, 'ec2_metadata')
end
# Upgrade the AlmaLinux release package for newer keys until our image is updated (RE-16096)
agents.each do |agent|
on(agent, 'dnf -y upgrade almalinux-release') if fact_on(agent, 'os.name') == 'AlmaLinux'
end
tag 'audit:high',
'audit:acceptance' # Uses a provider that depends on AIO packaging
require 'puppet/acceptance/rpm_util'
extend Puppet::Acceptance::RpmUtils
require 'puppet/acceptance/common_utils'
extend Puppet::Acceptance::CommandUtils
rpm_options = {:pkg => 'guid', :version => '1.0'}
teardown do
step "cleanup"
agents.each do |agent|
clean_rpm agent, rpm_options
end
end
step "Verify gem and ruby-devel on fedora-22 and above if not aio" do
if @options[:type] != 'aio' then
agents.each do |agent|
if agent[:platform] =~ /fedora-2[2-9]/ then
unless check_for_package agent, 'rubygems'
install_package agent, 'rubygems'
end
unless check_for_package agent, 'ruby-devel'
install_package agent, 'ruby-devel'
end
end
end
end
end
def gem_provider
if @options[:type] == 'aio'
'puppet_gem'
else
'gem'
end
end
def verify_state(hosts, pkg, state, match)
hosts.each do |agent|
cmd = rpm_provider(agent)
# Note yum lists packages as <name>.<arch>
on(agent, "#{cmd} list installed") do |result|
method(match).call(/^#{pkg}\./, result.stdout)
end
on(agent, "#{gem_command(agent, @options[:type])} list --local") do |result|
method(match).call(/^#{pkg} /, result.stdout)
end
end
end
def verify_present(hosts, pkg)
verify_state(hosts, pkg, '(?!purged|absent)[^\']+', :assert_match)
end
def verify_absent(hosts, pkg)
verify_state(hosts, pkg, '(?:purged|absent)', :refute_match)
end
# Setup repo and package
agents.each do |agent|
clean_rpm agent, rpm_options
setup_rpm agent, rpm_options
send_rpm agent, rpm_options
end
verify_absent agents, 'guid'
# Test error trying to install duplicate packages
collide1_manifest = <<-MANIFEST
package {'guid': ensure => installed}
package {'other-guid': name => 'guid', ensure => present}
MANIFEST
apply_manifest_on(agents, collide1_manifest, :acceptable_exit_codes => [1]) do |result|
assert_match(/Error while evaluating a Resource Statement, Cannot alias Package\[other-guid\] to \[nil, "guid", nil\]/, "#{result.host}: #{result.stderr}")
end
verify_absent agents, 'guid'
gem_source = if ENV['GEM_SOURCE'] then "source => '#{ENV['GEM_SOURCE']}'," else '' end
collide2_manifest = <<-MANIFEST
package {'guid': ensure => '0.1.0', provider => #{gem_provider}, #{gem_source}}
package {'other-guid': name => 'guid', ensure => installed, provider => #{gem_provider}, #{gem_source}}
MANIFEST
apply_manifest_on(agents, collide2_manifest, :acceptable_exit_codes => [1]) do |result|
assert_match(/Error while evaluating a Resource Statement, Cannot alias Package\[other-guid\] to \[nil, "guid", "#{gem_provider}"\]/, "#{result.host}: #{result.stderr}")
end
verify_absent agents, 'guid'
# Test successful parallel installation
install_manifest = <<-MANIFEST
package {'guid': ensure => installed}
package {'gem-guid':
provider => #{gem_provider},
name => 'guid',
ensure => installed,
#{gem_source}
}
MANIFEST
apply_manifest_on(agents, install_manifest) do |result|
assert_match('Package[guid]/ensure: created', "#{result.host}: #{result.stdout}")
assert_match('Package[gem-guid]/ensure: created', "#{result.host}: #{result.stdout}")
end
verify_present agents, 'guid'
# Test removal
remove_manifest = <<-MANIFEST
package {'gem-guid':
provider => #{gem_provider},
name => 'guid',
ensure => absent,
#{gem_source}
}
package {'guid': ensure => absent}
MANIFEST
apply_manifest_on(agents, remove_manifest) do |result|
assert_match('Package[guid]/ensure: removed', "#{result.host}: #{result.stdout}")
assert_match('Package[gem-guid]/ensure: removed', "#{result.host}: #{result.stdout}")
end
verify_absent agents, 'guid'
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/acceptance/tests/resource/package/windows.rb | acceptance/tests/resource/package/windows.rb | test_name "Windows Package Provider" do
confine :to, :platform => 'windows'
tag 'audit:high',
'audit:acceptance'
require 'puppet/acceptance/windows_utils'
extend Puppet::Acceptance::WindowsUtils
def package_manifest(name, params, installer_source)
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
package { '#{name}':
source => '#{installer_source}',
#{params_str}
}
MANIFEST
end
mock_package = {
:name => "MockPackage"
}
agents.each do |agent|
tmpdir = agent.tmpdir("mock_installer")
installer_location = create_mock_package(agent, tmpdir, mock_package)
step 'Verify that ensure = present installs the package' do
apply_manifest_on(agent, package_manifest(mock_package[:name], {ensure: :present}, installer_location))
assert(package_installed?(agent, mock_package[:name]), 'Package succesfully installed')
end
step 'Verify that ensure = absent removes the package' do
apply_manifest_on(agent, package_manifest(mock_package[:name], {ensure: :absent}, installer_location))
assert_equal(false, package_installed?(agent, mock_package[:name]), 'Package successfully Uninstalled')
end
tmpdir = agent.tmpdir("mock_installer")
mock_package[:name] = "MockPackageWithFile"
mock_package[:install_commands] = 'System.IO.File.ReadAllLines("install.txt");'
installer_location = create_mock_package(agent, tmpdir, mock_package)
# Since we didn't add the install.txt package the installation should fail with code 1004
step 'Verify that ensure = present fails when an installer fails with a non-zero exit code' do
apply_manifest_on(agent, package_manifest(mock_package[:name], {ensure: :present}, installer_location)) do |result|
assert_match(/#{mock_package[:name]}/, result.stderr, 'Windows package provider did not fail when the package install failed')
end
end
step 'Verify that ensure = present installs a package that requires additional resources' do
create_remote_file(agent, "#{tmpdir}/install.txt", 'foobar')
apply_manifest_on(agent, package_manifest(mock_package[:name], {ensure: :present}, installer_location))
assert(package_installed?(agent, mock_package[:name]), 'Package succesfully installed')
end
step 'Verify that ensure = absent removes the package that required additional resources' do
apply_manifest_on(agent, package_manifest(mock_package[:name], {ensure: :absent}, installer_location))
assert_equal(false, package_installed?(agent, mock_package[:name]), 'Package successfully Uninstalled')
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.