repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/parser_functions/puppet_lookup_cmd.rb
acceptance/tests/parser_functions/puppet_lookup_cmd.rb
test_name "Puppet Lookup Command" tag 'audit:high', 'audit:acceptance', 'audit:refactor' # Master is not required for this test. Replace with agents.each # Wrap steps in blocks in accordance with Beaker style guide # doc: # https://puppet.com/docs/puppet/latest/hiera_automatic.html @module_name = "puppet_lookup_command_test" ### @testroot = "/etc/puppetlabs" @testroot = master.tmpdir("#{@module_name}") @coderoot = "#{@testroot}/code" @confdir = "#{@testroot}/puppet" @node1 = 'node1.example.org' @node2 = 'node2.example.org' @master_opts = { 'main' => { 'environmentpath' => "#{@coderoot}/environments", 'hiera_config' => "#{@coderoot}/hiera.yaml", }, } @manifest = <<MANIFEST File { ensure => directory, mode => "0755", } file { '#{@confdir}':; '#{@coderoot}':; '#{@coderoot}/hieradata':; '#{@coderoot}/environments':; ##### default environment, production '#{@coderoot}/environments/production':; '#{@coderoot}/environments/production/data':; '#{@coderoot}/environments/production/functions':; '#{@coderoot}/environments/production/functions/environment':; '#{@coderoot}/environments/production/lib':; '#{@coderoot}/environments/production/lib/puppet':; '#{@coderoot}/environments/production/lib/puppet/functions':; '#{@coderoot}/environments/production/lib/puppet/functions/environment':; '#{@coderoot}/environments/production/manifests':; '#{@coderoot}/environments/production/modules':; # module mod1 hiera '#{@coderoot}/environments/production/modules/mod1':; '#{@coderoot}/environments/production/modules/mod1/manifests':; '#{@coderoot}/environments/production/modules/mod1/data':; '#{@coderoot}/environments/production/modules/mod1/functions':; '#{@coderoot}/environments/production/modules/mod1/lib':; '#{@coderoot}/environments/production/modules/mod1/lib/puppet':; '#{@coderoot}/environments/production/modules/mod1/lib/puppet/functions':; '#{@coderoot}/environments/production/modules/mod1/lib/puppet/functions/mod1':; # module mod2 ruby function '#{@coderoot}/environments/production/modules/mod2':; '#{@coderoot}/environments/production/modules/mod2/manifests':; '#{@coderoot}/environments/production/modules/mod2/data':; '#{@coderoot}/environments/production/modules/mod2/functions':; '#{@coderoot}/environments/production/modules/mod2/lib':; '#{@coderoot}/environments/production/modules/mod2/lib/puppet':; '#{@coderoot}/environments/production/modules/mod2/lib/puppet/functions':; '#{@coderoot}/environments/production/modules/mod2/lib/puppet/functions/mod2':; # module mod3 puppet function '#{@coderoot}/environments/production/modules/mod3':; '#{@coderoot}/environments/production/modules/mod3/manifests':; '#{@coderoot}/environments/production/modules/mod3/data':; '#{@coderoot}/environments/production/modules/mod3/functions':; '#{@coderoot}/environments/production/modules/mod3/not-lib':; '#{@coderoot}/environments/production/modules/mod3/not-lib/puppet':; '#{@coderoot}/environments/production/modules/mod3/not-lib/puppet/functions':; '#{@coderoot}/environments/production/modules/mod3/not-lib/puppet/functions/mod3':; # module mod4 none '#{@coderoot}/environments/production/modules/mod4':; '#{@coderoot}/environments/production/modules/mod4/manifests':; '#{@coderoot}/environments/production/modules/mod4/data':; '#{@coderoot}/environments/production/modules/mod4/functions':; '#{@coderoot}/environments/production/modules/mod4/lib':; '#{@coderoot}/environments/production/modules/mod4/lib/puppet':; '#{@coderoot}/environments/production/modules/mod4/lib/puppet/functions':; '#{@coderoot}/environments/production/modules/mod4/lib/puppet/functions/mod4':; ##### env1 hiera '#{@coderoot}/environments/env1':; '#{@coderoot}/environments/env1/data':; '#{@coderoot}/environments/env1/functions':; '#{@coderoot}/environments/env1/functions/environment':; '#{@coderoot}/environments/env1/lib':; '#{@coderoot}/environments/env1/lib/puppet':; '#{@coderoot}/environments/env1/lib/puppet/functions':; '#{@coderoot}/environments/env1/lib/puppet/functions/environment':; '#{@coderoot}/environments/env1/manifests':; '#{@coderoot}/environments/env1/modules':; # module mod1 hiera '#{@coderoot}/environments/env1/modules/mod1':; '#{@coderoot}/environments/env1/modules/mod1/manifests':; '#{@coderoot}/environments/env1/modules/mod1/data':; '#{@coderoot}/environments/env1/modules/mod1/functions':; '#{@coderoot}/environments/env1/modules/mod1/lib':; '#{@coderoot}/environments/env1/modules/mod1/lib/puppet':; '#{@coderoot}/environments/env1/modules/mod1/lib/puppet/functions':; '#{@coderoot}/environments/env1/modules/mod1/lib/puppet/functions/mod1':; # module mod2 ruby function '#{@coderoot}/environments/env1/modules/mod2':; '#{@coderoot}/environments/env1/modules/mod2/manifests':; '#{@coderoot}/environments/env1/modules/mod2/data':; '#{@coderoot}/environments/env1/modules/mod2/functions':; '#{@coderoot}/environments/env1/modules/mod2/lib':; '#{@coderoot}/environments/env1/modules/mod2/lib/puppet':; '#{@coderoot}/environments/env1/modules/mod2/lib/puppet/functions':; '#{@coderoot}/environments/env1/modules/mod2/lib/puppet/functions/mod2':; # module mod3 puppet function '#{@coderoot}/environments/env1/modules/mod3':; '#{@coderoot}/environments/env1/modules/mod3/manifests':; '#{@coderoot}/environments/env1/modules/mod3/data':; '#{@coderoot}/environments/env1/modules/mod3/functions':; '#{@coderoot}/environments/env1/modules/mod3/not-lib':; '#{@coderoot}/environments/env1/modules/mod3/not-lib/puppet':; '#{@coderoot}/environments/env1/modules/mod3/not-lib/puppet/functions':; '#{@coderoot}/environments/env1/modules/mod3/not-lib/puppet/functions/mod3':; # module mod4 none '#{@coderoot}/environments/env1/modules/mod4':; '#{@coderoot}/environments/env1/modules/mod4/manifests':; '#{@coderoot}/environments/env1/modules/mod4/data':; '#{@coderoot}/environments/env1/modules/mod4/functions':; '#{@coderoot}/environments/env1/modules/mod4/lib':; '#{@coderoot}/environments/env1/modules/mod4/lib/puppet':; '#{@coderoot}/environments/env1/modules/mod4/lib/puppet/functions':; '#{@coderoot}/environments/env1/modules/mod4/lib/puppet/functions/mod4':; ##### env2 ruby function '#{@coderoot}/environments/env2':; '#{@coderoot}/environments/env2/data':; '#{@coderoot}/environments/env2/functions':; '#{@coderoot}/environments/env2/functions/environment':; '#{@coderoot}/environments/env2/lib':; '#{@coderoot}/environments/env2/lib/puppet':; '#{@coderoot}/environments/env2/lib/puppet/functions':; '#{@coderoot}/environments/env2/lib/puppet/functions/environment':; '#{@coderoot}/environments/env2/manifests':; '#{@coderoot}/environments/env2/modules':; # module mod1 hiera '#{@coderoot}/environments/env2/modules/mod1':; '#{@coderoot}/environments/env2/modules/mod1/manifests':; '#{@coderoot}/environments/env2/modules/mod1/data':; '#{@coderoot}/environments/env2/modules/mod1/functions':; '#{@coderoot}/environments/env2/modules/mod1/lib':; '#{@coderoot}/environments/env2/modules/mod1/lib/puppet':; '#{@coderoot}/environments/env2/modules/mod1/lib/puppet/functions':; '#{@coderoot}/environments/env2/modules/mod1/lib/puppet/functions/mod1':; # module mod2 ruby function '#{@coderoot}/environments/env2/modules/mod2':; '#{@coderoot}/environments/env2/modules/mod2/manifests':; '#{@coderoot}/environments/env2/modules/mod2/data':; '#{@coderoot}/environments/env2/modules/mod2/functions':; '#{@coderoot}/environments/env2/modules/mod2/lib':; '#{@coderoot}/environments/env2/modules/mod2/lib/puppet':; '#{@coderoot}/environments/env2/modules/mod2/lib/puppet/functions':; '#{@coderoot}/environments/env2/modules/mod2/lib/puppet/functions/mod2':; # module mod3 puppet function '#{@coderoot}/environments/env2/modules/mod3':; '#{@coderoot}/environments/env2/modules/mod3/manifests':; '#{@coderoot}/environments/env2/modules/mod3/data':; '#{@coderoot}/environments/env2/modules/mod3/functions':; '#{@coderoot}/environments/env2/modules/mod3/not-lib':; '#{@coderoot}/environments/env2/modules/mod3/not-lib/puppet':; '#{@coderoot}/environments/env2/modules/mod3/not-lib/puppet/functions':; '#{@coderoot}/environments/env2/modules/mod3/not-lib/puppet/functions/mod3':; # module mod4 none '#{@coderoot}/environments/env2/modules/mod4':; '#{@coderoot}/environments/env2/modules/mod4/manifests':; '#{@coderoot}/environments/env2/modules/mod4/data':; '#{@coderoot}/environments/env2/modules/mod4/functions':; '#{@coderoot}/environments/env2/modules/mod4/lib':; '#{@coderoot}/environments/env2/modules/mod4/lib/puppet':; '#{@coderoot}/environments/env2/modules/mod4/lib/puppet/functions':; '#{@coderoot}/environments/env2/modules/mod4/lib/puppet/functions/mod4':; ##### env3 puppet function '#{@coderoot}/environments/env3':; '#{@coderoot}/environments/env3/data':; '#{@coderoot}/environments/env3/functions':; '#{@coderoot}/environments/env3/functions/environment':; '#{@coderoot}/environments/env3/not-lib':; '#{@coderoot}/environments/env3/not-lib/puppet':; '#{@coderoot}/environments/env3/not-lib/puppet/functions':; '#{@coderoot}/environments/env3/not-lib/puppet/functions/environment':; '#{@coderoot}/environments/env3/manifests':; '#{@coderoot}/environments/env3/modules':; # module mod1 hiera '#{@coderoot}/environments/env3/modules/mod1':; '#{@coderoot}/environments/env3/modules/mod1/manifests':; '#{@coderoot}/environments/env3/modules/mod1/data':; '#{@coderoot}/environments/env3/modules/mod1/functions':; '#{@coderoot}/environments/env3/modules/mod1/lib':; '#{@coderoot}/environments/env3/modules/mod1/lib/puppet':; '#{@coderoot}/environments/env3/modules/mod1/lib/puppet/functions':; '#{@coderoot}/environments/env3/modules/mod1/lib/puppet/functions/mod1':; # module mod2 ruby function '#{@coderoot}/environments/env3/modules/mod2':; '#{@coderoot}/environments/env3/modules/mod2/manifests':; '#{@coderoot}/environments/env3/modules/mod2/data':; '#{@coderoot}/environments/env3/modules/mod2/functions':; '#{@coderoot}/environments/env3/modules/mod2/lib':; '#{@coderoot}/environments/env3/modules/mod2/lib/puppet':; '#{@coderoot}/environments/env3/modules/mod2/lib/puppet/functions':; '#{@coderoot}/environments/env3/modules/mod2/lib/puppet/functions/mod2':; # module mod3 puppet function '#{@coderoot}/environments/env3/modules/mod3':; '#{@coderoot}/environments/env3/modules/mod3/manifests':; '#{@coderoot}/environments/env3/modules/mod3/data':; '#{@coderoot}/environments/env3/modules/mod3/functions':; '#{@coderoot}/environments/env3/modules/mod3/not-lib':; '#{@coderoot}/environments/env3/modules/mod3/not-lib/puppet':; '#{@coderoot}/environments/env3/modules/mod3/not-lib/puppet/functions':; '#{@coderoot}/environments/env3/modules/mod3/not-lib/puppet/functions/mod3':; # module mod4 none '#{@coderoot}/environments/env3/modules/mod4':; '#{@coderoot}/environments/env3/modules/mod4/manifests':; '#{@coderoot}/environments/env3/modules/mod4/data':; '#{@coderoot}/environments/env3/modules/mod4/functions':; '#{@coderoot}/environments/env3/modules/mod4/lib':; '#{@coderoot}/environments/env3/modules/mod4/lib/puppet':; '#{@coderoot}/environments/env3/modules/mod4/lib/puppet/functions':; '#{@coderoot}/environments/env3/modules/mod4/lib/puppet/functions/mod4':; ##### env4 none '#{@coderoot}/environments/env4':; '#{@coderoot}/environments/env4/data':; '#{@coderoot}/environments/env4/functions':; '#{@coderoot}/environments/env4/functions/environment':; '#{@coderoot}/environments/env4/lib':; '#{@coderoot}/environments/env4/lib/puppet':; '#{@coderoot}/environments/env4/lib/puppet/functions':; '#{@coderoot}/environments/env4/lib/puppet/functions/environment':; '#{@coderoot}/environments/env4/manifests':; '#{@coderoot}/environments/env4/modules':; # module mod1 hiera '#{@coderoot}/environments/env4/modules/mod1':; '#{@coderoot}/environments/env4/modules/mod1/manifests':; '#{@coderoot}/environments/env4/modules/mod1/data':; '#{@coderoot}/environments/env4/modules/mod1/functions':; '#{@coderoot}/environments/env4/modules/mod1/lib':; '#{@coderoot}/environments/env4/modules/mod1/lib/puppet':; '#{@coderoot}/environments/env4/modules/mod1/lib/puppet/functions':; '#{@coderoot}/environments/env4/modules/mod1/lib/puppet/functions/mod1':; # module mod2 ruby function '#{@coderoot}/environments/env4/modules/mod2':; '#{@coderoot}/environments/env4/modules/mod2/manifests':; '#{@coderoot}/environments/env4/modules/mod2/data':; '#{@coderoot}/environments/env4/modules/mod2/functions':; '#{@coderoot}/environments/env4/modules/mod2/lib':; '#{@coderoot}/environments/env4/modules/mod2/lib/puppet':; '#{@coderoot}/environments/env4/modules/mod2/lib/puppet/functions':; '#{@coderoot}/environments/env4/modules/mod2/lib/puppet/functions/mod2':; # module mod3 puppet function '#{@coderoot}/environments/env4/modules/mod3':; '#{@coderoot}/environments/env4/modules/mod3/manifests':; '#{@coderoot}/environments/env4/modules/mod3/data':; '#{@coderoot}/environments/env4/modules/mod3/functions':; '#{@coderoot}/environments/env4/modules/mod3/not-lib':; '#{@coderoot}/environments/env4/modules/mod3/not-lib/puppet':; '#{@coderoot}/environments/env4/modules/mod3/not-lib/puppet/functions':; '#{@coderoot}/environments/env4/modules/mod3/not-lib/puppet/functions/mod3':; # module mod4 none '#{@coderoot}/environments/env4/modules/mod4':; '#{@coderoot}/environments/env4/modules/mod4/manifests':; '#{@coderoot}/environments/env4/modules/mod4/data':; '#{@coderoot}/environments/env4/modules/mod4/functions':; '#{@coderoot}/environments/env4/modules/mod4/lib':; '#{@coderoot}/environments/env4/modules/mod4/lib/puppet':; '#{@coderoot}/environments/env4/modules/mod4/lib/puppet/functions':; '#{@coderoot}/environments/env4/modules/mod4/lib/puppet/functions/mod4':; } ## Global data provider config (hiera) file { '#{@coderoot}/hiera.yaml': ensure => file, mode => "0644", content => '--- :backends: - "yaml" :logger: "console" :hierarchy: - "global" :yaml: :datadir: "#{@coderoot}/hieradata" ', } ## facts file file { '#{@coderoot}/facts.yaml': ensure => file, mode => "0644", content => '--- my_data_key: "my_data_value" ', } file { '#{@coderoot}/hieradata/global.yaml': ensure => file, mode => "0644", content => '--- global_key: "global-hiera provided value for key" another_global_key: "global-hiera provided value for key" mod1::global_key: "global-hiera provided value for key" mod2::global_key: "global-hiera provided value for key" mod3::global_key: "global-hiera provided value for key" mod4::global_key: "global-hiera provided value for key" ', } ## Evironment data provider configuration file { '#{@coderoot}/environments/production/environment.conf': ensure => file, mode => "0644", content => 'environment_timeout = 0 ', } file { '#{@coderoot}/environments/env1/environment.conf': ensure => file, mode => "0644", content => 'environment_timeout = 0 environment_data_provider = "hiera" ', } file { '#{@coderoot}/environments/env2/environment.conf': ensure => file, mode => "0644", content => 'environment_timeout = 0 environment_data_provider = "function" ', } file { '#{@coderoot}/environments/env3/environment.conf': ensure => file, mode => "0644", content => 'environment_timeout = 0 environment_data_provider = "function" ', } file { '#{@coderoot}/environments/env4/environment.conf': ensure => file, mode => "0644", content => 'environment_timeout = 0 environment_data_provider = "none" ', } # Environment hiera data provider file { '#{@coderoot}/environments/production/hiera.yaml': ensure => file, mode => "0644", content => '--- version: 4 ', } file { '#{@coderoot}/environments/production/data/common.yaml': ensure => file, mode => "0644", content => '--- global_key: "env-production hiera provided value" environment_key: "env-production hiera provided value" ', } file { '#{@coderoot}/environments/env1/hiera.yaml': ensure => file, mode => "0644", content => '--- version: 4 ', } file { '#{@coderoot}/environments/env1/data/common.yaml': ensure => file, mode => "0644", content => '--- global_key: "env-env1 hiera provided value" environment_key: "env-env1 hiera provided value" ', } file { '#{@coderoot}/environments/env2/hiera.yaml': ensure => file, mode => "0644", content => '--- version: 4 ', } file { '#{@coderoot}/environments/env2/data/common.yaml': ensure => file, mode => "0644", content => '--- global_key: "env-env1 hiera provided value" environment_key: "env-env1 hiera provided value" ', } file { '#{@coderoot}/environments/env3/hiera.yaml': ensure => file, mode => "0644", content => '--- version: 4 ', } file { '#{@coderoot}/environments/env3/data/common.yaml': ensure => file, mode => "0644", content => '--- global_key: "env-env1 hiera provided value" environment_key: "env-env1 hiera provided value" ', } file { '#{@coderoot}/environments/env4/hiera.yaml': ensure => file, mode => "0644", content => '--- version: 4 ', } file { '#{@coderoot}/environments/env4/data/common.yaml': ensure => file, mode => "0644", content => '--- global_key: "env-env1 hiera provided value" environment_key: "env-env1 hiera provided value" ', } # Environment ruby function data provider file { '#{@coderoot}/environments/production/lib/puppet/functions/environment/data.rb': ensure => file, mode => "0644", content => "Puppet::Functions.create_function(:'environment::data') do def data() { 'environment_key': 'env-production-ruby-function data() provided value', 'global_key': 'env-production-ruby-function data () provided value', } end end ", } file { '#{@coderoot}/environments/env1/lib/puppet/functions/environment/data.rb': ensure => file, mode => "0644", content => "Puppet::Functions.create_function(:'environment::data') do def data() { 'environment_key' => 'env-env1-ruby-function data() provided value', 'global_key' => 'env-env1-ruby-function data () provided value', } end end ", } file { '#{@coderoot}/environments/env2/lib/puppet/functions/environment/data.rb': ensure => file, mode => "0644", content => "Puppet::Functions.create_function(:'environment::data') do def data() { 'environment_key' => 'env-env2-ruby-function data() provided value', 'global_key' => 'env-env2-ruby-function data () provided value', } end end ", } file { '#{@coderoot}/environments/env3/not-lib/puppet/functions/environment/data.rb': ensure => file, mode => "0644", content => "Puppet::Functions.create_function(:'environment::data') do def data() { 'environment_key' => 'env-env3-ruby-function data() provided value', 'global_key' => 'env-env3-ruby-function data () provided value', } end end ", } file { '#{@coderoot}/environments/env4/lib/puppet/functions/environment/data.rb': ensure => file, mode => "0644", content => "Puppet::Functions.create_function(:'environment::data') do def data() { 'environment_key' => 'env-env4-ruby-function data() provided value', 'global_key' => 'env-env4-ruby-function data () provided value', } end end ", } # Environment puppet function data provider file { '#{@coderoot}/environments/production/functions/environment/data.pp': ensure => file, mode => "0755", content => 'function environment::data() { { "environment_key" => "env-production-puppet-function data() provided value", "global_key" => "env-production-puppet-function data() provided value", } } ', } file { '#{@coderoot}/environments/env1/functions/environment/data.pp': ensure => file, mode => "0755", content => 'function environment::data() { { "environment_key" => "env-env1-puppet-function data() provided value", "global_key" => "env-env1-puppet-function data() provided value", } } ', } file { '#{@coderoot}/environments/env2/functions/environment/data.pp': ensure => file, mode => "0755", content => 'function environment::data() { { "environment_key" => "env-env2-puppet-function data() provided value", "global_key" => "env-env2-puppet-function data() provided value", } } ', } file { '#{@coderoot}/environments/env3/functions/environment/data.pp': ensure => file, mode => "0755", content => 'function environment::data() { { "environment_key" => "env-env3-puppet-function data() provided value", "global_key" => "env-env3-puppet-function data() provided value", } } ', } file { '#{@coderoot}/environments/env4/functions/environment/data.pp': ensure => file, mode => "0755", content => 'function environment::data() { { "environment_key" => "env-env4-puppet-function data() provided value", "global_key" => "env-env4-puppet-function data() provided value", } } ', } ## Module data provider configuration # Module hiera data provider file { '#{@coderoot}/environments/production/modules/mod1/hiera.yaml': ensure => file, mode => "0644", content => '--- version: 4 ', } file { '#{@coderoot}/environments/production/modules/mod1/data/common.yaml': ensure => file, mode => "0644", content => '--- "mod1::module_key": "module-production-mod1-hiera provided value" "mod1::global_key": "module-production-mod1-hiera provided value" "environment_key": "module-production-mod1-hiera provided value" "global_key": "module-production-mod1-hiera provided value" ', } file { '#{@coderoot}/environments/production/modules/mod2/hiera.yaml': ensure => file, mode => "0644", content => '--- version: 4 ', } file { '#{@coderoot}/environments/production/modules/mod2/data/common.yaml': ensure => file, mode => "0644", content => '--- "mod2::module_key": "module-production-mod2-hiera provided value" "mod2::global_key": "module-production-mod2-hiera provided value" "environment_key": "module-production-mod2-hiera provided value" "global_key": "module-production-mod2-hiera provided value" ', } file { '#{@coderoot}/environments/production/modules/mod3/hiera.yaml': ensure => file, mode => "0644", content => '--- version: 4 ', } file { '#{@coderoot}/environments/production/modules/mod3/data/common.yaml': ensure => file, mode => "0644", content => '--- "mod3::module_key": "module-production-mod3-hiera provided value" "mod3::global_key": "module-production-mod3-hiera provided value" "environment_key": "module-production-mod3-hiera provided value" "global_key" => "module-production-mod3-hiera provided value" ', } file { '#{@coderoot}/environments/production/modules/mod4/hiera.yaml': ensure => file, mode => "0644", content => '--- version: 4 ', } file { '#{@coderoot}/environments/production/modules/mod4/data/common.yaml': ensure => file, mode => "0644", content => '--- "mod4::module_key": "module-production-mod4-hiera provided value" "mod4::global_key": "module-production-mod4-hiera provided value" "environment_key": "module-production-mod4-hiera provided value" "global_key": "module-production-mod4-hiera provided value" ', } file { '#{@coderoot}/environments/env1/modules/mod1/hiera.yaml': ensure => file, mode => "0644", content => '--- version: 4 ', } file { '#{@coderoot}/environments/env1/modules/mod1/data/common.yaml': ensure => file, mode => "0644", content => '--- "mod1::module_key": "module-env1-mod1-hiera provided value" "global_key": "module-env1-mod1-hiera provided value" "environment_key": "module-env1-mod1-hiera provided value" ', } file { '#{@coderoot}/environments/env1/modules/mod2/hiera.yaml': ensure => file, mode => "0644", content => '--- version: 4 ', } file { '#{@coderoot}/environments/env1/modules/mod2/data/common.yaml': ensure => file, mode => "0644", content => '--- "mod2::module_key": "module-env1-mod2-hiera provided value" "global_key": "module-env1-mod2-hiera provided value" "environment_key": "module-env1-mod2-hiera provided value" ', } file { '#{@coderoot}/environments/env1/modules/mod3/hiera.yaml': ensure => file, mode => "0644", content => '--- version: 4 ', } file { '#{@coderoot}/environments/env1/modules/mod3/data/common.yaml': ensure => file, mode => "0644", content => '--- "mod3::module_key": "module-env1-mod3-hiera provided value" "global_key": "module-env1-mod3-hiera provided value" "environment_key": "module-env1-mod3-hiera provided value" ', } file { '#{@coderoot}/environments/env1/modules/mod4/hiera.yaml': ensure => file, mode => "0644", content => '--- version: 4 ', } file { '#{@coderoot}/environments/env1/modules/mod4/data/common.yaml': ensure => file, mode => "0644", content => '--- "mod4::module_key": "module-env1-mod4-hiera provided value" "global_key": "module-env1-mod4-hiera provided value" "environment_key": "module-env1-mod4-hiera provided value" ', } file { '#{@coderoot}/environments/env2/modules/mod1/hiera.yaml': ensure => file, mode => "0644", content => '--- version: 4 ', } file { '#{@coderoot}/environments/env2/modules/mod1/data/common.yaml': ensure => file, mode => "0644", content => '--- "mod1::module_key": "module-env2-mod1-hiera provided value" "global_key": "module-env2-mod1-hiera provided value" "environment_key": "module-env2-mod1-hiera provided value" ', } file { '#{@coderoot}/environments/env2/modules/mod2/hiera.yaml': ensure => file, mode => "0644", content => '--- version: 4 ', } file { '#{@coderoot}/environments/env2/modules/mod2/data/common.yaml': ensure => file, mode => "0644", content => '--- "mod2::module_key": "module-env2-mod2-hiera provided value" "global_key": "module-env2-mod2-hiera provided value" "environment_key": "module-env2-mod2-hiera provided value" ', } file { '#{@coderoot}/environments/env2/modules/mod3/hiera.yaml': ensure => file, mode => "0644", content => '--- version: 4 ', } file { '#{@coderoot}/environments/env2/modules/mod3/data/common.yaml': ensure => file, mode => "0644", content => '--- "mod3::module_key": "module-env2-mod3-hiera provided value" "global_key": "module-env2-mod3-hiera provided value" "environment_key": "module-env2-mod3-hiera provided value" ', } file { '#{@coderoot}/environments/env2/modules/mod4/hiera.yaml': ensure => file, mode => "0644", content => '--- version: 4 ', } file { '#{@coderoot}/environments/env2/modules/mod4/data/common.yaml': ensure => file, mode => "0644", content => '--- "mod4::module_key": "module-env2-mod4-hiera provided value" "global_key": "module-env2-mod4-hiera provided value" "environment_key": "module-env2-mod4-hiera provided value" ', } file { '#{@coderoot}/environments/env3/modules/mod1/hiera.yaml': ensure => file, mode => "0644", content => '--- version: 4 ', } file { '#{@coderoot}/environments/env3/modules/mod1/data/common.yaml': ensure => file, mode => "0644", content => '--- "mod1::module_key": "module-env3-mod1-hiera provided value" "global_key": "module-env3-mod1-hiera provided value" "environment_key": "module-env3-mod1-hiera provided value" ', } file { '#{@coderoot}/environments/env3/modules/mod2/hiera.yaml': ensure => file, mode => "0644", content => '--- version: 4 ', } file { '#{@coderoot}/environments/env3/modules/mod2/data/common.yaml': ensure => file, mode => "0644", content => '--- "mod2::module_key": "module-env3-mod2-hiera provided value" "global_key": "module-env3-mod2-hiera provided value" "environment_key": "module-env3-mod2-hiera provided value" ', } file { '#{@coderoot}/environments/env3/modules/mod3/hiera.yaml': ensure => file, mode => "0644", content => '--- version: 4 ', } file { '#{@coderoot}/environments/env3/modules/mod3/data/common.yaml': ensure => file, mode => "0644", content => '--- "mod3::module_key": "module-env3-mod3-hiera provided value" "global_key": "module-env3-mod3-hiera provided value" "environment_key": "module-env3-mod3-hiera provided value" ', } file { '#{@coderoot}/environments/env3/modules/mod4/hiera.yaml': ensure => file, mode => "0644", content => '--- version: 4 ', } file { '#{@coderoot}/environments/env3/modules/mod4/data/common.yaml': ensure => file, mode => "0644", content => '--- "mod4::module_key": "module-env3-mod4-hiera provided value" "global_key": "module-env3-mod4-hiera provided value" "environment_key": "module-env3-mod4-hiera provided value" ', } file { '#{@coderoot}/environments/env4/modules/mod1/hiera.yaml': ensure => file, mode => "0644", content => '--- version: 4 ', } file { '#{@coderoot}/environments/env4/modules/mod1/data/common.yaml': ensure => file, mode => "0644", content => '--- "mod1::module_key": "module-env4-mod1-hiera provided value" "global_key": "module-env4-mod1-hiera provided value" "environment_key": "module-env4-mod1-hiera provided value" ', } file { '#{@coderoot}/environments/env4/modules/mod2/hiera.yaml': ensure => file, mode => "0644", content => '--- version: 4 ', } file { '#{@coderoot}/environments/env4/modules/mod2/data/common.yaml': ensure => file, mode => "0644", content => '--- "mod2::module_key": "module-env4-mod2-hiera provided value" "global_key": "module-env4-mod2-hiera provided value" "environment_key": "module-env4-mod2-hiera provided value" ', } file { '#{@coderoot}/environments/env4/modules/mod3/hiera.yaml': ensure => file, mode => "0644", content => '--- version: 4 ', } file { '#{@coderoot}/environments/env4/modules/mod3/data/common.yaml': ensure => file, mode => "0644", content => '--- "mod3::module_key": "module-env4-mod3-hiera provided value" "global_key": "module-env4-mod3-hiera provided value" "environment_key": "module-env4-mod3-hiera provided value" ', } file { '#{@coderoot}/environments/env4/modules/mod4/hiera.yaml': ensure => file, mode => "0644", content => '--- version: 4 ', } file { '#{@coderoot}/environments/env4/modules/mod4/data/common.yaml': ensure => file, mode => "0644", content => '--- "mod4::module_key": "module-env4-mod4-hiera provided value" "global_key": "module-env4-mod4-hiera provided value" "environment_key": "module-env4-mod4-hiera provided value" ', } # Module ruby function data provider file { '#{@coderoot}/environments/production/modules/mod1/lib/puppet/functions/mod1/data.rb': ensure => file, mode => "0644", content => "Puppet::Functions.create_function(:'mod1::data') do def data() { 'mod1::module_key' => 'module-production-mod1-ruby-function provided value', 'mod1::global_key' => 'module-production-mod1-ruby-function provided value', } end end ", } file { '#{@coderoot}/environments/production/modules/mod2/lib/puppet/functions/mod2/data.rb': ensure => file, mode => "0644", content => "Puppet::Functions.create_function(:'mod2::data') do def data() { 'mod2::module_key' => 'module-production-mod2-ruby-function provided value', 'mod2::global_key' => 'module-production-mod2-ruby-function provided value', } end end ", } file { '#{@coderoot}/environments/production/modules/mod3/not-lib/puppet/functions/mod3/data.rb': ensure => file, mode => "0644", content => "Puppet::Functions.create_function(:'mod3::data') do def data() { 'mod3::module_key' => 'module-production-mod3-ruby-function provided value', 'mod3::global_key' => 'module-production-mod3-ruby-function provided value', } end end ", } file { '#{@coderoot}/environments/production/modules/mod4/lib/puppet/functions/mod4/data.rb': ensure => file, mode => "0644", content => "Puppet::Functions.create_function(:'mod4::data') do def data() { 'mod4::module_key' => 'module-production-mod4-ruby-function provided value', 'mod4::global_key' => 'module-production-mod4-ruby-function provided value', } end end ", } file { '#{@coderoot}/environments/env1/modules/mod1/lib/puppet/functions/mod1/data.rb': ensure => file, mode => "0644", content => "Puppet::Functions.create_function(:'mod1::data') do def data() { 'mod1::module_key' => 'module-env1-mod1-ruby-function provided value', } end end ", } file { '#{@coderoot}/environments/env1/modules/mod2/lib/puppet/functions/mod2/data.rb': ensure => file, mode => "0644",
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
true
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/parser_functions/calling_all_functions.rb
acceptance/tests/parser_functions/calling_all_functions.rb
test_name 'Calling all functions.. test in progress!' tag 'audit:high', 'audit:acceptance' # create single manifest calling all functions step 'Apply manifest containing all function calls' def manifest_call_each_function_from_array(functions) manifest = '' # use index to work around puppet's immutable variables # use variables so we can concatenate strings functions.each_with_index do |function,index| if function[:rvalue] manifest << "$pre#{index} = \"sayeth #{function[:name].capitalize}: Scope(Class[main]): \" " manifest << "$output#{index} = #{function[:name]}(#{function[:args]}) " manifest << "#{function[:lambda]} notice \"${pre#{index}}${output#{index}}\"\n" else manifest << "$pre#{index} = \"sayeth #{function[:name].capitalize}: \" " manifest << "notice \"${pre#{index}}\"\n" manifest << "#{function[:name]}(#{function[:args]}) " manifest << "#{function[:lambda]}\n" end end manifest end agents.each do |agent| testdir = agent.tmpdir('calling_all_functions') # if agent["platform"] =~ /win/ # generator = {:args => '"c:/windows/system32/tasklist.exe"', :expected => /\nImage Name/} # else # generator = {:args => '"/bin/date"', :expected => /\w\w\w.*?\d\d:\d\d\:\d\d/} # end # create list of 3x functions and args # notes: hiera functions are well tested elsewhere, included for completeness # special cases: contain (call this from call_em_all) # do fail last because it errors out functions_3x = [ {:name => :alert, :args => '"consider yourself on alert"', :lambda => nil, :expected => 'consider yourself on alert', :rvalue => false}, {:name => :binary_file, :args => '"call_em_all/rickon.txt"', :lambda => nil, :expected => '', :rvalue => true}, #{:name => :break, :args => '', :lambda => nil, :expected => '', :rvalue => false}, # this is explicitly called from call_em_all module which is included below #{:name => :contain, :args => 'call_em_all', :lambda => nil, :expected => '', :rvalue => true}, # below doens't instance the resource. no output {:name => :create_resources, :args => 'notify, {"w"=>{message=>"winter is coming"}}', :lambda => nil, :expected => '', :rvalue => false}, {:name => :crit, :args => '"consider yourself critical"', :lambda => nil, :expected => 'consider yourself critical', :rvalue => false}, {:name => :debug, :args => '"consider yourself bugged"', :lambda => nil, :expected => '', :rvalue => false}, # no output expected unless run with debug {:name => :defined, :args => 'File["/tmp"]', :lambda => nil, :expected => 'false', :rvalue => true}, {:name => :dig, :args => '[100]', :lambda => nil, :expected => '[100]', :rvalue => true}, # Expect sha256 hash value for the digest {:name => :digest, :args => '"Sansa"', :lambda => nil, :expected => '4ebf3a5527313f06c7965749d7764c15cba6fe86da11691ca9bd0ce448563979', :rvalue => true}, {:name => :emerg, :args => '"consider yourself emergent"', :lambda => nil, :expected => 'consider yourself emergent', :rvalue => false}, {:name => :err, :args => '"consider yourself in err"', :lambda => nil, :expected => 'consider yourself in err', :rvalue => false}, {:name => :file, :args => '"call_em_all/rickon.txt"', :lambda => nil, :expected => 'who?', :rvalue => true}, {:name => :fqdn_rand, :args => '100000', :lambda => nil, :expected => /Fqdn_rand: Scope\(Class\[main\]\): \d{1,5}/, :rvalue => true}, # generate requires a fully qualified exe; which requires specifics for windows vs posix #{:name => :generate, :args => generator[:args], :lambda => nil, :expected => generator[:expected], :rvalue => true}, {:name => :hiera_array, :args => 'date,default_array', :lambda => nil, :expected => 'default_array', :rvalue => true}, {:name => :hiera_hash, :args => 'date,default_hash', :lambda => nil, :expected => 'default_hash', :rvalue => true}, {:name => :hiera_include, :args => 'date,call_em_all', :lambda => nil, :expected => '', :rvalue => false}, {:name => :hiera, :args => 'date,default_date', :lambda => nil, :expected => 'default_date', :rvalue => true}, {:name => :include, :args => 'call_em_all', :lambda => nil, :expected => '', :rvalue => false}, {:name => :info, :args => '"consider yourself informed"', :lambda => nil, :expected => '', :rvalue => false}, # no ouput unless in debug mode {:name => :inline_template, :args => '\'empty<%= @x %>space\'', :lambda => nil, :expected => 'emptyspace', :rvalue => true}, # test the living life out of this thing in lookup.rb, and it doesn't allow for a default value #{:name => :lookup, :args => 'date,lookup_date', :lambda => nil, :expected => '', :rvalue => true}, # well tested elsewhere {:name => :sha256, :args => '"Bran"', :lambda => nil, :expected => '824264f7f73d6026550b52a671c50ad0c4452af66c24f3784e30f515353f2ce0', :rvalue => true}, # Integer.new {:name => :Integer, :args => '"100"', :lambda => nil, :expected => '100', :rvalue => true}, {:name => :notice, :args => '"consider yourself under notice"', :lambda => nil, :expected => 'consider yourself under notice', :rvalue => false}, {:name => :realize, :args => 'User[arya]', :lambda => nil, :expected => '', :rvalue => false}, # TODO: create a virtual first {:name => :regsubst, :args => '"Cersei","Cer(\\\\w)ei","Daenery\\\\1"',:lambda => nil, :expected => 'Daenerys', :rvalue => true}, # explicitly called in call_em_all; implicitly called by the include above #{:name => :require, :args => '[4,5,6]', :lambda => nil, :expected => '', :rvalue => true}, # 4x output contains brackets around scanf output {:name => :scanf, :args => '"Eddard Stark","%6s"', :lambda => nil, :expected => '[Eddard]', :rvalue => true}, {:name => :sha1, :args => '"Sansa"', :lambda => nil, :expected => '4337ce5e4095e565d51e0ef4c80df1fecf238b29', :rvalue => true}, {:name => :shellquote, :args => '["-1", "--two"]', :lambda => nil, :expected => '-1 --two', :rvalue => true}, # 4x output contains brackets around split output and commas btwn values {:name => :split, :args => '"9,8,7",","', :lambda => nil, :expected => '[9, 8, 7]', :rvalue => true}, {:name => :sprintf, :args => '"%b","123"', :lambda => nil, :expected => '1111011', :rvalue => true}, {:name => :step, :args => '[100,99],1', :lambda => nil, :expected => 'Iterator[Integer]-Value', :rvalue => true}, # explicitly called in call_em_all #{:name => :tag, :args => '[4,5,6]', :lambda => nil, :expected => '', :rvalue => true}, {:name => :tagged, :args => '"yer_it"', :lambda => nil, :expected => 'false', :rvalue => true}, {:name => :template, :args => '"call_em_all/template.erb"', :lambda => nil, :expected => 'no defaultsno space', :rvalue => true}, {:name => :type, :args => '42', :lambda => nil, :expected => 'Integer[42, 42]', :rvalue => true}, {:name => :versioncmp, :args => '"1","2"', :lambda => nil, :expected => '-1', :rvalue => true}, {:name => :warning, :args => '"consider yourself warned"', :lambda => nil, :expected => 'consider yourself warned', :rvalue => false}, # do this one last or it will not allow the others to run. {:name => :fail, :args => '"Jon Snow"', :lambda => nil, :expected => /Error:.*Jon Snow/, :rvalue => false}, ] puppet_version = on(agent, puppet('--version')).stdout.chomp functions_4x = [ {:name => :assert_type, :args => '"String[1]", "Valar morghulis"', :lambda => nil, :expected => 'Valar morghulis', :rvalue => true}, {:name => :each, :args => '[1,2,3]', :lambda => '|$x| {$x}', :expected => '[1, 2, 3]', :rvalue => true}, {:name => :epp, :args => '"call_em_all/template.epp",{x=>droid}', :lambda => nil, :expected => 'This is the droid you are looking for!', :rvalue => true}, {:name => :filter, :args => '[4,5,6]', :lambda => '|$x| {true}', :expected => '[4, 5, 6]', :rvalue => true}, # find_file() called by binary_file #{:name => :find_file, :args => '[4,5,6]', :lambda => '|$x| {true}', :expected => '[4, 5, 6]', :rvalue => true}, {:name => :inline_epp, :args => '\'<%= $x %>\',{x=>10}', :lambda => nil, :expected => '10', :rvalue => true}, #{:name => :lest, :args => '100', :lambda => '"100"', :expected => '100', :rvalue => true}, {:name => :map, :args => '[7,8,9]', :lambda => '|$x| {$x * $x}', :expected => '[49, 64, 81]', :rvalue => true}, {:name => :match, :args => '"abc", /b/', :lambda => nil, :expected => '[b]', :rvalue => true}, #{:name => :next, :args => '100', :lambda => nil, :expected => '100', :rvalue => true}, {:name => :reduce, :args => '[4,5,6]', :lambda => '|$sum, $n| { $sum+$n }', :expected => '15', :rvalue => true}, #{:name => :return, :args => '100', :lambda => nil, :expected => '100', :rvalue => true}, {:name => :reverse_each, :args => '[100,99]', :lambda => nil, :expected => 'Iterator[Integer]-Value', :rvalue => true}, # :reuse,:recycle {:name => :slice, :args => '[1,2,3,4,5,6], 2', :lambda => nil, :expected => '[[1, 2], [3, 4], [5, 6]]', :rvalue => true}, {:name => :strftime, :args => 'Timestamp("4216-09-23T13:14:15.123 UTC"), "%C"', :lambda => nil, :expected => '42', :rvalue => true}, {:name => :then, :args => '100', :lambda => '|$x| {$x}', :expected => '100', :rvalue => true}, {:name => :with, :args => '1, "Catelyn"', :lambda => '|$x, $y| {"$x, $y"}', :expected => '1, Catelyn', :rvalue => true}, ] module_manifest = <<PP File { ensure => directory, } file { '#{testdir}':; '#{testdir}/environments':; '#{testdir}/environments/production':; '#{testdir}/environments/production/modules':; '#{testdir}/environments/production/modules/tagged':; '#{testdir}/environments/production/modules/tagged/manifests':; '#{testdir}/environments/production/modules/contained':; '#{testdir}/environments/production/modules/contained/manifests':; '#{testdir}/environments/production/modules/required':; '#{testdir}/environments/production/modules/required/manifests':; '#{testdir}/environments/production/modules/call_em_all':; '#{testdir}/environments/production/modules/call_em_all/manifests':; '#{testdir}/environments/production/modules/call_em_all/templates':; '#{testdir}/environments/production/modules/call_em_all/files':; } file { '#{testdir}/environments/production/modules/tagged/manifests/init.pp': ensure => file, content => 'class tagged { notice tagged tag yer_it }', } file { '#{testdir}/environments/production/modules/required/manifests/init.pp': ensure => file, content => 'class required { notice required }', } file { '#{testdir}/environments/production/modules/contained/manifests/init.pp': ensure => file, content => 'class contained { notice contained }', } file { '#{testdir}/environments/production/modules/call_em_all/manifests/init.pp': ensure => file, content => 'class call_em_all { notice call_em_all contain contained require required tag yer_it }', } file { '#{testdir}/environments/production/modules/call_em_all/files/rickon.txt': ensure => file, content => 'who?', } file { '#{testdir}/environments/production/modules/call_em_all/templates/template.epp': ensure => file, content => 'This is the <%= $x %> you are looking for!', } file { '#{testdir}/environments/production/modules/call_em_all/templates/template.erb': ensure => file, content => 'no defaults<%= @x %>no space', } PP apply_manifest_on(agent, module_manifest, :catch_failures => true) scope = 'Scope(Class[main]):' # apply the 4x function manifest with future parser puppet_apply_options = {:modulepath => "#{testdir}/environments/production/modules/", :acceptable_exit_codes => 1} puppet_apply_options[:future_parser] = true if puppet_version =~ /\A3\./ apply_manifest_on(agent, manifest_call_each_function_from_array(functions_4x), puppet_apply_options) do |result| functions_4x.each do |function| expected = "#{function[:name].capitalize}: #{scope} #{function[:expected]}" unless agent['locale'] == 'ja' assert_match(expected, result.output, "#{function[:name]} output didn't match expected value") end end end file_path = agent.tmpfile('apply_manifest.pp') create_remote_file(agent, file_path, manifest_call_each_function_from_array(functions_3x)) trusted_3x = puppet_version =~ /\A3\./ ? '--trusted_node_data ' : '' on(agent, puppet("apply #{trusted_3x} --color=false --modulepath #{testdir}/environments/production/modules/ #{file_path}"), :acceptable_exit_codes => 1 ) do |result| functions_3x.each do |function| # append the function name to the matcher so it's more expressive if function[:expected].is_a?(String) if function[:name] == :fail expected = function[:expected] elsif function[:name] == :crit expected = "#{function[:name].capitalize}ical: #{scope} #{function[:expected]}" elsif function[:name] == :emerg expected = "#{function[:name].capitalize}ency: #{scope} #{function[:expected]}" elsif function[:name] == :err expected = "#{function[:name].capitalize}or: #{scope} #{function[:expected]}" elsif function[:expected] == '' expected = "#{function[:name].capitalize}: #{function[:expected]}" else expected = "#{function[:name].capitalize}: #{scope} #{function[:expected]}" end elsif function[:expected].is_a?(Regexp) expected = function[:expected] else raise 'unhandled function expectation type (we allow String or Regexp)' end unless agent['locale'] == 'ja' assert_match(expected, result.output, "#{function[:name]} output didn't match expected value") end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/parser_functions/hiera_hash/lookup_data.rb
acceptance/tests/parser_functions/hiera_hash/lookup_data.rb
test_name "Lookup data using the hiera_hash parser function" tag 'audit:high', 'audit:acceptance', 'audit:refactor' # Master is not required for this test. Replace with agents.each testdir = master.tmpdir('hiera') step 'Setup' apply_manifest_on(master, <<-PP, :catch_failures => true) File { ensure => directory, mode => "0750", owner => #{master.puppet['user']}, group => #{master.puppet['group']}, } file { '#{testdir}':; '#{testdir}/hieradata':; '#{testdir}/environments':; '#{testdir}/environments/production':; '#{testdir}/environments/production/manifests':; '#{testdir}/environments/production/modules':; } file { '#{testdir}/hiera.yaml': ensure => file, content => '--- :backends: - "yaml" :logger: "console" :hierarchy: - "%{environment}" - "global" :yaml: :datadir: "#{testdir}/hieradata" ', mode => "0640"; } file { '#{testdir}/hieradata/global.yaml': ensure => file, content => "--- database_user: name: postgres uid: 500 gid: 500 ", mode => "0640"; } file { '#{testdir}/hieradata/production.yaml': ensure => file, content => "--- database_user: shell: '/bin/bash' ", mode => "0640"; } file { '#{testdir}/environments/production/modules/ntp/':; '#{testdir}/environments/production/modules/ntp/manifests':; } file { '#{testdir}/environments/production/modules/ntp/manifests/init.pp': ensure => file, content => 'class ntp { $database_user = hiera_hash("database_user") notify { "the database user": message => "name: ${database_user["name"]} shell: ${database_user["shell"]}" } }', mode => "0640"; } file { '#{testdir}/environments/production/manifests/site.pp': ensure => file, content => " node default { include ntp }", mode => "0640"; } PP step "Try to lookup hash data" master_opts = { 'main' => { 'environmentpath' => "#{testdir}/environments", 'hiera_config' => "#{testdir}/hiera.yaml", }, } with_puppet_running_on master, master_opts, testdir do agents.each do |agent| on(agent, puppet('agent', "-t"), :acceptable_exit_codes => [2]) do |result| assert_match("name: postgres shell: /bin/bash", result.stdout) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/parser_functions/hiera_array/lookup_data.rb
acceptance/tests/parser_functions/hiera_array/lookup_data.rb
test_name "Lookup data using the hiera_array parser function" tag 'audit:high', 'audit:acceptance', 'audit:refactor' # Master is not required for this test. Replace with agents.each testdir = master.tmpdir('hiera') step 'Setup' apply_manifest_on(master, <<-PP, :catch_failures => true) File { ensure => directory, mode => "0750", owner => #{master.puppet['user']}, group => #{master.puppet['group']}, } file { '#{testdir}':; '#{testdir}/hieradata':; '#{testdir}/environments':; '#{testdir}/environments/production':; '#{testdir}/environments/production/manifests':; '#{testdir}/environments/production/modules':; } file { '#{testdir}/hiera.yaml': ensure => file, content => '--- :backends: - "yaml" :logger: "console" :hierarchy: - "%{environment}" - "global" :yaml: :datadir: "#{testdir}/hieradata" ', mode => "0640"; } file { '#{testdir}/hieradata/global.yaml': ensure => file, content => "--- port: '8080' ntpservers: ['global.ntp.puppetlabs.com'] ", mode => "0640"; } file { '#{testdir}/hieradata/production.yaml': ensure => file, content => "--- ntpservers: ['production.ntp.puppetlabs.com'] ", mode => "0640"; } file { '#{testdir}/environments/production/modules/ntp':; '#{testdir}/environments/production/modules/ntp/manifests':; } file { '#{testdir}/environments/production/modules/ntp/manifests/init.pp': ensure => file, content => ' class ntp { $ntpservers = hiera_array("ntpservers") define print { $server = $name notify { "ntpserver ${server}": } } ntp::print { $ntpservers: } }', mode => "0640"; } file { '#{testdir}/environments/production/manifests/site.pp': ensure => file, content => " node default { include ntp }", mode => "0640"; } PP step "Try to lookup array data" master_opts = { 'main' => { 'environmentpath' => "#{testdir}/environments", 'hiera_config' => "#{testdir}/hiera.yaml", }, } with_puppet_running_on master, master_opts, testdir do agents.each do |agent| on(agent, puppet('agent', "-t"), :acceptable_exit_codes => [2]) do |result| assert_match('ntpserver global.ntp.puppetlabs.com', result.stdout) assert_match('ntpserver production.ntp.puppetlabs.com', result.stdout) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/parser_functions/hiera/lookup_data.rb
acceptance/tests/parser_functions/hiera/lookup_data.rb
test_name "Lookup data using the hiera parser function" tag 'audit:high', 'audit:acceptance', 'audit:refactor' # Master is not required for this test. Replace with agents.each testdir = master.tmpdir('hiera') step 'Setup' apply_manifest_on(master, <<-PP, :catch_failures => true) File { ensure => directory, mode => "0750", owner => #{master.puppet['user']}, group => #{master.puppet['group']}, } file { '#{testdir}':; '#{testdir}/hieradata':; '#{testdir}/environments':; '#{testdir}/environments/production':; '#{testdir}/environments/production/manifests':; '#{testdir}/environments/production/modules':; } file { '#{testdir}/hiera.yaml': ensure => file, content => '--- :backends: - "yaml" :logger: "console" :hierarchy: - "%{environment}" - "global" :yaml: :datadir: "#{testdir}/hieradata" ', mode => "0640", } file { '#{testdir}/hieradata/global.yaml': ensure => file, content => "--- port: 8080 ", mode => "0640", } file { '#{testdir}/environments/production/modules/apache':; '#{testdir}/environments/production/modules/apache/manifests':; } file { '#{testdir}/environments/production/modules/apache/manifests/init.pp': ensure => file, content => ' class apache { $port = hiera("port") notify { "port from hiera": message => "apache server port: ${port}" } }', mode => "0640", } file { '#{testdir}/environments/production/manifests/site.pp': ensure => file, content => " node default { include apache }", mode => "0640", } PP step "Try to lookup string data" master_opts = { 'main' => { 'environmentpath' => "#{testdir}/environments", 'hiera_config' => "#{testdir}/hiera.yaml", }, } with_puppet_running_on master, master_opts, testdir do agents.each do |agent| on(agent, puppet('agent', "-t"), :acceptable_exit_codes => [2]) do |result| assert_match('apache server port: 8080', result.stdout) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/environment/directory_environment_production_created_master.rb
acceptance/tests/environment/directory_environment_production_created_master.rb
test_name 'ensure production environment created by master if missing' tag 'audit:high', 'audit:integration', 'server' testdir = create_tmpdir_for_user master, 'prod-env-created' step 'make environmentpath' master_user = puppet_config(master, 'user', section: 'master') apply_manifest_on(master, <<-MANIFEST, :catch_failures => true) File { ensure => directory, owner => #{master_user}, group => #{master.puppet['group']}, mode => '0640', } file { "#{testdir}":; "#{testdir}/environments":; } MANIFEST master_opts = { 'main' => { 'environmentpath' => "#{testdir}/environments", } } step 'run master; ensure production environment created' with_puppet_running_on(master, master_opts, testdir) do on(master, "test -d '#{testdir}/environments/production'") step 'ensure catalog returned from production env with no changes' agents.each do |agent| on(agent, puppet("agent -t --environment production --detailed-exitcodes")) do |result| # detailed-exitcodes produces a 0 when no changes are made. assert_equal(0, result.exit_code) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/environment/use_enc_environment_for_pluginsync.rb
acceptance/tests/environment/use_enc_environment_for_pluginsync.rb
test_name "Agent should use environment given by ENC for pluginsync" do tag 'audit:high', 'audit:integration', 'audit:refactor', # This test should be rolled into use_enc_environment 'server' # Remove all traces of the last used environment teardown do agents.each do |agent| on(agent, puppet('config print lastrunfile')) do |command_result| agent.rm_rf(command_result.stdout) end end end testdir = create_tmpdir_for_user(master, 'respect_enc_test') create_remote_file(master, "#{testdir}/enc.rb", <<END) #!#{master['privatebindir']}/ruby puts <<YAML parameters: environment: special YAML END on(master, "chmod 755 #{testdir}/enc.rb") apply_manifest_on(master, <<-MANIFEST, :catch_failures => true) File { ensure => directory, mode => "0770", owner => #{master.puppet['user']}, group => #{master.puppet['group']}, } file { '#{testdir}/environments':; '#{testdir}/environments/production':; '#{testdir}/environments/special/':; '#{testdir}/environments/special/modules':; '#{testdir}/environments/special/modules/amod':; '#{testdir}/environments/special/modules/amod/lib':; '#{testdir}/environments/special/modules/amod/lib/puppet':; } file { '#{testdir}/environments/special/modules/amod/lib/puppet/foo.rb': ensure => file, mode => "0640", content => "#special_version", } MANIFEST master_opts = { 'main' => { 'environmentpath' => "#{testdir}/environments", }, 'master' => { 'node_terminus' => 'exec', 'external_nodes' => "#{testdir}/enc.rb" }, } with_puppet_running_on(master, master_opts, testdir) do agents.each do |agent| agent_vardir = agent.puppet['vardir'] teardown do on(agent, "rm -rf '#{agent_vardir}/lib'") end run_agent_on(agent, "-t --no-daemonize --onetime") on(agent, "cat '#{agent_vardir}/lib/puppet/foo.rb'") do |result| assert_match(/#special_version/, result.stdout, "The plugin from environment 'special' was not synced") end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/environment/custom_type_provider_from_same_environment.rb
acceptance/tests/environment/custom_type_provider_from_same_environment.rb
test_name 'C59122: ensure provider from same env as custom type' do require 'puppet/acceptance/environment_utils' extend Puppet::Acceptance::EnvironmentUtils tag 'audit:high', 'audit:integration', # This behavior is specific to the master to 'do the right thing' 'server' app_type = File.basename(__FILE__, '.*') tmp_environment = mk_tmp_environment_with_teardown(master, app_type) file_correct = "#{tmp_environment}-correct.txt" file_wrong = "#{tmp_environment}-wrong.txt" fq_tmp_environmentpath = "#{environmentpath}/#{tmp_environment}" fq_prod_environmentpath = "#{environmentpath}/production" teardown do step 'clean out production env' do on(master, "rm -rf #{fq_prod_environmentpath}/modules/*", :accept_all_exit_codes => true) on(master, "rm #{fq_prod_environmentpath}/manifests/site.pp", :accept_all_exit_codes => true) end step 'clean out file resources' do on(hosts, "rm #{file_correct} #{file_wrong}", :accept_all_exit_codes => true) end agents.each do |agent| on(agent, puppet('config print lastrunfile')) do |command_result| agent.rm_rf(command_result.stdout) end end end step "create a custom type and provider in each of production and #{tmp_environment}" do type_name = 'test_custom_type' provider_name = 'universal' type_content = <<TYPE Puppet::Type.newtype(:#{type_name}) do @doc = "Manage a file (the simple version)." ensurable newparam(:name) do desc "The full path to the file." end end TYPE def provider_content(file_file_content, type_name, provider_name) return <<PROVIDER Puppet::Type.type(:#{type_name}).provide(:#{provider_name}) do desc "#{provider_name} file mgmt, yo" def create File.open(@resource[:name], "w") { |f| f.puts "#{file_file_content}!" } end def destroy File.unlink(@resource[:name]) end def exists? File.exist?(@resource[:name]) end end PROVIDER end manifest = <<MANIFEST File { ensure => directory } file { '#{fq_tmp_environmentpath}/modules/simple_type':; '#{fq_tmp_environmentpath}/modules/simple_type/lib':; '#{fq_tmp_environmentpath}/modules/simple_type/lib/puppet':; '#{fq_tmp_environmentpath}/modules/simple_type/lib/puppet/type/':; '#{fq_tmp_environmentpath}/modules/simple_type/lib/puppet/provider/':; '#{fq_tmp_environmentpath}/modules/simple_type/lib/puppet/provider/#{type_name}':; '#{fq_prod_environmentpath}/modules':; '#{fq_prod_environmentpath}/modules/simple_type':; '#{fq_prod_environmentpath}/modules/simple_type/lib':; '#{fq_prod_environmentpath}/modules/simple_type/lib/puppet':; '#{fq_prod_environmentpath}/modules/simple_type/lib/puppet/type/':; '#{fq_prod_environmentpath}/modules/simple_type/lib/puppet/provider/':; '#{fq_prod_environmentpath}/modules/simple_type/lib/puppet/provider/#{type_name}':; } file { '#{fq_tmp_environmentpath}/modules/simple_type/lib/puppet/type/#{type_name}.rb': ensure => file, content => '#{type_content}', } file { '#{fq_prod_environmentpath}/modules/simple_type/lib/puppet/type/#{type_name}.rb': ensure => file, content => '#{type_content}', } file { '#{fq_tmp_environmentpath}/modules/simple_type/lib/puppet/provider/#{type_name}/#{provider_name}.rb': ensure => file, content => '#{provider_content('correct', type_name, provider_name)}', } file { '#{fq_prod_environmentpath}/modules/simple_type/lib/puppet/provider/#{type_name}/#{provider_name}.rb': ensure => file, content => '#{provider_content('wrong', type_name, provider_name)}', } file { '#{fq_tmp_environmentpath}/manifests/site.pp': ensure => file, content => 'node default { #{type_name}{"#{file_correct}": ensure=>present} }', } file { '#{fq_prod_environmentpath}/manifests': } file { '#{fq_prod_environmentpath}/manifests/site.pp': ensure => file, content => 'node default { #{type_name}{"#{file_wrong}": ensure=>present} }', } MANIFEST apply_manifest_on(master, manifest, :catch_failures => true) end step "run agent in #{tmp_environment}, ensure it finds the correct provider" do with_puppet_running_on(master,{}) do agents.each do |agent| on(agent, puppet("agent -t --environment #{tmp_environment}"), :accept_all_exit_codes => true) do |result| assert_equal(2, result.exit_code, 'agent did not exit with the correct code of 2') assert_match(/#{file_correct}/, result.stdout, 'agent did not ensure the correct file') assert(agent.file_exist?(file_correct), 'puppet did not create the file') end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/environment/broken_unassigned_environment_handled_gracefully.rb
acceptance/tests/environment/broken_unassigned_environment_handled_gracefully.rb
test_name 'PUP-3755 Test an un-assigned broken environment' tag 'audit:high', 'audit:integration', 'audit:refactor', # Use mk_tmp_environment_with_teardown helper 'server' teardown do agents.each do |agent| on(agent, puppet('config print lastrunfile')) do |command_result| agent.rm_rf(command_result.stdout) end end end step 'setup environments' testdir = create_tmpdir_for_user(master, 'confdir') environment = 'debug' manifest = <<-MANIFEST File { ensure => directory, owner => #{master.puppet['user']}, group => #{master.puppet['group']}, mode => "0750", } file { "#{testdir}":; "#{testdir}/environments":; "#{testdir}/environments/production":; "#{testdir}/environments/production/manifests":; "#{testdir}/environments/production/modules":; "#{testdir}/environments/#{environment}":; "#{testdir}/environments/#{environment}/manifests":; "#{testdir}/environments/#{environment}/modules":; } # broken envioronment file { "#{testdir}/environments/production/manifests/site.pp": ensure => file, content => 'import "/tmp/bogus/*.pp"' } file { "#{testdir}/environments/#{environment}/manifests/site.pp": ensure => file, content => 'node default{\nnotify{"you win":}\n}' } MANIFEST apply_manifest_on(master, manifest, :catch_failures => true) step 'run agents, ensure no one complains about the other environment' master_opts = { 'main' => { 'environmentpath' => "#{testdir}/environments" } } with_puppet_running_on(master, master_opts, testdir) do agents.each do |agent| on(agent, puppet('agent', "--test --environment #{environment}"), :acceptable_exit_codes => (0..255)) do |result| assert_match(/you win/, result.stdout, 'agent did not pickup newly classified environment.') end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/environment/use_enc_environment_for_files.rb
acceptance/tests/environment/use_enc_environment_for_files.rb
test_name "Agent should use environment given by ENC for fetching remote files" do tag 'audit:high', 'audit:integration', 'audit:refactor', # This test should be rolled into use_enc_environment 'server' # Remove all traces of the last used environment teardown do agents.each do |agent| on(agent, puppet('config print lastrunfile')) do |command_result| agent.rm_rf(command_result.stdout) end end end testdir = create_tmpdir_for_user(master, 'respect_enc_test') create_remote_file(master, "#{testdir}/enc.rb", <<END) #!#{master['privatebindir']}/ruby puts <<YAML parameters: environment: special YAML END on(master, "chmod 755 '#{testdir}/enc.rb'") apply_manifest_on(master, <<-MANIFEST, :catch_failures => true) File { ensure => directory, mode => "0770", owner => #{master.puppet['user']}, group => #{master.puppet['group']}, } file { '#{testdir}/environments':; '#{testdir}/environments/production':; '#{testdir}/environments/special/':; '#{testdir}/environments/special/manifests':; '#{testdir}/environments/special/modules':; '#{testdir}/environments/special/modules/amod':; '#{testdir}/environments/special/modules/amod/files':; } file { '#{testdir}/environments/special/modules/amod/files/testy': ensure => file, mode => "0640", content => 'special_environment', } MANIFEST master_opts = { 'main' => { 'environmentpath' => "#{testdir}/environments", 'environment_timeout' => 0, }, 'master' => { 'node_terminus' => 'exec', 'external_nodes' => "#{testdir}/enc.rb", }, } with_puppet_running_on(master, master_opts, testdir) do agents.each do |agent| atmp = agent.tmpdir('respect_enc_test') teardown do on(agent, "rm -rf '#{atmp}'") end logger.debug "agent: #{agent} \tagent.tmpdir => #{atmp}" create_remote_file(master, "#{testdir}/environments/special/manifests/different.pp", <<END) file { "#{atmp}/special_testy": source => "puppet:///modules/amod/testy", } END on(master, "chmod 644 '#{testdir}/environments/special/manifests/different.pp'") run_agent_on(agent, "--no-daemonize --onetime --verbose --trace") on(agent, "cat '#{atmp}/special_testy'") do |result| assert_match(/special_environment/, result.stdout, "The file from environment 'special' was not found") end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/environment/use_last_server_specified_environment.rb
acceptance/tests/environment/use_last_server_specified_environment.rb
test_name "Agent should use the last server-specified environment if server is authoritative" do require 'puppet/acceptance/environment_utils' extend Puppet::Acceptance::EnvironmentUtils tag 'audit:high', 'server' # Remove all traces of the last used environment teardown do agents.each do |agent| on(agent, puppet('config print lastrunfile')) do |command_result| agent.rm_rf(command_result.stdout) end end end testdir = create_tmpdir_for_user(master, 'use_enc_env') create_remote_file(master, "#{testdir}/enc.rb", <<END) #!#{master['privatebindir'] || '/opt/puppetlabs/puppet/bin'}/ruby puts <<YAML parameters: environment: special YAML END on(master, "chmod 755 '#{testdir}/enc.rb'") apply_manifest_on(master, <<-MANIFEST, :catch_failures => true) File { ensure => directory, mode => "0770", owner => #{master.puppet['user']}, group => #{master.puppet['group']}, } file { '#{testdir}/environments':; '#{testdir}/environments/production':; '#{testdir}/environments/production/manifests':; '#{testdir}/environments/special/':; '#{testdir}/environments/special/manifests':; } file { '#{testdir}/environments/production/manifests/site.pp': ensure => file, mode => "0640", content => 'notify { "production environment": }', } file { '#{testdir}/environments/special/manifests/different.pp': ensure => file, mode => "0640", content => 'notify { "special environment": }', } MANIFEST master_opts = { 'main' => { 'environmentpath' => "#{testdir}/environments", }, } master_opts['master'] = { 'node_terminus' => 'exec', 'external_nodes' => "#{testdir}/enc.rb", } if !master.is_pe? with_puppet_running_on(master, master_opts, testdir) do agents.each do |agent| step 'ensure the lastrunfile is absent for the first run' do on(agent, puppet('config print lastrunfile')) do |command_result| agent.rm_rf(command_result.stdout) end end step 'first run: agent makes a node request to get the environment' do run_agent_on(agent, '--no-daemonize --onetime --debug') do |result| assert_match(/Local environment: 'production' doesn't match server specified node environment 'special', switching agent to 'special'/, result.stdout) assert_match(/Debug: HTTP GET .*\/puppet\/v3\/node/, result.stdout) assert_match(/Notice: special environment/, result.stdout) end end step 'second run: agent uses the environment from lastrunfile' do run_agent_on(agent, '--no-daemonize --onetime --debug') do |result| assert_match(/Debug: Successfully loaded last environment from the lastrunfile/, result.stdout) assert_match(/Notice: special environment/, result.stdout) end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/environment/environment_scenario-bad.rb
acceptance/tests/environment/environment_scenario-bad.rb
test_name 'Test behavior of directory environments when environmentpath is set to a non-existent directory' do require 'puppet/acceptance/environment_utils' extend Puppet::Acceptance::EnvironmentUtils require 'puppet/acceptance/classifier_utils' extend Puppet::Acceptance::ClassifierUtils tag 'audit:high', 'audit:unit', # The error responses for the agent should be covered by Ruby unit tests. # The server 404/400 response should be covered by server integration tests. 'server' teardown do agents.each do |agent| on(agent, puppet('config print lastrunfile')) do |command_result| agent.rm_rf(command_result.stdout) end end end classify_nodes_as_agent_specified_if_classifer_present step 'setup environments' testdir = create_tmpdir_for_user(master, 'confdir') puppet_conf_backup_dir = create_tmpdir_for_user(master, "puppet-conf-backup-dir") apply_manifest_on(master, environment_manifest(testdir), :catch_failures => true) step 'Test' do env_path = '/doesnotexist' master_opts = { 'main' => { 'environmentpath' => "#{env_path}", } } env = 'testing' results = use_an_environment(env, 'bad environmentpath', master_opts, testdir, puppet_conf_backup_dir, :directory_environments => true) expectations = { :puppet_config => { :exit_code => 0, :matches => [%r{basemodulepath = /etc/puppetlabs/code/modules:/opt/puppetlabs/puppet/modules}, %r{modulepath =}, %r{manifest =}, %r{config_version =}], }, :puppet_apply => { :exit_code => 1, :matches => [%r{Could not find a directory environment named '#{env}' anywhere in the path.*#{env_path}}], }, :puppet_agent => { :exit_code => 0, }, } agents.each do |host| unless host['locale'] == 'ja' expectations[:puppet_agent][:matches] = [%r{Environment '#{env}' not found on server, skipping initial pluginsync.}, %r{Local environment: '#{env}' doesn't match server specified environment 'production', restarting agent run with environment 'production'}] end end assert_review(review_results(results, expectations)) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/environment/can_enumerate_environments.rb
acceptance/tests/environment/can_enumerate_environments.rb
test_name "Can enumerate environments via an HTTP endpoint" tag 'audit:high', 'audit:integration', 'server' confine :except, :platform => /osx/ # see PUP-4820 def server_port(agent) setting_on(agent, "agent", "serverport") end def setting_on(host, section, name) on(host, puppet("config", "print", name, "--section", section)).stdout.chomp end def full_path(host, path) if host['platform'] =~ /win/ on(host, "cygpath '#{path}'").stdout.chomp else path end end def curl_master_from(agent, path, headers = '', &block) url = "https://#{master}:#{server_port(agent)}#{path}" cert_path = full_path(agent, setting_on(agent, "agent", "hostcert")) key_path = full_path(agent, setting_on(agent, "agent", "hostprivkey")) curl_base = "curl --tlsv1 -sg --cert \"#{cert_path}\" --key \"#{key_path}\" -k -H '#{headers}'" on agent, "#{curl_base} '#{url}'", &block end master_user = puppet_config(master, 'user', section: 'master') environments_dir = create_tmpdir_for_user master, "environments" apply_manifest_on(master, <<-MANIFEST) File { ensure => directory, owner => #{master_user}, group => #{master.puppet['group']}, mode => "0770", } file { "#{environments_dir}":; "#{environments_dir}/env1":; "#{environments_dir}/env2":; } MANIFEST master_opts = { :master => { :environmentpath => environments_dir } } if master.is_pe? master_opts[:master][:basemodulepath] = master['sitemoduledir'] end with_puppet_running_on(master, master_opts) do step "Ensure that an unauthenticated client cannot access the environments list" do on(master, "curl --tlsv1 -ksv https://#{master}:#{server_port(master)}/puppet/v3/environments", :acceptable_exit_codes => [0,7]) do |result| assert_match(/< HTTP\/1\.\d 403/, result.stderr) end end step "Ensure that an authenticated client can retrieve the list of environments" do curl_master_from(master, '/puppet/v3/environments') do |result| data = JSON.parse(result.stdout) assert_equal(["env1", "env2", "production"], data["environments"].keys.sort) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/environment/enc_nonexistent_directory_environment.rb
acceptance/tests/environment/enc_nonexistent_directory_environment.rb
test_name "Master should produce error if enc specifies a nonexistent environment" do require 'puppet/acceptance/classifier_utils.rb' extend Puppet::Acceptance::ClassifierUtils tag 'audit:high', 'audit:unit', 'server' teardown do agents.each do |agent| on(agent, puppet('config print lastrunfile')) do |command_result| agent.rm_rf(command_result.stdout) end end end testdir = create_tmpdir_for_user(master, 'nonexistent_env') apply_manifest_on(master, <<-MANIFEST, :catch_failures => true) File { ensure => directory, owner => #{master.puppet['user']}, group => #{master.puppet['group']}, mode => '0755', } file { "#{testdir}":; "#{testdir}/environments":; "#{testdir}/environments/production":; "#{testdir}/environments/production/manifests":; "#{testdir}/environments/production/manifests/site.pp": ensure => file, mode => '0644', content => 'notify { "In the production environment": }'; } MANIFEST if master.is_pe? group = { 'name' => 'Environment Does Not Exist', 'description' => 'Classify our test agent nodes in an environment that does not exist.', 'environment' => 'doesnotexist', 'environment_trumps' => true, } create_group_for_nodes(agents, group) else apply_manifest_on(master, <<-MANIFEST, :catch_failures => true) file { "#{testdir}/enc.rb": ensure => file, mode => '0775', content => '#!#{master['privatebindir']}/ruby puts "environment: doesnotexist" '; } MANIFEST end master_opts = { 'main' => { 'environmentpath' => "#{testdir}/environments", } } master_opts['master'] = { 'node_terminus' => 'exec', 'external_nodes' => "#{testdir}/enc.rb", } if !master.is_pe? with_puppet_running_on(master, master_opts, testdir) do agents.each do |agent| on(agent, puppet("agent -t --verbose"), :acceptable_exit_codes => [1]) do |result| unless agent['locale'] == 'ja' assert_match(/Could not find a directory environment named 'doesnotexist'/, result.stderr, "Errors when nonexistent environment is specified") end refute_match(/In the production environment/, result.stdout, "Executed manifest from production environment") end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/environment/use_agent_environment_when_enc_doesnt_specify.rb
acceptance/tests/environment/use_agent_environment_when_enc_doesnt_specify.rb
test_name "Agent should use agent environment if there is an enc that does not specify the environment" do require 'puppet/acceptance/classifier_utils' extend Puppet::Acceptance::ClassifierUtils tag 'audit:high', 'audit:integration', 'server' # Remove all traces of the last used environment teardown do agents.each do |agent| on(agent, puppet('config print lastrunfile')) do |command_result| agent.rm_rf(command_result.stdout) end end end classify_nodes_as_agent_specified_if_classifer_present testdir = create_tmpdir_for_user(master, 'use_agent_env') create_remote_file(master, "#{testdir}/enc.rb", <<END) #!#{master['privatebindir']}/ruby puts <<YAML parameters: YAML END on(master, "chmod 755 '#{testdir}/enc.rb'") apply_manifest_on(master, <<-MANIFEST, :catch_failures => true) File { ensure => directory, mode => "0770", owner => #{master.puppet['user']}, group => #{master.puppet['group']}, } file { '#{testdir}/environments':; '#{testdir}/environments/production':; '#{testdir}/environments/production/manifests':; '#{testdir}/environments/more_different/':; '#{testdir}/environments/more_different/manifests':; } file { '#{testdir}/environments/production/manifests/site.pp': ensure => file, mode => "0640", content => 'notify { "production environment": }', } file { '#{testdir}/environments/more_different/manifests/more_different.pp': ensure => file, mode => "0640", content => 'notify { "more_different_string": }', } MANIFEST master_opts = { 'main' => { 'environmentpath' => "#{testdir}/environments", 'node_terminus' => 'exec', 'external_nodes' => "#{testdir}/enc.rb", }, } with_puppet_running_on(master, master_opts, testdir) do agents.each do |agent| run_agent_on(agent, "--no-daemonize --onetime --verbose --environment more_different") do |result| assert_match(/more_different_string/, result.stdout, "Did not find more_different_string from \"more_different\" environment") end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/environment/use_enc_environment.rb
acceptance/tests/environment/use_enc_environment.rb
test_name 'Agent should use environment given by ENC and only compile a catalog once' do require 'puppet/acceptance/classifier_utils.rb' extend Puppet::Acceptance::ClassifierUtils tag 'audit:high', 'audit:integration', 'server' # Remove all traces of the last used environment teardown do agents.each do |agent| on(agent, puppet('config print lastrunfile')) do |command_result| agent.rm_rf(command_result.stdout) end end end testdir = create_tmpdir_for_user(master, 'use_enc_env') if master.is_pe? group = { 'name' => 'Special Environment', 'description' => 'Classify our test agent nodes in the special environment.', 'environment' => 'special', 'environment_trumps' => true, } create_group_for_nodes(agents, group) else create_remote_file(master, "#{testdir}/enc.rb", <<END) #!#{master['privatebindir']}/ruby puts <<YAML parameters: environment: special YAML END on(master, "chmod 755 '#{testdir}/enc.rb'") end apply_manifest_on(master, <<-MANIFEST, :catch_failures => true) File { ensure => directory, mode => "0770", owner => #{master.puppet['user']}, group => #{master.puppet['group']}, } file { '#{testdir}/environments':; '#{testdir}/environments/production':; '#{testdir}/environments/production/manifests':; '#{testdir}/environments/special/':; '#{testdir}/environments/special/manifests':; } file { '#{testdir}/environments/production/manifests/site.pp': ensure => file, mode => "0640", content => 'notify { "production environment": }', } file { '#{testdir}/environments/special/manifests/different.pp': ensure => file, mode => "0640", content => 'notify { "expected_string": }', } MANIFEST master_opts = { 'main' => { 'environmentpath' => "#{testdir}/environments", }, } master_opts['master'] = { 'node_terminus' => 'exec', 'external_nodes' => "#{testdir}/enc.rb", } if !master.is_pe? with_puppet_running_on(master, master_opts, testdir) do agents.each do |agent| run_agent_on(agent, "--no-daemonize --onetime --verbose") do |result| assert_match(/expected_string/, result.stdout, "Did not find expected_string from \"special\" environment") caching_catalog_message_count = result.stdout.split(/Info: Caching catalog for/).length - 1 assert_equal(caching_catalog_message_count, 1, 'Should only compile and cache the catalog once during the run') end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/environment/variables_refreshed_each_compilation.rb
acceptance/tests/environment/variables_refreshed_each_compilation.rb
test_name 'C98115 compilation should get new values in variables on each compilation' do require 'puppet/acceptance/environment_utils' extend Puppet::Acceptance::EnvironmentUtils confine :except, :platform => /^(aix|osx|solaris)/ tag 'audit:high', 'audit:integration', 'server' teardown do agents.each do |agent| on(agent, puppet('config print lastrunfile')) do |command_result| agent.rm_rf(command_result.stdout) end end end app_type = File.basename(__FILE__, '.*') tmp_environment = mk_tmp_environment_with_teardown(master, app_type) fq_tmp_environmentpath = "#{environmentpath}/#{tmp_environment}" create_remote_file(master, "#{fq_tmp_environmentpath}/environment.conf", <<-CONF) environment_timeout = unlimited CONF # the module function loading logic is different from inside a single manifest # we exercise both here on(master, "mkdir -p '#{fq_tmp_environmentpath}'/modules/custom_time/{manifests,functions,facts.d}") create_remote_file(master, "#{fq_tmp_environmentpath}/modules/custom_time/manifests/init.pp", <<-FILE) class custom_time { $t = custom_time::my_system_time() notify { 'custom time': message => "module_${t}_module", } } FILE create_remote_file(master, "#{fq_tmp_environmentpath}/modules/custom_time/functions/my_system_time.pp", <<-FILE) function custom_time::my_system_time() { $facts['custom_time'] } FILE create_sitepp(master, tmp_environment, <<-SITE) function bar() { $facts['custom_time'] } class foo::bar { notify { "local_${bar()}_local": } } include foo::bar include custom_time SITE create_remote_file(master, "#{fq_tmp_environmentpath}/modules/custom_time/facts.d/custom_time.sh", <<-FILE) #!/bin/bash if [[ `uname` == 'Darwin' ]]; then echo -n "custom_time=$(date +%s)" else echo -n "custom_time=$(date +%s%N)" fi FILE on(master, "chmod -R 0777 '#{fq_tmp_environmentpath}/'") windows_fact_location = "#{fq_tmp_environmentpath}/modules/custom_time/facts.d/custom_time.ps1" create_remote_file(master, windows_fact_location, <<-FILE) echo "custom_time=$(get-date -format HHmmssffffff)" FILE on(master, "chmod -R 0666 '#{windows_fact_location}'") step "run agent in #{tmp_environment}, ensure it increments the customtime with each run" do with_puppet_running_on(master, {}) do local_custom_time_pattern = 'local_(\d+)_local' module_custom_time_pattern = 'module_(\d+)_module' agents.each do |agent| # ensure our custom facts have been synced on(agent, puppet("agent -t --environment '#{tmp_environment}'"), :accept_all_exit_codes => true) local_custom_time1 = module_custom_time1 = nil local_custom_time2 = module_custom_time2 = nil on(agent, puppet("agent -t --environment '#{tmp_environment}'"), :accept_all_exit_codes => [2]) do |result| assert_match(/Notice: #{local_custom_time_pattern}/, result.stdout, 'first custom time was not as expected') assert_match(/Notice: #{module_custom_time_pattern}/, result.stdout, 'first module uptime was not as expected') local_custom_time1 = result.stdout.match(/Notice: #{local_custom_time_pattern}/)[1].to_i module_custom_time1 = result.stdout.match(/Notice: #{module_custom_time_pattern}/)[1].to_i end sleep 1 on(agent, puppet("agent -t --environment '#{tmp_environment}'"), :accept_all_exit_codes => [2]) do |result| assert_match(/Notice: #{local_custom_time_pattern}/, result.stdout, 'second custom time was not as expected') assert_match(/Notice: #{module_custom_time_pattern}/, result.stdout, 'second module uptime was not as expected') local_custom_time2 = result.stdout.match(/Notice: #{local_custom_time_pattern}/)[1].to_i module_custom_time2 = result.stdout.match(/Notice: #{module_custom_time_pattern}/)[1].to_i end assert(local_custom_time2 > local_custom_time1, 'local custom time did not change as expected if at all') assert(module_custom_time2 > module_custom_time1, 'module custom time did not change as expected if at all') end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/environment/use_agent_environment_when_no_enc.rb
acceptance/tests/environment/use_agent_environment_when_no_enc.rb
test_name "Agent should use agent environment if there is no enc-specified environment" do tag 'audit:high', 'audit:integration', 'audit:refactor', # This can be combined with use_agent_environment_when_enc_doesnt_specify test 'server' # Remove all traces of the last used environment teardown do agents.each do |agent| on(agent, puppet('config print lastrunfile')) do |command_result| agent.rm_rf(command_result.stdout) end end end testdir = create_tmpdir_for_user(master, 'use_agent_env') apply_manifest_on(master, <<-MANIFEST, :catch_failures => true) File { ensure => directory, mode => "0770", owner => #{master.puppet['user']}, group => #{master.puppet['group']}, } file { '#{testdir}/environments':; '#{testdir}/environments/production':; '#{testdir}/environments/production/manifests':; '#{testdir}/environments/more_different/':; '#{testdir}/environments/more_different/manifests':; } file { '#{testdir}/environments/production/manifests/site.pp': ensure => file, mode => "0640", content => 'notify { "production environment": }', } file { '#{testdir}/environments/more_different/manifests/more_different.pp': ensure => file, mode => "0640", content => 'notify { "more_different_string": }', } MANIFEST master_opts = { 'main' => { 'environmentpath' => "#{testdir}/environments", }, 'master' => { 'node_terminus' => 'plain' }, } with_puppet_running_on(master, master_opts, testdir) do agents.each do |agent| run_agent_on(agent, "--no-daemonize --onetime --verbose --environment more_different") do |result| assert_match(/more_different_string/, result.stdout, "Did not find more_different_string from \"more_different\" environment") end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/environment/use_environment_from_environmentpath.rb
acceptance/tests/environment/use_environment_from_environmentpath.rb
test_name "Use environments from the environmentpath" do require 'puppet/acceptance/classifier_utils' extend Puppet::Acceptance::ClassifierUtils tag 'audit:high', 'audit:integration', 'server' classify_nodes_as_agent_specified_if_classifer_present testdir = create_tmpdir_for_user(master, 'use_environmentpath') def generate_environment(path_to_env, environment) <<-EOS "#{path_to_env}/#{environment}":; "#{path_to_env}/#{environment}/manifests":; "#{path_to_env}/#{environment}/modules":; EOS end def generate_module_content(module_name, options = {}) base_path = options[:base_path] environment = options[:environment] env_path = options[:env_path] path_to_module = [base_path, env_path, environment, "modules"].compact.join("/") module_info = "module-#{module_name}" module_info << "-from-#{environment}" if environment <<-EOS "#{path_to_module}/#{module_name}":; "#{path_to_module}/#{module_name}/manifests":; "#{path_to_module}/#{module_name}/files":; "#{path_to_module}/#{module_name}/templates":; "#{path_to_module}/#{module_name}/lib":; "#{path_to_module}/#{module_name}/lib/facter":; "#{path_to_module}/#{module_name}/manifests/init.pp": ensure => file, mode => "0640", content => 'class #{module_name} { notify { "template-#{module_name}": message => template("#{module_name}/our_template.erb") } file { "$agent_file_location/file-#{module_info}": source => "puppet:///modules/#{module_name}/data" } }' ; "#{path_to_module}/#{module_name}/lib/facter/environment_fact_#{module_name}.rb": ensure => file, mode => "0640", content => "Facter.add(:environment_fact_#{module_name}) { setcode { 'environment fact from #{module_info}' } }" ; "#{path_to_module}/#{module_name}/files/data": ensure => file, mode => "0640", content => "data file from #{module_info}" ; "#{path_to_module}/#{module_name}/templates/our_template.erb": ensure => file, mode => "0640", content => "<%= @environment_fact_#{module_name} %>" ; EOS end def generate_site_manifest(path_to_manifest, *modules_to_include) <<-EOS "#{path_to_manifest}/site.pp": ensure => file, mode => "0640", content => "#{modules_to_include.map {|m| "include #{m}"}.join("\n")}" ; EOS end apply_manifest_on(master, <<-MANIFEST, :catch_failures => true) File { ensure => directory, owner => #{master.puppet['user']}, group => #{master.puppet['group']}, mode => "0770", } file { "#{testdir}":; "#{testdir}/base":; "#{testdir}/additional":; "#{testdir}/modules":; #{generate_environment("#{testdir}/base", "shadowed")} #{generate_environment("#{testdir}/base", "onlybase")} #{generate_environment("#{testdir}/additional", "shadowed")} #{generate_module_content("atmp", :base_path => testdir, :env_path => 'base', :environment => 'shadowed')} #{generate_site_manifest("#{testdir}/base/shadowed/manifests", "atmp", "globalmod")} #{generate_module_content("atmp", :base_path => testdir, :env_path => 'base', :environment => 'onlybase')} #{generate_site_manifest("#{testdir}/base/onlybase/manifests", "atmp", "globalmod")} #{generate_module_content("atmp", :base_path => testdir, :env_path => 'additional', :environment => 'shadowed')} #{generate_site_manifest("#{testdir}/additional/shadowed/manifests", "atmp", "globalmod")} # And one global module (--modulepath setting) #{generate_module_content("globalmod", :base_path => testdir)} "#{testdir}/additional/production":; "#{testdir}/additional/production/manifests":; #{generate_site_manifest("#{testdir}/additional/production/manifests", "globalmod")} } MANIFEST def run_with_environment(agent, environment, options = {}) expected_exit_code = options[:expected_exit_code] || 2 step "running an agent in environment '#{environment}'" atmp = agent.tmpdir("use_environmentpath_#{environment}") teardown do on(agent, "rm -rf '#{atmp}'") end agent_config = [ "-t" ] agent_config << '--environment' << environment if environment # This to test how the agent behaves when using the directory environment # loaders (which will not load an environment if it does not exist) agent_config << "--environmentpath='$confdir/environments'" if agent != master agent_config << { 'ENV' => { "FACTER_agent_file_location" => atmp }, } on(agent, puppet("agent", *agent_config), :acceptable_exit_codes => [expected_exit_code]) do |result| yield atmp, result end end master_opts = { 'master' => { 'environmentpath' => "#{testdir}/additional:#{testdir}/base", 'basemodulepath' => "#{testdir}/modules", } } if master.is_pe? master_opts['master']['basemodulepath'] << ":#{master['sitemoduledir']}" end with_puppet_running_on(master, master_opts, testdir) do agents.each do |agent| run_with_environment(agent, "shadowed") do |tmpdir, catalog_result| ["module-atmp-from-shadowed", "module-globalmod"].each do |expected| assert_match(/environment fact from #{expected}/, catalog_result.stdout) end ["module-atmp-from-shadowed", "module-globalmod"].each do |expected| on(agent, "cat '#{tmpdir}/file-#{expected}'") do |file_result| assert_match(/data file from #{expected}/, file_result.stdout) end end end run_with_environment(agent, "onlybase") do |tmpdir, catalog_result| ["module-atmp-from-onlybase", "module-globalmod"].each do |expected| assert_match(/environment fact from #{expected}/, catalog_result.stdout) end ["module-atmp-from-onlybase", "module-globalmod"].each do |expected| on(agent, "cat '#{tmpdir}/file-#{expected}'") do |file_result| assert_match(/data file from #{expected}/, file_result.stdout) end end end run_with_environment(agent, "production", :expected_exit_code => 2) do |tmpdir, catalog_result| refute_match(/module-atmp/, catalog_result.stdout, "module-atmp was included despite the default environment being loaded") assert_match(/environment fact from module-globalmod/, catalog_result.stdout) on(agent, "cat '#{tmpdir}/file-module-globalmod'") do |file_result| assert_match(/data file from module-globalmod/, file_result.stdout) end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/environment/feature_branch_configured_environment.rb
acceptance/tests/environment/feature_branch_configured_environment.rb
test_name "Agent should use set environment after running with specified environment" do require 'puppet/acceptance/environment_utils' extend Puppet::Acceptance::EnvironmentUtils tag 'audit:high', 'server' # Remove all traces of the last used environment teardown do agents.each do |agent| on(agent, puppet('config print lastrunfile')) do |command_result| agent.rm_rf(command_result.stdout) end end end tmp_environment = mk_tmp_environment_with_teardown(master, 'special') agents.each do |agent| on(agent, puppet("agent -t --environment #{tmp_environment}")) do |result| assert_match(/Info: Using environment 'special_\w+'/, result.stdout) end on(agent, puppet('agent -t')) do |result| assert_match(/Info: Using environment 'production'/, result.stdout) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/environment/should_find_existing_production_environment.rb
acceptance/tests/environment/should_find_existing_production_environment.rb
test_name "should find existing production environment" tag 'audit:medium' require 'puppet/acceptance/i18ndemo_utils' extend Puppet::Acceptance::I18nDemoUtils agents.each do |agent| path_separator = agent.platform_defaults[:pathseparator] initial_environment = on(agent, puppet("config print environment")).stdout.chomp initial_environment_paths = on(agent, puppet("config print environmentpath")).stdout.chomp.split(path_separator) default_environment_path = '' custom_environment_path = agent.tmpdir('custom_environment') teardown do step 'uninstall the module' do uninstall_i18n_demo_module(master) uninstall_i18n_demo_module(agent) end step 'Remove custom environment paths' do environment_paths = on(agent, puppet("config print environmentpath")).stdout.chomp environment_paths.split(path_separator).each do |path| agent.rm_rf(path) unless initial_environment_paths.include?(path) end agent.rm_rf(custom_environment_path) end step 'Reset environment settings' do on(agent, puppet("config set environmentpath #{initial_environment_paths.join(path_separator)}")) on(agent, puppet('config print lastrunfile')) do |command_result| agent.rm_rf(command_result.stdout) end if initial_environment == 'production' on(agent, puppet("config delete environment")) else on(agent, puppet("config set environment #{initial_environment}")) end on(agent, puppet("agent -t")) end end step 'Ensure a clean environment with default settings' do step 'Remove the lastrunfile which contains the last used agent environment' do on(agent, puppet('config print lastrunfile')) do |command_result| agent.rm_rf(command_result.stdout) end end step 'Change to the default environment setting' do on(agent, puppet("config delete environment")) on(agent, puppet("config print environment")) do |result| assert_match('production', result.stdout, "Default environment is not 'production' as expected") end end step 'Change to the default environmentpath setting and remove production folder' do on(agent, puppet("config delete environmentpath")) default_environment_path = on(agent, puppet("config print environmentpath")).stdout.chomp agent.rm_rf("#{default_environment_path}/production") end step 'Apply changes and expect puppet to create the production folder back' do on(agent, puppet("agent -t")) on(agent, "ls #{default_environment_path}") do |result| assert_match('production', result.stdout, "Default environment folder was not generated in last puppet run") end end end step 'Install a module' do install_i18n_demo_module(master) end step 'Expect output from the custom fact of the module' do on(agent, puppet("agent -t"), :acceptable_exit_codes => [0, 2]) do |result| assert_match(/Error:.*i18ndemo/, result.stderr) end end step 'Add a custom environment path before the current one' do current_environment_path = on(agent, puppet("config print environmentpath")).stdout.chomp on(agent, puppet("config set environmentpath '#{custom_environment_path}#{path_separator}#{current_environment_path}'")) end step 'Expect the module to still be found' do on(agent, puppet("agent -t"), :acceptable_exit_codes => [0, 2]) do |result| assert_match(/Error:.*i18ndemo/, result.stderr) end end step 'Expect no production environment folder changes' do on(agent, "ls #{custom_environment_path}") do |result| refute_match(/production/, result.stdout) end on(agent, "ls #{default_environment_path}") do |result| assert_match('production', result.stdout) end end step 'Remove production folder' do agent.rm_rf("#{default_environment_path}/production") end step 'Expect production environment folder to be recreated in the custom path' do on(agent, puppet("agent -t"), :acceptable_exit_codes => [0, 2]) do |result| step 'Expect the module to be gone on the server node' do refute_match(/Error:.*i18ndemo/, result.stderr) end if agent == master step 'Expect the production environment, along with the module, to be synced back on the agent node' do assert_match(/Error:.*i18ndemo/, result.stderr) end if agent != master end on(agent, "ls #{custom_environment_path}") do |result| assert_match('production', result.stdout, "Default environment folder was not generated in last puppet run") end on(agent, "ls #{default_environment_path}") do |result| refute_match(/production/, result.stdout) end end step 'Set back to just default environmentpath setting' do on(agent, puppet("config delete environmentpath")) end step 'Expect production environment folder to be found in both paths but use the default one' do on(agent, puppet("agent -t"), :acceptable_exit_codes => [0, 2]) do |result| step 'Expect the module to be gone' do refute_match(/Error:.*i18ndemo/, result.stderr) end if agent == master end on(agent, "ls #{default_environment_path}") do |result| assert_match('production', result.stdout, "Default environment folder was not generated in last puppet run") end on(agent, "ls #{custom_environment_path}") do |result| assert_match('production', result.stdout) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/security/cve-2013-1640_facter_string.rb
acceptance/tests/security/cve-2013-1640_facter_string.rb
# Setting a custom fact to "string" will overwrite a local variable during # template compilation on the master allowing remote code execution by # any authenticated client. test_name "CVE 2013-1640 Remote Code Execution" do tag 'audit:high', # low risk, high (security) impact 'audit:integration' confine :except, :platform => 'windows' on agents, %q[ FACTER_string="<%= %x{ /bin/echo hax0rd } %>" ] + %q[ puppet apply -e ] + %q[ 'notice(inline_template("<%= \"I am Safe\" %>"))' ] do |test| assert_match(/I am Safe/, test.stdout) refute_match(/hax0rd/, test.stdout) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/security/cve-2013-4761_injection_of_class_names_loading_code.rb
acceptance/tests/security/cve-2013-4761_injection_of_class_names_loading_code.rb
test_name "CVE 2013-4761 Injection of bad class names causing code loading" do confine :except, :platform => 'windows' tag 'audit:high', # low risk, high (security) impact 'audit:integration', # issue is completely on the master side 'server' testdir = create_tmpdir_for_user master, 'class-names-injection' exploit_path = "#{testdir}/exploit.rb" exploited_path = "#{testdir}/exploited" # @return [String] path to the manifest file def create_exploit_manifest(path, exploit_path_expression) apply_manifest_on(master, <<-MANIFEST, :catch_failures => true) File { ensure => directory, mode => "0770", owner => #{master.puppet['user']}, group => #{master.puppet['group']}, } file { '#{path}/environments':; '#{path}/environments/production':; '#{path}/environments/production/manifests':; '#{path}/environments/production/manifests/site.pp': ensure => file, content => ' $enc_data = "#{exploit_path_expression}" include $enc_data ', mode => "0640", } MANIFEST end def should_not_be_able_to_exploit(exploited_path) agents.each do |agent| next if agent['roles'].include?('master') step "Request a catalog to trigger the exploit" do on agent, puppet('agent', '-t'), :acceptable_exit_codes => [1] end step "Check that the exploit marker was not created" do on master, "test ! -e #{exploited_path}" end end end step "Create exploit file" do create_remote_file(master, exploit_path, <<-EXPLOIT) ::File.open('#{exploited_path}', 'w') { |f| f.puts("exploited") } EXPLOIT on(master, "chmod 777 #{exploit_path}") end master_opts = { 'main' => { 'environmentpath' => "#{testdir}/environments", }, } with_puppet_running_on(master, master_opts) do step "Class name is not interpreted as an absolute path" do create_exploit_manifest(testdir, 'tmp::exploit') should_not_be_able_to_exploit(exploited_path) end step "Class name cannot be used for a directory traversal out of the module path" do # This is just a guess about how far back we need to go... traversal_exploit_expression = "#{'::..' * 20}#{exploit_path.gsub(File::SEPARATOR,'::')}" create_exploit_manifest(testdir, traversal_exploit_expression) should_not_be_able_to_exploit(exploited_path) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/security/cve-2013-1652_poison_other_node_cache.rb
acceptance/tests/security/cve-2013-1652_poison_other_node_cache.rb
test_name "CVE 2013-1652 Poison node cache" do tag 'audit:high', # low risk, high (security) impact 'audit:integration', # master side only 'server' step "Determine suitability of the test" do skip_test( "This test will only run on Puppet 3.x" ) if on(master, puppet('--version')).stdout =~ /\A2\./ end with_puppet_running_on( master, {} ) do # Ensure agent has a signed cert on master, puppet('agent', '-t' ) certname = on( master, puppet('agent', "--configprint certname")).stdout.chomp cert_path = on( master, puppet('agent', "--configprint hostcert")).stdout.chomp key_path = on( master, puppet('agent', "--configprint hostprivkey")).stdout.chomp curl_base = "curl --tlsv1 -g --cert \"#{cert_path}\" " + "--key \"#{key_path}\" -k -H 'Accept: application/json'" step "Attempt to poison the master's node cache" do yamldir = puppet_config(master, 'yamldir', section: 'master') exploited = "#{yamldir}/node/you.lose.yaml" on master, "rm -rf #{exploited}" on master, "rm -rf #{yamldir}/node/*" payload2 = "https://#{master}:8140/puppet/v3/node/#{certname}?environment=production" + "&instance=---+%21ruby%2Fobject%3APuppet%3A%3ANode%0A+classes" + "%3A%0A+-+foo%0A+name%3A+you.lose%0A+parameters" + "%3A+%7B%7D%0A+time%3A+2013-02-28+15%3A12%3A30.367008+-08%3A00" on master, "#{curl_base} '#{payload2}'" fail_test( "Found exploit file #{exploited}" ) if on( master, "[ ! -f #{exploited} ]", :acceptable_exit_codes => [0,1] ).exit_code == 1 end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/security/cve-2013-2275_report_acl.rb
acceptance/tests/security/cve-2013-2275_report_acl.rb
test_name "(#19531) report save access control" tag 'audit:high', # low risk, high (security) impact 'audit:refactor', # Use block style `test_name` 'audit:integration', # issue completely on the server side 'server' step "Verify puppet only allows saving reports from the node matching the certificate" fake_report = <<-EOYAML --- !ruby/object:Puppet::Transaction::Report host: mccune metrics: {} logs: [] puppet_version: "2.7.20" status: failed report_format: 3 EOYAML with_puppet_running_on(master, {}) do submit_fake_report_cmd = [ "curl --tlsv1 -k -X PUT", "--cacert \"$(puppet config print --section server cacert)\"", "--cert \"$(puppet config print --section server hostcert)\"", "--key \"$(puppet config print --section server hostprivkey)\"", "-H 'Content-Type: text/yaml'", "-d '#{fake_report}'", "\"https://#{master}:8140/puppet/v3/report/mccune?environment=production\"", ].join(" ") on(master, submit_fake_report_cmd, :acceptable_exit_codes => [0]) do |result| msg = "(#19531) (CVE-2013-2275) Puppet Server accepted a report for a node that does not match the certname" assert_match(/Forbidden request/, result.stdout, msg) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/security/cve-2013-1652_improper_query_params.rb
acceptance/tests/security/cve-2013-1652_improper_query_params.rb
require 'json' test_name "CVE 2013-1652 Improper query parameter validation" do confine :except, :platform => 'windows' confine :except, :platform => /osx/ # see PUP-4820 confine :except, :platform => /aix/ tag 'audit:high', # risk low, high (security) impact 'audit:integration', 'server' with_puppet_running_on master, {} do # Ensure each agent has a signed cert on agents, puppet('agent', "-t") agents.each do |agent| next if agent['roles'].include?( 'master' ) certname = on(agent, puppet('agent', "--configprint certname")).stdout.chomp payload = "https://#{master}:8140/puppet/v3/catalog/#{certname}" + "?environment=production&use_node=" + "---%20!ruby/object:Puppet::Node%0A%20%20" + "name:%20#{master}%0A%20%20classes:%20\[\]%0A%20%20" + "parameters:%20%7B%7D%0A%20%20facts:%20%7B%7D" cert_path = on(agent, puppet('agent', "--configprint hostcert")).stdout.chomp key_path = on(agent, puppet('agent', "--configprint hostprivkey")).stdout.chomp curl_base = "curl --tlsv1 -g --cert \"#{cert_path}\" --key \"#{key_path}\" -k -H 'Accept: application/json'" curl_call = "#{curl_base} '#{payload}'" step "Attempt to retrieve another nodes catalog" do on agent, curl_call do |test| begin res = JSON.parse( test.stdout ) fail_test( "Retrieved catalog for #{master} from #{agent}" ) if res['data'] && res['data']['name'] == master.name rescue JSON::ParserError # good, continue end end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/ssl/autosign_command.rb
acceptance/tests/ssl/autosign_command.rb
test_name "autosign command and csr attributes behavior (#7243,#7244)" do skip_test "Test requires at least one non-master agent" if hosts.length == 1 tag 'audit:high', # cert/ca core behavior 'audit:integration', 'server' # Ruby implementation is deprecated def assert_key_generated(name, stdout) assert_match(/Creating a new RSA SSL key for #{name}/, stdout, "Expected agent to create a new SSL key for autosigning") end testdirs = {} test_certnames = [] step "Generate tmp dirs on all hosts" do hosts.each do |host| testdirs[host] = host.tmpdir('autosign_command') on(host, "chmod 755 #{testdirs[host]}") end end hostname = master.execute('facter hostname') fqdn = master.execute('facter fqdn') teardown do step "clear test certs" master_opts = { 'main' => { 'server' => fqdn }, 'master' => { 'dns_alt_names' => "puppet,#{hostname},#{fqdn}" } } with_puppet_running_on(master, master_opts) do on(master, "puppetserver ca clean --certname #{test_certnames.join(',')}", :acceptable_exit_codes => [0,24]) end end step "Step 1: ensure autosign command can approve CSRs" do # Our script needs to consume stdin (SERVER-1116) # We should revert back to /bin/true once resolved autosign_true_script = <<-EOF !#/bin/bash while read line do : # noop command done exit 0 EOF autosign_true_script_path = "#{testdirs[master]}/mytrue" create_remote_file(master, autosign_true_script_path, autosign_true_script) on(master, "chmod 777 #{autosign_true_script_path}") master_opts = { 'master' => { 'autosign' => autosign_true_script_path, 'dns_alt_names' => "puppet,#{hostname},#{fqdn}" } } with_puppet_running_on(master, master_opts) do agents.each do |agent| next if agent == master test_certnames << (certname = "#{agent}-autosign") on(agent, puppet("agent --test", "--waitforcert 0", "--ssldir", "'#{testdirs[agent]}/ssldir-autosign'", "--certname #{certname}"), :acceptable_exit_codes => [0,2]) do |result| unless agent['locale'] == 'ja' assert_key_generated(agent, result.stdout) assert_match(/Downloaded certificate for #{agent}/, result.stdout, "Expected certificate to be autosigned") end end end end end step "Step 2: ensure autosign command can reject CSRs" do # Our script needs to consume stdin (SERVER-1116) # We should revert back to /bin/false once resolved autosign_false_script = <<-EOF !#/bin/bash while read line do : # noop command done exit 1 EOF autosign_false_script_path = "#{testdirs[master]}/myfalse" create_remote_file(master, autosign_false_script_path, autosign_false_script) on(master, "chmod 777 #{autosign_false_script_path}") master_opts = { 'master' => { 'autosign' => autosign_false_script_path, 'dns_alt_names' => "puppet,#{hostname},#{fqdn}" } } with_puppet_running_on(master, master_opts) do agents.each do |agent| next if agent == master test_certnames << (certname = "#{agent}-reject") on(agent, puppet("agent --test", "--waitforcert 0", "--ssldir", "'#{testdirs[agent]}/ssldir-reject'", "--certname #{certname}"), :acceptable_exit_codes => [1]) do |result| unless agent['locale'] == 'ja' assert_key_generated(agent, result.stdout) assert_match(/Certificate for #{agent}-reject has not been signed yet/, result.stdout, "Expected certificate to not be autosigned") end end end end end autosign_inspect_csr_path = "#{testdirs[master]}/autosign_inspect_csr.rb" step "Step 3: setup an autosign command that inspects CSR attributes" do autosign_inspect_csr = <<-END #!/opt/puppetlabs/puppet/bin/ruby require 'openssl' def unwrap_attr(attr) set = attr.value str = set.value.first str.value end csr_text = STDIN.read csr = OpenSSL::X509::Request.new(csr_text) passphrase = csr.attributes.find { |a| a.oid == '1.3.6.1.4.1.34380.2.1' } # And here we jump hoops to unwrap ASN1's Attr Set Str if unwrap_attr(passphrase) == 'my passphrase' exit 0 end exit 1 END create_remote_file(master, autosign_inspect_csr_path, autosign_inspect_csr) on master, "chmod 777 #{testdirs[master]}" on master, "chmod 777 #{autosign_inspect_csr_path}" end agent_csr_attributes = {} step "Step 4: create attributes for inclusion on csr on agents" do csr_attributes = <<-END custom_attributes: 1.3.6.1.4.1.34380.2.0: hostname.domain.com 1.3.6.1.4.1.34380.2.1: my passphrase 1.3.6.1.4.1.34380.2.2: # system IPs in hex - 0xC0A80001 # 192.168.0.1 - 0xC0A80101 # 192.168.1.1 END agents.each do |agent| agent_csr_attributes[agent] = "#{testdirs[agent]}/csr_attributes.yaml" create_remote_file(agent, agent_csr_attributes[agent], csr_attributes) end end step "Step 5: successfully obtain a cert" do master_opts = { 'master' => { 'autosign' => autosign_inspect_csr_path, 'dns_alt_names' => "puppet,#{hostname},#{fqdn}" }, } with_puppet_running_on(master, master_opts) do agents.each do |agent| next if agent == master step "attempting to obtain cert for #{agent}" test_certnames << (certname = "#{agent}-attrs") on(agent, puppet("agent --test", "--waitforcert 0", "--ssldir", "'#{testdirs[agent]}/ssldir-attrs'", "--csr_attributes '#{agent_csr_attributes[agent]}'", "--certname #{certname}"), :acceptable_exit_codes => [0,2]) do |result| assert_key_generated(agent, result.stdout) unless agent['locale'] == 'ja' assert_match(/Downloaded certificate for #{agent}/, result.stdout, "Expected certificate to be autosigned") end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/ssl/certificate_extensions.rb
acceptance/tests/ssl/certificate_extensions.rb
require 'puppet/acceptance/temp_file_utils' extend Puppet::Acceptance::TempFileUtils test_name "certificate extensions available as trusted data" do skip_test "Test requires at least one non-master agent" if hosts.length == 1 tag 'audit:high', # ca/cert core functionality 'audit:integration', 'server' # Ruby implementation is deprecated initialize_temp_dirs agent_certnames = [] hostname = master.execute('facter networking.hostname') fqdn = master.execute('facter networking.fqdn') teardown do step "Cleanup the test agent certs" master_config = { 'main' => { 'server' => fqdn }, 'master' => { 'dns_alt_names' => "puppet,#{hostname},#{fqdn}" } } with_puppet_running_on(master, master_config) do on(master, "puppetserver ca clean --certname #{agent_certnames.join(',')}", :acceptable_exit_codes => [0,24]) end end environments_dir = get_test_file_path(master, "environments") master_config = { 'main' => { 'environmentpath' => environments_dir, }, 'master' => { 'autosign' => true, 'dns_alt_names' => "puppet,#{hostname},#{fqdn}", } } csr_attributes = YAML.dump({ 'extension_requests' => { # registered puppet extensions 'pp_uuid' => 'b5e63090-5167-11e3-8f96-0800200c9a66', 'pp_instance_id' => 'i-3fkva', # private (arbitrary) extensions '1.3.6.1.4.1.34380.1.2.1' => 'db-server', # node role '1.3.6.1.4.1.34380.1.2.2' => 'webops' # node group } }) step "Generate a production environment manifest to dump trusted data" apply_manifest_on(master, <<-MANIFEST, :catch_failures => true) File { ensure => directory, mode => "0770", owner => #{master.puppet['user']}, group => #{master.puppet['group']}, } file { '#{environments_dir}':; '#{environments_dir}/production':; '#{environments_dir}/production/manifests':; '#{environments_dir}/production/manifests/site.pp': ensure => file, content => ' file { "$test_dir/trusted.yaml": ensure => file, content => inline_template("<%= YAML.dump(@trusted) %>") } ', mode => "0640", } MANIFEST with_puppet_running_on(master, master_config) do agents.each do |agent| next if agent == master step "Create agent csr_attributes.yaml on #{agent}" agent_csr_attributes = get_test_file_path(agent, "csr_attributes.yaml") agent_ssldir = get_test_file_path(agent, "ssldir") create_remote_file(agent, agent_csr_attributes, csr_attributes) agent_certname = "#{agent}-extensions" agent_certnames << agent_certname step "Check in as #{agent_certname}" on(agent, puppet("agent", "--test", "--waitforcert", 0, "--csr_attributes", agent_csr_attributes, "--certname", agent_certname, "--ssldir", agent_ssldir, 'ENV' => { "FACTER_test_dir" => get_test_file_path(agent, "") }), :acceptable_exit_codes => [0, 2]) trusted_data = YAML.load(on(agent, "cat #{get_test_file_path(agent, 'trusted.yaml')}").stdout) agent_hostname, agent_domain = agent_certname.split('.', 2) step "Verify trusted data" assert_equal({ 'authenticated' => 'remote', 'certname' => agent_certname, 'extensions' => { 'pp_uuid' => 'b5e63090-5167-11e3-8f96-0800200c9a66', 'pp_instance_id' => 'i-3fkva', '1.3.6.1.4.1.34380.1.2.1' => 'db-server', '1.3.6.1.4.1.34380.1.2.2' => 'webops' }, 'hostname' => agent_hostname, 'domain' => agent_domain, 'external' => {} }, trusted_data) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/ssl/trusted_external_facts.rb
acceptance/tests/ssl/trusted_external_facts.rb
test_name "trusted external fact test" do require 'puppet/acceptance/environment_utils' extend Puppet::Acceptance::EnvironmentUtils ### HELPERS ### SEPARATOR="<TRUSTED_JSON>" def parse_trusted_json(puppet_output) trusted_json = puppet_output.split(SEPARATOR)[1] if trusted_json.nil? raise "Puppet output does not contain the expected '#{SEPARATOR}<trusted_json>#{SEPARATOR}' output" end JSON.parse(trusted_json) rescue => e raise "Failed to parse the trusted JSON: #{e}" end ### END HELPERS ### tag 'audit:high', # external facts 'server' skip_test 'requires a master for serving module content' if master.nil? testdir = master.tmpdir('trusted_external_facts') on(master, "chmod 755 #{testdir}") tmp_environment = mk_tmp_environment_with_teardown(master, File.basename(__FILE__, '.*')) teardown do on(master, "rm -r '#{testdir}'", :accept_all_exit_codes => true) # 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 step "create 'external' module referencing trusted hash" do on(master, "mkdir -p #{environmentpath}/#{tmp_environment}/modules/external/manifests") master_module_manifest = "#{environmentpath}/#{tmp_environment}/modules/external/manifests/init.pp" manifest = <<MANIFEST class external { $trusted_json = inline_template('<%= @trusted.to_json %>') notify { 'trusted facts': message => "#{SEPARATOR}${trusted_json}#{SEPARATOR}" } } 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 external } SITE_PP create_remote_file(master, site_pp_file, site_pp) on(master, "chmod 644 '#{site_pp_file}'") end step "when trusted_external_command is a file" do external_trusted_fact_script_path = "#{testdir}/external_facts.sh" step "create the file" do external_trusted_fact_script = <<EOF #!/bin/bash CERTNAME=$1 printf '{"doot":"%s"}\n' "$CERTNAME" EOF create_remote_file(master, external_trusted_fact_script_path, external_trusted_fact_script) on(master, "chmod 777 #{external_trusted_fact_script_path}") end step "start the master and perform the test" do master_opts = { 'main' => { 'trusted_external_command' => external_trusted_fact_script_path } } with_puppet_running_on(master, master_opts) do agents.each do |agent| on(agent, puppet("agent", "-t", "--environment", tmp_environment), :acceptable_exit_codes => [0,2]) do |res| trusted_hash = parse_trusted_json(res.stdout) assert_includes(trusted_hash, 'external', "Trusted fact hash contains external key") assert_equal(agent.to_s, trusted_hash['external']['doot'], "trusted facts contains certname") end end end end end step "when trusted_external_command is a directory" do dir_path = "#{testdir}/commands" executable_files = { 'no_extension' => <<EOF, #!/bin/bash CERTNAME=$1 printf '{"no_extension_key":"%s"}\n' "$CERTNAME" EOF 'shell.sh' => <<EOF, #!/bin/bash CERTNAME=$1 printf '{"shell_key":"%s"}\n' "$CERTNAME" EOF 'ruby.rb' => <<EOF, #!#{master[:privatebindir]}/ruby require 'json' CERTNAME=ARGV[0] data = { "ruby_key" => CERTNAME } print data.to_json EOF } step "create the directory" do on(master, "mkdir #{dir_path}") on(master, "chmod 755 #{dir_path}") executable_files.each do |filename, content| filepath = "#{dir_path}/#{filename}" create_remote_file(master, filepath, content) on(master, "chmod 777 #{filepath}") end # Create a non-executable file and an executable child-directory # to ensure that these cases are skipped during external data # retrieval create_remote_file(master, "#{dir_path}/non_executable_file", "foo") executable_child_dir = "#{dir_path}/child_dir" on(master, "mkdir #{executable_child_dir}") on(master, "chmod 777 #{executable_child_dir}") end master_opts = { 'main' => { 'trusted_external_command' => dir_path } } step "start the master and perform the test" do with_puppet_running_on(master, master_opts) do agents.each do |agent| on(agent, puppet("agent", "-t", "--environment", tmp_environment), :acceptable_exit_codes => [0,2]) do |res| trusted_hash = parse_trusted_json(res.stdout) assert_includes(trusted_hash, 'external', "Trusted fact hash contains external key") external_keys = [ 'no_extension', 'shell', 'ruby' ] assert_equal(external_keys.sort, trusted_hash['external'].keys.sort, "trusted['external'] does not contain <basename> keys of all executable files") external_keys.each do |key| expected_data = { "#{key}_key" => agent.to_s } data = trusted_hash['external'][key] assert_equal(expected_data, data, "trusted['external'][#{key}] does not contain #{key}'s data") end end end end end step "when there's more than executable <basename> script" do step "create the conflicting file" do filepath = "#{dir_path}/shell.rb" create_remote_file(master, filepath, executable_files['shell.sh']) on(master, "chmod 777 #{filepath}") end step "start the master and perform the test" do with_puppet_running_on(master, master_opts) do agents.each do |agent| on(agent, puppet("agent", "-t", "--environment", tmp_environment), :acceptable_exit_codes => [1]) do |res| assert_match(/.*shell.*#{Regexp.escape(dir_path)}/, res.stderr) end end end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/windows/PUP-9719_windows_system_first_pa_run.rb
acceptance/tests/windows/PUP-9719_windows_system_first_pa_run.rb
# frozen_string_literal: true test_name 'PUP-9719 Windows First Agent run as SYSTEM sets cache file permissions correctly' do tag 'risk:high', 'audit:high', 'audit:integration' confine :to, platform: 'windows' require 'puppet/acceptance/temp_file_utils' extend Puppet::Acceptance::TempFileUtils agents.each do |agent| publicdir = on(agent, puppet('config print publicdir')).stdout.chomp client_datadir = on(agent, puppet('config print client_datadir')).stdout.chomp teardown do on agent, 'schtasks /delete /tn PuppetSystemRun /F' on agent, "rm -rf #{publicdir}/*" unless publicdir.empty? on agent, "rm -rf #{client_datadir}/catalog/*" unless client_datadir.empty? end step 'Clean the public and catalog directories first' do fail_test("The publicdir config is not set!") if publicdir.empty? fail_test("The client_datadir config is not set!") if client_datadir.empty? on agent, "rm -rf #{publicdir}/*" on agent, "rm -rf #{client_datadir}/catalog/*" end step 'Create and run a scheduled task on System Account.' do date_format = if agent['locale'] == 'ja' '%Y/%m/%d' else '%m/%d/%Y' end on agent, %Q( schtasks /create /tn PuppetSystemRun /RL HIGHEST /RU SYSTEM /F /SC ONCE /SD \ #{(Date.today + 1).strftime(date_format)} /ST 23:59 /TR \ 'cmd /c \"%ProgramFiles%\\Puppet Labs\\Puppet\\bin\\puppet.bat\" agent -t' ) on agent, 'schtasks /run /tn PuppetSystemRun' end step 'Wait for Puppet Agent run to complete' do last_puppet_run = File.join(publicdir, 'last_run_summary.yaml') trymax = 10 try = 1 last_wait = 2 wait = 3 file_found = false while try <= trymax if file_exists?(agent, last_puppet_run) logger.info('Puppet run has completed') file_found = true break end @logger.warn "Wait for Puppet (SYSTEM) run to complete, Try #{try}, Trying again in #{wait} seconds" sleep wait (last_wait, wait) = wait, last_wait + wait try += 1 end fail_test("Puppet Run (SYSTEM) didn't complete") unless file_found end step "Test that normal PA run under Administrator doesn't fail." do on agent, 'cmd /c puppet agent -t --detailed-exitcodes', acceptable_exit_codes: [0] end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/windows/QA-760_win_dash_dot_file_test.rb
acceptance/tests/windows/QA-760_win_dash_dot_file_test.rb
test_name "QA-760 - Windows Files Containing '-' and '.'" tag 'risk:high', 'audit:high', 'audit:refactor', # Use block style `test_name` 'audit:integration' confine(:to, :platform => 'windows') temp_folder = <<-MANIFEST file { 'c:/temp': ensure => directory } MANIFEST dash_dot_file = <<-MANIFEST file { 'c:/temp/dash-dot-%s.file': ensure => file, content => "The file has new content: %s!", } MANIFEST step "Generate Manifest" first_run_manifest = "" second_run_manifest = "" for i in 1..100 first_run_manifest += "#{dash_dot_file}\n" % [i,i] second_run_manifest += "#{dash_dot_file}\n" % [i,-i] end step "Create Temp Folder" agents.each do |agent| on(agent, puppet('apply', '--debug'), :stdin => temp_folder) end step "Create Dash Dot File 100 Times" agents.each do |agent| on(agent, puppet('apply', '--debug'), :stdin => first_run_manifest) end step "Update Dash Dot File 100 Times" agents.each do |agent| on(agent, puppet('apply', '--debug'), :stdin => second_run_manifest) end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/windows/QA-506_windows_exit_codes_test.rb
acceptance/tests/windows/QA-506_windows_exit_codes_test.rb
test_name "Windows Exec `exit_code` Parameter Acceptance Test" tag 'risk:high', 'audit:high', 'audit:refactor', # Use block style `test_name` 'audit:integration' # exec resource succeeds when the `exit_code` parameter # is given a windows specific exit code and a exec # returns that exit code, ie. it either correctly matches # exit_code parameter to returned exit code, or ignores both (; confine :to, :platform => 'windows' pass_exitcode_manifest = <<-MANIFEST winexitcode::execute { '0': exit_code => 0 } MANIFEST upper_8bit_boundary_manifest = <<-MANIFEST winexitcode::execute { '255': exit_code => 255 } MANIFEST cross_8bit_boundary_manifest = <<-MANIFEST winexitcode::execute { '256': exit_code => 256 } MANIFEST upper_32bit_boundary_manifest = <<-MANIFEST winexitcode::execute { '4294967295': exit_code => 4294967295 } MANIFEST cross_32bit_boundary_manifest = <<-MANIFEST winexitcode::execute { '4294967296': exit_code => 0 } MANIFEST negative_boundary_manifest = <<-MANIFEST winexitcode::execute { '-1': exit_code => 4294967295 } MANIFEST step "Install Custom Module for Testing" agents.each do |agent| if (on(agent, puppet("--version")).stdout.split('.')[0].to_i < 4) module_path_config_property = "confdir" else module_path_config_property = "codedir" end native_modules_path = on(agent, puppet("config print #{module_path_config_property}")).stdout.gsub('C:', '/cygdrive/c').strip #Check to see if we are running on Windows 2003. Do a crazy hack to get around SCP issues. if (on(agent, facter("os.release.major")).stdout =~ /2003/) on(agent, "ln -s #{native_modules_path.gsub(/ /, '\ ')} /tmp/puppet_etc") modules_path = '/tmp/puppet_etc' else modules_path = native_modules_path end #Create the modules directory if it doesn't exist if on(agent, "test ! -d #{modules_path}/modules", :acceptable_exit_codes => [0,1]).exit_code == 0 on(agent, "mkdir -p #{modules_path}/modules") end # copy custom module. scp_to(agent, File.expand_path(File.join(File.dirname(__FILE__), "winexitcode")), "#{modules_path}/modules") end agents.each do |agent| step "Verify '0' is a Valid Exit Code" #Apply the manifest and verify Puppet returns success. on(agent, puppet('apply', '--debug'), :stdin => pass_exitcode_manifest) step "Verify Unsigned 8bit Upper Boundary" #Apply the manifest and verify Puppet returns success. on(agent, puppet('apply', '--debug'), :stdin => upper_8bit_boundary_manifest) step "Verify Unsigned 8bit Cross Boundary" #Apply the manifest and verify Puppet returns success. on(agent, puppet('apply', '--debug'), :stdin => cross_8bit_boundary_manifest) step "Verify Unsigned 32bit Upper Boundary" #Apply the manifest and verify Puppet returns success. on(agent, puppet('apply', '--debug'), :stdin => upper_32bit_boundary_manifest) step "Verify Unsigned 32bit Cross Boundary" #Apply the manifest and verify Puppet returns success. on(agent, puppet('apply', '--debug'), :stdin => cross_32bit_boundary_manifest) step "Verify Negative Exit Code Rollover Boundary" #Apply the manifest and verify Puppet returns success. on(agent, puppet('apply', '--debug'), :stdin => negative_boundary_manifest) end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/windows/enable_password_changes_special_users.rb
acceptance/tests/windows/enable_password_changes_special_users.rb
test_name 'Puppet should change passwords for disabled, expired, or locked out Windows user accounts' do tag 'audit:high', 'audit:acceptance' require 'date' require 'puppet/acceptance/windows_utils' extend Puppet::Acceptance::WindowsUtils confine :to, platform: 'windows' def random_username "pl#{rand(999999).to_i}" end def change_password_manifest(username) return <<-MANIFEST user { '#{username}': ensure => 'present', password => '#{NEW_PASSWORD}' } MANIFEST end INITIAL_PASSWORD='iP@ssword' NEW_PASSWORD="Password-#{rand(999999).to_i}" agents.each do |host| disabled_username = random_username step "Create a disabled user account" do on(host, "cmd.exe /c net user #{disabled_username} #{INITIAL_PASSWORD} /active:no /add") end step "Change the disabled user account's password with puppet" do apply_manifest_on(host, change_password_manifest(disabled_username)) end step "Enabling the user account as the AccountManagement context can't verify disabled users" do on(host, "cmd.exe /c net user #{disabled_username} /active:yes") end step "Ensure the password was changed" do assert_password_matches_on(host, disabled_username, NEW_PASSWORD, "Expected the disabled user account's password to be changed") end expired_username = random_username step "Create an expired user account" do date_format = host["locale"] == "ja" ? "%y/%m/%d" : "%m/%d/%y" on(host, "cmd.exe /c net user #{expired_username} #{INITIAL_PASSWORD} /expires:#{(Date.today - 1).strftime(date_format)} /add") end step "Change the expired user's password with puppet" do apply_manifest_on(host, change_password_manifest(expired_username)) end step "Make expired user valid, as AccountManagement context can't verify expired user credentials" do date_format = host["locale"] == "ja" ? "%y/%m/%d" : "%m/%d/%y" on(host, "cmd.exe /c net user #{expired_username} /expires:#{(Date.today + 1).strftime(date_format)}") on(host, "cmd.exe /c net user #{expired_username} /active:yes") end step "Ensure the password was changed" do assert_password_matches_on(host, expired_username, NEW_PASSWORD, "Expected the expired user account's password to be changed") end locked_username = random_username step "Create a user account, lower the account lockout threshold, and lock the new account by using the wrong password" do on(host, "cmd.exe /c net user #{locked_username} #{INITIAL_PASSWORD} /add") on(host, "cmd.exe /c net accounts /lockoutthreshold:1") on(host, "cmd.exe /c runas /user:#{locked_username} hostname.exe", accept_all_exit_codes: true) end step "Change the locked account's password with puppet" do apply_manifest_on(host, change_password_manifest(locked_username)) end step "Unlock the account(set it as active) as AccountManagement context can't verify credentials of locked out accounts" do on(host, "cmd.exe /c net user #{locked_username} /active:yes") end step "Ensure the password was changed" do assert_password_matches_on(host, locked_username, NEW_PASSWORD, "Expected the locked out user account's password to be changed") end teardown do on(host, "cmd.exe /c net accounts /lockoutthreshold:0") host.user_absent(disabled_username) host.user_absent(expired_username) host.user_absent(locked_username) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/windows/service_manager_integration.rb
acceptance/tests/windows/service_manager_integration.rb
test_name 'Test agent state via service control manager' do tag 'audit:integration' confine :to, platform: 'windows' teardown do agents.each do |agent| state = query_agent_state(agent) if state != "STOPPED" stop_puppet_windows_daemon(agent) ensure_agent_state(agent, "STOPPED") end end end def query_agent_state(host) on(host, 'sc query puppet').stdout.match(/STATE.+\s{1}(\w+)/)[1] end def start_puppet_windows_daemon(host) on(host, 'sc start puppet') end def stop_puppet_windows_daemon(host) on(host, 'sc stop puppet') end def ensure_agent_state(host, state) retry_attempts = 0 while retry_attempts < 5 return if state == query_agent_state(host) retry_attempts += 1 sleep 1 end fail_test "State not #{state} after 5 tries" end step 'store initial state' do agents.each do |agent| initial_state = query_agent_state(agent) assert_match("STOPPED", initial_state, "agent daemon should initially be stopped") start_puppet_windows_daemon(agent) ensure_agent_state(agent, "RUNNING") stop_puppet_windows_daemon(agent) ensure_agent_state(agent, "STOPPED") end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/windows/PA-2191_windows_nocodepage_utf8_fallback.rb
acceptance/tests/windows/PA-2191_windows_nocodepage_utf8_fallback.rb
test_name 'PA-2191 - winruby fallsback to UTF8 for invalid CodePage' do confine :to, platform: 'windows' tag 'audit:high', 'audit:acceptance' agents.each do |host| initial_chcp_code = on(host, 'cmd.exe /c chcp').stdout.delete('^0-9') teardown do on(host, "cmd.exe /c chcp #{initial_chcp_code}") end step 'set an invalid Code Page and check if puppet can run' do on(host, 'cmd.exe /c chcp 720') begin on(host, puppet('--version'), acceptable_exit_codes: [0]) rescue StandardError fail_test('Code Page 720 is invalid') end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/agent/last_run_summary_report.rb
acceptance/tests/agent/last_run_summary_report.rb
test_name "The 'last_run_summary.yaml' report has the right location and permissions" do tag 'audit:high' require 'puppet/acceptance/temp_file_utils' extend Puppet::Acceptance::TempFileUtils agents.each do |agent| skip_test('This test does not work on Windows in japanese') if agent['platform'] =~ /windows/ && agent['locale'] == 'ja' custom_publicdir = agent.tmpdir('custom_public_dir') statedir = on(agent, puppet('config print statedir')).stdout.chomp fail_test("The 'statedir' config is not set!") if statedir.empty? publicdir = on(agent, puppet('config print publicdir')).stdout.chomp fail_test("The 'publicdir' config is not set!") if publicdir.empty? teardown do agent.rm_rf(custom_publicdir) agent.rm_rf("#{publicdir}/*") unless publicdir.empty? on(agent, puppet("config set publicdir #{publicdir}")) end step "Check if '#{publicdir}' was created during puppet installation" do on(agent, "ls #{publicdir}", :acceptable_exit_codes => [0]) end step "Check if '#{publicdir}' has '0755' permissions" do if agent['platform'] =~ /windows/ on(agent, "icacls #{publicdir}") do |result| # Linux 'Owner' permissions class equivalent assert_match(/BUILTIN\\Administrators:.*\(F\)/, result.stdout) # Known issue on Windows: 'C:\ProgramData\PuppetLabs\puppet' permissions are inherited # by its subfolders and it does not have any permissions for 'Everyone' (see 'PuppetAppDir' # in 'puppet-agent/resources/windows/wix/appdatafiles.wxs') # Below line should be added when solution is found: # assert_match(/Everyone:.*\(RX\)/, result.stdout) end else on(agent, "ls -al #{publicdir}") do |result| assert_match(/rwxr-xr-x.+\.$/, result.stdout) end end end step "Create the 'last_run_summary.yaml' report file by applying catalog" do on(agent, puppet('agent -t')) do |result| assert_match('Applied catalog', result.stdout) end end step "Check if the 'last_run_summary.yaml' report file created has '0640' permissions" do if agent['platform'] =~ /windows/ on(agent, "icacls #{File.join(publicdir, 'last_run_summary.yaml')}") do |result| # Linux 'Owner' premissions class equivalent assert_match('Administrator:(R,W', result.stdout) # Linux 'Group' permissions class equivalent assert_match('None:(R)', result.stdout) # Linux 'Public' permissions class equivalent assert_match('Everyone:(Rc,S,RA)', result.stdout) # According to icacls docs: # Rc = Read control # S = Synchronize # RA = Read attributes # More at https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/icacls end else on(agent, "ls -al #{publicdir}") do |result| assert_match(/rw-r-----.+last_run_summary\.yaml$/, result.stdout) end end end step "Check that '#{statedir}' exists and has no 'last_run_summary.yaml' file" do on(agent, "ls #{statedir}",:acceptable_exit_codes => [0]) do |result| refute_match(/last_run_summary.yaml/, result.stdout) end end step "Check that 'publicdir' can be reconfigured" do on(agent, puppet("config set publicdir #{custom_publicdir}")) on(agent, puppet('config print publicdir')) do |result| assert_match(custom_publicdir, result.stdout) end end step "Create a new 'last_run_summary.yaml' report file by applying catalog" do on(agent, puppet('agent -t')) do |result| assert_match('Applied catalog', result.stdout) end end step "Check if the 'last_run_summary.yaml' report file was created in the new location and still has '0640' permissions" do if agent['platform'] =~ /windows/ on(agent, "icacls #{File.join(custom_publicdir, 'last_run_summary.yaml')}") do |result| # Linux 'Owner' premissions class equivalent assert_match('Administrator:(R,W', result.stdout) # Linux 'Group' permissions class equivalent assert_match('None:(R)', result.stdout) # Linux 'Public' permissions class equivalent assert_match('Everyone:(Rc,S,RA)', result.stdout) # According to icacls docs: # Rc = Read control # S = Synchronize # RA = Read attributes # More at https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/icacls end else on(agent, "ls -al #{custom_publicdir}") do |result| assert_match(/rw-r-----.+last_run_summary\.yaml$/, result.stdout) end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/agent/agent_disable_lockfile.rb
acceptance/tests/agent/agent_disable_lockfile.rb
test_name "C4553 - agent --disable/--enable functionality should manage the agent lockfile properly" tag 'audit:integration', # lockfile uses the standard `vardir` location to store/query lockfile. # The validation of the `vardir` at the OS level # should be accomplished in another test. 'audit:high', 'audit:refactor' # This test should not require a master. Remove the use of `with_puppet_running_on`. # # This test is intended to ensure that puppet agent --enable/--disable # work properly, both in terms of complying with our public "API" around # lockfile semantics ( http://links.puppet.com/agent_lockfiles ), and # in terms of actually restricting or allowing new agent runs to begin. # require 'puppet/acceptance/temp_file_utils' extend Puppet::Acceptance::TempFileUtils initialize_temp_dirs() @all_tests_passed = false ############################################################################### # BEGIN TEST LOGIC ############################################################################### teardown do if @all_tests_passed then remove_temp_dirs() end agents.each do |agent| on(agent, puppet('agent', "--enable")) end end tuples = [ ["reason not specified", false], ["I'm busy; go away.'", true] ] with_puppet_running_on(master, {}) do tuples.each do |expected_message, explicitly_specify_message| step "disable the agent; specify message? '#{explicitly_specify_message}', message: '#{expected_message}'" do agents.each do |agent| if (explicitly_specify_message) on(agent, puppet('agent', "--disable \"#{expected_message}\"")) else on(agent, puppet('agent', "--disable")) end agent_disabled_lockfile = "#{agent.puppet['vardir']}/state/agent_disabled.lock" unless file_exists?(agent, agent_disabled_lockfile) then fail_test("Failed to create disabled lock file '#{agent_disabled_lockfile}' on agent '#{agent}'") end lock_file_content = file_contents(agent, agent_disabled_lockfile) # This is a hack; we should parse the JSON into a hash, but I don't # think I have a library available from the acceptance test framework # that I can use to do that. So I'm falling back to <gasp> regex. lock_file_content_regex = /"disabled_message"\s*:\s*"#{expected_message}"/ unless lock_file_content =~ lock_file_content_regex fail_test("Disabled lock file contents invalid; expected to match '#{lock_file_content_regex}', got '#{lock_file_content}' on agent '#{agent}'") end end end step "attempt to run the agent (message: '#{expected_message}')" do agents.each do |agent| on(agent, puppet('agent', "--test"), :acceptable_exit_codes => [1]) do |result| disabled_regex = /administratively disabled.*'#{expected_message}'/ unless result.stdout =~ disabled_regex fail_test("Unexpected output from attempt to run agent disabled; expecting to match '#{disabled_regex}', got '#{result.stdout}' on agent '#{agent}'") unless agent['locale'] == 'ja' end end end end step "enable the agent (message: '#{expected_message}')" do agents.each do |agent| agent_disabled_lockfile = "#{agent.puppet['vardir']}/state/agent_disabled.lock" on(agent, puppet('agent', "--enable")) if file_exists?(agent, agent_disabled_lockfile) then fail_test("Failed to remove disabled lock file '#{agent_disabled_lockfile}' on agent '#{agent}'") end end end step "verify that we can run the agent (message: '#{expected_message}')" do agents.each do |agent| on(agent, puppet('agent', "--test")) end end end # tuples block end # with_puppet_running_on block @all_tests_passed = true
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/agent/agent_fails_with_unknown_resource.rb
acceptance/tests/agent/agent_fails_with_unknown_resource.rb
test_name "agent run should fail if it finds an unknown resource type" do tag 'audit:high', 'audit:integration' require 'puppet/acceptance/common_utils' require 'puppet/acceptance/environment_utils' extend Puppet::Acceptance::EnvironmentUtils require 'puppet/acceptance/temp_file_utils' extend Puppet::Acceptance::TempFileUtils step "agent should fail when it can't find a resource" do vendor_modules_path = master.tmpdir('vendor_modules') tmp_environment = mk_tmp_environment_with_teardown(master, 'tmp') site_pp_content = <<-SITEPP define foocreateresource($one) { $msg = 'hello' notify { $name: message => $msg } } class example($x) { if $x == undef or $x == [] or $x == '' { notice 'foo' return() } notice 'bar' } node default { class { example: x => [] } create_resources('foocreateresource', {'blah'=>{'one'=>'two'}}) mycustomtype{'foobar':} } SITEPP manifests_path = "/tmp/#{tmp_environment}/manifests" on(master, "mkdir -p '#{manifests_path}'") create_remote_file(master, "#{manifests_path}/site.pp", site_pp_content) custom_type_content = <<-CUSTOMTYPE Puppet::Type.newtype(:mycustomtype) do @doc = "Create a new mycustomtype thing." newparam(:name, :namevar => true) do desc "Name of mycustomtype instance" end def refresh end end CUSTOMTYPE type_path = "#{vendor_modules_path}/foo/lib/puppet/type" on(master, "mkdir -p '#{type_path}'") create_remote_file(master, "#{type_path}/mycustomtype.rb", custom_type_content) on(master, "chmod -R 750 '#{vendor_modules_path}' '/tmp/#{tmp_environment}'") on(master, "chown -R #{master.puppet['user']}:#{master.puppet['group']} '#{vendor_modules_path}' '/tmp/#{tmp_environment}'") master_opts = { 'main' => { 'environment' => tmp_environment, 'vendormoduledir' => vendor_modules_path } } with_puppet_running_on(master, master_opts) do agents.each do |agent| teardown do agent.rm_rf(vendor_modules_path) end # override vendormoduledir in case agent and server are on the same host agent_dir = get_test_file_path(agent, 'vendormodulepath') on(agent, puppet('agent', '-t', '--environment', tmp_environment, '--vendormoduledir', agent_dir), acceptable_exit_codes: [1]) do |result| assert_match(/Error: Failed to apply catalog: Resource type 'Mycustomtype' was not found/, result.stderr) end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/agent/agent_parses_json_catalog.rb
acceptance/tests/agent/agent_parses_json_catalog.rb
test_name "C99978: Agent parses a JSON catalog" tag 'risk:high', 'audit:high', # tests defined catalog format 'audit:integration', # There is no OS specific risk here. 'server', 'catalog:json' require 'puppet/acceptance/common_utils' require 'json' step "Agent parses a JSON catalog" do agents.each do |agent| # Path to a ruby binary ruby = Puppet::Acceptance::CommandUtils.ruby_command(agent) # Refresh the catalog on(agent, puppet("agent --test")) # The catalog file should be parseable JSON json_catalog = File.join(agent.puppet['client_datadir'], 'catalog', "#{agent.puppet['certname']}.json") on(agent, "cat #{json_catalog} | #{ruby} -rjson -e 'JSON.parse(STDIN.read)'") # Can the agent parse it as JSON? on(agent, puppet("catalog find --terminus json > /dev/null")) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/agent/fallback_to_cached_catalog.rb
acceptance/tests/agent/fallback_to_cached_catalog.rb
test_name "fallback to the cached catalog" tag 'audit:high', 'audit:integration', # This test is not OS sensitive. 'audit:refactor' # A catalog fixture can be used for this test. Remove the usage of `with_puppet_running_on`. step "run agents once to cache the catalog" do with_puppet_running_on master, {} do on(agents, puppet("agent -t")) end end step "run agents again, verify they use cached catalog" do agents.each do |agent| # can't use --test, because that will set usecacheonfailure=false # We use a server that the agent can't possibly talk to in order # to guarantee that no communication can take place. on(agent, puppet("agent --onetime --no-daemonize --server puppet.example.com --verbose")) do |result| assert_match(/Using cached catalog/, result.stdout) unless agent['locale'] == 'ja' end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/direct_puppet/static_catalog_env_control.rb
acceptance/tests/direct_puppet/static_catalog_env_control.rb
test_name "Environment control of static catalogs" tag 'audit:high', 'audit:acceptance', 'audit:refactor', # use mk_tmp_environment_with_teardown helper for environment construction 'server' skip_test 'requires puppetserver to test static catalogs' if @options[:type] != 'aio' require 'json' @testroot = master.tmpdir(File.basename(__FILE__, '/*')) @coderoot = "#{@testroot}/code" @confdir = master['puppetserver-confdir'] @master_opts = { 'main' => { 'environmentpath' => "#{@coderoot}/environments", }, } @production_files = {} @canary_files = {} @agent_manifests = {} @catalog_files = {} agents.each do |agent| hn = agent.node_name resdir = agent.tmpdir('results') @production_files[hn] = "#{resdir}/prod_hello_from_puppet_uri" @canary_files[hn] = "#{resdir}/can_hello_from_puppet_uri" @catalog_files[hn] = "#{on(agent, puppet('config', 'print', 'client_datadir')).stdout.chomp}/catalog/#{hn}.json" @agent_manifests[hn] = <<MANIFESTAGENT file { '#{@coderoot}/environments/production/modules/hello/manifests/init.pp': ensure => file, mode => "0644", content => "class hello { notice('hello from production-hello') file { '#{resdir}' : ensure => directory, mode => '0755', } file { '#{resdir}/prod_hello_from_puppet_uri' : ensure => file, mode => '0644', source => 'puppet:///modules/hello/hello_msg', } }", } file { '#{@coderoot}/environments/canary/modules/can_hello/manifests/init.pp': ensure => file, mode => "0644", content => 'class can_hello { notice("hello from production-hello") file { "#{resdir}": ensure => directory, mode => "0755", } file { "#{resdir}/can_hello_from_puppet_uri" : ensure => file, mode => "0644", source => "puppet:///modules/can_hello/hello_msg", } }', } MANIFESTAGENT end # The code_content script needs to return the correct content whose checksum # matches the metadata contained in the static catalog. PRODUCTION_CONTENT = "Hello message from production/hello module, content from source attribute.".freeze CANARY_CONTENT = "Hello message from canary/can_hello module, content from source attribute.".freeze @manifest = <<MANIFEST File { ensure => directory, mode => "0755", } file { '#{@testroot}':; '#{@coderoot}':; '#{@coderoot}/environments':; '#{@coderoot}/environments/production':; '#{@coderoot}/environments/production/manifests':; '#{@coderoot}/environments/production/modules':; '#{@coderoot}/environments/production/modules/hello':; '#{@coderoot}/environments/production/modules/hello/manifests':; '#{@coderoot}/environments/production/modules/hello/files':; '#{@coderoot}/environments/canary':; '#{@coderoot}/environments/canary/manifests':; '#{@coderoot}/environments/canary/modules':; '#{@coderoot}/environments/canary/modules/can_hello':; '#{@coderoot}/environments/canary/modules/can_hello/manifests':; '#{@coderoot}/environments/canary/modules/can_hello/files':; } file { '#{@coderoot}/code_id.sh' : ensure => file, mode => "0755", content => '#! /bin/bash echo "code_version_1" ', } file { '#{@coderoot}/code_content.sh' : ensure => file, mode => "0755", content => '#! /bin/bash # script arguments: # $1 environment # $2 code_id # $3 path relative to mount # use echo -n to omit newline if [ $1 == "production" ] ; then echo -n "#{PRODUCTION_CONTENT}" else echo -n "#{CANARY_CONTENT}" fi ', } file { '#{@coderoot}/environments/production/environment.conf': ensure => file, mode => "0644", content => 'environment_timeout = 0 ', } file { '#{@coderoot}/environments/canary/environment.conf': ensure => file, mode => "0644", content => 'environment_timeout = 0 static_catalogs = false ', } file { '#{@coderoot}/environments/production/manifests/site.pp': ensure => file, mode => "0644", content => "node default { include hello } ", } file { '#{@coderoot}/environments/canary/manifests/site.pp': ensure => file, mode => "0644", content => "node default { include can_hello } ", } file { '#{@coderoot}/environments/production/modules/hello/files/hello_msg': ensure => file, mode => "0644", content => "#{PRODUCTION_CONTENT}", } file { '#{@coderoot}/environments/canary/modules/can_hello/files/hello_msg': ensure => file, mode => "0644", content => "#{CANARY_CONTENT}", } MANIFEST teardown do on(master, "mv #{@confdir}/puppetserver.conf.bak #{@confdir}/puppetserver.conf") on(master, "rm -rf #{@testroot}") agents.each do |agent| on(agent, puppet('config print lastrunfile')) do |command_result| agent.rm_rf(command_result.stdout) end end end step 'apply main manifest, static_catalogs unspecified in global scope, unspecified in production environment, disabled in canary environment' on( master, "cp #{@confdir}/puppetserver.conf #{@confdir}/puppetserver.conf.bak" ) apply_manifest_on(master, @manifest, :catch_failures => true) step "Add versioned-code parameters to puppetserver.conf and ensure the server is running" puppetserver_config = "#{master['puppetserver-confdir']}/puppetserver.conf" on master, "cp #{puppetserver_config} #{@coderoot}/puppetserver.conf.bak" versioned_code_settings = { "jruby-puppet" => { "master-code-dir" => @coderoot }, "versioned-code" => { "code-id-command" => "#{@coderoot}/code_id.sh", "code-content-command" => "#{@coderoot}/code_content.sh" } } modify_tk_config(master, puppetserver_config, versioned_code_settings) step 'start puppet server' with_puppet_running_on master, @master_opts, @coderoot do agents.each do |agent| hn = agent.node_name apply_manifest_on(master, @agent_manifests[hn], :catch_failures => true) step 'agent gets a production catalog, should be static catalog by default' on( agent, puppet( 'agent', '-t', '--environment', 'production' ), :acceptable_exit_codes => [0, 2] ) step 'verify production environment' r = on(agent, "cat #{@catalog_files[hn]}") catalog_content = JSON.parse(r.stdout) assert_equal( catalog_content['environment'], 'production', 'catalog for unexpectected environment' ) step 'verify static catalog by finding metadata section in catalog' assert( catalog_content['metadata'] && catalog_content['metadata'][@production_files[hn]], 'metadata section of catalog not found' ) step 'agent gets a canary catalog, static catalog should be disabled' on( agent, puppet( 'agent', '-t', '--environment', 'canary' ), :acceptable_exit_codes => [0, 2] ) step 'verify canary environment' r = on(agent, "cat #{@catalog_files[hn]}") catalog_content = JSON.parse(r.stdout) assert_equal( catalog_content['environment'], 'canary', 'catalog for unexpectected environment' ) step 'verify not static catalog by absence of metadata section in catalog' assert_nil( catalog_content['metadata'], 'unexpected metadata section found in catalog' ) end end step 'enable static catalog for canary environment' @static_canary_manifest = <<MANIFEST2 file { '#{@coderoot}/environments/canary/environment.conf': ensure => file, mode => "0644", content => 'environment_timeout = 0 static_catalogs = true ', } MANIFEST2 apply_manifest_on(master, @static_canary_manifest, :catch_failures => true) step 'disable global static catalog setting' @master_opts = { 'master' => { 'static_catalogs' => false }, 'main' => { 'environmentpath' => "#{@coderoot}/environments", }, } step 'bounce server for static catalog disable setting to take effect.' with_puppet_running_on master, @master_opts, @coderoot do agents.each do |agent| hn = agent.node_name apply_manifest_on(master, @agent_manifests[hn], :catch_failures => true) step 'agent gets a production catalog, should not be a static catalog' on( agent, puppet( 'agent', '-t', '--environment', 'production' ), :acceptable_exit_codes => [0, 2] ) step 'verify production environment' r = on(agent, "cat #{@catalog_files[hn]}") catalog_content = JSON.parse(r.stdout) assert_equal( catalog_content['environment'], 'production', 'catalog for unexpectected environment' ) step 'verify production environment, not static catalog' assert_nil( catalog_content['metadata'], 'unexpected metadata section found in catalog' ) step 'agent gets a canary catalog, static catalog should be enabled' on( agent, puppet( 'agent', '-t', '--environment', 'canary' ), :acceptable_exit_codes => [0, 2] ) step 'verify canary catalog' r = on(agent, "cat #{@catalog_files[hn]}") catalog_content = JSON.parse(r.stdout) assert_equal( catalog_content['environment'], 'canary', 'catalog for unexpectected environment' ) step 'verify canary static catalog' assert( catalog_content['metadata'] && catalog_content['metadata'][@canary_files[hn]], 'metadata section of catalog not found' ) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/direct_puppet/supports_utf8.rb
acceptance/tests/direct_puppet/supports_utf8.rb
test_name "C97172: static catalogs support utf8" do require 'puppet/acceptance/environment_utils' extend Puppet::Acceptance::EnvironmentUtils require 'puppet/acceptance/agent_fqdn_utils' extend Puppet::Acceptance::AgentFqdnUtils tag 'audit:high', 'audit:acceptance', 'audit:refactor' # Review for agent side UTF validation. app_type = File.basename(__FILE__, '.*') tmp_environment = mk_tmp_environment_with_teardown(master, app_type) tmp_file = {} agents.each do |agent| tmp_file[agent_to_fqdn(agent)] = agent.tmpfile(tmp_environment) end teardown do # Remove all traces of the last used environment agents.each do |agent| on(agent, puppet('config print lastrunfile')) do |command_result| agent.rm_rf(command_result.stdout) end end step 'clean out produced resources' do agents.each do |agent| if tmp_file.has_key?(agent_to_fqdn(agent)) && !tmp_file[agent_to_fqdn(agent)].empty? on(agent, "rm -f '#{tmp_file[agent_to_fqdn(agent)]}'") end end end end file_contents = 'Mønti Pythøn ik den Hølie Gräilen, yër? € ‰ ㄘ 万 竹 Ü Ö' step 'create site.pp with utf8 chars' do manifest = <<MANIFEST file { '#{environmentpath}/#{tmp_environment}/manifests/site.pp': ensure => file, content => ' \$test_path = \$facts["networking"]["fqdn"] ? #{tmp_file} file { \$test_path: content => @(UTF8) #{file_contents} | UTF8 } ', } MANIFEST apply_manifest_on(master, manifest, :catch_failures => true) end step 'run agent(s)' do with_puppet_running_on(master, {}) do agents.each do |agent| config_version = '' config_version_matcher = /configuration version '(\d+)'/ on(agent, puppet("agent -t --environment '#{tmp_environment}'"), :acceptable_exit_codes => 2).stdout do |result| config_version = result.match(config_version_matcher)[1] end on(agent, "cat '#{tmp_file[agent_to_fqdn(agent)]}'").stdout do |result| assert_equal(file_contents, result, 'file contents did not match accepted') end on(agent, "rm -f '#{tmp_file[agent_to_fqdn(agent)]}'") on(agent, puppet("agent -t --environment '#{tmp_environment}' --use_cached_catalog"), :acceptable_exit_codes => 2).stdout do |result| assert_match(config_version_matcher, result, 'agent did not use cached catalog') second_config_version = result.match(config_version_matcher)[1] asset_equal(config_version, second_config_version, 'config version should have been the same') end on(agent, "cat '#{tmp_file[agent_to_fqdn(agent)]}'").stdout do |result| assert_equal(file_contents, result, 'file contents did not match accepted') end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/direct_puppet/catalog_uuid_correlates_catalogs_with_reports.rb
acceptance/tests/direct_puppet/catalog_uuid_correlates_catalogs_with_reports.rb
test_name "PUP-5872: catalog_uuid correlates catalogs with reports" do tag 'audit:high', 'audit:acceptance', 'audit:refactor' # remove dependence on server by adding a # catalog and report fixture to validate against. master_reportdir = create_tmpdir_for_user(master, 'reportdir') def remove_reports_on_master(master_reportdir, agent_node_name) on(master, "rm -rf #{master_reportdir}/#{agent_node_name}/*") end def get_catalog_uuid_from_cached_catalog(host, agent_vardir, agent_node_name) cache_catalog_uuid = nil on(host, "cat #{agent_vardir}/client_data/catalog/#{agent_node_name}.json") do |result| cache_catalog_uuid = result.stdout.match(/"catalog_uuid":"([a-z0-9\-]*)",/)[1] end cache_catalog_uuid end def get_catalog_uuid_from_report(master_reportdir, agent_node_name) report_catalog_uuid = nil on(master, "cat #{master_reportdir}/#{agent_node_name}/*") do |result| report_catalog_uuid = result.stdout.match(/catalog_uuid: '?([a-z0-9\-]*)'?/)[1] end report_catalog_uuid end with_puppet_running_on(master, :master => { :reportdir => master_reportdir, :reports => 'store' }) do agents.each do |agent| agent_vardir = agent.tmpdir(File.basename(__FILE__, '.*')) step "agent: #{agent}: Initial run to retrieve a catalog and generate the first report" do on(agent, puppet("agent", "-t", "--vardir #{agent_vardir}"), :acceptable_exit_codes => [0,2]) end cache_catalog_uuid = get_catalog_uuid_from_cached_catalog(agent, agent_vardir, agent.node_name) step "agent: #{agent}: Ensure the catalog and report share the same catalog_uuid" do report_catalog_uuid = get_catalog_uuid_from_report(master_reportdir, agent.node_name) assert_equal(cache_catalog_uuid, report_catalog_uuid, "catalog_uuid found in cached catalog, #{cache_catalog_uuid} did not match report #{report_catalog_uuid}") end step "cleanup reports on master" do remove_reports_on_master(master_reportdir, agent.node_name) end step "Run with --use_cached_catalog and ensure catalog_uuid in the new report matches the cached catalog" do on(agent, puppet("agent", "--onetime", "--no-daemonize", "--use_cached_catalog", "--vardir #{agent_vardir}"), :acceptance_exit_codes => [0,2]) report_catalog_uuid = get_catalog_uuid_from_report(master_reportdir, agent.node_name) assert_equal(cache_catalog_uuid, report_catalog_uuid, "catalog_uuid found in cached catalog, #{cache_catalog_uuid} did not match report #{report_catalog_uuid}") end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/direct_puppet/cached_catalog_remediate_local_drift.rb
acceptance/tests/direct_puppet/cached_catalog_remediate_local_drift.rb
require 'puppet/acceptance/static_catalog_utils' extend Puppet::Acceptance::StaticCatalogUtils test_name "PUP-5122: Puppet remediates local drift using code_id and content_uri" do tag 'audit:high', 'audit:acceptance', 'audit:refactor', # use mk_tmp_environment_with_teardown helper for environment construction 'server' skip_test 'requires puppetserver installation' if @options[:type] != 'aio' basedir = master.tmpdir(File.basename(__FILE__, '.*')) module_dir = "#{basedir}/environments/production/modules" master_opts = { 'main' => { 'environmentpath' => "#{basedir}/environments" } } step "Add versioned-code parameters to puppetserver.conf and ensure the server is running" do setup_puppetserver_code_id_scripts(master, basedir) end teardown do cleanup_puppetserver_code_id_scripts(master, basedir) on master, "rm -rf #{basedir}" agents.each do |agent| on(agent, puppet('config print lastrunfile')) do |command_result| agent.rm_rf(command_result.stdout) end end end step "Create a module and a file with content representing the first code_id version" do apply_manifest_on(master, <<MANIFEST, :catch_failures => true) File { ensure => directory, mode => "0750", owner => #{master.puppet['user']}, group => #{master.puppet['group']}, } file { '#{basedir}':; '#{basedir}/environments':; '#{basedir}/environments/production':; '#{basedir}/environments/production/manifests':; '#{module_dir}':; '#{module_dir}/foo':; '#{module_dir}/foo/files':; } MANIFEST end with_puppet_running_on master, master_opts, basedir do agents.each do |agent| agent_test_file_path = agent.tmpfile('foo_file') step "Add test file resource to site.pp on master with agent-specific file path" do apply_manifest_on(master, <<MANIFEST, :catch_failures => true) File { owner => #{master.puppet['user']}, group => #{master.puppet['group']}, } file { "#{basedir}/environments/production/manifests/site.pp" : ensure => file, mode => "0640", content => "node default { file { '#{agent_test_file_path}' : ensure => file, source => 'puppet:///modules/foo/foo.txt' } }", } file { "#{module_dir}/foo/files/foo.txt" : ensure => file, content => "code_version_1", mode => "0640", } MANIFEST end step "agent: #{agent}: Initial run: create the file with code version 1 and cache the catalog" on(agent, puppet("agent", "-t"), :acceptable_exit_codes => [0,2]) # When there is no drift, there should be no request made to the server # for file metadata or file content. A puppet run depending on # a non-server will fail if such a request is made. Verify the agent # sends a report. step "Remove existing reports from server reports directory" on(master, "rm -rf /opt/puppetlabs/server/data/puppetserver/reports/#{agent.node_name}/*") r = on(master, "ls /opt/puppetlabs/server/data/puppetserver/reports/#{agent.node_name} | wc -l").stdout.chomp assert_equal(r, '0', "reports directory should be empty!") step "Verify puppet run without drift does not make file request from server" r = on(agent, puppet("agent", "--use_cached_catalog", "--server", "no_such_host", "--report_server", master.hostname, "--onetime", "--no-daemonize", "--detailed-exitcodes", "--verbose" )).stderr assert_equal(r, "", "Fail: Did agent try to contact server?") step "Verify report was delivered to server" r = on(master, "ls /opt/puppetlabs/server/data/puppetserver/reports/#{agent.node_name} | wc -l").stdout.chomp assert_equal(r, '1', "Reports directory should have one file") step "agent: #{agent}: Remove the test file to simulate drift" on(agent, "rm -rf #{agent_test_file_path}") step "Alter the source file on the master to simulate a code update" apply_manifest_on(master, <<MANIFEST, :catch_failures => true) file { "#{module_dir}/foo/files/foo.txt" : ensure => file, mode => "0640", content => "code_version_2", } MANIFEST step "Run agent again using --use_cached_catalog and ensure content from the first code_id is used" on(agent, puppet("agent", "-t", "--use_cached_catalog"), :acceptable_exit_codes => [0,2]) on(agent, "cat #{agent_test_file_path}") do |result| assert_equal('code_version_1', result.stdout) end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/face/parser_validate.rb
acceptance/tests/face/parser_validate.rb
test_name 'parser validate' do tag 'audit:high', 'audit:unit' # Parser validation should be core to ruby # and platform agnostic. require 'puppet/acceptance/environment_utils' extend Puppet::Acceptance::EnvironmentUtils require 'puppet/acceptance/temp_file_utils' extend Puppet::Acceptance::TempFileUtils app_type = File.basename(__FILE__, '.*') teardown do agents.each do |agent| on(agent, puppet('config print lastrunfile')) do |command_result| agent.rm_rf(command_result.stdout) end end end agents.each do |agent| skip_test('this test fails on windows French due to Cygwin/UTF Issues - PUP-8319,IMAGES-492') if agent['platform'] =~ /windows/ && agent['locale'] == 'fr' step 'manifest with parser function call' do if agent.platform !~ /windows/ tmp_environment = mk_tmp_environment_with_teardown(agent, app_type) create_sitepp(agent, tmp_environment, <<-SITE) function validate_this() { notice('hello, puppet') } validate_this() SITE on(agent, puppet("parser validate --environment #{tmp_environment}"), :pty => true) # default manifest end # manifest with Type aliases create_test_file(agent, "#{app_type}.pp", <<-PP) function validate_this() { notice('hello, puppet') } validate_this() type MyInteger = Integer notice 42 =~ MyInteger PP tmp_manifest = get_test_file_path(agent, "#{app_type}.pp") on(agent, puppet("parser validate #{tmp_manifest}")) end step 'manifest with bad syntax' do create_test_file(agent, "#{app_type}_broken.pp", "notify 'hello there'") tmp_manifest = get_test_file_path(agent, "#{app_type}_broken.pp") on(agent, puppet("parser validate #{tmp_manifest}"), :accept_all_exit_codes => true) do |result| assert_equal(result.exit_code, 1, 'parser validate did not exit with 1 upon parse failure') expected = /Error: Could not parse for environment production: This Name has no effect\. A value was produced and then forgotten \(one or more preceding expressions may have the wrong form\) \(file: .*_broken\.pp, line: 1, column: 1\)/ assert_match(expected, result.output, "parser validate did not output correctly: '#{result.output}'. expected: '#{expected.to_s}'") unless agent['locale'] == 'ja' end end step '(large) manifest with exported resources' do fixture_path = File.join(File.dirname(__FILE__), '..', '..', 'fixtures/manifest_large_exported_classes_node.pp') create_test_file(agent, "#{app_type}_exported.pp", File.read(fixture_path)) tmp_manifest = get_test_file_path(agent, "#{app_type}_exported.pp") on(agent, puppet("parser validate #{tmp_manifest}")) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/face/loadable_from_modules.rb
acceptance/tests/face/loadable_from_modules.rb
test_name "Exercise loading a face from a module" # Because the module tool does not work on windows, we can't run this test there confine :except, :platform => 'windows' tag 'audit:high', 'audit:acceptance', # This has been OS sensitive. 'audit:refactor' # Remove the confine against windows and refactor to # accommodate the Windows platform. require 'puppet/acceptance/temp_file_utils' extend Puppet::Acceptance::TempFileUtils initialize_temp_dirs metadata_json_file = <<-FILE { "name": "puppetlabs-helloworld", "version": "0.0.1", "author": "Puppet Labs", "summary": "Nginx Module", "license": "Apache Version 2.0", "source": "https://github.com/puppetlabs/puppetlabs-nginx", "project_page": "https://github.com/puppetlabs/puppetlabs-nginx", "issues_url": "https://github.com/puppetlabs/puppetlabs-nginx", "dependencies": [ {"name":"puppetlabs-stdlub","version_requirement":">= 1.0.0"} ] } FILE agents.each do |agent| if on(agent, facter("fips_enabled")).stdout =~ /true/ puts "Module build, loading and installing not supported on fips enabled platforms" next end environmentpath = get_test_file_path(agent, 'environments') dev_modulepath = "#{environmentpath}/dev/modules" module_base_dir = "#{dev_modulepath}/helloworld" teardown do on agent, "rm -rf #{module_base_dir}" end # make sure that we use the modulepath from the dev environment puppetconf = get_test_file_path(agent, 'puppet.conf') on agent, puppet("config", "set", "environmentpath", environmentpath, "--section", "main", "--config", puppetconf) on agent, puppet("config", "set", "environment", "dev", "--section", "user", "--config", puppetconf) mkdirs agent, module_base_dir create_remote_file(agent, "#{module_base_dir}/metadata.json", metadata_json_file) mkdirs agent, "#{module_base_dir}/lib/puppet/application" mkdirs agent, "#{module_base_dir}/lib/puppet/face" # copy application, face, and utility module create_remote_file(agent, "#{module_base_dir}/lib/puppet/application/helloworld.rb", <<'EOM') require 'puppet/face' require 'puppet/application/face_base' class Puppet::Application::Helloworld < Puppet::Application::FaceBase end EOM create_remote_file(agent, "#{module_base_dir}/lib/puppet/face/helloworld.rb", <<'EOM') Puppet::Face.define(:helloworld, '0.1.0') do summary "Hello world face" description "This is the hello world face" action 'actionprint' do summary "Prints hello world from an action" when_invoked do |options| puts "Hello world from an action" end end action 'moduleprint' do summary "Prints hello world from a required module" when_invoked do |options| require 'puppet/helloworld.rb' Puppet::Helloworld.print end end end EOM create_remote_file(agent, "#{module_base_dir}/lib/puppet/helloworld.rb", <<'EOM') module Puppet::Helloworld def print puts "Hello world from a required module" end module_function :print end EOM on(agent, puppet('help', '--config', puppetconf)) do |result| assert_match(/helloworld\s*Hello world face/, result.stdout, "Face missing from list of available subcommands") end on(agent, puppet('help', 'helloworld', '--config', puppetconf)) do |result| assert_match(/This is the hello world face/, result.stdout, "Descripion help missing") assert_match(/moduleprint\s*Prints hello world from a required module/, result.stdout, "help for moduleprint action missing") assert_match(/actionprint\s*Prints hello world from an action/, result.stdout, "help for actionprint action missing") end on(agent, puppet('helloworld', 'actionprint', '--config', puppetconf)) do |result| assert_match(/^Hello world from an action$/, result.stdout, "face did not print hello world") end on(agent, puppet('helloworld', 'moduleprint', '--config', puppetconf)) do |result| assert_match(/^Hello world from a required module$/, result.stdout, "face did not load module to print hello world") end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/face/4654_facts_face.rb
acceptance/tests/face/4654_facts_face.rb
test_name "Puppet facts face should resolve custom and external facts" tag 'audit:high', 'audit:integration' # The facter acceptance tests should be acceptance. # However, the puppet face merely needs to interact with libfacter. # So, this should be an integration test. # # This test is intended to ensure that custom and external facts present # on the agent are resolved and displayed by the puppet facts face. # custom_fact = <<CFACT Facter.add('custom_fact') do setcode do 'foo' end end CFACT unix_external_fact = <<EFACT #!/bin/sh echo 'external_fact=bar' EFACT win_external_fact = <<EFACT @echo off echo external_fact=bar EFACT agents.each do |agent| if agent['platform'] =~ /windows/ external_fact = win_external_fact ext = '.bat' else external_fact = unix_external_fact ext = '.sh' end step "Create custom and external facts in their default directories on the agent" teardown do on agent, "rm -rf #{agent.puppet['plugindest']}/facter" on agent, "rm -rf #{agent.puppet['pluginfactdest']}/external#{ext}" end on agent, puppet('apply'), :stdin => <<MANIFEST file { "#{agent.puppet['plugindest']}/facter": ensure => directory, } file { "#{agent.puppet['plugindest']}/facter/custom.rb": ensure => file, content => "#{custom_fact}", } file { "#{agent.puppet['pluginfactdest']}/external#{ext}": ensure => file, mode => "0755", content => "#{external_fact}", } MANIFEST step "Agent #{agent}: custom_fact and external_fact should be present in the output of `puppet facts`" on agent, puppet('facts') do |result| assert_match(/"custom_fact": "foo"/, result.stdout, "custom_fact did not match expected output") assert_match(/"external_fact": "bar"/, result.stdout, "external_fact did not match expected output") end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/language/sensitive_data_type.rb
acceptance/tests/language/sensitive_data_type.rb
test_name 'C98120, C98077: Sensitive Data is redacted on CLI, logs, reports' do require 'puppet/acceptance/puppet_type_test_tools.rb' extend Puppet::Acceptance::PuppetTypeTestTools tag 'audit:high', 'audit:acceptance', # Tests that sensitive data is retains integrity # between server and agent transport/application. # Leaving at acceptance layer due to validate # written logs. 'server' teardown do agents.each do |agent| on(agent, puppet('config print lastrunfile')) do |command_result| agent.rm_rf(command_result.stdout) end end end app_type = File.basename(__FILE__, '.*') tmp_environment = mk_tmp_environment_with_teardown(master, app_type) tmp_filename_win = tmp_filename_else = '' agents.each do |agent| # ugh... this won't work with more than two agents of two types if agent.platform =~ /32$/ tmp_filename_win = "C:\\cygwin\\tmp\\#{tmp_environment}.txt" else tmp_filename_win = "C:\\cygwin64\\tmp\\#{tmp_environment}.txt" end tmp_filename_else = "/tmp/#{tmp_environment}.txt" on agent, "echo 'old content' > /tmp/#{tmp_environment}.txt" end # first attempts at a reasonable table driven test. needs API work # FIXME: # expand this to other resource types, make parameters arbitrary, make assertions arbitrary # FIXME: add context messaging to each instance notify_redacted = 'Sensitive \[value redacted\]' file_redacted = 'changed \[redacted\] to \[redacted\]' test_resources = [ {:type => 'notify', :parameters => {:namevar => "1:${Sensitive.new('sekrit1')}"}, :assertions => [{:refute_match => 'sekrit1'}, {:assert_match => "1:#{notify_redacted}"}]}, {:type => 'notify', :parameters => {:namevar => "2:${Sensitive.new($meh2)}"}, :pre_code => '$meh2="sekrit2"', :assertions => [{:refute_match => 'sekrit2'}, {:assert_match => "2:#{notify_redacted}"}]}, {:type => 'notify', :parameters => {:namevar => "3:meh", :message => '"3:${Sensitive.new(\'sekrit3\')}"'}, :assertions => [{:refute_match => 'sekrit3'}, {:assert_match => "3:#{notify_redacted}"}]}, {:type => 'notify', :parameters => {:namevar => "4:meh", :message => "Sensitive.new($meh4)"}, :pre_code => '$meh4="sekrit4"', :assertions => [{:refute_match => 'sekrit4'}, {:assert_match => file_redacted}]}, {:type => 'notify', :parameters => {:namevar => "5:meh", :message => "$meh5"}, :pre_code => '$meh5=Sensitive.new("sekrit5")', :assertions => [{:refute_match => 'sekrit5'}, {:assert_match => file_redacted}]}, {:type => 'notify', :parameters => {:namevar => "6:meh", :message => '"6:${meh6}"'}, :pre_code => '$meh6=Sensitive.new("sekrit6")', :assertions => [{:refute_match => 'sekrit6'}, {:assert_match => "6:#{notify_redacted}"}]}, {:type => 'notify', :parameters => {:namevar => "7:${Sensitive('sekrit7')}"}, :assertions => [{:refute_match => 'sekrit7'}, {:assert_match => "7:#{notify_redacted}"}]}, # unwrap(), these should be en-clair {:type => 'notify', :parameters => {:namevar => "8:${unwrap(Sensitive.new('sekrit8'))}"}, :assertions => {:assert_match => "8:sekrit8"}}, {:type => 'notify', :parameters => {:namevar => "9:meh", :message => '"9:${unwrap(Sensitive.new(\'sekrit9\'))}"'}, :assertions => {:assert_match => "9:sekrit9"}}, {:type => 'notify', :parameters => {:namevar => "A:meh", :message => '"A:${unwrap($mehA)}"'}, :pre_code => '$mehA=Sensitive.new("sekritA")', :assertions => {:assert_match => "A:sekritA"}}, {:type => 'notify', :parameters => {:namevar => "B:meh", :message => '"B:${$mehB.unwrap}"'}, :pre_code => '$mehB=Sensitive.new("sekritB")', :assertions => {:assert_match => "B:sekritB"}}, {:type => 'notify', :parameters => {:namevar => "C:meh", :message => '"C:${$mehC.unwrap |$unwrapped| { "blk_${unwrapped}_blk" } } nonblk_${mehC}_nonblk"'}, :pre_code => '$mehC=Sensitive.new("sekritC")', :assertions => {:assert_match => ["C:blk_sekritC_blk", "nonblk_#{notify_redacted}_nonblk"]}}, # for --show_diff {:type => 'file', :parameters => {:namevar => "$pup_tmp_filename", :content => "Sensitive.new('sekritD')"}, :pre_code => "$pup_tmp_filename = if $facts['os']['family'] == 'windows' { '#{tmp_filename_win}' } else { '#{tmp_filename_else}' }", :assertions => [{:refute_match => 'sekritD'}, {:assert_match => /#{tmp_environment}\.txt..content. #{file_redacted}/}]}, ] sitepp_content = generate_manifest(test_resources) assertion_code = generate_assertions(test_resources) # Make a copy of the full set of 'test_resources' but filtered down to include # only the assertions of type ':refute_match'. So for example, where the # 'test_resources' array might have an entry like this... # # {:type => 'notify', ... # :assertions => [{:refute_match => 'sekrit1'}, # {:assert_match => "1:#{notify_redacted}"}]} # # ... the ':assert_match' entry would be filtered out in the new # 'refutation_resources' array, producing: # # {:type => 'notify', ... # :assertions => [{:refute_match => 'sekrit1'}]} # # This is done so that when validating the log output, we can refute the # existence of any of the sensitive info in the log without having to # assert that redacted info is in the log. The redacted info appears in # the console output from the Puppet agent run - by virtue of including a # '--debug' flag on the agent command line - whereas the redacted info is not # expected to be piped into the log. refutation_resources = test_resources.collect do |assertion_group| refutation_group = assertion_group.clone refutation_group[:assertions] = assertion_group[:assertions].select do |assertion| assertion.has_key?(:refute_match) end refutation_group end refutation_code = generate_assertions(refutation_resources) create_sitepp(master, tmp_environment, sitepp_content) step "run agent in #{tmp_environment}, run all assertions" do with_puppet_running_on(master,{}) do agents.each do |agent| # redirect logging to a temp location to avoid platform specific syslogs on(agent, puppet("agent -t --debug --trace --show_diff --environment #{tmp_environment}"), :accept_all_exit_codes => true) do |result| assert_equal(result.exit_code, 2,'puppet agent run failed') run_assertions(assertion_code, result) unless agent['locale'] == 'ja' step "assert no redacted data in log" do run_assertions(refutation_code, result) end end # don't do this before the agent log scanning, above. it will skew the results step "assert no redacted data in vardir" do # no recursive grep in solaris :facepalm: on(agent, "find #{agent.puppet['vardir']} -type f | xargs grep sekrit", :accept_all_exit_codes => true) do |result| refute_match(/sekrit(1|2|3|6|7)/, result.stdout, 'found redacted data we should not have') #TODO: if/when this is fixed, we should just be able to eval(assertion_code_ in this result block also! expect_failure 'file resource contents will end up in the cached catalog en-clair' do refute_match(/sekritD/, result.stdout, 'found redacted file data we should not have') end end end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/language/pcore_generate_env_isolation.rb
acceptance/tests/language/pcore_generate_env_isolation.rb
test_name 'C98345: ensure puppet generate assures env. isolation' do require 'puppet/acceptance/environment_utils.rb' extend Puppet::Acceptance::EnvironmentUtils tag 'audit:high', 'audit:integration', 'server' teardown do agents.each do |agent| on(agent, puppet('config print lastrunfile')) do |command_result| agent.rm_rf(command_result.stdout) end end end app_type = File.basename(__FILE__, '.*') tmp_environment = mk_tmp_environment_with_teardown(master, app_type) tmp_environment2 = mk_tmp_environment_with_teardown(master, app_type) fq_tmp_environmentpath = "#{environmentpath}/#{tmp_environment}" fq_tmp_environmentpath2 = "#{environmentpath}/#{tmp_environment2}" type_name = 'conflicting' relative_type_dir = 'modules/conflict/lib/puppet/type' relative_type_path = "#{relative_type_dir}/#{type_name}.rb" step 'create custom type in two environments' do on(master, "mkdir -p #{fq_tmp_environmentpath}/#{relative_type_dir}") on(master, "mkdir -p #{fq_tmp_environmentpath2}/#{relative_type_dir}") custom_type1 = <<-END Puppet::Type.newtype(:#{type_name}) do newparam :name, :namevar => true END custom_type2 = "#{custom_type1}" custom_type2 << " newparam :other\n" custom_type1 << " end\n" custom_type2 << " end\n" create_remote_file(master, "#{fq_tmp_environmentpath}/#{relative_type_path}", custom_type1) create_remote_file(master, "#{fq_tmp_environmentpath2}/#{relative_type_path}", custom_type2) site_pp1 = <<-PP notify{$environment:} #{type_name}{"somename":} PP site_pp2 = <<-PP notify{$environment:} #{type_name}{"somename": other => "uhoh"} PP create_sitepp(master, tmp_environment, site_pp1) create_sitepp(master, tmp_environment2, site_pp2) end on master, "chmod -R 755 /tmp/#{tmp_environment}" on master, "chmod -R 755 /tmp/#{tmp_environment2}" with_puppet_running_on(master,{}) do agents.each do |agent| on(agent, puppet("agent -t --environment #{tmp_environment}"), :acceptable_exit_codes => 2) step 'run agent in environment with type with an extra parameter. try to use this parameter' do on(agent, puppet("agent -t --environment #{tmp_environment2}"), :accept_all_exit_codes => true) do |result| unless agent['locale'] == 'ja' assert_match("Error: no parameter named 'other'", result.output, 'did not produce environment isolation issue as expected') end end end end step 'generate pcore files' do on(master, puppet("generate types --environment #{tmp_environment}")) on(master, puppet("generate types --environment #{tmp_environment2}")) end agents.each do |agent| step 'rerun agents after generate, ensure proper runs' do on(agent, puppet("agent -t --environment #{tmp_environment}"), :acceptable_exit_codes => 2) on(agent, puppet("agent -t --environment #{tmp_environment2}"), :acceptable_exit_codes => 2) end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/language/functions_in_puppet_language.rb
acceptance/tests/language/functions_in_puppet_language.rb
test_name 'Puppet executes functions written in the Puppet language' tag 'audit:high', 'audit:integration', 'audit:refactor', # use mk_tmp_environment_with_teardown helper for environment construction 'server' teardown do on master, 'rm -rf /etc/puppetlabs/code/modules/jenny' on master, 'rm -rf /etc/puppetlabs/code/environments/tommy' on master, 'rm -rf /etc/puppetlabs/code/environments/production/modules/one' on master, 'rm -rf /etc/puppetlabs/code/environments/production/modules/three' agents.each do |agent| on(agent, puppet('config print lastrunfile')) do |command_result| agent.rm_rf(command_result.stdout) end end end step 'Create some functions' do manifest = <<-EOF File { ensure => 'present', owner => 'root', group => 'root', mode => '0644', } file {['/etc/puppetlabs/', '/etc/puppetlabs/code/', '/etc/puppetlabs/code/modules/', '/etc/puppetlabs/code/modules/jenny', '/etc/puppetlabs/code/modules/jenny/functions', '/etc/puppetlabs/code/modules/jenny/functions/nested', '/etc/puppetlabs/code/environments', '/etc/puppetlabs/code/environments/production', '/etc/puppetlabs/code/environments/production/modules', '/etc/puppetlabs/code/environments/production/modules/one', '/etc/puppetlabs/code/environments/production/modules/one/functions', '/etc/puppetlabs/code/environments/production/modules/one/manifests', '/etc/puppetlabs/code/environments/production/modules/three', '/etc/puppetlabs/code/environments/production/modules/three/functions', '/etc/puppetlabs/code/environments/production/modules/three/manifests', '/etc/puppetlabs/code/environments/tommy', '/etc/puppetlabs/code/environments/tommy/modules', '/etc/puppetlabs/code/environments/tommy/modules/two', '/etc/puppetlabs/code/environments/tommy/modules/two/functions', ]: ensure => directory, mode => '0755', } # "Global" functions, no env file { '/etc/puppetlabs/code/modules/jenny/functions/mini.pp': content => 'function jenny::mini($a, $b) {if $a <= $b {$a} else {$b}}', require => File['/etc/puppetlabs/code/modules/jenny/functions'], } file { '/etc/puppetlabs/code/modules/jenny/functions/nested/maxi.pp': content => 'function jenny::nested::maxi($a, $b) {if $a >= $b {$a} else {$b}}', require => File['/etc/puppetlabs/code/modules/jenny/functions/nested'], } # Module "one", "production" env file { '/etc/puppetlabs/code/environments/production/modules/one/functions/foo.pp': content => 'function one::foo() {"This is the one::foo() function in the production environment"}', require => File['/etc/puppetlabs/code/environments/production/modules/one/functions'], } file { '/etc/puppetlabs/code/environments/production/modules/one/manifests/init.pp': content => 'class one { }', require => File['/etc/puppetlabs/code/environments/production/modules/one/manifests'], } # Module "three", "production" env file { '/etc/puppetlabs/code/environments/production/modules/three/functions/baz.pp': content => 'function three::baz() {"This is the three::baz() function in the production environment"}', require => File['/etc/puppetlabs/code/environments/production/modules/three/functions'], } file { '/etc/puppetlabs/code/environments/production/modules/three/manifests/init.pp': content => 'class three { }', require => File['/etc/puppetlabs/code/environments/production/modules/three/functions'], } # Module "two", "tommy" env file { '/etc/puppetlabs/code/environments/tommy/modules/two/functions/bar.pp': content => 'function two::bar() {"This is the two::bar() function in the tommy environment"}', require => File['/etc/puppetlabs/code/environments/tommy/modules/two/functions'], } EOF apply_manifest_on(master, manifest, {:catch_failures => true, :acceptable_exit_codes => [0,1]}) end manifest = <<-MANIFEST notice 'jenny::mini(1, 2) =', jenny::mini(1,2) notice 'jenny::nested::maxi(1, 2) =', jenny::nested::maxi(1,2) notice 'one::foo() =', one::foo() require 'one'; notice 'three::baz() =', three::baz() MANIFEST rc = apply_manifest_on(master, manifest, {:accept_all_exit_codes => true,}) step 'Call a global function' do fail_test 'Failed to call a "global" function' \ unless rc.stdout.include?('jenny::mini(1, 2) = 1') end step 'Call a global nested function' do fail_test 'Failed to call a "global" nested function' \ unless rc.stdout.include?('jenny::nested::maxi(1, 2) = 2') end step 'Call an env-specific function' do fail_test 'Failed to call a function defined in the current environment' \ unless rc.stdout.include?('This is the one::foo() function in the production environment') end step 'Call a function defined in an un-included module' do fail_test 'Failed to call a function defined in an un-required module' \ unless rc.stdout.include?('This is the three::baz() function in the production environment') end manifest = <<-MANIFEST.strip notice "two::bar() =", two::bar() MANIFEST # This should fail step 'Call a function not defined in the current environment' do rc = on master, puppet("apply -e '#{manifest}' --environment production"), {:accept_all_exit_codes => true,} fail_test 'Should not be able to call a function not defined in the current environment' \ unless rc.stderr.include?("Error: Evaluation Error: Unknown function: 'two::bar'") end step 'Call an env-specific function in a non-default environment' do rc = on master, puppet("apply -e '#{manifest}' --environment tommy") fail_test 'Failed to call env-specific function from that environment' \ unless rc.stdout.include?('This is the two::bar() function in the tommy environment') end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/language/server_set_facts.rb
acceptance/tests/language/server_set_facts.rb
test_name 'C64667: ensure server_facts is set and error if any value is overwritten by an agent' do require 'puppet/acceptance/environment_utils.rb' extend Puppet::Acceptance::EnvironmentUtils tag 'audit:high', 'audit:acceptance', # Validating server/client interaction 'server' teardown do agents.each do |agent| on(agent, puppet('config print lastrunfile')) do |command_result| agent.rm_rf(command_result.stdout) end end end app_type = File.basename(__FILE__, '.*') tmp_environment = mk_tmp_environment_with_teardown(master, app_type) step 'ensure $server_facts exist' do create_sitepp(master, tmp_environment, <<~SITE) $server_facts_hash_exists_and_is_not_empty = ($server_facts =~ Hash) and ($server_facts.length != 0) notify { "server_facts hash exists and is not empty: ${server_facts_hash_exists_and_is_not_empty}": } SITE master_opts = {} with_puppet_running_on(master, master_opts) do agents.each do |agent| on(agent, puppet("agent -t --environment #{tmp_environment}"), :acceptable_exit_codes => 2) do |result| assert_match(/Notify\[server_facts hash exists and is not empty: true\]/, result.stdout, "#{agent}: $server_facts should have some stuff" ) end end end end step 'ensure puppet issues a warning if an agent overwrites a server fact' do agents.each do |agent| on(agent, puppet("agent -t", 'ENV' => { 'FACTER_server_facts' => 'overwrite' }), :acceptable_exit_codes => 1) do |result| # Do not perform this check on non-English hosts unless agent['locale'] == 'ja' assert_match(/Error.*Attempt to assign to a reserved variable name: 'server_facts'/, result.stderr, "#{agent}: $server_facts should error if overwritten" ) end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/language/objects_in_catalog.rb
acceptance/tests/language/objects_in_catalog.rb
test_name 'C99627: can use Object types in the catalog and apply/agent' do require 'puppet/acceptance/environment_utils.rb' extend Puppet::Acceptance::EnvironmentUtils tag 'audit:high', 'audit:integration', 'audit:refactor' # The use of apply on a reference system should # be adequate to test puppet. Running this in # context of server/agent should not be necessary. manifest = <<-PP type Mod::Foo = Object[{ attributes => { 'name' => String, 'size' => Integer[0, default] } }] define mod::foo_notifier(Mod::Foo $foo) { notify { $foo.name: } } class mod { mod::foo_notifier { xyz: foo => Mod::Foo('A foo', 42) } } include mod PP agents.each do |agent| # This is currently only expected to work with apply as the custom data type # definition will not be present on the agent to deserialize properly step "apply manifest on agent #{agent.hostname} and assert notify output" do apply_manifest_on(agent, manifest) do |result| assert(result.exit_code == 0, "agent didn't exit properly: (#{result.exit_code})") assert_match(/A foo/, result.stdout, 'agent didn\'t notify correctly') end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/language/resource_refs_with_nested_arrays.rb
acceptance/tests/language/resource_refs_with_nested_arrays.rb
test_name "#7681: Allow using array variables in resource references" tag 'audit:high', 'audit:unit' agents.each do |agent| test_manifest = <<MANIFEST $exec_names = ["first", "second"] exec { "first": command => "#{agent.echo('the first command')}", path => "#{agent.path}", logoutput => true, } exec { "second": command => "#{agent.echo('the second command')}", path => "#{agent.path}", logoutput => true, } exec { "third": command => "#{agent.echo('the final command')}", path => "#{agent.path}", logoutput => true, require => Exec[$exec_names], } MANIFEST apply_manifest_on(agent, test_manifest) do |result| assert_match(/Exec\[third\].*the final command/, result.stdout) end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/language/binary_data_type.rb
acceptance/tests/language/binary_data_type.rb
test_name 'C98346: Binary data type' do require 'puppet/acceptance/puppet_type_test_tools.rb' extend Puppet::Acceptance::PuppetTypeTestTools tag 'audit:high', 'audit:integration', # Tests that binary data is retains integrity # between server and agent transport/application. # The weak link here is final ruby translation and # should not be OS sensitive. 'server' teardown do agents.each do |agent| on(agent, puppet('config print lastrunfile')) do |command_result| agent.rm_rf(command_result.stdout) end end end app_type = File.basename(__FILE__, '.*') tmp_environment = mk_tmp_environment_with_teardown(master, app_type) tmp_filename_win = tmp_filename_else = '' agents.each do |agent| # ugh... this won't work with more than two agents of two types if agent.platform =~ /32$/ tmp_filename_win = "C:\\cygwin\\tmp\\#{tmp_environment}.txt" else tmp_filename_win = "C:\\cygwin64\\tmp\\#{tmp_environment}.txt" end tmp_filename_else = "/tmp/#{tmp_environment}.txt" on(agent, "echo 'old content' > '/tmp/#{tmp_environment}.txt'") end # create a fake module files... file for binary_file() on(master, puppet_apply("-e 'file{[\"#{environmentpath}/#{tmp_environment}/modules\",\"#{environmentpath}/#{tmp_environment}/modules/empty\",\"#{environmentpath}/#{tmp_environment}/modules/empty/files\"]: ensure => \"directory\"} file{\"#{environmentpath}/#{tmp_environment}/modules/empty/files/blah.txt\": content => \"binary, yo\"}'")) base64_relaxed = Base64.encode64("invasionfromspace#{random_string}").strip base64_strict = Base64.strict_encode64("invasion from space #{random_string}\n") base64_urlsafe = Base64.urlsafe_encode64("invasion from-space/#{random_string}\n") test_resources = [ { :type => 'notify', :parameters => { :namevar => "1:$hell" }, :pre_code => "$hell = Binary('hello','%b')", :assertions => { :assert_match => 'Notice: 1:hell' } }, { :type => 'notify', :parameters => { :namevar => "2:$relaxed" }, :pre_code => "$relaxed = Binary('#{base64_relaxed}')", :assertions => { :assert_match => "Notice: 2:#{base64_relaxed}" } }, { :type => 'notify', :parameters => { :namevar => "3:$cHVwcGV0" }, :pre_code => "$cHVwcGV0 = Binary('cHVwcGV0')", :assertions => { :assert_match => 'Notice: 3:cHVwcGV0' } }, { :type => 'notify', :parameters => { :namevar => "4:$strict" }, :pre_code => "$strict = Binary('#{base64_strict}')", :assertions => { :assert_match => "Notice: 4:#{base64_strict}" } }, { :type => 'notify', :parameters => { :namevar => "5:$urlsafe" }, :pre_code => "$urlsafe = Binary('#{base64_urlsafe}')", :assertions => { :assert_match => "Notice: 5:#{base64_urlsafe}" } }, { :type => 'notify', :parameters => { :namevar => "6:$byte_array" }, :pre_code => "$byte_array = Binary([67,68])", :assertions => { :assert_match => "Notice: 6:Q0Q=" } }, { :type => 'notify', :parameters => { :namevar => "7:${empty_array}empty" }, :pre_code => "$empty_array = Binary([])", :assertions => { :assert_match => "Notice: 7:empty" } }, { :type => 'notify', :parameters => { :namevar => "8:${relaxed[1]}" }, :assertions => { :assert_match => "Notice: 8:bg==" } }, { :type => 'notify', :parameters => { :namevar => "9:${relaxed[1,3]}" }, :assertions => { :assert_match => "Notice: 9:bnZh" } }, { :type => 'notify', :parameters => { :namevar => "A:${utf8}" }, :pre_code => '$utf8=String(Binary([0xF0, 0x9F, 0x91, 0x92]),"%s")', :assertions => { :assert_match => 'Notice: A:\\xF0\\x9F\\x91\\x92' } }, { :type => 'notify', :parameters => { :namevar => "B:${type($bin_file)}" }, :pre_code => '$bin_file=binary_file("empty/blah.txt")', :assertions => { :assert_match => 'Notice: B:Binary' } }, { :type => 'file', :parameters => { :namevar => "$pup_tmp_filename", :content => "$relaxed" }, :pre_code => "$pup_tmp_filename = if $facts['os']['family'] == 'windows' { '#{tmp_filename_win}' } else { '#{tmp_filename_else}' }", :assertions => { :assert_match => /#{base64_relaxed}/ } }, ] sitepp_content = generate_manifest(test_resources) assertion_code = generate_assertions(test_resources) create_sitepp(master, tmp_environment, sitepp_content) step "run agent in #{tmp_environment}, run all assertions" do with_puppet_running_on(master, {}) do agents.each do |agent| on(agent, puppet("agent -t --environment '#{tmp_environment}'"), :acceptable_exit_codes => [2]) do |result| run_assertions(assertion_code, result) end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/language/exported_resources.rb
acceptance/tests/language/exported_resources.rb
test_name "C94788: exported resources using a yaml terminus for storeconfigs" do require 'puppet/acceptance/environment_utils' extend Puppet::Acceptance::EnvironmentUtils tag 'audit:high', 'audit:integration', 'audit:refactor', # This could be a component of a larger workflow scenario. 'server' skip_test 'requires puppetserver to service restart' if @options[:type] != 'aio' app_type = File.basename(__FILE__, '.*') tmp_environment = mk_tmp_environment_with_teardown(master, app_type) exported_username = 'er0ck' teardown do step 'stop puppet server' do service(master, :stop, master['puppetservice']) end step 'remove cached agent json catalogs from the master' do on(master, "rm -f #{File.join(master.puppet['yamldir'],'catalog','*')}", :accept_all_exit_codes => true) end on(master, "mv #{File.join('','tmp','puppet.conf')} #{master.puppet['confdir']}", :accept_all_exit_codes => true) step 'clean out collected resources' do on(hosts, puppet_resource("user #{exported_username} ensure=absent"), :accept_all_exit_codes => true) end agents.each do |agent| on(agent, puppet('config print lastrunfile')) do |command_result| agent.rm_rf(command_result.stdout) end end end storeconfigs_backend_name = 'json_storeconfigs' step 'create a yaml storeconfigs terminus in the modulepath' do moduledir = File.join(environmentpath,tmp_environment,'modules') terminus_class_name = 'JsonStoreconfigs' manifest = <<MANIFEST File { ensure => directory, } file { '#{moduledir}':; '#{moduledir}/yaml_terminus':; '#{moduledir}/yaml_terminus/lib':; '#{moduledir}/yaml_terminus/lib/puppet':; '#{moduledir}/yaml_terminus/lib/puppet/indirector':; '#{moduledir}/yaml_terminus/lib/puppet/indirector/catalog':; '#{moduledir}/yaml_terminus/lib/puppet/indirector/facts':; '#{moduledir}/yaml_terminus/lib/puppet/indirector/node':; '#{moduledir}/yaml_terminus/lib/puppet/indirector/resource':; } file { '#{moduledir}/yaml_terminus/lib/puppet/indirector/catalog/#{storeconfigs_backend_name}.rb': ensure => file, content => ' require "puppet/indirector/catalog/yaml" class Puppet::Resource::Catalog::#{terminus_class_name} < Puppet::Resource::Catalog::Yaml def save(request) raise ArgumentError.new("You can only save objects that respond to :name") unless request.instance.respond_to?(:name) file = path(request.key) basedir = File.dirname(file) # This is quite likely a bad idea, since we are not managing ownership or modes. Dir.mkdir(basedir) unless Puppet::FileSystem.exist?(basedir) begin # We cannot dump anonymous modules in yaml, so dump to json File.open(file, "w") { |f| f.write request.instance.to_json } rescue TypeError => detail Puppet.err "Could not save \#{self.name} \#{request.key}: \#{detail}" end end def find(request) nil end end ', } file { '#{moduledir}/yaml_terminus/lib/puppet/indirector/facts/#{storeconfigs_backend_name}.rb': ensure => file, content => ' require "puppet/indirector/facts/yaml" class Puppet::Node::Facts::#{terminus_class_name} < Puppet::Node::Facts::Yaml def find(request) nil end end ', } file { '#{moduledir}/yaml_terminus/lib/puppet/indirector/node/#{storeconfigs_backend_name}.rb': ensure => file, content => ' require "puppet/indirector/node/yaml" class Puppet::Node::#{terminus_class_name} < Puppet::Node::Yaml def find(request) nil end end ', } file { '#{moduledir}/yaml_terminus/lib/puppet/indirector/resource/#{storeconfigs_backend_name}.rb': ensure => file, content => ' require "puppet/indirector/yaml" require "puppet/resource/catalog" class Puppet::Resource::#{terminus_class_name} < Puppet::Indirector::Yaml desc "Read resource instances from cached catalogs" def search(request) catalog_dir = File.join(Puppet.run_mode.server? ? Puppet[:yamldir] : Puppet[:clientyamldir], "catalog", "*") results = Dir.glob(catalog_dir).collect { |file| catalog = Puppet::Resource::Catalog.convert_from(:json, File.read(file)) if catalog.name == request.options[:host] next end catalog.resources.select { |resource| resource.type == request.key && resource.exported }.map! { |res| data_hash = res.to_data_hash parameters = data_hash["parameters"].map do |name, value| Puppet::Parser::Resource::Param.new(:name => name, :value => value) end attrs = {:parameters => parameters, :scope => request.options[:scope]} result = Puppet::Parser::Resource.new(res.type, res.title, attrs) result.collector_id = "\#{catalog.name}|\#{res.type}|\#{res.title}" result } }.flatten.compact results end end ', } # all the filtering is taken care of in the terminii # so any tests on filtering belong with puppetdb or pe file { '#{environmentpath}/#{tmp_environment}/manifests/site.pp': ensure => file, content => ' node "#{master.hostname}" { @@user{"#{exported_username}": ensure => present,} } node "default" { # collect resources on all nodes (puppet prevents collection on same node) User<<| |>> } ', } MANIFEST apply_manifest_on(master, manifest, :catch_failures => true) end # must specify environment in puppet.conf for it to pickup the terminus code in an environment module # but we have to bounce the server to pickup the storeconfigs... config anyway # we can't use with_puppet_running_on here because it uses puppet resource to bounce the server # puppet resource tries to use yaml_storeconfig's path() which doesn't exist # and fails back to yaml which indicates an attempted directory traversal and fails. # we could implemnt path() properly, but i'm just going to start the server the old fashioned way # and... config set is broken and doesn't add a main section step 'turn on storeconfigs, start puppetserver the old fashioned way' do on(master, "cp #{File.join(master.puppet['confdir'],'puppet.conf')} #{File.join('','tmp')}") on(master, "echo [main] >> #{File.join(master.puppet['confdir'],'puppet.conf')}") on(master, "echo environment=#{tmp_environment} >> #{File.join(master.puppet['confdir'],'puppet.conf')}") on(master, puppet('config set storeconfigs true --section main')) on(master, puppet("config set storeconfigs_backend #{storeconfigs_backend_name} --section main")) service(master, :restart, master['puppetservice']) step 'run the master agent to export the resources' do on(master, puppet("agent -t --environment #{tmp_environment}")) end agents.each do |agent| next if agent == master step 'run the agents to collect exported resources' do on(agent, puppet("agent -t --environment #{tmp_environment}"), :acceptable_exit_codes => 2) on(agent, puppet_resource("user #{exported_username}"), :accept_all_exit_codes => true) do |result| assert_match(/present/, result.stdout, 'collected resource not found') end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/language/pcore_resource_types_should_have_precedence_over_ruby.rb
acceptance/tests/language/pcore_resource_types_should_have_precedence_over_ruby.rb
test_name 'C98097 - generated pcore resource types should be loaded instead of ruby for custom types' do tag 'audit:high', 'audit:integration', 'audit:refactor', # use `mk_tmp_environment_with_teardown` helper to build environment 'server' environment = 'production' step 'setup - install module with custom ruby resource type' do #{{{ testdir = master.tmpdir('c98097') codedir = "#{testdir}/codedir" site_manifest_content =<<EOM node default { notice(mycustomtype{"foobar":}) } EOM custom_type_content =<<EOM Puppet::Type.newtype(:mycustomtype) do @doc = "Create a new mycustomtype thing." newparam(:name, :namevar => true) do desc "Name of mycustomtype instance" $stderr.puts "this indicates that we are running ruby code and should not be seen when running generated pcore resource" end def refresh end end EOM apply_manifest_on(master, <<MANIFEST, :catch_failures => true) File { ensure => directory, mode => "0755", } file {[ '#{codedir}', '#{codedir}/environments', '#{codedir}/environments/#{environment}', '#{codedir}/environments/#{environment}/manifests', '#{codedir}/environments/#{environment}/modules', '#{codedir}/environments/#{environment}/modules/mymodule', '#{codedir}/environments/#{environment}/modules/mymodule/manifests', '#{codedir}/environments/#{environment}/modules/mymodule/lib', '#{codedir}/environments/#{environment}/modules/mymodule/lib/puppet', '#{codedir}/environments/#{environment}/modules/mymodule/lib/puppet/type' ]: } file { '#{codedir}/environments/#{environment}/manifests/site.pp': ensure => file, content => '#{site_manifest_content}', } file { '#{codedir}/environments/#{environment}/modules/mymodule/lib/puppet/type/mycustomtype.rb': ensure => file, content => '#{custom_type_content}', } MANIFEST conf_opts = { 'main' => { 'environmentpath' => "#{codedir}/environments" } } backup_file = backup_the_file(master, puppet_config(master, 'confdir', section: 'master'), testdir, 'puppet.conf') lay_down_new_puppet_conf master, conf_opts, testdir teardown do restore_puppet_conf_from_backup( master, backup_file ) # See PUP-6995 on(master, "rm -f #{puppet_config(master, 'yamldir', section: 'master')}/node/*.yaml") agents.each do |agent| on(agent, puppet('config print lastrunfile')) do |command_result| agent.rm_rf(command_result.stdout) end end end #}}} catalog_results = {} catalog_results[master.hostname] = { 'ruby_cat' => '', 'pcore_cat' => '' } step 'compile catalog using ruby resource' do on master, puppet('catalog', 'find', master.hostname) do |result| assert_match(/running ruby code/, result.stderr) catalog_results[master.hostname]['ruby_cat'] = JSON.parse(result.stdout.sub(/^[^{]+/,'')) end end step 'generate pcore type from ruby type' do on master, puppet('generate', 'types', '--environment', environment) end step 'compile catalog and make sure that ruby code is NOT executed' do on master, puppet('catalog', 'find', master.hostname) do |result| refute_match(/running ruby code/, result.stderr) catalog_results[master.hostname]['pcore_cat'] = JSON.parse(result.stdout.sub(/^[^{]+/,'')) end end step 'ensure that the resources created in the catalog using ruby and pcore are the same' do assert_equal(catalog_results[master.hostname]['ruby_cat']['resources'], catalog_results[master.hostname]['pcore_cat']['resources']) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/utf8/utf8-in-puppet-describe.rb
acceptance/tests/utf8/utf8-in-puppet-describe.rb
test_name 'utf-8 characters in module doc string, puppet describe' do tag 'audit:high', # utf-8 is high impact in general, puppet describe low risk? 'audit:integration', # not package dependent but may want to vary platform by LOCALE/encoding 'audit:refactor' # if keeping, use mk_tmp_environment_with_teardown # remove with_puppet_running_on unless pluginsync is absolutely necessary # (if it is, add 'server' tag # utf8chars = "€‰ㄘ万竹ÜÖ" utf8chars = "\u20ac\u2030\u3118\u4e07\u7af9\u00dc\u00d6" master_mod_dir = master.tmpdir("describe_master") on(master, "chmod -R 755 #{master_mod_dir}"); teardown do on(master, "rm -rf #{master_mod_dir}") agents.each do |agent| on(agent, puppet('config print lastrunfile')) do |command_result| agent.rm_rf(command_result.stdout) end end end master_manifest = <<MASTER_MANIFEST File { ensure => directory, mode => "0755", } file { '#{master_mod_dir}/code':; '#{master_mod_dir}/code/environments':; '#{master_mod_dir}/code/environments/production':; '#{master_mod_dir}/code/environments/production/modules':; '#{master_mod_dir}/code/environments/production/modules/master_mytype_module':; '#{master_mod_dir}/code/environments/production/modules/master_mytype_module/lib':; '#{master_mod_dir}/code/environments/production/modules/master_mytype_module/lib/puppet':; '#{master_mod_dir}/code/environments/production/modules/master_mytype_module/lib/puppet/type':; } file { '#{master_mod_dir}/code/environments/production/modules/master_mytype_module/lib/puppet/type/master_mytype.rb' : ensure => file, mode => '0755', content => ' Puppet::Type.newtype(:master_mytype) do @doc = "Testing to see if puppet handles describe blocks correctly when they contain utf8 characters, such as #{utf8chars} " newparam(:name) do isnamevar desc " name parameter for mytype, also with some utf8 chars #{utf8chars}" end end ', } MASTER_MANIFEST step "Apply master manifest" do apply_manifest_on(master, master_manifest) end master_opts = { 'main' => { 'environmentpath' => "#{master_mod_dir}/code/environments", } } step "Start puppet server" with_puppet_running_on(master, master_opts, master_mod_dir) do agents.each do |agent| puts "agent name: #{agent.hostname}, platform: #{agent.platform}" step "Run puppet agent for plugin sync" do on( agent, puppet("agent", "-t"), :acceptable_exit_codes => [0, 2] ) end step "Puppet describe for master-hosted mytype" do on(agent, puppet("describe", "master_mytype")) do |result| assert_match( /master_mytype.*such as #{utf8chars}/m, result.stdout, "Main description of master_mytype did not match utf8 chars, '#{utf8chars}'" ) assert_match( /name parameter.*chars #{utf8chars}/, result.stdout, "Name parameter description of master_mytype did not match utf8 chars, '#{utf8chars}'" ) end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/utf8/utf8-in-function-args.rb
acceptance/tests/utf8/utf8-in-function-args.rb
test_name 'utf-8 characters in function parameters' do confine :except, :platform => /debian-12-amd64/ # PUP-12020 tag 'audit:high', 'audit:integration', # not package dependent but may want to vary platform by LOCALE/encoding 'audit:refactor' # if keeping, use mk_tmp_environment_with_teardown confine :except, :platform => [ 'windows', # PUP-6983 'aix', # PUP-7194 ] teardown do agents.each do |agent| on(agent, puppet('config print lastrunfile')) do |command_result| agent.rm_rf(command_result.stdout) end end end # utf8chars = "€‰ㄘ万竹ÜÖ" utf8chars = "\u20ac\u2030\u3118\u4e07\u7af9\u00dc\u00d6" agents.each do |agent| step 'alert' do result = on( agent, puppet("apply", "-e" "'alert(\"alert #{utf8chars}\")'"), :environment => {:LANG => "en_US.UTF-8"} ) assert_match( /#{utf8chars}/, result.stderr, "Did not find the utf8 chars." ) end step 'assert_type' do on( agent, puppet( "apply", "-e", "'notice(assert_type(String, \"#{utf8chars}\"))'" ), { :environment => {:LANG => "en_US.UTF-8"}, :acceptable_exit_codes => [0], } ) on( agent, puppet("apply", "-e 'notice(assert_type(Float, \"#{utf8chars}\"))'"), { :environment => {:LANG => "en_US.UTF-8"}, :acceptable_exit_codes => [1], } ) end step 'filter' do puppet_cmd = "' [$a] = [[\"abc\", \"#{utf8chars}\", \"100\"]]; [$f] = [filter($a) |$p| {$p =~ /#{utf8chars}/}]; notice(\"f = $f\") '" result = on( agent, puppet("apply", "-e", puppet_cmd), :environment => {:LANG => "en_US.UTF-8"} ) assert_match(/#{utf8chars}/, result.stdout, "filter() failed.") end agent_lookup_test_dir = agent.tmpdir("lookup_test_dir") mod_name = "lookup_module" mod_key = "#{mod_name}::mod_key_#{utf8chars}" mod_val = "mod_val_#{utf8chars}" env_key = "env_key_#{utf8chars}" env_val = "env_val_#{utf8chars}" array_key = "array_key_with_utf8_#{utf8chars}" array_val_2 = "array value 2 with utf8 #{utf8chars}" scalar_key = "scalar_key_with_utf8_#{utf8chars}" scalar_val = "scalar value with utf8 #{utf8chars}" non_key = "non_key_#{utf8chars}" step 'apply hiera/lookup manifest' do # I want the banner in the output but # some results: orig_hiera_config, # orig_environmentpath from operations # here are used later, so I don't want # them local to a step block. end lookup_manifest = <<LOOKUP_MANIFEST File { ensure => directory, mode => "0755", } file { "#{agent_lookup_test_dir}" :; "#{agent_lookup_test_dir}/hiera_data" :; "#{agent_lookup_test_dir}/environments" :; "#{agent_lookup_test_dir}/environments/production" :; "#{agent_lookup_test_dir}/environments/production/data" :; "#{agent_lookup_test_dir}/environments/production/manifests" :; "#{agent_lookup_test_dir}/environments/production/modules" :; "#{agent_lookup_test_dir}/environments/production/modules/#{mod_name}" :; "#{agent_lookup_test_dir}/environments/production/modules/#{mod_name}/manifests" :; "#{agent_lookup_test_dir}/environments/production/modules/#{mod_name}/data" :; } file { "#{agent_lookup_test_dir}/environments/production/modules/#{mod_name}/hiera.yaml" : ensure => file, mode => "0644", content => '--- version: 5 ', } file { "#{agent_lookup_test_dir}/environments/production/modules/#{mod_name}/data/common.yaml" : ensure => "file", mode => "0644", content => '--- #{mod_key}: #{mod_val} ', } file { "#{agent_lookup_test_dir}/environments/production/environment.conf" : ensure => file, mode => "0644", content => ' # environment_data_provider = "hiera" ' } file { "#{agent_lookup_test_dir}/environments/production/hiera.yaml" : ensure => file, mode => "0644", content => ' --- version: 5 ' } file { "#{agent_lookup_test_dir}/environments/production/data/common.yaml" : ensure => file, mode => "0644", content => ' --- #{env_key} : #{env_val} ', } file { "#{agent_lookup_test_dir}/hiera.yaml" : ensure => file, mode => "0644", content => '--- :backends: - yaml :hierarchy: - common :yaml: :datadir: #{agent_lookup_test_dir}/hiera_data ', } file { "#{agent_lookup_test_dir}/hiera_data/common.yaml" : ensure => file, mode => "0644", content => ' #{array_key} : - "array value 1" - "#{array_val_2}" #{scalar_key} : "#{scalar_val}" ', } LOOKUP_MANIFEST apply_manifest_on( agent, lookup_manifest, :environment => {:LANG => "en_US.UTF-8"} ) result = on( agent, puppet("config", "print hiera_config"), :environment => {:LANG => "en_US.UTF-8"} ) orig_hiera_config = result.stdout.chomp result = on( agent, puppet("config", "print environmentpath"), :environment => {:LANG => "en_US.UTF-8"} ) orig_environmentpath = result.stdout.chomp on( agent, puppet( "config", "set hiera_config #{agent_lookup_test_dir}/hiera.yaml" ), :environment => {:LANG => "en_US.UTF-8"} ) on( agent, puppet( "config", "set environmentpath #{agent_lookup_test_dir}/environments" ), :environment => {:LANG => "en_US.UTF-8"} ) step 'hiera' do result = on( agent, puppet("apply", "-e", "'notice(hiera(\"#{array_key}\"))'"), :environment => {:LANG => "en_US.UTF-8"} ) assert_match(/#{array_val_2}/, result.stdout, "hiera array lookup") result = on( agent, puppet("apply", "-e", "'notice(hiera(\"#{scalar_key}\"))'"), :environment => {:LANG => "en_US.UTF-8"} ) assert_match(/#{scalar_val}/, result.stdout, "hiera scalar lookup") result = on( agent, puppet("apply", "-e", "'notice(hiera(\"#{non_key}\"))'"), { :acceptable_exit_codes => (0..255), :environment => {:LANG => "en_US.UTF-8"} } ) assert_match( /did not find a value for the name '#{non_key}'/, result.stderr, "hiera non_key lookup" ) end step 'lookup' do result = on( agent, puppet("apply", "-e", "'notice(lookup(\"#{env_key}\"))'"), :environment => {:LANG => "en_US.UTF-8"} ) assert_match( /#{env_val}/, result.stdout, "env lookup failed for '#{env_key}'" ) result = on( agent, puppet("apply", "-e", "'notice(lookup(\"#{mod_key}\"))'"), :environment => {:LANG => "en_US.UTF-8"} ) assert_match( /#{mod_val}/, result.stdout, "module lookup failed for '#{mod_key}'" ) on( agent, puppet("config", "set hiera_config #{orig_hiera_config}"), :environment => {:LANG => "en_US.UTF-8"} ) on( agent, puppet("config", "set environmentpath #{orig_environmentpath}"), :environment => {:LANG => "en_US.UTF-8"} ) end step 'dig' do hash_string = "{ a => { b => [ { x => 10, y => 20, }, { x => 100, y => \"dig_result = #{utf8chars}\" }, ] } }" puppet_cmd = "' [$v] = [#{hash_string}]; [$dig_result] = [dig($v, a, b, 1, y)]; notice($dig_result) '" result = on( agent, puppet("apply", "-e", puppet_cmd), :environment => {:LANG => "en_US.UTF-8"} ) assert_match( /dig_result = #{utf8chars}/, result.stdout, "dig() test failed." ) end step 'match' do strings = [ "string1_#{utf8chars}", "string2_#{utf8chars}", "string3_no-utf8", "string4_no-utf8" ] puppet_cmd = "' [$vec] = [#{strings}]; [$found] = [match($vec, /#{utf8chars}/)]; notice($found) '" result = on( agent, puppet("apply", "-e", puppet_cmd), :environment => {:LANG => "en_US.UTF-8"} ) assert_match( /[[#{utf8chars}], [#{utf8chars}], , ]/, result.stdout, "match() result unexpected" ) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/utf8/utf8-in-catalog.rb
acceptance/tests/utf8/utf8-in-catalog.rb
test_name 'utf-8 characters in cached catalog' do tag 'audit:high', # utf-8 is high impact in general 'audit:integration', # not package dependent but may want to vary platform by LOCALE/encoding 'audit:refactor', # use mk_tmp_environment_with_teardown 'server' utf8chars = "\u20ac\u2030\u3118\u4e07\u7af9\u00dc\u00d6" file_content = "This is the file content. file #{utf8chars}" codedir = master.tmpdir("code") on(master, "rm -rf '#{codedir}'") env_dir = "#{codedir}/environments" agents.each do |agent| step "agent name: #{agent.hostname}, platform: #{agent.platform}" agent_vardir = agent.tmpdir("agent_vardir") agent_file = agent.tmpfile("file" + utf8chars) teardown do on(agent, "rm -rf '#{agent_vardir}' '#{agent_file}'") on(agent, puppet('config print lastrunfile')) do |command_result| agent.rm_rf(command_result.stdout) end end step "Apply manifest" do on(agent, "rm -rf '#{agent_file}'", :environment => { :LANG => "en_US.UTF-8" }) master_manifest = <<PP File { ensure => directory, mode => "0755", } file { '#{codedir}/':; '#{codedir}/environments':; '#{codedir}/environments/production':; '#{codedir}/environments/production/manifests':; } file { '#{env_dir}/production/manifests/site.pp' : ensure => file, mode => '0644', content => ' file { "#{agent_file}" : ensure => file, mode => "0644", content => "#{file_content} ", } ', } PP apply_manifest_on(master, master_manifest, {:acceptable_exit_codes => [0, 2], :catch_failures => true, :environment => { :LANG => "en_US.UTF-8" }}) end master_opts = { 'main' => { 'environmentpath' => "#{env_dir}", }, 'agent' => { 'use_cached_catalog' => 'true' } } with_puppet_running_on(master, master_opts, codedir) do step "apply utf-8 catalog" do on(agent, puppet("agent -t --vardir '#{agent_vardir}'"), { :acceptable_exit_codes => [2], :environment => { :LANG => "en_US.UTF-8" } }) end step "verify cached catalog" do catalog_file_name = "#{agent_vardir}/client_data/catalog/#{agent.node_name}.json" on(agent, "cat '#{catalog_file_name}'", :environment => { :LANG => "en_US.UTF-8" }) do |result| assert_match(/#{agent_file}/, result.stdout, "cached catalog does not contain expected agent file name") assert_match(/#{file_content}/, result.stdout, "cached catalog does not contain expected file content") end end step "apply cached catalog" do on(agent, puppet("resource file '#{agent_file}' ensure=absent"), :environment => { :LANG => "en_US.UTF-8" }) on(agent, puppet("catalog apply --vardir '#{agent_vardir}' --terminus json"), :environment => { :LANG => "en_US.UTF-8" }) on(agent, "cat '#{agent_file}'", :environment => { :LANG => "en_US.UTF-8" }) do |result| assert_match(/#{utf8chars}/, result.stdout, "result stdout did not contain \"#{utf8chars}\"") end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/utf8/utf8-in-file-resource.rb
acceptance/tests/utf8/utf8-in-file-resource.rb
test_name 'utf-8 characters in resource title and param values' do tag 'audit:high', # utf-8 is high impact in general 'audit:integration' # not package dependent but may want to vary platform by LOCALE/encoding confine :except, :platform => [ 'windows', # PUP-6983 'aix', # PUP-7194 ] # utf8chars = "€‰ㄘ万竹ÜÖ" utf8chars = "\u20ac\u2030\u3118\u4e07\u7af9\u00dc\u00d6" agents.each do |agent| puts "agent name: #{agent.node_name}, platform: #{agent.platform}" agent_file = agent.tmpfile("file" + utf8chars) teardown do on(agent, "rm -rf #{agent_file}") end # remove this file, so puppet can create it and not merely correct # its drift. on(agent, "rm -rf #{agent_file}", :environment => {:LANG => "en_US.UTF-8"}) manifest = <<PP file { "#{agent_file}" : ensure => file, mode => "0644", content => "This is the file content. file #{utf8chars} ", } PP step "Apply manifest" do apply_manifest_on( agent, manifest, { :acceptable_exit_codes => [2], :catch_failures => true, :environment => {:LANG => "en_US.UTF-8"} } ) on(agent, "cat #{agent_file}", :environment => {:LANG => "en_US.UTF-8"}) do |result| assert_match(/#{utf8chars}/, result.stdout, "result stdout did not contain \"#{utf8chars}\"") end end step "Drift correction" do on( agent, "echo '' > #{agent_file}", :environment => {:LANG => "en_US.UTF-8"} ) apply_manifest_on( agent, manifest, { :acceptable_exit_codes => [2], :catch_failures => true, :environment => {:LANG => "en_US.UTF-8"} } ) on(agent, "cat #{agent_file}", :environment => {:LANG => "en_US.UTF-8"}) do |result| assert_match(/#{utf8chars}/, result.stdout, "result stdout did not contain \"#{utf8chars}\"") end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/tests/utf8/utf8-recursive-copy.rb
acceptance/tests/utf8/utf8-recursive-copy.rb
test_name "PUP-8735: UTF-8 characters are preserved after recursively copying directories" do tag 'audit:high', # utf-8 is high impact in general 'audit:integration' # not package dependent but may want to vary platform by LOCALE/encoding # Translation is not supported on these platforms: confine :except, :platform => /^solaris/ # for file_exists? require 'puppet/acceptance/temp_file_utils' extend Puppet::Acceptance::TempFileUtils # for enable_locale_language require 'puppet/acceptance/i18n_utils' extend Puppet::Acceptance::I18nUtils agents.each do |host| filename = "Fișier" content = <<-CONTENT 閑けさや 岩にしみいる 蝉の声 CONTENT workdir = host.tmpdir("tmp#{rand(999999).to_i}") source_dir = "#{workdir}/Adresář" target_dir = "#{workdir}/目录" manifest = %Q| file { ["#{workdir}", "#{source_dir}"]: ensure => directory, } file { "#{source_dir}/#{filename}": ensure => file, content => "#{content}", } file { "#{source_dir}/#{filename}_Copy": ensure => file, source => "#{source_dir}/#{filename}", } file { "#{target_dir}": ensure => directory, source => "#{source_dir}", recurse => remote, replace => true, }| step "Ensure the en_US locale is enabled (and skip this test if not)" do if enable_locale_language(host, 'en_US').nil? skip_test("Host #{host} is missing the en_US locale. Skipping this test.") end end step "Create and recursively copy a directory with UTF-8 filenames and contents" do apply_manifest_on(host, manifest, environment: {'LANGUAGE' => 'en_US', 'LANG' => 'en_US'}) end step "Ensure that the files' names and their contents are preserved" do ["#{target_dir}/#{filename}", "#{target_dir}/#{filename}_Copy"]. each do |filepath| assert(file_exists?(host, filepath), "Expected the UTF-8 directory's files to be recursivly copied, but they were not") assert(file_contents(host, filepath) == content, "Expected the contents of the copied UTF-8 files to be preserved, but they were not") end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/teardown/common/099_Archive_Logs.rb
acceptance/teardown/common/099_Archive_Logs.rb
require 'date' def file_glob(host, path) result = on(host, "ls #{path}", :acceptable_exit_codes => [0, 2]) return [] if result.exit_code != 0 return result.stdout.strip.split("\n") end # This test is prefixed with zzz so it will hopefully run last. test_name 'Backup puppet logs and app data on all hosts' do today = Date.today().to_s # truncate the job name so it only has the name-y part and no parameters job_name = (ENV['JOB_NAME'] || 'unknown_jenkins_job') .sub(/[A-Z0-9_]+=.*$/, '') .gsub(/[\/,.]/, '_')[0..200] archive_name = "#{job_name}__#{ENV['BUILD_ID']}__#{today}__sut-files.tgz" archive_root = "SUT_#{today}" hosts.each do |host| step("Capturing log errors for #{host}") do case host[:platform] when /windows/ # on Windows, all of the desired data (including logs) is in the data dir puppetlabs_data = 'C:/ProgramData/PuppetLabs' archive_file_from(host, puppetlabs_data, {}, archive_root, archive_name) # Note: Windows `ls` uses absolute paths for all matches when an absolute path is supplied. tempdir = 'C:/Windows/TEMP' file_glob(host, File.join(tempdir, 'install-puppet-*.log')).each do |install_log| archive_file_from(host, install_log, {}, archive_root, archive_name) end file_glob(host, File.join(tempdir, 'puppet-*-installer.log')).each do |install_log| archive_file_from(host, install_log, {}, archive_root, archive_name) end else puppetlabs_logdir = '/var/log/puppetlabs' grep_for_alerts = if host[:platform] =~ /solaris/ "egrep -i 'warn|error|fatal'" elsif host[:platform] =~ /aix/ "grep -iE -B5 -A10 'warn|error|fatal'" else "grep -i -B5 -A10 'warn\\|error\\|fatal'" end ## If there are any PL logs, try to echo all warning, error, and fatal ## messages from all PL logs to the job's output on(host, <<-GREP_FOR_ALERTS, :accept_all_exit_codes => true ) if [ -d #{puppetlabs_logdir} ] && [ -n "$(find #{puppetlabs_logdir} -name '*.log*')" ]; then for log in $(find #{puppetlabs_logdir} -name '*.log*'); do # grep /dev/null only to get grep to print filenames, since -H is not in POSIX spec for grep #{grep_for_alerts} $log /dev/null; echo "" done fi GREP_FOR_ALERTS step("Archiving logs for #{host} into #{archive_name} (muzzling everything but :warn or higher beaker logs...)") do ## turn the logger off to avoid getting hundreds of lines of scp progress output previous_level = @logger.log_level @logger.log_level = :warn pxp_cache = '/opt/puppetlabs/pxp-agent/spool' puppetlabs_data = '/etc/puppetlabs' version_lookup_result = on(host, "cat /opt/puppetlabs/puppet/VERSION", :accept_all_exit_codes => true) # If we can't find a VERSION file, chances are puppet wasn't # installed and these paths aren't present. Beaker's # archive_file_from() will fail if it can't find the file, and we # want to proceed... if version_lookup_result.exit_code == 0 agent_version = version_lookup_result.output.strip archive_file_from(host, pxp_cache, {}, archive_root, archive_name) unless version_is_less(agent_version, "1.3.2") archive_file_from(host, puppetlabs_data, {}, archive_root, archive_name) archive_file_from(host, puppetlabs_logdir, {}, archive_root, archive_name) end syslog_dir = '/var/log' syslog_name = 'messages' if host[:platform] =~ /ubuntu|debian/ syslog_name = 'syslog' elsif host[:platform] =~ /solaris/ syslog_dir = '/var/adm' # Next few lines are for debugging POOLER-200, once that is resolved this can be removed @logger.log_level = previous_level on(host, 'egrep -i \'reboot after panic\' /var/adm/messages', :acceptable_exit_codes => [0,1,2]) @logger.log_level = :warn elsif host[:platform] =~ /osx/ syslog_name = "system.log" elsif host[:platform] =~ /fedora/ on(host, "journalctl --no-pager > /var/log/messages") elsif host[:platform] =~ /aix/ on(host, "alog -o -t console > /var/log/messages") end syslog_path = File.join(syslog_dir, syslog_name) if host.file_exist?(syslog_path) archive_file_from(host, syslog_path, {}, archive_root, archive_name) end ## turn the logger back on in case someone else wants to log things @logger.log_level = previous_level end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/pre-suite/015_prep_locales.rb
acceptance/pre-suite/015_prep_locales.rb
test_name 'Ensure locales are present' do agents.each do |agent| package = case agent.platform when /^el/ then 'glibc-all-langpacks' when /debian/ then 'locales-all' else nil end on(agent, puppet_resource('package', package, 'ensure=present')) if !package.nil? end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/pre-suite/040_ValidateSignCert.rb
acceptance/pre-suite/040_ValidateSignCert.rb
test_name 'Validate Sign Cert' do need_to_run = false hosts.each do |host| need_to_run ||= !host['use_existing_container'] end skip_test 'No new hosts to create, skipping' unless need_to_run skip_test 'not testing with puppetserver' unless @options['is_puppetserver'] hostname = on(master, 'facter hostname').stdout.strip fqdn = on(master, 'facter fqdn').stdout.strip step 'Ensure puppet is stopped' on(master, puppet('resource', 'service', master['puppetservice'], 'ensure=stopped')) step 'Clear SSL on all hosts' hosts.each do |host| ssldir = on(host, puppet('agent --configprint ssldir')).stdout.chomp # preserve permissions for master's ssldir so puppetserver can read it on(host, "rm -rf '#{ssldir}/'*") end step "Set 'server' setting" hosts.each do |host| on(host, puppet("config set server #{fqdn} --section main")) end step 'Start puppetserver' do master_opts = { main: { dns_alt_names: "puppet,#{hostname},#{fqdn}", server: fqdn, autosign: true, }, } on(master, 'puppetserver ca setup') with_puppet_running_on(master, master_opts) do step 'Agents: Run agent --test with autosigning enabled to get cert' on(agents, puppet('agent --test'), acceptable_exit_codes: [0, 2]) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/pre-suite/000_configure_type_defaults.rb
acceptance/pre-suite/000_configure_type_defaults.rb
# Ensures that the /root/.ssh/environment file is # set up with a path that includes /opt/puppetlabs/bin. # Normally this would be called as part of beaker-puppet # install steps, but we are installing openvox packages outside # of beaker-puppet, since it doesn't handle openvox. test_name('configure root ssh environment path') do configure_type_defaults_on(agents) end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/pre-suite/012_disable_dropsonde.rb
acceptance/pre-suite/012_disable_dropsonde.rb
# Ensure openvox-server telemetry is off, for one because we wouldn't # want false results from test runs, and more specifically because of # reload delays: # https://github.com/OpenVoxProject/openvox-server/issues/24 test_name 'Disable Dropsonde' do skip_test 'not testing with puppetserver' unless @options['is_puppetserver'] puppetserver_opts = { dropsonde: { enabled: false, }, } puppetserver_conf = File.join("#{master['puppetserver-confdir']}", 'puppetserver.conf') modify_tk_config(master, puppetserver_conf, puppetserver_opts) end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/pre-suite/045_EnsureMasterStarted.rb
acceptance/pre-suite/045_EnsureMasterStarted.rb
test_name 'Ensure the master is running' skip_test 'not testing with puppetserver' unless @options['is_puppetserver'] on(master, puppet('resource', 'service', master['puppetservice'], 'ensure=running', 'enable=true'))
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/pre-suite/010_set_puppetserver_memory_defaults.rb
acceptance/pre-suite/010_set_puppetserver_memory_defaults.rb
# Tune puppetserver java to half the system memory. test_name 'Set Puppetserver Memory Defaults' do skip_test 'No primary node to configure Puppetserver memory defaults for' unless master mem_in_bytes = on(master, 'facter memory.system.total_bytes').stdout.strip megabytes = 1024 * 1024 half_mem = (mem_in_bytes.to_i / megabytes / 2) defaults_dir = case master.platform when /debian|ubuntu/ then '/etc/default' else '/etc/sysconfig' end if half_mem > 2048 on(master, "sed -i -E -e '/^JAVA_ARGS=/ s/-Xms[0-9]+[m|g] -Xmx[0-9]+[m|g]/-Xms#{half_mem}m -Xmx#{half_mem}m/' #{defaults_dir}/puppetserver") on(master, "cat #{defaults_dir}/puppetserver") else logger.info("System memory on the primary is less than 4GB (#{(mem_in_bytes.to_i / megabytes)}m). Leaving the defult 2GB for Puppetserver memory.") end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/lib/helper.rb
acceptance/lib/helper.rb
$LOAD_PATH << File.expand_path(File.dirname(__FILE__)) require 'beaker-puppet' require 'mkmf' module Beaker module DSL module Helpers module PuppetAcceptance # A sad little abstraction around service/systemctl to handle # os differences for edge cases not suited to puppet resource # service calls. def service(host, action, service_name, acceptable_exit_codes: [0]) if find_executable('systemctl') command = Command.new("systemctl #{action} #{service_name}") elsif find_executable('service') command = Command.new("service #{service_name} #{action}") else raise "Neither systemctl nor service found on #{host.name}" end host.exec(command, acceptable_exit_codes: acceptable_exit_codes) end # Override beaker-puppet BeakerPuppet::Helpers::PuppetHelpers#bounce_service # to allow for systems that only have systemctl now (el9+, etc.) # # Ostensibly we should fork beaker-puppet...I'm just not quite ready # to touch that yet... # # Restarts the named puppet service # # @param [Host] host Host the service runs on # @param [String] service Name of the service to restart # @param [Fixnum] curl_retries Number of seconds to wait for the restart to complete before failing # @param [Fixnum] port Port to check status at # # @return [Result] Result of last status check # @!visibility private def bounce_service(host, service, curl_retries = nil, port = nil) curl_retries = 120 if curl_retries.nil? port = options[:puppetserver_port] if port.nil? result = service(host, :reload, service, acceptable_exit_codes: [0, 1, 3]) return result if result.exit_code == 0 host.exec puppet_resource('service', service, 'ensure=stopped') host.exec puppet_resource('service', service, 'ensure=running') curl_with_retries(" #{service} ", host, "https://localhost:#{port}", [35, 60], curl_retries) end end end end end # Register the DSL extension Beaker::DSL.register(Beaker::DSL::Helpers::PuppetAcceptance)
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/lib/acceptance_spec_helper.rb
acceptance/lib/acceptance_spec_helper.rb
require 'fileutils' dir = File.expand_path(File.dirname(__FILE__)) $LOAD_PATH.unshift dir RSpec.configure do |config| config.mock_with :mocha end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/lib/puppet/acceptance/environment_utils_spec.rb
acceptance/lib/puppet/acceptance/environment_utils_spec.rb
require File.join(File.dirname(__FILE__),'../../acceptance_spec_helper.rb') require 'puppet/acceptance/environment_utils' module EnvironmentUtilsSpec describe 'EnvironmentUtils' do class ATestCase include Puppet::Acceptance::EnvironmentUtils def step(str) yield end def on(host, command, options = nil) stdout = host.do(command, options) yield TestResult.new(stdout) if block_given? end end class TestResult attr_accessor :stdout def initialize(stdout) self.stdout = stdout end end class TestHost attr_accessor :did, :directories, :attributes def initialize(directories, attributes = {}) self.directories = directories self.did = [] self.attributes = attributes end def do(command, options) did << (options.nil? ? command : [command, options]) case command when /^ls (.*)/ then directories[$1] end end def [](param) attributes[param] end end let(:testcase) { ATestCase.new } let(:host) { TestHost.new(directory_contents, 'user' => 'root', 'group' => 'puppet') } let(:directory_contents) do { '/etc/puppetlabs/puppet' => 'foo bar baz widget', '/tmp/dir' => 'foo dingo bar thing', } end it "runs the block of code" do ran_code = false testcase.safely_shadow_directory_contents_and_yield(host, '/etc/puppetlabs/puppet', '/tmp/dir') do ran_code = true end expect(ran_code).to be true expect(host.did).to eq([ "ls /etc/puppetlabs/puppet", "ls /tmp/dir", "mv /etc/puppetlabs/puppet/foo /etc/puppetlabs/puppet/foo.bak", "mv /etc/puppetlabs/puppet/bar /etc/puppetlabs/puppet/bar.bak", "cp -R /tmp/dir/foo /etc/puppetlabs/puppet/foo", "cp -R /tmp/dir/dingo /etc/puppetlabs/puppet/dingo", "cp -R /tmp/dir/bar /etc/puppetlabs/puppet/bar", "cp -R /tmp/dir/thing /etc/puppetlabs/puppet/thing", "chown -R root:puppet /etc/puppetlabs/puppet/foo /etc/puppetlabs/puppet/dingo /etc/puppetlabs/puppet/bar /etc/puppetlabs/puppet/thing", "chmod -R 770 /etc/puppetlabs/puppet/foo /etc/puppetlabs/puppet/dingo /etc/puppetlabs/puppet/bar /etc/puppetlabs/puppet/thing", "rm -rf /etc/puppetlabs/puppet/foo /etc/puppetlabs/puppet/dingo /etc/puppetlabs/puppet/bar /etc/puppetlabs/puppet/thing", "mv /etc/puppetlabs/puppet/foo.bak /etc/puppetlabs/puppet/foo", "mv /etc/puppetlabs/puppet/bar.bak /etc/puppetlabs/puppet/bar" ]) end it "backs up the original items that are shadowed by tmp items" do testcase.safely_shadow_directory_contents_and_yield(host, '/etc/puppetlabs/puppet', '/tmp/dir') {} expect(host.did.grep(%r{mv /etc/puppetlabs/puppet/\w+ })).to eq([ "mv /etc/puppetlabs/puppet/foo /etc/puppetlabs/puppet/foo.bak", "mv /etc/puppetlabs/puppet/bar /etc/puppetlabs/puppet/bar.bak", ]) end it "copies in all the tmp items into the working dir" do testcase.safely_shadow_directory_contents_and_yield(host, '/etc/puppetlabs/puppet', '/tmp/dir') {} expect(host.did.grep(%r{cp})).to eq([ "cp -R /tmp/dir/foo /etc/puppetlabs/puppet/foo", "cp -R /tmp/dir/dingo /etc/puppetlabs/puppet/dingo", "cp -R /tmp/dir/bar /etc/puppetlabs/puppet/bar", "cp -R /tmp/dir/thing /etc/puppetlabs/puppet/thing", ]) end it "opens the permissions on all copied files to 770 and sets ownership based on host settings" do testcase.safely_shadow_directory_contents_and_yield(host, '/etc/puppetlabs/puppet', '/tmp/dir') {} expect(host.did.grep(%r{ch(mod|own)})).to eq([ "chown -R root:puppet /etc/puppetlabs/puppet/foo /etc/puppetlabs/puppet/dingo /etc/puppetlabs/puppet/bar /etc/puppetlabs/puppet/thing", "chmod -R 770 /etc/puppetlabs/puppet/foo /etc/puppetlabs/puppet/dingo /etc/puppetlabs/puppet/bar /etc/puppetlabs/puppet/thing", ]) end it "deletes all the tmp items from the working dir" do testcase.safely_shadow_directory_contents_and_yield(host, '/etc/puppetlabs/puppet', '/tmp/dir') {} expect(host.did.grep(%r{rm})).to eq([ "rm -rf /etc/puppetlabs/puppet/foo /etc/puppetlabs/puppet/dingo /etc/puppetlabs/puppet/bar /etc/puppetlabs/puppet/thing", ]) end it "replaces the original items that had been shadowed into the working dir" do testcase.safely_shadow_directory_contents_and_yield(host, '/etc/puppetlabs/puppet', '/tmp/dir') {} expect(host.did.grep(%r{mv /etc/puppetlabs/puppet/\w+\.bak})).to eq([ "mv /etc/puppetlabs/puppet/foo.bak /etc/puppetlabs/puppet/foo", "mv /etc/puppetlabs/puppet/bar.bak /etc/puppetlabs/puppet/bar" ]) end it "always cleans up, even if the code we yield to raises an error" do expect do testcase.safely_shadow_directory_contents_and_yield(host, '/etc/puppetlabs/puppet', '/tmp/dir') do raise 'oops' end end.to raise_error('oops') expect(host.did).to eq([ "ls /etc/puppetlabs/puppet", "ls /tmp/dir", "mv /etc/puppetlabs/puppet/foo /etc/puppetlabs/puppet/foo.bak", "mv /etc/puppetlabs/puppet/bar /etc/puppetlabs/puppet/bar.bak", "cp -R /tmp/dir/foo /etc/puppetlabs/puppet/foo", "cp -R /tmp/dir/dingo /etc/puppetlabs/puppet/dingo", "cp -R /tmp/dir/bar /etc/puppetlabs/puppet/bar", "cp -R /tmp/dir/thing /etc/puppetlabs/puppet/thing", "chown -R root:puppet /etc/puppetlabs/puppet/foo /etc/puppetlabs/puppet/dingo /etc/puppetlabs/puppet/bar /etc/puppetlabs/puppet/thing", "chmod -R 770 /etc/puppetlabs/puppet/foo /etc/puppetlabs/puppet/dingo /etc/puppetlabs/puppet/bar /etc/puppetlabs/puppet/thing", "rm -rf /etc/puppetlabs/puppet/foo /etc/puppetlabs/puppet/dingo /etc/puppetlabs/puppet/bar /etc/puppetlabs/puppet/thing", "mv /etc/puppetlabs/puppet/foo.bak /etc/puppetlabs/puppet/foo", "mv /etc/puppetlabs/puppet/bar.bak /etc/puppetlabs/puppet/bar" ]) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/lib/puppet/acceptance/static_catalog_utils.rb
acceptance/lib/puppet/acceptance/static_catalog_utils.rb
module Puppet module Acceptance module StaticCatalogUtils # Adds code-id-command and code-content-command scripts # to the server and updates puppetserver.conf. This is # necessary for testing static catalogs. # @param master [String] the host running puppetserver. # @param scriptdir [String] the path to the directory where the scripts should be placed. def setup_puppetserver_code_id_scripts(master, scriptdir) code_id_command = <<EOF #! /bin/bash echo -n 'code_version_1' EOF code_content_command = <<EOF #! /bin/bash if [ \\\$2 == 'code_version_1' ] ; then echo -n 'code_version_1' else echo -n 'newer_code_version' fi EOF apply_manifest_on(master, <<MANIFEST, :catch_failures => true) file { '#{scriptdir}/code_id.sh': ensure => file, content => "#{code_id_command}", mode => "0755", } file { '#{scriptdir}/code_content.sh': ensure => file, content => "#{code_content_command}", mode => "0755", } MANIFEST puppetserver_config = "#{master['puppetserver-confdir']}/puppetserver.conf" on master, "cp #{puppetserver_config} #{scriptdir}/puppetserver.conf.bak" versioned_code_settings = {"versioned-code" => {"code-id-command" => "#{scriptdir}/code_id.sh", "code-content-command" => "#{scriptdir}/code_content.sh"}} modify_tk_config(master, puppetserver_config, versioned_code_settings) end def cleanup_puppetserver_code_id_scripts(master, scriptdir) # These are -f so we don't bail on the teardown if for some reason they didn't get laid down on master, "rm -f #{scriptdir}/code_id.sh" on master, "rm -f #{scriptdir}/code_content.sh" puppetserver_config = "#{master['puppetserver-confdir']}/puppetserver.conf" on master, "cp #{scriptdir}/puppetserver.conf.bak #{puppetserver_config}" end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/lib/puppet/acceptance/agent_fqdn_utils.rb
acceptance/lib/puppet/acceptance/agent_fqdn_utils.rb
module Puppet module Acceptance module AgentFqdnUtils @@hostname_to_fqdn = {} # convert from an Beaker::Host (agent) to the systems fqdn as returned by facter def agent_to_fqdn(agent) unless @@hostname_to_fqdn.has_key?(agent.hostname) @@hostname_to_fqdn[agent.hostname] = on(agent, facter('networking.fqdn')).stdout.chomp end @@hostname_to_fqdn[agent.hostname] end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/lib/puppet/acceptance/i18ndemo_utils.rb
acceptance/lib/puppet/acceptance/i18ndemo_utils.rb
module Puppet module Acceptance module I18nDemoUtils require 'puppet/acceptance/i18n_utils' extend Puppet::Acceptance::I18nUtils I18NDEMO_NAME = "i18ndemo" I18NDEMO_MODULE_NAME = "eputnam-#{I18NDEMO_NAME}" def configure_master_system_locale(requested_language) language = enable_locale_language(master, requested_language) fail_test("puppet server machine is missing #{requested_language} locale. help...") if language.nil? on(master, "localectl set-locale LANG=#{language}") on(master, puppet_resource('service', master['puppetservice'], 'ensure=stopped')) on(master, puppet_resource('service', master['puppetservice'], 'ensure=running')) end def reset_master_system_locale language = enable_locale_language(master, 'en_US') on(master, "localectl set-locale LANG=#{language}") on(master, puppet_resource('service', master['puppetservice'], 'ensure=stopped')) on(master, puppet_resource('service', master['puppetservice'], 'ensure=running')) end def install_i18n_demo_module(node, environment=nil) env_options = environment.nil? ? '' : "--environment #{environment}" on(node, puppet("module install #{I18NDEMO_MODULE_NAME} #{env_options}")) end def uninstall_i18n_demo_module(node, environment=nil) env_options = environment.nil? ? '' : "--environment #{environment}" [I18NDEMO_MODULE_NAME, 'puppetlabs-stdlib', 'puppetlabs-translate'].each do |module_name| on(node, puppet("module uninstall #{module_name} #{env_options}"), :acceptable_exit_codes => [0,1]) end var_dir = on(node, puppet('config print vardir')).stdout.chomp on(node, "rm -rf '#{File.join(var_dir, 'locales', 'ja')}' '#{File.join(var_dir, 'locales', 'fi')}'") end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/lib/puppet/acceptance/common_utils.rb
acceptance/lib/puppet/acceptance/common_utils.rb
module Puppet module Acceptance module BeakerUtils # TODO: This should be added to Beaker def assert_matching_arrays(expected, actual, message = "") assert_equal(expected.sort, actual.sort, message) end end module PackageUtils def package_present(host, package, version = nil) host.install_package(package, '', version) end def package_absent(host, package, cmdline_args = '', opts = {}) host.uninstall_package(package, cmdline_args, opts) end end module CommandUtils def ruby_command(host) "env PATH=\"#{host['privatebindir']}:${PATH}\" ruby" end module_function :ruby_command def gem_command(host, type='aio') if type == 'aio' if host['platform'] =~ /windows/ "env PATH=\"#{host['privatebindir']}:${PATH}\" cmd /c gem" else "env PATH=\"#{host['privatebindir']}:${PATH}\" gem" end else on(host, 'which gem').stdout.chomp end end module_function :gem_command end module ManifestUtils def resource_manifest(resource, title, params = {}) params_str = params.map do |param, value| # This is not quite correct for all parameter values, # but it is good enough for most purposes. value_str = value.to_s value_str = "\"#{value_str}\"" if value.is_a?(String) " #{param} => #{value_str}" end.join(",\n") <<-MANIFEST #{resource} { '#{title}': #{params_str} } MANIFEST end def file_manifest(path, params = {}) resource_manifest('file', path, params) end def user_manifest(username, params = {}) resource_manifest('user', username, params) end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/lib/puppet/acceptance/windows_utils.rb
acceptance/lib/puppet/acceptance/windows_utils.rb
require 'puppet/acceptance/common_utils' module Puppet module Acceptance module WindowsUtils require 'puppet/acceptance/windows_utils/service.rb' require 'puppet/acceptance/windows_utils/package_installer.rb' def profile_base(agent) ruby = Puppet::Acceptance::CommandUtils.ruby_command(agent) getbasedir = <<'END' puts ENV['USERPROFILE'].match(/(.*)\\\\[^\\\\]*/)[1] END on(agent, "#{ruby} -e \"#{getbasedir}\"").stdout.chomp end # Checks whether the account with the given username has the given password on a host def assert_password_matches_on(host, username, password, msg = nil) script = <<-PS1 Add-Type -AssemblyName System.DirectoryServices.AccountManagement $ctx = New-Object System.DirectoryServices.AccountManagement.PrincipalContext([System.DirectoryServices.AccountManagement.ContextType]::Machine, $env:COMPUTERNAME) $ctx.ValidateCredentials("#{username}", "#{password}") PS1 result = execute_powershell_script_on(host, script) assert_match(/True/, result.stdout.strip, msg) end def deny_administrator_access_to(host, filepath) # we need to create a fake directory in the user's tempdir with powershell because the ACL # perms set down by cygwin when making tempdirs makes the ACL unusable. Thus we create a # tempdir using powershell and pull its' ACL as a starting point for the new ACL. script = <<-PS1 mkdir -Force $env:TMP\\fake-dir-for-acl $acl = Get-ACL $env:TMP\\fake-dir-for-acl rm -Force $env:TMP\\fake-dir-for-acl $ar = New-Object system.security.accesscontrol.filesystemaccessrule("Administrator","FullControl","Deny") $acl.SetAccessRule($ar) Set-ACL #{filepath} $acl PS1 execute_powershell_script_on(host, script) end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/lib/puppet/acceptance/classifier_utils.rb
acceptance/lib/puppet/acceptance/classifier_utils.rb
require 'httparty' require 'tempfile' require 'stringio' require 'uuidtools' require 'json' require 'pp' module Puppet module Acceptance module ClassifierUtils DEFAULT_GROUP_ID = "00000000-0000-4000-8000-000000000000" SSL_PORT = 4433 PREFIX = "/classifier-api" # Keep track of our local tmpdirs for cleanup def self.tmpdirs @classifier_utils_tmpdirs ||= [] end # PE creates a "Production environment" group during installation which # all nodes are a member of by default. This method just looks up this # group and returns its uuid so that other methods may reference it. def get_production_environment_group_uuid step "Get classifier groups so we can locate the 'Production environment' group" response = classifier_handle.get("/v1/groups") assert_equal(200, response.code, "Unable to get classifer groups: #{response.body}") groups_json = response.body groups = JSON.parse(groups_json) if production_environment = groups.find { |g| g['name'] == 'Production environment' } production_environment['id'] else nil end end # Create a Classifier Group which by default will apply to all of the passed # nodes. The Group will merge in the passed group_hash which will be converted # into the json body for a Classifier PUT /v1/groups/:id request. # # A teardown body is registered to delete the created group at the end of the test. # # @returns String the created uuid for the group. def create_group_for_nodes(nodes, group_hash) group_uuid = UUIDTools::UUID.random_create() response = nil teardown do step "Deleting group #{group_uuid}" do response = classifier_handle.delete("/v1/groups/#{group_uuid}") assert_equal(204, response.code, "Failed to delete group #{group_uuid}, #{response.code}:#{response.body}") end if response && response.code == 201 end teardown do step "Cleaning up classifier certs on test host" do cleanup_local_classifier_certs end end hostnames = nodes.map { |n| n.hostname } step "Add group #{group_uuid} for #{hostnames.join(", ")}" rule = hostnames.inject(["or"]) do |r,name| r << ["~", "name", name] r end # In order to override the environment for test nodes, we need the # groups we create to be a child of this "Production environment" group, # otherwise we get a classification error from the conflicting groups. parent = get_production_environment_group_uuid || Puppet::Acceptance::ClassifierUtils::DEFAULT_GROUP_ID body = { "description" => "A classification group for the following acceptance test nodes: (#{hostnames.join(", ")})", "parent" => parent, "rule" => rule, "classes" => {} }.merge group_hash response = classifier_handle.put("/v1/groups/#{group_uuid}", :body => body.to_json) assert_equal(201, response.code, "Unexpected response code: #{response.code}, #{response.body}") return group_uuid end # Creates a group which allows the given nodes to specify their own environments. # Will be torn down at the end of the test. def classify_nodes_as_agent_specified(nodes) create_group_for_nodes(nodes, { "name" => "Agent Specified Test Nodes", "environment" => "agent-specified", "environment_trumps" => true, "description" => "The following acceptance suite nodes (#{nodes.map { |n| n.hostname }.join(", ")}) expect to be able to specify their environment for tesing purposes.", }) end def classify_nodes_as_agent_specified_if_classifer_present classifier_node = false begin classifier_node = find_only_one(:classifier) rescue Beaker::DSL::Outcomes::FailTest end if classifier_node || master.is_pe? classify_nodes_as_agent_specified(agents) end end def classifier_host find_only_one(:classifier) rescue Beaker::DSL::Outcomes::FailTest # fallback to master since currently the sqautils genconfig does not recognize # a classifier role. master end def master_cert @master_cert ||= on(master, "cat `puppet config print hostcert`", :silent => true).stdout end def master_key @master_key ||= on(master, "cat `puppet config print hostprivkey`", :silent => true).stdout end def master_ca_cert_file unless @ca_cert_file ca_cert = on(master, "cat `puppet config print localcacert`", :silent => true).stdout cert_dir = Dir.mktmpdir("pe_classifier_certs") Puppet::Acceptance::ClassifierUtils.tmpdirs << cert_dir @ca_cert_file = File.join(cert_dir, "cacert.pem") # RFC 1421 states PEM is 7-bit ASCII https://tools.ietf.org/html/rfc1421 File.open(@ca_cert_file, "w:ASCII") do |f| f.write(ca_cert) end end @ca_cert_file end def cleanup_local_classifier_certs Puppet::Acceptance::ClassifierUtils.tmpdirs.each do |d| FileUtils.rm_rf(d) end end def clear_classifier_utils_cache @master_cert = nil @master_key = nil @ca_cert_file = nil @classifier_handle = nil end def classifier_handle(options = {}) unless @classifier_handle server = options[:server] || classifier_host.reachable_name port = options[:port] || SSL_PORT prefix = options[:prefix] || PREFIX cert = options[:cert] || master_cert key = options[:key] || master_key ca_cert_file = options[:ca_cert_file] || master_ca_cert_file logger = options[:logger] || self.logger # HTTParty performs a lot of configuration at the class level. # This is inconvenient for our needs because we don't have the # server/cert info available at the time the class is loaded. I'm # sidestepping this by generating an anonymous class on the fly when # the test code actually requests a handle to the classifier. @classifier_handle = Class.new do include HTTParty extend Classifier @debugout = StringIO.new @logger = logger base_uri("https://#{server}:#{port}#{prefix}") debug_output(@debugout) headers({'Content-Type' => 'application/json'}) pem(cert + key) ssl_ca_file(ca_cert_file) end end @classifier_handle end # Handle logging module Classifier [:head, :get, :post, :put, :delete].each do |method| define_method(method) do |*args, &block| log_output do super(*args, &block) end end end private # Ensure that the captured debugging output is logged to Beaker. def log_output yield ensure @debugout.rewind @debugout.each_line { |l| @logger.info(l) } @debugout.truncate(0) end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/lib/puppet/acceptance/environment_utils.rb
acceptance/lib/puppet/acceptance/environment_utils.rb
require 'puppet/acceptance/module_utils' module Puppet module Acceptance module EnvironmentUtils include Puppet::Acceptance::ModuleUtils # Generate puppet manifest for the creation of an environment with # the given modulepath and manifest and env_name. The created environment # will have on testing_mod module, and manifest site.pp which includes it. # # @param options [Hash<Sym,String>] # @option options [String] :modulepath Modules directory # @option options [String] :manifest Manifest directory # @option options [String] :env_name Environment name # @return [String] Puppet manifest to create the environment files def generate_environment(options) modulepath = options[:modulepath] manifestpath = options[:manifestpath] env_name = options[:env_name] <<-MANIFEST_SNIPPET file { ################################################### # #{env_name} #{generate_module("testing_mod", env_name, modulepath)} "#{manifestpath}":; "#{manifestpath}/site.pp": ensure => file, mode => "0640", content => ' notify { "in #{env_name} site.pp": } include testing_mod ' ; } MANIFEST_SNIPPET end # Generate one module's manifest code. def generate_module(module_name, env_name, modulepath) <<-MANIFEST_SNIPPET "#{modulepath}":; "#{modulepath}/#{module_name}":; "#{modulepath}/#{module_name}/manifests":; "#{modulepath}/#{module_name}/manifests/init.pp": ensure => file, mode => "0640", content => 'class #{module_name} { notify { "include #{env_name} #{module_name}": } }' ; MANIFEST_SNIPPET end # Default, legacy, dynamic and directory environments # using generate_manifest(), all rooted in testdir. # # @param [String] testdir path to the temp directory which will be the confdir all # the environments live in # @return [String] Puppet manifest to generate all of the environment files. def environment_manifest(testdir) <<-MANIFEST File { ensure => directory, owner => #{master.puppet['user']}, group => #{master.puppet['group']}, mode => "0750", } file { "#{testdir}": } #{generate_environment( :modulepath => "#{testdir}/modules", :manifestpath => "#{testdir}/manifests", :env_name => "default environment")} #{generate_environment( :modulepath => "#{testdir}/testing-modules", :manifestpath => "#{testdir}/testing-manifests", :env_name => "legacy testing environment")} file { "#{testdir}/dynamic":; "#{testdir}/dynamic/testing":; } #{generate_environment( :modulepath => "#{testdir}/dynamic/testing/modules", :manifestpath => "#{testdir}/dynamic/testing/manifests", :env_name => "dynamic testing environment")} file { "#{testdir}/environments":; "#{testdir}/environments/testing":; } #{generate_environment( :modulepath => "#{testdir}/environments/testing/modules", :manifestpath => "#{testdir}/environments/testing/manifests", :env_name => "directory testing environment")} file { "#{testdir}/environments/testing_environment_conf":; } #{generate_environment( :modulepath => "#{testdir}/environments/testing_environment_conf/nonstandard-modules", :manifestpath => "#{testdir}/environments/testing_environment_conf/nonstandard-manifests", :env_name => "directory testing with environment.conf")} file { "#{testdir}/environments/testing_environment_conf/environment.conf": ensure => file, mode => "0640", content => ' modulepath = nonstandard-modules:$basemodulepath manifest = nonstandard-manifests config_version = local-version.sh ' } file { "#{testdir}/environments/testing_environment_conf/local-version.sh": ensure => file, mode => "0640", content => '#! /usr/bin/env bash echo "local testing_environment_conf"' ; } ################### # Services file { "#{testdir}/services":; "#{testdir}/services/testing":; #{generate_module('service_mod', "service testing environment", "#{testdir}/services/testing/modules")} } ####################### # Config version script file { "#{testdir}/static-version.sh": ensure => file, mode => "0640", content => '#! /usr/bin/env bash echo "static"' ; } MANIFEST end def get_directory_hash_from(host, path) dir_hash = {} on(host, "ls #{path}") do |result| result.stdout.split.inject(dir_hash) do |hash,f| hash[f] = "#{path}/#{f}" hash end end dir_hash end def safely_shadow_directory_contents_and_yield(host, original_path, new_path, &block) original_files = get_directory_hash_from(host, original_path) new_files = get_directory_hash_from(host, new_path) conflicts = original_files.keys & new_files.keys step "backup original files" do conflicts.each do |c| on(host, "mv #{original_files[c]} #{original_files[c]}.bak") end end step "shadow original files with temporary files" do new_files.each do |name,full_path_name| on(host, "cp -R #{full_path_name} #{original_path}/#{name}") end end new_file_list = new_files.keys.map { |name| "#{original_path}/#{name}" }.join(' ') step "open permissions to 755 on all temporary files copied into working dir and set ownership" do on(host, "chown -R #{host.puppet['user']}:#{host.puppet['group']} #{new_file_list}") on(host, "chmod -R 755 #{new_file_list}") end if host.check_for_command("selinuxenabled") result = on(host, "selinuxenabled", :acceptable_exit_codes => [0,1]) if result.exit_code == 0 step "mirror selinux contexts" do context = on(host, "matchpathcon #{original_path}").stdout.chomp.split(' ')[1] on(host, "chcon -R #{context} #{new_file_list}") end end end yield ensure step "clear out the temporary files" do files_to_delete = new_files.keys.map { |name| "#{original_path}/#{name}" } on(host, "rm -rf #{files_to_delete.join(' ')}") end step "move the shadowed files back to their original places" do conflicts.each do |c| on(host, "mv #{original_files[c]}.bak #{original_files[c]}") end end end # Stand up a puppet master on the master node with the given master_opts # using the passed envdir as the source of the puppet environment files, # and passed confdir as the directory to use for the temporary # puppet.conf. It then runs through a series of environment tests for the # passed environment and returns a hashed structure of the results. # # @return [Hash<Beaker::Host,Hash<Sym,Beaker::Result>>] Hash of # Beaker::Hosts for each agent run keyed to a hash of Beaker::Result # objects keyed by each subtest that was performed. def use_an_environment(environment, description, master_opts, envdir, confdir, options = {}) master_puppet_conf = master_opts.dup # shallow clone results = {} safely_shadow_directory_contents_and_yield(master, puppet_config(master, 'codedir', section: 'master'), envdir) do config_print = options[:config_print] directory_environments = options[:directory_environments] with_puppet_running_on(master, master_puppet_conf, confdir) do agents.each do |agent| agent_results = results[agent] = {} step "puppet agent using #{description} environment" args = "-t", "--server", master args << ["--environment", environment] if environment # Test agents configured to use directory environments (affects environment # loading on the agent, especially with regards to requests/node environment) args << "--environmentpath='$confdir/environments'" if directory_environments && agent != master on(agent, puppet("agent", *args), :acceptable_exit_codes => (0..255)) do |result| agent_results[:puppet_agent] = result end args = ["--trace"] args << ["--environment", environment] if environment step "print puppet config for #{description} environment" on(master, puppet(*(["config", "print", "basemodulepath", "modulepath", "manifest", "config_version", config_print] + args)), :acceptable_exit_codes => (0..255)) do |result| agent_results[:puppet_config] = result end step "puppet apply using #{description} environment" on(master, puppet(*(["apply", '-e', '"include testing_mod"'] + args)), :acceptable_exit_codes => (0..255)) do |result| agent_results[:puppet_apply] = result end end end end return results end # For each Beaker::Host in the results Hash, generates a chart, comparing # the expected exit code and regexp matches from expectations to the # Beaker::Result.output for a particular command that was executed in the # environment. Outputs either 'ok' or text highlighting the errors, and # returns false if any errors were found. # # @param [Hash<Beaker::Host,Hash<Sym,Beaker::Result>>] results # @param [Hash<Sym,Hash{Sym => Integer,Array<Regexp>}>] expectations # @return [Array] Returns an empty array of there were no failures, or an # Array of failed cases. def review_results(results, expectations) failed = [] results.each do |agent, agent_results| divider = "-" * 79 logger.info divider logger.info "For: (#{agent.name}) #{agent}" logger.info divider agent_results.each do |testname, execution_results| expected_exit_code = expectations[testname][:exit_code] match_tests = expectations[testname][:matches] || [] not_match_tests = expectations[testname][:does_not_match] || [] expect_failure = expectations[testname][:expect_failure] notes = expectations[testname][:notes] errors = [] if execution_results.exit_code != expected_exit_code errors << "To exit with an exit code of '#{expected_exit_code}', instead of '#{execution_results.exit_code}'" end match_tests.each do |regexp| if execution_results.output !~ regexp errors << "#{errors.empty? ? "To" : "And"} match: #{regexp}" end end not_match_tests.each do |regexp| if execution_results.output =~ regexp errors << "#{errors.empty? ? "Not to" : "And not"} match: #{regexp}" end end error_msg = "Expected the output:\n#{execution_results.output}\n#{errors.join("\n")}" unless errors.empty? case_failed = case when errors.empty? && expect_failure then 'ok - failed as expected' when errors.empty? && !expect_failure then 'ok' else '*UNEXPECTED FAILURE*' end logger.info "#{testname}: #{case_failed}" if case_failed == 'ok - failed as expected' logger.info divider logger.info "Case is known to fail as follows:\n#{execution_results.output}\n" elsif case_failed == '*UNEXPECTED FAILURE*' failed << "Unexpected failure for #{testname}" logger.info divider logger.info "#{error_msg}" end logger.info("------\nNotes: #{notes}") if notes logger.info divider end end return failed end def assert_review(review) failures = [] review.each do |failed| if !failed.empty? problems = "Problems in the output reported above:\n #{failed}" logger.warn(problems) failures << problems end end assert failures.empty?, "Failed Review:\n\n#{failures.join("\n")}\n" end # generate a random string of 6 letters and numbers. NOT secure def random_string [*('a'..'z'),*('0'..'9')].shuffle[0,8].join end private :random_string # if the first test to call this has changed the environmentpath, this will cause trouble # maybe not the best idea to memoize this? def environmentpath @@memoized_environmentpath ||= master.puppet['environmentpath'] end module_function :environmentpath # create a tmpdir to hold a temporary environment bound by puppet environment naming restrictions # symbolically link environment into environmentpath # we can't use the temp_file utils in our own lib because host.tmpdir violates puppet's naming requirements # in rare cases we want to do this on agents when testing things that use the default manifest def mk_tmp_environment_with_teardown(host, environment) # add the tmp_environment to a set to ensure no collisions @@tmp_environment_set ||= Set.new deadman = 100; loop_num = 0 while @@tmp_environment_set.include?(tmp_environment = environment.downcase + '_' + random_string) do break if (loop_num = loop_num + 1) > deadman end @@tmp_environment_set << tmp_environment tmpdir = File.join('','tmp',tmp_environment) on host, "mkdir -p #{tmpdir}/manifests #{tmpdir}/modules; chmod -R 755 #{tmpdir}" # register teardown to remove the link below teardown do on host, "rm -rf #{File.join(environmentpath,tmp_environment)}" end # WARNING: this won't work with filesync (symlinked environments are not supported) on host, "mkdir -p #{environmentpath}; ln -sf #{tmpdir} #{File.join(environmentpath,tmp_environment)}" return tmp_environment end module_function :mk_tmp_environment_with_teardown # create sitepp in a tmp_environment as created by mk_tmp_environment_with_teardown def create_sitepp(host, tmp_environment, file_content) file_path = File.join('','tmp',tmp_environment,'manifests','site.pp') create_remote_file(host, file_path, file_content) on host, "chmod -R 755 #{file_path}" end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/lib/puppet/acceptance/service_utils.rb
acceptance/lib/puppet/acceptance/service_utils.rb
require 'puppet/acceptance/common_utils' module Puppet module Acceptance module ServiceUtils # Return whether a host supports the systemd provider. # @param host [String] hostname # @return [Boolean] whether the systemd provider is supported. def supports_systemd?(host) # The Windows MSI doesn't put Puppet in the Ruby vendor or site dir, so loading it fails. return false if host.platform.variant == 'windows' ruby = Puppet::Acceptance::CommandUtils.ruby_command(host) suitable = on(host, "#{ruby} -e \"require 'puppet'; puts Puppet::Type.type(:service).provider(:systemd).suitable?\"" ).stdout.chomp suitable == "true" ? true : false end # Construct manifest ensuring service status. # @param service [String] name of the service # @param status [Hash] properties to set - can include 'ensure' and 'enable' keys. # @return [String] a manifest def service_manifest(service, status) ensure_status = "ensure => '#{status[:ensure]}'," if status[:ensure] enable_status = "enable => '#{status[:enable]}'," if status[:enable] %Q{ service { '#{service}': #{ensure_status} #{enable_status} } } end # Alter the state of a service using puppet apply and assert that a change was logged. # Assumes the starting state is not the desired state. # @param host [String] hostname. # @param service [String] name of the service. # @param status [Hash] properties to set - can include 'ensure' and 'enable' keys. # @return None def ensure_service_change_on_host(host, service, status) # the process of creating the service will also start it # to avoid a flickering test from the race condition, this test will ensure # that the exit code is either # 2 => something changed, or # 0 => no change needed apply_manifest_on(host, service_manifest(service, status), :acceptable_exit_codes => [0, 2]) do |result| assert_match(/Service\[#{service}\]\/ensure: ensure changed '\w+' to '#{status[:ensure]}'/, result.stdout, 'Service status change failed') if status[:ensure] assert_match(/Service\[#{service}\]\/enable: enable changed '\w+' to '#{status[:enable]}'/, result.stdout, 'Service enable change failed') if status[:enable] end end # Ensure the state of a service using puppet apply and assert that no change was logged. # Assumes the starting state is the ensured state. # @param host [String] hostname. # @param service [String] name of the service. # @param status [Hash] properties to set - can include 'ensure' and 'enable' keys. # @return None def ensure_service_idempotent_on_host(host, service, status) # ensure idempotency apply_manifest_on(host, service_manifest(service, status)) do |result| refute_match(/Service\[#{service}\]\/ensure/, result.stdout, 'Service status not idempotent') if status[:ensure] refute_match(/Service\[#{service}\]\/enable/, result.stdout, 'Service enable not idempotent') if status[:enable] end end # Alter the state of a service using puppet apply, assert that it changed and change is idempotent. # Can set 'ensure' and 'enable'. Assumes the starting state is not the desired state. # @param host [String] hostname. # @param service [String] name of the service. # @param status [Hash] properties to set - can include 'ensure' and 'enable' keys. # @param block [Proc] optional: block to verify service state # @return None def ensure_service_on_host(host, service, status, &block) ensure_service_change_on_host(host, service, status) assert_service_status_on_host(host, service, status, &block) ensure_service_idempotent_on_host(host, service, status) assert_service_status_on_host(host, service, status, &block) end # Checks that the ensure and/or enable status of a service are as expected. # @param host [String] hostname. # @param service [String] name of the service. # @param status [Hash] properties to set - can include 'ensure' and 'enable' keys. # @param block [Proc] optional: block to verify service state # @return None def assert_service_status_on_host(host, service, status, &block) ensure_status = "ensure.+=> '#{status[:ensure]}'" if status[:ensure] enable_status = "enable.+=> '#{status[:enable]}'" if status[:enable] on(host, puppet_resource('service', service)) do |result| assert_match(/'#{service}'.+#{ensure_status}.+#{enable_status}/m, result.stdout, "Service status does not match expectation #{status}") end # Verify service state on the system using a custom block if block yield block end end # Refreshes a service. # @param host [String] hostname. # @param service [String] name of the service to refresh. # @return None def refresh_service_on_host(host, service) refresh_manifest = %Q{ service { '#{service}': } notify { 'Refreshing #{service}': notify => Service['#{service}'], } } apply_manifest_on(host, refresh_manifest) end # Runs some common acceptance tests for nonexistent services. # @param service [String] name of the service # @return None def run_nonexistent_service_tests(service) step "Verify that a nonexistent service is considered stopped, disabled and no logonaccount is reported" do on(agent, puppet_resource('service', service)) do |result| { enable: false, ensure: :stopped }.each do |property, value| assert_match(/#{property}.*#{value}.*$/, result.stdout, "Puppet does not report #{property}=#{value} for a non-existent service") end refute_match(/logonaccount\s+=>/, result.stdout, "Puppet reports logonaccount for a non-existent service") end end step "Verify that stopping and disabling a nonexistent service is a no-op" do manifest = service_manifest(service, ensure: :stopped, enable: false) apply_manifest_on(agent, manifest, catch_changes: true) end [ [ :enabling, [ :enable, true ]], [ :starting, [ :ensure, :running ]] ].each do |operation, (property, value)| manifest = service_manifest(service, property => value) step "Verify #{operation} a non-existent service prints an error message but does not fail the run without detailed exit codes" do apply_manifest_on(agent, manifest) do |result| assert_match(/Error:.*#{service}.*$/, result.stderr, "Puppet does not error when #{operation} a non-existent service.") end end step "Verify #{operation} a non-existent service with detailed exit codes correctly returns an error code" do apply_manifest_on(agent, manifest, :acceptable_exit_codes => [4]) end end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/lib/puppet/acceptance/temp_file_utils.rb
acceptance/lib/puppet/acceptance/temp_file_utils.rb
module Puppet module Acceptance module TempFileUtils RWXR_XR_X = '0755' PUPPET_CODEDIR_PERMISSIONS = RWXR_XR_X # Return the name of the root user, as appropriate for the platform. def root_user(host) case host['platform'] when /windows/ 'Administrator' else 'root' end end # Return the name of the root group, as appropriate for the platform. def root_group(host) case host['platform'] when /windows/ 'Administrators' when /aix/ 'system' when /osx|bsd/ 'wheel' else 'root' end end # Create a file on the host. # Parameters: # [host] the host to create the file on # [file_path] the path to the file to be created # [file_content] a string containing the contents to be written to the file # [options] a hash containing additional behavior options. Currently supported: # * :mkdirs (default false) if true, attempt to create the parent directories on the remote host before writing # the file # * :owner (default 'root') the username of the user that the file should be owned by # * :group (default 'puppet') the name of the group that the file should be owned by # * :mode (default '644') the mode (file permissions) that the file should be created with def create_test_file(host, file_rel_path, file_content, options = {}) # set default options options[:mkdirs] ||= false options[:mode] ||= "755" unless options[:owner] if host['roles'].include?('master') then options[:owner] = host.puppet['user'] else options[:owner] = root_user(host) end end unless options[:group] if host['roles'].include?('master') then options[:group] = host.puppet['group'] else options[:group] = root_group(host) end end file_path = get_test_file_path(host, file_rel_path) mkdirs(host, File.dirname(file_path)) if (options[:mkdirs] == true) create_remote_file(host, file_path, file_content) # # NOTE: we need these chown/chmod calls because the acceptance framework connects to the nodes as "root", but # puppet 'master' runs as user 'puppet'. Therefore, in order for puppet master to be able to read any files # that we've created, we have to carefully set their permissions # chown(host, options[:owner], options[:group], file_path) chmod(host, options[:mode], file_path) end # Given a relative path, returns an absolute path for a test file. Basically, this just prepends the # a unique temp dir path (specific to the current test execution) to your relative path. def get_test_file_path(host, file_rel_path) initialize_temp_dirs unless @host_test_tmp_dirs File.join(@host_test_tmp_dirs[host.name], file_rel_path) end # Check for the existence of a temp file for the current test; basically, this just calls file_exists?(), # but prepends the path to the current test's temp dir onto the file_rel_path parameter. This allows # tests to be written using only a relative path to specify file locations, while still taking advantage # of automatic temp file cleanup at test completion. def test_file_exists?(host, file_rel_path) file_exists?(host, get_test_file_path(host, file_rel_path)) end def file_exists?(host, file_path) host.execute("test -f \"#{file_path}\"", :acceptable_exit_codes => [0, 1]) do |result| return result.exit_code == 0 end end def dir_exists?(host, dir_path) host.execute("test -d \"#{dir_path}\"", :acceptable_exit_codes => [0, 1]) do |result| return result.exit_code == 0 end end def link_exists?(host, link_path) host.execute("test -L \"#{link_path}\"", :acceptable_exit_codes => [0, 1]) do |result| return result.exit_code == 0 end end def file_contents(host, file_path) host.execute("cat \"#{file_path}\"") do |result| return result.stdout end end def tmpdir(host, basename) host_tmpdir = host.tmpdir(basename) # we need to make sure that the puppet user can traverse this directory... chmod(host, "755", host_tmpdir) host_tmpdir end def mkdirs(host, dir_path) on(host, "mkdir -p #{dir_path}") end def chown(host, owner, group, path) on(host, "chown #{owner}:#{group} #{path}") end def chmod(host, mode, path) on(host, "chmod #{mode} #{path}") end # Returns an array containing the owner, group and mode of # the file specified by path. The returned mode is an integer # value containing only the file mode, excluding the type, e.g # S_IFDIR 0040000 def stat(host, path) require File.join(File.dirname(__FILE__),'common_utils.rb') ruby = Puppet::Acceptance::CommandUtils.ruby_command(host) owner = on(host, "#{ruby} -e 'require \"etc\"; puts (Etc.getpwuid(File.stat(\"#{path}\").uid).name)'").stdout.chomp group = on(host, "#{ruby} -e 'require \"etc\"; puts (Etc.getgrgid(File.stat(\"#{path}\").gid).name)'").stdout.chomp mode = on(host, "#{ruby} -e 'puts (File.stat(\"#{path}\").mode & 07777)'").stdout.chomp.to_i [owner, group, mode] end def initialize_temp_dirs() # pluck this out of the test case environment; not sure if there is a better way @cur_test_file = @path @cur_test_file_shortname = File.basename(@cur_test_file, File.extname(@cur_test_file)) # we need one list of all of the hosts, to assist in managing temp dirs. It's possible # that the master is also an agent, so this will consolidate them into a unique set @all_hosts = Set[master, *agents] # now we can create a hash of temp dirs--one per host, and unique to this test--without worrying about # doing it twice on any individual host @host_test_tmp_dirs = Hash[@all_hosts.map do |host| [host.name, tmpdir(host, @cur_test_file_shortname)] end ] end def remove_temp_dirs() @all_hosts.each do |host| on(host, "rm -rf #{@host_test_tmp_dirs[host.name]}") end end # a silly variable for keeping track of whether or not all of the tests passed... @all_tests_passed = false end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/lib/puppet/acceptance/solaris_util.rb
acceptance/lib/puppet/acceptance/solaris_util.rb
module Puppet module Acceptance module IPSUtils def clean(agent, o={}) o = {:repo => '/var/tstrepo', :pkg => 'mypkg', :publisher => 'tstpub.lan'}.merge(o) on agent, "rm -rf %s||:" % o[:repo] on agent, "rm -rf /tst||:" on agent, "pkg uninstall %s||:" % o[:pkg] on agent, "pkg unset-publisher %s ||:" % o[:publisher] end def setup(agent, o={}) o = {:repo => '/var/tstrepo', :publisher => 'tstpub.lan'}.merge(o) on agent, "mkdir -p %s" % o[:repo] on agent, "pkgrepo create %s" % o[:repo] on agent, "pkgrepo set -s %s publisher/prefix=%s" % [o[:repo], o[:publisher]] on agent, "pkgrepo -s %s refresh" % o[:repo] end def setup_fakeroot(agent, o={}) o = {:root=>'/opt/fakeroot'}.merge(o) on agent, "rm -rf %s" % o[:root] on agent, "mkdir -p %s/tst/usr/bin" % o[:root] on agent, "mkdir -p %s/tst/etc" % o[:root] on agent, "echo dummy > %s/tst/usr/bin/x" % o[:root] on agent, "echo val > %s/tst/etc/y" % o[:root] end def setup_fakeroot2(agent, o={}) o = {:root=>'/opt/fakeroot'}.merge(o) on agent, "rm -rf %s" % o[:root] on agent, "mkdir -p %s/tst2/usr/bin" % o[:root] on agent, "mkdir -p %s/tst2/etc" % o[:root] on agent, "echo dummy > %s/tst2/usr/bin/x" % o[:root] on agent, "echo val > %s/tst2/etc/y" % o[:root] end def send_pkg2(agent, o={}) o = {:repo=>'/var/tstrepo', :root=>'/opt/fakeroot', :publisher=>'tstpub.lan', :pkg=>'mypkg2@0.0.1', :pkgdep => 'mypkg@0.0.1'}.merge(o) on agent, "(pkgsend generate %s; echo set name=pkg.fmri value=pkg://%s/%s)> /tmp/%s.p5m" % [o[:root], o[:publisher], o[:pkg], o[:pkg]] on agent, "echo depend type=require fmri=%s >> /tmp/%s.p5m" % [o[:pkgdep], o[:pkg]] on agent, "pkgsend publish -d %s -s %s /tmp/%s.p5m" % [o[:root], o[:repo], o[:pkg]] on agent, "pkgrepo refresh -p %s -s %s" % [o[:publisher], o[:repo]] on agent, "pkg refresh" on agent, "pkg list -g %s" % o[:repo] end def send_pkg(agent, o={}) o = {:repo=>'/var/tstrepo', :root=>'/opt/fakeroot', :publisher=>'tstpub.lan', :pkg=>'mypkg@0.0.1'}.merge(o) on agent, "(pkgsend generate %s; echo set name=pkg.fmri value=pkg://%s/%s)> /tmp/%s.p5m" % [o[:root], o[:publisher], o[:pkg], o[:pkg]] on agent, "pkgsend publish -d %s -s %s /tmp/%s.p5m" % [o[:root], o[:repo], o[:pkg]] on agent, "pkgrepo refresh -p %s -s %s" % [o[:publisher], o[:repo]] on agent, "pkg refresh" end def set_publisher(agent, o={}) o = {:repo=>'/var/tstrepo', :publisher=>'tstpub.lan'}.merge(o) on agent, "pkg set-publisher -g %s %s" % [o[:repo], o[:publisher]] on agent, "pkg refresh" end end module SMFUtils def clean(agent, o={}) o = {:service => 'tstapp'}.merge(o) on(agent, "svcs -l %s" % o[:service], acceptable_exit_codes: [0, 1]) do |result| next if result.stdout =~ /doesn't match/ lines = result.stdout.chomp.lines instances = lines.select { |line| line =~ /^fmri/ }.map { |line| line.split(' ')[1].chomp } instances.each do |instance| on agent, "svcadm disable %s ||:" % instance on agent, "svccfg delete %s ||:" % instance end end on agent, "rm -rf /var/svc/manifest/application/%s.xml ||:" % o[:service] on agent, "rm -f /opt/bin/%s ||:" % o[:service] end def setup(agent, o={}) setup_methodscript(agent, o) end def setup_methodscript(agent, o={}) o = {:service => 'tstapp'}.merge(o) on agent, "mkdir -p /opt/bin" create_remote_file agent, '/lib/svc/method/%s' % o[:service], %[ #!/usr/bin/sh . /lib/svc/share/smf_include.sh case "$1" in start) /opt/bin/%s ;; stop) ctid=`svcprop -p restarter/contract $SMF_FMRI` if [ -n "$ctid" ]; then smf_kill_contract $ctid TERM fi ;; *) echo "Usage: $0 { start | stop }" ; exit 1 ;; esac exit $SMF_EXIT_OK ] % ([o[:service]] * 4) create_remote_file agent, ('/opt/bin/%s' % o[:service]), %[ #!/usr/bin/sh cleanup() { rm -f /tmp/%s.pidfile; exit 0 } trap cleanup INT TERM trap '' HUP (while :; do sleep 1; done) & echo $! > /tmp/%s.pidfile ] % ([o[:service]] * 2) on agent, "chmod 755 /lib/svc/method/%s" % o[:service] on agent, "chmod 755 /opt/bin/%s" % o[:service] on agent, "mkdir -p /var/svc/manifest/application" create_remote_file agent, ('/var/smf-%s.xml' % o[:service]), %[<?xml version="1.0"?> <!DOCTYPE service_bundle SYSTEM "/usr/share/lib/xml/dtd/service_bundle.dtd.1"> <service_bundle type='manifest' name='%s:default'> <service name='application/tstapp' type='service' version='1'> <create_default_instance enabled='false' /> <method_context> <method_credential user='root' group='root' /> </method_context> <exec_method type='method' name='start' exec='/lib/svc/method/%s start' timeout_seconds="60" /> <exec_method type='method' name='stop' exec='/lib/svc/method/%s stop' timeout_seconds="60" /> <exec_method type='method' name='refresh' exec='/lib/svc/method/%s refresh' timeout_seconds="60" /> <stability value='Unstable' /> <template> <common_name> <loctext xml:lang='C'>Dummy</loctext> </common_name> <documentation> <manpage title='tstapp' section='1m' manpath='/usr/share/man' /> </documentation> </template> </service> </service_bundle> ] % ([o[:service]] * 4) on agent, "svccfg -v validate /var/smf-%s.xml" % o[:service] on agent, "echo > /var/svc/log/application-%s:default.log" % o[:service] return ("/var/smf-%s.xml" % o[:service]), ("/lib/svc/method/%s" % o[:service]) end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/lib/puppet/acceptance/rpm_util.rb
acceptance/lib/puppet/acceptance/rpm_util.rb
module Puppet module Acceptance module RpmUtils # Utilities for creating a basic rpm package and using it in tests @@defaults = {:repo => '/tmp/rpmrepo', :pkg => 'mypkg', :publisher => 'tstpub.lan', :version => '1.0'} @@setup_packages = {} def rpm_provider(agent) has_dnf = on(agent, 'which dnf', :acceptable_exit_codes => [0,1]).exit_code if has_dnf == 0 'dnf' else 'yum' end end def setup(agent) @@setup_packages[agent] ||= {} cmd = rpm_provider(agent) required_packages = ['createrepo', 'curl', 'rpm-build'] required_packages.each do |pkg| pkg_installed = (on agent, "#{cmd} list installed #{pkg}", :acceptable_exit_codes => (0..255)).exit_code == 0 # package not present, so perform a new install if !pkg_installed on agent, "#{cmd} install -y #{pkg}" # package is present, but has not yet attempted an upgrade # note that this may influence YUM cache behavior elsif !@@setup_packages[agent].has_key?(pkg) # first pass, always attempt an upgrade to latest version # fixes Fedora 25 curl compat with python-pycurl for instance on agent, "#{cmd} upgrade -y #{pkg}" end @@setup_packages[agent][pkg] = true end end def clean_rpm(agent, o={}) cmd = rpm_provider(agent) o = @@defaults.merge(o) on agent, "rm -rf #{o[:repo]}", :acceptable_exit_codes => (0..255) on agent, "#{cmd} remove -y #{o[:pkg]}", :acceptable_exit_codes => (0..255) on agent, "rm -f /etc/yum.repos.d/#{o[:publisher]}.repo", :acceptable_exit_codes => (0..255) end def setup_rpm(agent, o={}) setup(agent) o = @@defaults.merge(o) on agent, "mkdir -p #{o[:repo]}/{RPMS,SRPMS,BUILD,SOURCES,SPECS}" on agent, "echo '%_topdir #{o[:repo]}' > ~/.rpmmacros" on agent, "createrepo #{o[:repo]}" on agent, "cat <<EOF > /etc/yum.repos.d/#{o[:publisher]}.repo [#{o[:publisher]}] name=#{o[:publisher]} baseurl=file://#{o[:repo]}/ enabled=1 gpgcheck=0 EOF " end def send_rpm(agent, o={}) setup(agent) o = @@defaults.merge(o) on agent, "mkdir -p #{o[:repo]}/#{o[:pkg]}-#{o[:version]}/usr/bin" on agent, "cat <<EOF > #{o[:repo]}/#{o[:pkg]} #!/bin/bash echo Hello World EOF " pkg_name = "#{o[:pkg]}-#{o[:version]}" on agent, "install -m 755 #{o[:repo]}/#{o[:pkg]} #{o[:repo]}/#{pkg_name}/usr/bin" on agent, "tar -zcvf #{o[:repo]}/SOURCES/#{pkg_name}.tar.gz -C #{o[:repo]} #{pkg_name}" on agent, "cat <<EOF > #{o[:repo]}/SPECS/#{o[:pkg]}.spec # Don't try fancy stuff like debuginfo, which is useless on binary-only packages. Don't strip binary too # Be sure buildpolicy set to do nothing %define __spec_install_post %{nil} %define debug_package %{nil} %define __os_install_post %{_dbpath}/brp-compress Summary: A very simple toy bin rpm package Name: #{o[:pkg]} Version: #{o[:version]} Release: 1 Epoch: #{o[:epoch] || 0} BuildArch: noarch License: GPL+ Group: Development/Tools SOURCE0 : %{name}-%{version}.tar.gz URL: https://www.puppetlabs.com/ BuildRoot: %{_topdir}/BUILD/%{name}-%{version}-%{release}-root %description %{summary} %prep %setup -q %build # Empty section. %install rm -rf %{buildroot} mkdir -p %{buildroot} # in builddir cp -a * %{buildroot} %clean rm -rf %{buildroot} %files %defattr(-,root,root,-) %{_bindir}/* %changelog * Mon Dec 01 2014 Michael Smith <michael.smith@puppetlabs.com> #{o[:version]}-1 - First Build EOF " on agent, "rpmbuild -ba #{o[:repo]}/SPECS/#{o[:pkg]}.spec" on agent, "createrepo --update #{o[:repo]}" cmd = rpm_provider(agent) # DNF requires a cache reset to make local repositories accessible. if cmd == 'dnf' on agent, "dnf clean metadata" end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/lib/puppet/acceptance/module_utils.rb
acceptance/lib/puppet/acceptance/module_utils.rb
module Puppet module Acceptance module ModuleUtils # Return an array of module paths for a given host. # # Example return value: # # [ # "/etc/puppetlabs/code/environments/production/modules", # "/etc/puppetlabs/code/modules", # "/opt/puppet/share/puppet/modules", # ] # # @param host [String] hostname # @return [Array] paths for found modulepath def get_modulepaths_for_host(host) environment = on(host, puppet("config print environment")).stdout.chomp on(host, puppet("config print modulepath --environment #{environment}")).stdout.chomp.split(host['pathseparator']) end # Return a string of the default (first) path in modulepath for a given host. # # Example return value: # # "/etc/puppetlabs/code/environments/production/modules" # # @param host [String] hostname # @return [String] first path for found modulepath def get_default_modulepath_for_host(host) get_modulepaths_for_host(host)[0] end # Return an array of paths to installed modules for a given host. # # Example return value: # # [ # "/opt/puppet/share/puppet/modules/apt", # "/opt/puppet/share/puppet/modules/auth_conf", # "/opt/puppet/share/puppet/modules/concat", # ] # # @param host [String] hostname # @return [Array] paths for found modules def get_installed_modules_for_host(host) on(host, puppet('module list --render-as json')) do |result| str = result.stdout.lines.to_a.last pat = /\(([^()]+)\)/ mods = str.scan(pat).flatten return mods end end # Return a hash of array of paths to installed modules for a hosts. # The individual hostnames are the keys of the hash. The only value # for a given key is an array of paths for the found modules. # # Example return value: # # { # "my_master" => # [ # "/opt/puppet/share/puppet/modules/apt", # "/opt/puppet/share/puppet/modules/auth_conf", # "/opt/puppet/share/puppet/modules/concat", # ], # "my_agent01" => # [ # "/opt/puppet/share/puppet/modules/apt", # "/opt/puppet/share/puppet/modules/auth_conf", # "/opt/puppet/share/puppet/modules/concat", # ], # } # # @param hosts [Array] hostnames # @return [Hash] paths for found modules indexed by hostname def get_installed_modules_for_hosts(hosts) mods = {} hosts.each do |host| mods[host] = get_installed_modules_for_host host end return mods end # Compare the module paths in given hashes and remove paths that # are were not present in the first hash. The use case for this # method is to remove any modules that were installed during the # course of a test run. # # Installed module hashes would be gathered using the # `get_+installed_module_for_hosts` command in the setup stage # and teardown stages of a test. These hashes would be passed into # this method in order to find modules installed during the test # and delete them in order to return the SUT environments to their # initial state. # # TODO: Enhance to take versions into account, so that upgrade/ # downgrade events during a test does not persist in the SUT # environment. # # @param beginning_hash [Hash] paths for found modules indexed # by hostname. Taken in the setup stage of a test. # @param ending_hash [Hash] paths for found modules indexed # by hostname. Taken in the teardown stage of a test. def rm_installed_modules_from_hosts(beginning_hash, ending_hash) ending_hash.each do |host, mod_array| mod_array.each do |mod| if ! beginning_hash[host].include? mod on host, "rm -rf '#{mod}'" end end end end # Convert a semantic version number string to an integer. # # Example return value given an input of '1.2.42': # # 10242 # # @param semver [String] semantic version number def semver_to_i( semver ) # semver assumed to be in format <major>.<minor>.<patch> # calculation assumes that each segment is < 100 tmp = semver.split('.') tmp[0].to_i * 10000 + tmp[1].to_i * 100 + tmp[2].to_i end # Compare two given semantic version numbers. # # Returns an integer indicating the relationship between the two: # 0 indicates that both are equal # a value greater than 0 indicates that the semver1 is greater than semver2 # a value less than 0 indicates that the semver1 is less than semver2 # def semver_cmp( semver1, semver2 ) semver_to_i(semver1) - semver_to_i(semver2) end # Assert that a module was installed according to the UI.. # # This is a wrapper to centralize the validation about how # the UI responded that a module was installed. # It is called after a call # to `on ( host )` and inspects # STDOUT for specific content. # # @param stdout [String] # @param module_author [String] the author portion of a module name # @param module_name [String] the name portion of a module name # @param module_verion [String] the version of the module to compare to # installed version # @param compare_op [String] the operator for comparing the verions of # the installed module def assert_module_installed_ui( stdout, module_author, module_name, module_version = nil, compare_op = nil ) valid_compare_ops = {'==' => 'equal to', '>' => 'greater than', '<' => 'less than'} assert_match(/#{module_author}-#{module_name}/, stdout, "Notice that module '#{module_author}-#{module_name}' was installed was not displayed") if version /#{module_author}-#{module_name} \(.*v(\d+\.\d+\.\d+)/ =~ stdout installed_version = Regexp.last_match[1] if valid_compare_ops.include? compare_op assert_equal( true, semver_cmp(installed_version, module_version).send(compare_op, 0), "Installed version '#{installed_version}' of '#{module_name}' was not #{valid_compare_ops[compare_op]} '#{module_version}'") end end end # Assert that a module is installed on disk. # # @param host [HOST] the host object to make the remote call on # @param module_name [String] the name portion of a module name # @param optional moduledir [String, Array] the path where the module should be, will # iterate over components of the modulepath by default. def assert_module_installed_on_disk(host, module_name, moduledir=nil) moduledir ||= get_modulepaths_for_host(host) modulepath = moduledir.is_a?(Array) ? moduledir : [moduledir] moduledir= nil modulepath.each do |i| # module directory should exist if on(host, %Q{[ -d "#{i}/#{module_name}" ]}, :acceptable_exit_codes => (0..255)).exit_code == 0 moduledir = i end end fail_test('module directory not found') unless moduledir owner = '' group = '' on host, %Q{ls -ld "#{moduledir}"} do listing = stdout.split(' ') owner = listing[2] group = listing[3] end # A module's files should have: # * a mode of 644 (755, if they're a directory) # * owner == owner of moduledir # * group == group of moduledir on host, %Q{ls -alR "#{moduledir}/#{module_name}"} do listings = stdout.split("\n") listings = listings.grep(/^[bcdlsp-]/) listings = listings.reject { |l| l =~ /\.\.$/ } listings.each do |line| fileinfo = parse_ls(line) assert_equal owner, fileinfo[:owner] assert_equal group, fileinfo[:group] if fileinfo[:filetype] == 'd' assert_equal 'rwx', fileinfo[:perms][:user] assert_equal 'r-x', fileinfo[:perms][:group] assert_equal 'r-x', fileinfo[:perms][:other] else assert_equal 'rw-', fileinfo[:perms][:user] assert_equal 'r--', fileinfo[:perms][:group] assert_equal 'r--', fileinfo[:perms][:other] end end end end LS_REGEX = %r[(.)(...)(...)(...).?[[:space:]]+\d+[[:space:]]+([[:word:]]+)[[:space:]]+([[:word:]]+).*[[:space:]]+([[:graph:]]+)$] def parse_ls(line) match = line.match(LS_REGEX) if match.nil? fail_test "#{line.inspect} doesn't match ls output regular expression" end captures = match.captures { :filetype => captures[0], :perms => { :user => captures[1], :group => captures[2], :other => captures[3], }, :owner => captures[4], :group => captures[5], :file => captures[6] } end private :parse_ls # Assert that a module is not installed on disk. # # @param host [HOST] the host object to make the remote call on # @param module_name [String] the name portion of a module name # @param optional moduledir [String, Array] the path where the module should be, will # iterate over components of the modulepath by default. def assert_module_not_installed_on_disk(host, module_name, moduledir=nil) moduledir ||= get_modulepaths_for_host(host) modulepath = moduledir.is_a?(Array) ? moduledir : [moduledir] moduledir= nil modulepath.each do |i| # module directory should not exist on host, %Q{[ ! -d "#{i}/#{module_name}" ]} end end # Create a simple directory environment and puppet.conf at :tmpdir. # # @note Also registers a teardown block to remove generated files. # # @param tmpdir [String] directory to contain all the # generated environment files # @return [String] path to the new puppet configuration file defining the # environments def generate_base_directory_environments(tmpdir) puppet_conf = "#{tmpdir}/puppet2.conf" dir_envs = "#{tmpdir}/environments" step 'Configure a the direnv directory environment' apply_manifest_on master, %Q{ File { ensure => directory, owner => #{master.puppet['user']}, group => #{master.puppet['group']}, mode => "0750", } file { [ '#{dir_envs}', '#{dir_envs}/direnv', ]: } file { '#{puppet_conf}': ensure => file, content => " [main] environmentpath=#{dir_envs} " } } return puppet_conf end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/lib/puppet/acceptance/puppet_type_test_tools_spec.rb
acceptance/lib/puppet/acceptance/puppet_type_test_tools_spec.rb
require File.join(File.dirname(__FILE__),'../../acceptance_spec_helper.rb') require 'puppet/acceptance/puppet_type_test_tools.rb' require 'beaker/dsl/assertions' require 'beaker/result' module Puppet module Acceptance describe 'PuppetTypeTestTools' do include PuppetTypeTestTools include Beaker::DSL::Assertions include Beaker context '#generate_manifest' do it 'takes a single hash' do expect(generate_manifest({:type => 'fake'})).to match(/^fake{"fake_\w{8}":}$/) end it 'takes an array' do expect(generate_manifest([{:type => 'fake'}])).to match(/^fake{"fake_\w{8}":}$/) end it 'generates empty puppet code (assertion-only instance)' do expect(generate_manifest({:fake => 'fake'})).to eql('') end it 'puts a namevar in the right place' do expect(generate_manifest({:type => 'fake', :parameters => {:namevar => 'blah'}})).to match(/^fake{"blah":}$/) end it 'retains puppet code in a namevar' do expect(generate_manifest({:type => 'fake', :parameters => {:namevar => "half_${interpolated}_puppet_namevar"}})). to match(/^fake{"half_\${interpolated}_puppet_namevar":}$/) end it 'places pre_code before the type' do expect(generate_manifest({:type => 'fake', :pre_code => '$some = puppet_code'})). to match(/^\$some = puppet_code\nfake{"fake_\w{8}":}$/m) end it 'places multiple, arbitrary parameters' do expect(generate_manifest({:type => 'fake', :parameters => {:someprop => "function(call)", :namevar => "blah", :someparam => 2}})). to match(/^fake{"blah":someprop => function\(call\),someparam => 2,}$/) end end context '#generate_assertions' do it 'takes a single hash' do expect(generate_assertions({:assertions => {:fake => 'matcher'}})) .to match(/^fake\("matcher", result\.stdout, '"matcher"'\)$/) end it 'takes an array' do expect(generate_assertions([{:assertions => {:fake => 'matcher'}}])) .to match(/^fake\("matcher", result\.stdout, '"matcher"'\)$/) end it 'generates empty assertions (puppet-code only instance)' do expect(generate_assertions({:type => 'no assertions'})).to eql('') end it 'generates arbitrary assertions' do expect(generate_assertions({:assertions => [{:fake => 'matcher'}, {:other => 'othermatch'}]})) .to match(/^fake\("matcher", result\.stdout, '"matcher"'\)\nother\("othermatch", result.stdout, '"othermatch"'\)$/m) end it 'can give a regex to assertions' do expect(generate_assertions({:assertions => {:fake => /matcher/}})) .to match(/^fake\(\/matcher\/, result\.stdout, '\/matcher\/'\)$/) end it 'allows multiple of one assertion type' do expect(generate_assertions({:assertions => {:fake => ['matcher','othermatch']}})) .to match(/^fake\("matcher", result\.stdout, '"matcher"'\)\nfake\("othermatch", result.stdout, '"othermatch"'\)$/) end it 'allows multiple assertion_types with multiple values' do expect(generate_assertions({:assertions => [{:fake => ['matcher','othermatch']}, {:fake2 => ['matcher2','othermatch2']}]})) .to match(/^fake\("matcher", result\.stdout, '"matcher"'\)\nfake\("othermatch", result.stdout, '"othermatch"'\)\nfake2\("matcher2", result.stdout, '"matcher2"'\)\nfake2\("othermatch2", result.stdout, '"othermatch2"'\)\n$/) end context 'expect_failure' do it 'generates arbitrary assertion' do expect(generate_assertions({:assertions => {:expect_failure => {:fake => 'matcher'}}})) .to match(/^expect_failure '' do\nfake\(.*\)\nend$/) end it 'allows multiple of one assertion type' do expect(generate_assertions({:assertions => {:expect_failure => {:fake => ['matcher','othermatch']}}})) .to match(/^expect_failure '' do\nfake\(.*\)\nfake\(.*\)\nend$/) end it 'allows multiple assertion_types' do pending 'ack! requires recursion :-(' #expect(generate_assertions({:assertions => {:expect_failure => [{:fake => 'matcher'},{:fake2 => 'matcher2'}]}})) #.to match(/^expect_failure '' do\nfake\(.*\)\nfake2\(.*\)\nend$/) end it 'allows multiple assertion_types with an expect_failure on one' do expect(generate_assertions({:assertions => [{:expect_failure => {:fake => 'matcher'}}, {:fake2 => 'matcher2'}]})) .to match(/^expect_failure '' do\nfake\(.*\)\nend\nfake2\(.*\)$/) end it 'allows custom expect_failure messages' do expect(generate_assertions({:assertions => {:expect_failure => {:fake => 'matcher', :message => 'oh noes, this should fail but pass'}}})) .to match(/^expect_failure 'oh noes, this should fail but pass' do\nfake\(.*\)\nend$/) end end it 'allow custom assertion messages' end context 'run_assertions' do #def run_assertions(assertions = '', result) it 'takes a string result' do expect(run_assertions('assert_match("yes please", result.stdout)', 'yes please')).to be true end let(:result) {Beaker::Result.new('host','command')} it 'takes a beaker "type" Result' do result.stdout = 'yes please' expect(run_assertions('assert_match("yes please", result.stdout)', result)).to be true end it 'runs a bunch of assertions' do result.stdout = 'yes please' expect(run_assertions("assert_match('yes please', result.stdout)\nrefute_match('blah', result.stdout)", result)).to be false end it 'fails assertions' do pending 'why doesnt this work?' result.stdout = 'yes please' expect(run_assertions('assert_match("blah", result.stdout)', result)).to raise_error end context 'exceptions' do #rescue RuntimeError, SyntaxError => e it 'puts the assertion code, raises error' do pending 'why doesnt this work?' expect(run_assertions('assert_match("blah") }', result)).to raise_error end end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/lib/puppet/acceptance/puppet_type_test_tools.rb
acceptance/lib/puppet/acceptance/puppet_type_test_tools.rb
require 'puppet/acceptance/environment_utils' module Puppet module Acceptance module PuppetTypeTestTools include Puppet::Acceptance::EnvironmentUtils # for now, just for #random_string # FIXME: yardocs # TODO: create resource class which contains its manifest chunk, and assertions # can be an array or singular, holds the manifest and the assertion_code # has getter for the manifest # has #run_assertions(BeakerResult or string) def generate_manifest(test_resources) manifest = '' test_resources = [test_resources].flatten # ensure it's an array so we enumerate properly test_resources.each do |resource| manifest << resource[:pre_code] + "\n" if resource[:pre_code] namevar = (resource[:parameters][:namevar] if resource[:parameters]) || "#{resource[:type]}_#{random_string}" # ensure these are double quotes around the namevar incase users puppet-interpolate inside it # FIXME: add test ^^ manifest << resource[:type] + '{"' + namevar + '":' if resource[:type] if resource[:parameters] resource[:parameters].each do |key,value| next if key == :namevar manifest << "#{key} => #{value}," end end manifest << "}\n" if resource[:type] end return manifest end def generate_assertions(test_resources) assertion_code = '' test_resources = [test_resources].flatten # ensure it's an array so we enumerate properly test_resources.each do |resource| if resource[:assertions] resource[:assertions] = [resource[:assertions]].flatten # ensure it's an array so we enumerate properly resource[:assertions].each do |assertion_type| expect_failure = false if assertion_type[:expect_failure] expect_failure = true assertion_code << "expect_failure '#{assertion_type[:expect_failure][:message]}' do\n" # delete the message assertion_type[:expect_failure].delete(:message) # promote the hash in expect_failure assertion_type = assertion_type[:expect_failure] assertion_type.delete(:expect_failure) end # ensure all the values are arrays assertion_values = [assertion_type.values].flatten assertion_values.each do |assertion_value| # TODO: non matching asserts? # TODO: non stdout? (support stdout, stderr, exit_code) # TODO: what about checking resource state on host (non agent/apply #on use)? if assertion_type.keys.first =~ /assert_match/ assert_msg = 'found ' elsif assertion_type.keys.first =~ /refute_match/ assert_msg = 'did not find ' else assert_msg = '' end if assertion_value.is_a?(String) matcher = "\"#{assertion_value}\"" elsif assertion_value.is_a?(Regexp) matcher = assertion_value.inspect else matcher = assertion_value end assertion_code << "#{assertion_type.keys.first}(#{matcher}, result.stdout, '#{assert_msg}#{matcher}')\n" end assertion_code << "end\n" if expect_failure end end end return assertion_code end Result = Struct.new(:stdout) def run_assertions(assertions = '', result) result_struct = Result.new if result.respond_to? :stdout result_struct.stdout = result.stdout else # handle results sent in as string result_struct.stdout = result end result = result_struct begin eval(assertions) rescue RuntimeError, SyntaxError => e puts e puts assertions raise end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/lib/puppet/acceptance/aix_util.rb
acceptance/lib/puppet/acceptance/aix_util.rb
module Puppet module Acceptance module AixUtil def to_kv_array(attributes) attributes.map { |attribute, value| "#{attribute}=#{value}" } end def assert_object_attributes_on(host, object_get, object, expected_attributes) host.send(object_get, object) do |result| actual_attrs_kv_pairs = result.stdout.chomp.split(' ')[(1..-1)] actual_attrs = actual_attrs_kv_pairs.map do |kv_pair| attribute, value = kv_pair.split('=') next nil unless value [attribute, value] end.compact.to_h expected_attributes.each do |attribute, value| attribute_str = "attributes[#{object}][#{attribute}]" actual_value = actual_attrs[attribute] assert_match( /\A#{value}\z/, actual_value, "EXPECTED: #{attribute_str} = \"#{value}\", ACTUAL: #{attribute_str} = \"#{actual_value}\"" ) end end end def assert_puppet_changed_object_attributes(result, object_resource, object, changed_attributes) stdout = result.stdout.chomp changed_attributes.each do |attribute, value| prefix = /#{object_resource}\[#{object}\].*attributes changed.*/ attribute_str = "attributes[#{object}][#{attribute}]" assert_match( /#{prefix}#{attribute}=#{value}/, stdout, "Puppet did not indicate that #{attribute_str} changed to #{value}" ) end end def object_resource_manifest(object_resource, object, params) params_str = params.map do |param, value| value_str = value.to_s value_str = "\"#{value_str}\"" if value.is_a?(String) " #{param} => #{value_str}" end.join(",\n") <<-MANIFEST #{object_resource} { '#{object}': #{params_str} } MANIFEST end def run_attribute_management_tests(object_resource, id_property, initial_attributes, changed_attributes) object_get = "#{object_resource}_get".to_sym object_absent = "#{object_resource}_absent".to_sym name = "obj" teardown do agents.each { |agent| agent.send(object_absent, name) } end current_attributes = initial_attributes.dup agents.each do |agent| agent.send(object_absent, name) # We extract the code for this step as a lambda because we will be checking # for this case (1) Before the object has been created and (2) After the # object has been created (towards the end). We do this because in (1), Puppet # does not trigger the property setters after creating the object, while in (2) # it does. These are two different scenarios that we want to check. step_run_errors_when_property_is_passed_as_attribute = lambda do manifest = object_resource_manifest( object_resource, name, attributes: current_attributes.merge({ 'id' => '15' }) ) apply_manifest_on(agent, manifest) do |result| assert_match(/Error:.*'#{id_property}'.*'id'/, result.stderr, "specifying a Puppet property as part of an AIX attribute should have errored, but received #{result.stderr}") end end step "Ensure that Puppet errors if a Puppet property is passed in as an AIX attribute when creating the #{object_resource}" do step_run_errors_when_property_is_passed_as_attribute.call end step "Ensure that the #{object_resource} can be created with the specified attributes" do manifest = object_resource_manifest( object_resource, name, ensure: :present, attributes: to_kv_array(current_attributes) ) apply_manifest_on(agent, manifest) assert_object_attributes_on(agent, object_get, name, current_attributes) end step "Ensure that Puppet noops when the specified attributes are already set" do manifest = object_resource_manifest( object_resource, name, attributes: to_kv_array(current_attributes) ) apply_manifest_on(agent, manifest, catch_changes: true) end # Remember the changed attribute's old values old_attributes = current_attributes.select { |k, _| changed_attributes.keys.include?(k) } step "Ensure that Puppet updates only the specified attributes and nothing else" do current_attributes = current_attributes.merge(changed_attributes) manifest = object_resource_manifest( object_resource, name, attributes: to_kv_array(current_attributes) ) apply_manifest_on(agent, manifest) do |result| assert_puppet_changed_object_attributes( result, object_resource.capitalize, name, changed_attributes ) end assert_object_attributes_on(agent, object_get, name, current_attributes) end step "Ensure that Puppet accepts a hash for the attributes property" do # We want to see if Puppet will do something with the attributes property # when we pass it in as a hash so that it does not just pass validation # and end up noop-ing. Let's set one of our attributes back to its old # value in order to simulate an actual change. attribute = old_attributes.keys.first old_value = old_attributes.delete(attribute) current_attributes[attribute] = old_value manifest = object_resource_manifest( object_resource, name, attributes: current_attributes ) apply_manifest_on(agent, manifest) assert_object_attributes_on(agent, object_get, name, current_attributes) end step "Ensure that `puppet resource #{object_resource}` outputs valid Puppet code" do on(agent, puppet("resource #{object_resource} #{name}")) do |result| manifest = result.stdout.chomp apply_manifest_on(agent, manifest) end end step "Ensure that Puppet errors if a Puppet property is passed in as an AIX attribute after #{object_resource} has been created" do step_run_errors_when_property_is_passed_as_attribute.call end end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/lib/puppet/acceptance/i18n_utils.rb
acceptance/lib/puppet/acceptance/i18n_utils.rb
module Puppet module Acceptance module I18nUtils # try to enable the locale's for a given language on the agent and return the preferred language name # # @param agent [string] the agent to check the locale configuration on # @param language [string] the language attempt to configure if needed # @return language [string] the language string to use on the agent node, will return nil if not available def enable_locale_language(agent, language) if agent['platform'] =~ /ubuntu/ on(agent, 'locale -a') do |locale_result| if locale_result.stdout !~ /#{language}/ on(agent, "locale-gen --lang #{language}") end end elsif agent['platform'] =~ /debian/ on(agent, 'locale -a') do |locale_result| if locale_result.stdout !~ /#{language}/ on(agent, "cp /etc/locale.gen /etc/locale.gen.orig ; sed -e 's/# #{language}/#{language}/' /etc/locale.gen.orig > /etc/locale.gen") on(agent, 'locale-gen') end end end return language_name(agent, language) end # figure out the preferred language string for the requested language if the language is configured on the system def language_name(agent, language) step "PLATFORM #{agent['platform']}" on(agent, 'locale -a') do |locale_result| ["#{language}.utf8", "#{language}.UTF-8", language].each do |lang| return lang if locale_result.stdout =~ /#{lang}/ end end return nil end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/lib/puppet/acceptance/classifier_utils_spec.rb
acceptance/lib/puppet/acceptance/classifier_utils_spec.rb
require File.join(File.dirname(__FILE__),'../../acceptance_spec_helper.rb') require 'puppet/acceptance/classifier_utils' require 'stringio' require 'beaker' module ClassifierUtilsSpec describe 'ClassifierUtils' do class ATestCase < Beaker::TestCase include Puppet::Acceptance::ClassifierUtils attr_accessor :logger, :hosts def initialize @logger = Logger.new @hosts = [] end def logger @logger end def teardown end class Logger attr_reader :destination def initialize @destination = StringIO.new end def info(log) @destination << (log) end end end let(:testcase) { ATestCase.new } let(:handle) { testcase.classifier_handle( :server => 'foo', :cert => 'cert', :key => 'key', :ca_cert_file => 'file' ) } it "provides a handle to the classifier service" do handle.expects(:perform_request).with(Net::HTTP::Get, '/hi', {}) handle.get('/hi') end it "logs output from the http connection attempt" do TCPSocket.expects(:open).raises('no-connection') OpenSSL::X509::Certificate.expects(:new).with('certkey').returns(stub('cert')) OpenSSL::PKey::RSA.expects(:new).with('certkey', nil).returns(stub('key')) expect { handle.get('/hi') }.to raise_error('no-connection') expect(testcase.logger.destination.string).to match(/opening connection to foo/) end it "creates an agent-specified environment group for a passed set of nodes" do nodes = [ stub_everything('master', :hostname => 'abcmaster', :[] => ['master'] ), stub_everything('agent', :hostname => 'defagent', :[] => ['agent'] ), ] testcase.hosts = nodes uuid = nil handle.expects(:perform_request).with do |method,url,body_hash| expect(method).to eq(Net::HTTP::Put) test_regex = %r{/v1/groups/(\w+-\w+-\w+-\w+-\w+)} md = test_regex.match(url) expect(uuid = md[1]).to_not be_nil expect(body_hash[:body]).to match(/environment[^:]*:[^:]*agent-specified/) end.returns( stub_everything('response', :code => 201)) expect(testcase.classify_nodes_as_agent_specified(nodes).to_s).to eq(uuid) end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/lib/puppet/acceptance/windows_utils/package_installer.rb
acceptance/lib/puppet/acceptance/windows_utils/package_installer.rb
module Puppet module Acceptance module WindowsUtils # Sets up a mock installer on the host. def create_mock_package(host, tmpdir, config = {}, installer_file = 'MockInstaller.cs', uninstaller_file = 'MockUninstaller.cs') installer_exe_path = "#{tmpdir}/#{config[:name].gsub(/\s+/, '')}Installer.exe".gsub('/', '\\') uninstaller_exe_path = "#{tmpdir}/#{config[:name].gsub(/\s+/, '')}Uninstaller.exe".gsub('/', '\\') tranformations = { package_display_name: config[:name], uninstaller_location: uninstaller_exe_path, install_commands: config[:install_commands], uninstall_commands: config[:uninstall_commands] } [ { source: installer_file, destination: installer_exe_path }, { source: uninstaller_file, destination: uninstaller_exe_path }, ].each do |exe| fixture_path = File.join( File.dirname(__FILE__), '..', '..', '..', '..', 'fixtures', exe[:source] ) code = File.read(fixture_path) % tranformations build_mock_exe(host, exe[:destination], code) end # If the registry key still exists from a previous package install, then delete it. teardown do if package_installed?(host, config[:name]) on host, powershell("\"Remove-Item HKLM:\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\#{config[:name]}\"") end end # return the installer path for tests to use as the source: attribute installer_exe_path end def build_mock_exe(host, destination, code) # Make a source file containing the code on the SUT, the source file # will be the same location/name as the destination exe but with the .cs # extension source_path_on_host = destination.gsub(/\.exe$/, '.cs') create_remote_file(host, source_path_on_host.gsub('\\', '/'), code) # Create the installer.exe file by compiling the copied over C# code # with PowerShell create_installer_exe = "\"Add-Type"\ " -TypeDefinition (Get-Content #{source_path_on_host} | Out-String)"\ " -Language CSharp"\ " -OutputAssembly #{destination}"\ " -OutputType ConsoleApplication\"" on host, powershell(create_installer_exe) end def package_installed?(host, name) # A successfully installed mock package will have created a registry key under # HKLM:\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall. Simply checking # for that key should suffice as an indicator that the installer completed test_key = "\"Test-Path HKLM:\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\#{name}\"" on(host, powershell(test_key)) do |result| return result.stdout.chomp == 'True' end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/lib/puppet/acceptance/windows_utils/service.rb
acceptance/lib/puppet/acceptance/windows_utils/service.rb
module Puppet module Acceptance module WindowsUtils # Sets up a mock service on the host. The methodology here is a simplified # version of what's described in https://msdn.microsoft.com/en-us/magazine/mt703436.aspx def setup_service(host, config = {}, service_file = 'MockService.cs') config[:name] ||= "Mock Service" config[:display_name] ||= "#{config[:name]} (Puppet Acceptance Tests)" config[:description] ||= "Service created solely for acceptance testing the Puppet Windows Service provider" # Create a temporary directory to store the service's C# source code + # its .exe file. tmpdir = host.tmpdir("mock_service") # Copy-over the C# code code_fixture_path = File.join( File.dirname(__FILE__), '..', '..', '..', '..', 'fixtures', service_file ) code = File.read(code_fixture_path) % { service_name: config[:name], start_sleep: config[:start_sleep], pause_sleep: config[:pause_sleep], continue_sleep: config[:continue_sleep], stop_sleep: config[:stop_sleep] } code_path_unix = "#{tmpdir}/source.cs" code_path_win = code_path_unix.gsub('/', '\\') create_remote_file(host, code_path_unix, code) # Create the service.exe file by compiling the copied over C# code # with PowerShell service_exe_path_win = "#{tmpdir}/#{config[:name]}.exe".gsub('/', '\\') create_service_exe = "\"Add-Type"\ " -TypeDefinition (Get-Content #{code_path_win} | Out-String)"\ " -Language CSharp"\ " -OutputAssembly #{service_exe_path_win}"\ " -OutputType ConsoleApplication"\ " -ReferencedAssemblies 'System.ServiceProcess'\"" on host, powershell(create_service_exe) # Now register the service with SCM register_service_with_scm = "\"New-Service"\ " #{config[:name]}"\ " #{service_exe_path_win}"\ " -DisplayName '#{config[:display_name]}'"\ " -Description '#{config[:description]}'"\ " -StartupType Automatic\"" on host, powershell(register_service_with_scm) # Ensure that our service is deleted after the tests teardown { delete_service(host, config[:name]) } end def delete_service(host, name) # Check if our service has already been deleted. If so, then we # have nothing else to do. begin on host, powershell("Get-Service #{name}") rescue Beaker::Host::CommandFailure return end # Ensure that our service process is killed. We cannot do a Stop-Service here # b/c there's a chance that our service could be in a pending state (e.g. # "PausePending", "ContinuePending"). If this is the case, then Stop-Service # will fail. on host, powershell("\"Get-Process #{name} -ErrorAction SilentlyContinue | Stop-Process -Force\" | exit 0") # Now remove our service. We use sc.exe because older versions of PowerShell # may not have the Remove-Service commandlet. on agent, "sc.exe delete #{name}" end # Config should be a hash of <property> => <expected value> def assert_service_properties_on(host, name, properties = {}) properties.each do |property, expected_value| # We need to get the underlying WMI object for the service since that # object contains all of our service properties. The one returned by # Get-Service only has these properties for newer versions of PowerShell. get_property_value = "\"Get-WmiObject -Class Win32_Service"\ " | Where-Object { \\$_.name -eq '#{name}' }"\ " | ForEach-Object { \\$_.#{property} }\"" on(host, powershell(get_property_value)) do |result| actual_value = result.stdout.chomp property_str = "#{name}[#{property}]" assert_match(expected_value, actual_value, "EXPECTED: #{property_str} = #{expected_value}, ACTUAL: #{property_str} = #{actual_value}") end end end def assert_service_startmode_delayed(host, name) get_delayed_service = "\"Get-ChildItem HKLM:\\SYSTEM\\CurrentControlSet\\Services"\ " | Where-Object { \\$_.Property -Contains 'DelayedAutoStart' -And \\$_.PsChildName -Like '#{name}' }"\ " | Select-Object -ExpandProperty PSChildName\"" on(host, powershell(get_delayed_service)) do |result| svc = result.stdout.chomp assert(!svc.empty?, "Service #{name} does not exist or is not a delayed service") end end end end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/config/aio/options.rb
acceptance/config/aio/options.rb
{ :type => 'aio', 'is_puppetserver' => true, 'use-service' => true, # use service scripts to start/stop stuff 'puppetservice' => 'puppetserver', 'puppetserver-confdir' => '/etc/puppetlabs/puppetserver/conf.d', 'puppetserver-config' => '/etc/puppetlabs/puppetserver/conf.d/puppetserver.conf', }
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/config/gem/options.rb
acceptance/config/gem/options.rb
{ # Use `git` so that we have a sane ruby environment :type => 'git', }
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/config/git/options.rb
acceptance/config/git/options.rb
{ :type => 'git', :install => [ 'puppet', ], 'is_puppetserver' => false, 'use-service' => true, # use service scripts to start/stop stuff 'puppetservice' => 'puppetserver', 'puppetserver-confdir' => '/etc/puppetlabs/puppetserver/conf.d', 'puppetserver-config' => '/etc/puppetlabs/puppetserver/conf.d/puppetserver.conf' }
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/pending/ticket_5224_exec_should_unset_user_env_vars.rb
acceptance/pending/ticket_5224_exec_should_unset_user_env_vars.rb
test_name "#5224: exec resources should unset user-related environment variables" ####################################################################################### # NOTE ####################################################################################### # # This test depends on the following pull requests: # # https://github.com/puppetlabs/puppet-acceptance/pull/123 # # because it needs to be able to set some environment variables for the duration of # the puppet commands. Shouldn't be moved out of 'pending' until after that has been # merged. # ####################################################################################### temp_file_name = "/tmp/5224_exec_should_unset_user_env_vars.txt" sentinel_string = "Abracadabra" # these should match up with the value of Puppet::Util::POSIX_USER_ENV_VARS, # but I don't have access to that from here, so this is unfortunately hard-coded # (cprice 2012-01-27) POSIX_USER_ENV_VARS = ['HOME', 'USER', 'LOGNAME'] step "Check value of user-related environment variables" # in this step we are going to run some "exec" blocks that writes the value of the # user-related environment variables to a file. We need to verify that exec's are # unsetting these vars. test_printenv_manifest = <<HERE exec {"print %s environment variable": command => "/usr/bin/printenv %s > #{temp_file_name}", } HERE # loop over the vars that we care about; these should match up with the value of Puppet::Util::POSIX_USER_ENV_VARS, # but I don't have access to that from here, so this is unfortunately hard-coded (cprice 2012-01-27) POSIX_USER_ENV_VARS.each do |var| # apply the manifest. # # note that we are passing in an extra :environment argument, which will cause the # framework to temporarily set this variable before executing the puppet command. # this lets us know what value we should be looking for as the output of the exec. apply_manifest_on agents, test_printenv_manifest % [var, var], :environment => {var => sentinel_string} # cat the temp file and make sure it contained the correct value. on(agents, "cat #{temp_file_name}").each do |result| assert_equal("", "#{result.stdout.chomp}", "Unexpected result for host '#{result.host}', environment var '#{var}'") end end step "Check value of user-related environment variables when they are provided as part of the exec resource" # in this step we are going to run some "exec" blocks that write the value of the # user-related environment variables to a file. However, this time, the manifest # explicitly overrides these variables in the "environment" section, so we need to # be sure that we are respecting these overrides. test_printenv_with_env_overrides_manifest = <<HERE exec {"print %s environment variable": command => "/usr/bin/printenv %s > #{temp_file_name}", environment => ["%s=#{sentinel_string}", "FOO=bar"] } HERE # loop over the vars that we care about; POSIX_USER_ENV_VARS.each do |var| # apply the manifest. # # note that we are passing in an extra :environment argument, which will cause the # framework to temporarily set this variable before executing the puppet command. # this lets us know what value we should be looking for as the output of the exec. apply_manifest_on agents, test_printenv_with_env_overrides_manifest % [var, var, var], :environment => {var => sentinel_string} # cat the temp file and make sure it contained the correct value. on(agents, "cat #{temp_file_name}").each do |result| assert_equal(sentinel_string, "#{result.stdout.chomp}", "Unexpected result for host '#{result.host}', environment var '#{var}'") end end step "cleanup" # remove the temp file on agents, "rm -f #{temp_file_name}"
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/pending/ticket_4151_defined_function_should_not_return_true_for_unrealized_virtual_resources.rb
acceptance/pending/ticket_4151_defined_function_should_not_return_true_for_unrealized_virtual_resources.rb
test_name "#4151: defined function should not return true for unrealized virtual resources" # Jeff McCune <jeff@puppetlabs.com> # 2010-07-06 # # This script is expected to exit non-zero if ticket 4151 has not been # fixed. # # The expected behavior is for defined() to only return true if a virtual # resource has been realized. # # This test creates a virtual resource, does NOT realize it, then calls # the defined() function against it. If defined returns true, there will # be an error since Notify["goodbye"] will require a resource which has # not been realized. manifest1 = %q{ @notify { "hello": } if (defined(Notify["hello"])) { $requires = [ Notify["hello"] ] } notify { "goodbye": require => $requires } } apply_manifest_on(agents, manifest1)
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/pending/ticket_6928_puppet_master_parse_fails.rb
acceptance/pending/ticket_6928_puppet_master_parse_fails.rb
test_name "#6928: Puppet --parseonly should return deprication message" # Create good and bad formatted manifests step "Master: create valid, invalid formatted manifests" create_remote_file(master, '/tmp/good.pp', %w{notify{good:}} ) create_remote_file(master, '/tmp/bad.pp', 'notify{bad:') step "Master: use --parseonly on an invalid manifest, should return 1 and issue deprecation warning" on master, puppet_master( %w{--parseonly /tmp/bad.pp} ), :acceptable_exit_codes => [ 1 ] fail_test "Deprecation warning not issued for --parseonly" unless stdout.include? '--parseonly has been removed. Please use \'puppet parser validate <manifest>\'' step "Agents: create valid, invalid formatted manifests" agents.each do |host| create_remote_file(host, '/tmp/good.pp', %w{notify{good:}} ) create_remote_file(host, '/tmp/bad.pp', 'notify{bad:') end step "Agents: use --parseonly on an invalid manifest, should return 1 and issue deprecation warning" agents.each do |host| on(host, "puppet --parseonly /tmp/bad.pp}", :acceptable_exit_codes => [ 1 ]) do fail_test "Deprecation warning not issued for --parseonly" unless stdout.include? '--parseonly has been removed. Please use \'puppet parser validate <manifest>\'' end end step "Test Face for ‘parser validate’ with good manifest -- should pass" agents.each do |host| on(host, "puppet parser validate /tmp/good.pp", :acceptable_exit_codes => [ 0 ]) end step "Test Face for ‘parser validate’ with bad manifest -- should fail" agents.each do |host| on(host, "puppet parser validate /tmp/bad.pp", :acceptable_exit_codes => [ 1 ]) do fail_test "Bad manifest detection failed" unless stderr.include? 'Could not run: Could not parse for environment production' end end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/pending/ticket_11860_exec_should_not_override_locale.rb
acceptance/pending/ticket_11860_exec_should_not_override_locale.rb
test_name "#11860: exec resources should not override system locale" ####################################################################################### # NOTE ####################################################################################### # # This test won't run properly until the test agent nodes have the Spanish language # pack installed on them. On an ubuntu system, this can be done with the following: # # apt-get install language-pack-es-base # # Also, this test depends on the following pull requests: # # https://github.com/puppetlabs/puppet-acceptance/pull/123 # https://github.com/puppetlabs/facter/pull/159 # ####################################################################################### temp_file_name = "/tmp/11860_exec_should_not_override_locale.txt" locale_string = "es_ES.UTF-8" step "Check value of LANG environment variable" # in this step we are going to run an "exec" block that writes the value of the LANG # environment variable to a file. We need to verify that exec's are no longer # forcefully setting this var to 'C'. test_LANG_manifest = <<HERE exec {"es_ES locale print LANG environment variable": command => "/usr/bin/printenv LANG > #{temp_file_name}", } HERE # apply the manifest. # # note that we are passing in an extra :environment argument, which will cause the # framework to temporarily set this variable before executing the puppet command. # this lets us know what value we should be looking for as the output of the exec. apply_manifest_on agents, test_LANG_manifest, :environment => {:LANG => locale_string} # cat the temp file and make sure it contained the correct value. on(agents, "cat #{temp_file_name}").each do |result| assert_equal(locale_string, "#{result.stdout.chomp}", "Unexpected result for host '#{result.host}'") end step "Check for locale-specific output of cat command" # in this step we are going to run an "exec" block that runs the "cat" command. The command # is intentionally invalid, because we are going to run it using a non-standard locale and # we want to confirm that the error message is in the correct language. test_cat_manifest = <<HERE exec {"es_ES locale invalid cat command": command => "/bin/cat SOME_FILE_THAT_DOESNT_EXIST > #{temp_file_name} 2>&1", returns => 1, } HERE # apply the manifest, again passing in the extra :environment argument to set our locale. apply_manifest_on agents, test_cat_manifest, :environment => {:LANG => locale_string} # cat the output file and ensure that the error message is in spanish on(agents, "cat #{temp_file_name}").each do |result| assert_equal("/bin/cat: SOME_FILE_THAT_DOESNT_EXIST: No existe el fichero o el directorio", "#{result.stdout.chomp}", "Unexpected result for host '#{result.host}'") end step "cleanup" # remove the temp file on agents, "rm -f #{temp_file_name}"
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/pending/ticket_5027_warn_on_dynamic_scope.rb
acceptance/pending/ticket_5027_warn_on_dynamic_scope.rb
test_name "#5027: Issue warnings when using dynamic scope" step "Apply dynamic scoping manifest on agents" apply_manifest_on agents, %q{ $foo = 'foo_value' class a { $bar = 'bar_value' include b } class b inherits c { notify { $baz: } # should not generate a warning -- inherited from class c notify { $bar: } # should generate a warning -- uses dynamic scoping notify { $foo: } # should not generate a warning -- comes from top scope } class c { $baz = 'baz_value' } include a } step "Verify deprecation warning" fail_test "Deprecation warning not issued" unless stdout.include? 'warning: Dynamic lookup of $bar will not be supported in future versions. Use a fully-qualified variable name or parameterized classes.'
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/acceptance/pending/ticket_4149_parseonly_should_not_fail.rb
acceptance/pending/ticket_4149_parseonly_should_not_fail.rb
test_name "#4149: parseonly should do the right thing" step "test with a manifest with syntax errors" manifest = 'class someclass { notify { "hello, world" } }' apply_manifest_on(agents, manifest, :parseonly => true, :acceptable_exit_codes => [1]) { stdout =~ /Could not parse for .*: Syntax error/ or fail_test("didn't get a reported systax error") } step "test with a manifest with correct syntax" apply_manifest_on agents,'class someclass { notify("hello, world") }', :parseonly => true # REVISIT: This tests the current behaviour, which is IMO not actually the # correct behaviour. On the other hand, if we change this we might # unexpectedly break things out in the wild, so better to be warned than to be # surprised by it. --daniel 2010-12-22 step "test with a class with an invalid attribute" apply_manifest_on agents, 'file { "/tmp/whatever": fooble => 1 }', :parseonly => true
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false
OpenVoxProject/openvox
https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/ext/windows/service/daemon.rb
ext/windows/service/daemon.rb
#!/usr/bin/env ruby # frozen_string_literal: true require 'fileutils' require 'puppet/util/windows/daemon' # This file defines utilities for logging to eventlog. While it lives inside # Puppet, it is completely independent and loads no other parts of Puppet, so we # can safely require *just* it. require 'puppet/util/windows/eventlog' # monkey patches ruby Process to add .create method require 'puppet/util/windows/monkey_patches/process' class WindowsDaemon < Puppet::Util::Windows::Daemon CREATE_NEW_CONSOLE = 0x00000010 @run_thread = nil @LOG_TO_FILE = false @loglevel = 0 LOG_FILE = File.expand_path(File.join(ENV.fetch('ALLUSERSPROFILE', nil), 'PuppetLabs', 'puppet', 'var', 'log', 'windows.log')) LEVELS = [:debug, :info, :notice, :warning, :err, :alert, :emerg, :crit] LEVELS.each do |level| define_method("log_#{level}") do |msg| log(msg, level) end end def service_init end def service_main(*argsv) argsv = (argsv << ARGV).flatten.compact args = argsv.join(' ') @loglevel = LEVELS.index(argsv.index('--debug') ? :debug : :notice) @LOG_TO_FILE = (argsv.index('--logtofile') ? true : false) if @LOG_TO_FILE FileUtils.mkdir_p(File.dirname(LOG_FILE)) args = args.gsub("--logtofile", "") end base_dir = File.expand_path(File.join(File.dirname(__FILE__), '..')) load_env(base_dir) # The puppet installer registers a 'Puppet' event source. For the moment events will be logged with this key, but # it may be a good idea to split the Service and Puppet events later so it's easier to read in the windows Event Log. # # Example code to register an event source; # eventlogdll = File.expand_path(File.join(basedir, 'puppet', 'ext', 'windows', 'eventlog', 'puppetres.dll')) # if (File.exist?(eventlogdll)) # Win32::EventLog.add_event_source( # 'source' => "Application", # 'key_name' => "Puppet Agent", # 'category_count' => 3, # 'event_message_file' => eventlogdll, # 'category_message_file' => eventlogdll # ) # end puppet = File.join(base_dir, 'puppet', 'bin', 'puppet') ruby = File.join(base_dir, 'puppet', 'bin', 'ruby.exe') ruby_puppet_cmd = "\"#{ruby}\" \"#{puppet}\"" unless File.exist?(puppet) log_err("File not found: '#{puppet}'") return end log_debug("Using '#{puppet}'") cmdline_debug = argsv.index('--debug') ? :debug : nil @loglevel = parse_log_level(ruby_puppet_cmd, cmdline_debug) log_notice('Service started') service = self @run_thread = Thread.new do while service.running? runinterval = service.parse_runinterval(ruby_puppet_cmd) if service.state == RUNNING or service.state == IDLE service.log_notice("Executing agent with arguments: #{args}") pid = Process.create(:command_line => "#{ruby_puppet_cmd} agent --onetime #{args}", :creation_flags => CREATE_NEW_CONSOLE).process_id service.log_debug("Process created: #{pid}") else service.log_debug("Service is paused. Not invoking Puppet agent") end service.log_debug("Service worker thread waiting for #{runinterval} seconds") sleep(runinterval) service.log_debug('Service worker thread woken up') end rescue Exception => e service.log_exception(e) end @run_thread.join rescue Exception => e log_exception(e) ensure log_notice('Service stopped') end def service_stop log_notice('Service stopping / killing worker thread') @run_thread.kill if @run_thread end def service_pause log_notice('Service pausing') end def service_resume log_notice('Service resuming') end def service_shutdown log_notice('Host shutting down') end # Interrogation handler is just for debug. Can be commented out or removed entirely. # def service_interrogate # log_debug('Service is being interrogated') # end def log_exception(e) log_err(e.message) log_err(e.backtrace.join("\n")) end def log(msg, level) if LEVELS.index(level) >= @loglevel if @LOG_TO_FILE # without this change its possible that we get Encoding errors trying to write UTF-8 messages in current codepage File.open(LOG_FILE, 'a:UTF-8') { |f| f.puts("#{Time.now} Puppet (#{level}): #{msg}") } end native_type, native_id = Puppet::Util::Windows::EventLog.to_native(level) report_windows_event(native_type, native_id, msg.to_s) end end def report_windows_event(type, id, message) eventlog = nil eventlog = Puppet::Util::Windows::EventLog.open("Puppet") eventlog.report_event( :event_type => type, # EVENTLOG_ERROR_TYPE, etc :event_id => id, # 0x01 or 0x02, 0x03 etc. :data => message # "the message" ) rescue Exception # Ignore all errors ensure unless eventlog.nil? eventlog.close end end # Parses runinterval. # # @param puppet_path [String] The file path for the Puppet executable. # @return runinterval [Integer] How often to do a Puppet run, in seconds. def parse_runinterval(puppet_path) begin runinterval = %x(#{puppet_path} config --section agent --log_level notice print runinterval).chomp if runinterval == '' runinterval = 1800 log_err("Failed to determine runinterval, defaulting to #{runinterval} seconds") else # Use Kernel#Integer because to_i will return 0 with non-numeric strings. runinterval = Integer(runinterval) end rescue Exception => e log_exception(e) runinterval = 1800 end runinterval end def parse_log_level(puppet_path, cmdline_debug) begin loglevel = "notice" unless loglevel && respond_to?("log_#{loglevel}") loglevel = :notice log_err("Failed to determine loglevel, defaulting to #{loglevel}") end rescue Exception => e log_exception(e) loglevel = :notice end LEVELS.index(cmdline_debug || loglevel.to_sym) end private def load_env(base_dir) # ENV that uses backward slashes ENV['FACTER_env_windows_installdir'] = base_dir.tr('/', '\\') ENV['PL_BASEDIR'] = base_dir.tr('/', '\\') ENV['PUPPET_DIR'] = File.join(base_dir, 'puppet').tr('/', '\\') ENV['OPENSSL_CONF'] = File.join(base_dir, 'puppet', 'ssl', 'openssl.cnf').tr('/', '\\') ENV['SSL_CERT_DIR'] = File.join(base_dir, 'puppet', 'ssl', 'certs').tr('/', '\\') ENV['SSL_CERT_FILE'] = File.join(base_dir, 'puppet', 'ssl', 'cert.pem').tr('/', '\\') ENV['Path'] = [ File.join(base_dir, 'puppet', 'bin'), File.join(base_dir, 'bin') ].join(';').tr('/', '\\') + ';' + ENV.fetch('Path', nil) # ENV that uses forward slashes ENV['RUBYLIB'] = "#{File.join(base_dir, 'puppet', 'lib')};#{ENV.fetch('RUBYLIB', nil)}" rescue => e log_exception(e) end end if __FILE__ == $PROGRAM_NAME WindowsDaemon.mainloop end
ruby
Apache-2.0
9336df16a11679d701a2bd9ebe1308d4fb669f57
2026-01-04T17:47:45.967003Z
false