diff --git a/.gitignore b/.gitignore index 56efb9c..49bc2a4 100644 --- a/.gitignore +++ b/.gitignore @@ -1,22 +1,23 @@ .*.sw[op] .metadata .yardoc .yardwarns *.iml /.bundle/ /.idea/ /.vagrant/ /coverage/ /bin/ /doc/ /Gemfile.local /Gemfile.lock /junit/ /log/ /pkg/ /spec/fixtures/manifests/ /spec/fixtures/modules/ /tmp/ /vendor/ /convert_report.txt +/update_report.txt .DS_Store diff --git a/.gitignore b/.pdkignore similarity index 92% copy from .gitignore copy to .pdkignore index 56efb9c..49bc2a4 100644 --- a/.gitignore +++ b/.pdkignore @@ -1,22 +1,23 @@ .*.sw[op] .metadata .yardoc .yardwarns *.iml /.bundle/ /.idea/ /.vagrant/ /coverage/ /bin/ /doc/ /Gemfile.local /Gemfile.lock /junit/ /log/ /pkg/ /spec/fixtures/manifests/ /spec/fixtures/modules/ /tmp/ /vendor/ /convert_report.txt +/update_report.txt .DS_Store diff --git a/.rubocop.yml b/.rubocop.yml index 40a58e0..7ed6225 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -1,107 +1,115 @@ --- require: rubocop-rspec AllCops: DisplayCopNames: true TargetRubyVersion: '2.1' Include: - "./**/*.rb" Exclude: - bin/* - ".vendor/**/*" - - Gemfile - - Rakefile + - "**/Gemfile" + - "**/Rakefile" - pkg/**/* - spec/fixtures/**/* - vendor/**/* + - "**/Puppetfile" + - "**/Vagrantfile" + - "**/Guardfile" Metrics/LineLength: Description: People have wide screens, use them. Max: 200 RSpec/BeforeAfterAll: Description: Beware of using after(:all) as it may cause state to leak between tests. A necessary evil in acceptance testing. Exclude: - spec/acceptance/**/*.rb RSpec/HookArgument: Description: Prefer explicit :each argument, matching existing module's style EnforcedStyle: each Style/BlockDelimiters: Description: Prefer braces for chaining. Mostly an aesthetical choice. Better to be consistent then. EnforcedStyle: braces_for_chaining Style/ClassAndModuleChildren: Description: Compact style reduces the required amount of indentation. EnforcedStyle: compact Style/EmptyElse: Description: Enforce against empty else clauses, but allow `nil` for clarity. EnforcedStyle: empty Style/FormatString: Description: Following the main puppet project's style, prefer the % format format. EnforcedStyle: percent Style/FormatStringToken: Description: Following the main puppet project's style, prefer the simpler template tokens over annotated ones. EnforcedStyle: template Style/Lambda: Description: Prefer the keyword for easier discoverability. EnforcedStyle: literal Style/RegexpLiteral: Description: Community preference. See https://github.com/voxpupuli/modulesync_config/issues/168 EnforcedStyle: percent_r Style/TernaryParentheses: Description: Checks for use of parentheses around ternary conditions. Enforce parentheses on complex expressions for better readability, but seriously consider breaking it up. EnforcedStyle: require_parentheses_when_complex Style/TrailingCommaInArguments: Description: Prefer always trailing comma on multiline argument lists. This makes diffs, and re-ordering nicer. EnforcedStyleForMultiline: comma Style/TrailingCommaInLiteral: Description: Prefer always trailing comma on multiline literals. This makes diffs, and re-ordering nicer. EnforcedStyleForMultiline: comma Style/SymbolArray: Description: Using percent style obscures symbolic intent of array's contents. EnforcedStyle: brackets RSpec/MessageSpies: EnforcedStyle: receive +Style/Documentation: + Exclude: + - lib/puppet/parser/functions/**/* +Style/WordArray: + EnforcedStyle: brackets Style/CollectionMethods: Enabled: true Style/MethodCalledOnDoEndBlock: Enabled: true Style/StringMethods: Enabled: true Layout/EndOfLine: Enabled: false Metrics/AbcSize: Enabled: false Metrics/BlockLength: Enabled: false Metrics/ClassLength: Enabled: false Metrics/CyclomaticComplexity: Enabled: false Metrics/MethodLength: Enabled: false Metrics/ModuleLength: Enabled: false Metrics/ParameterLists: Enabled: false Metrics/PerceivedComplexity: Enabled: false RSpec/DescribeClass: Enabled: false RSpec/ExampleLength: Enabled: false RSpec/MessageExpectation: Enabled: false RSpec/MultipleExpectations: Enabled: false RSpec/NestedGroups: Enabled: false Style/AsciiComments: Enabled: false Style/IfUnlessModifier: Enabled: false Style/SymbolProc: Enabled: false diff --git a/.travis.yml b/.travis.yml index 1428837..76b202c 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,67 +1,61 @@ --- sudo: false dist: trusty language: ruby cache: bundler before_install: - bundle -v - rm -f Gemfile.lock - gem update --system - - gem update bundler - gem --version - bundle -v script: - 'bundle exec rake $CHECK' bundler_args: --without system_tests rvm: - 2.4.1 env: - - PUPPET_GEM_VERSION="~> 5.0" CHECK=spec + global: + - BEAKER_PUPPET_COLLECTION=puppet5 PUPPET_GEM_VERSION="~> 5.0" matrix: fast_finish: true include: - bundler_args: dist: trusty - env: PUPPET_INSTALL_TYPE=agent BEAKER_debug=true BEAKER_set=docker/centos-7 + env: PUPPET_INSTALL_TYPE=agent BEAKER_debug=true BEAKER_PUPPET_COLLECTION=puppet5 BEAKER_set=docker/centos-7 rvm: 2.4.1 script: bundle exec rake beaker services: docker sudo: required - bundler_args: dist: trusty - env: PUPPET_INSTALL_TYPE=agent BEAKER_debug=true BEAKER_set=docker/ubuntu-14.04 + env: PUPPET_INSTALL_TYPE=agent BEAKER_debug=true BEAKER_PUPPET_COLLECTION=puppet5 BEAKER_set=docker/ubuntu-14.04 rvm: 2.4.1 script: bundle exec rake beaker services: docker sudo: required - - env: CHECK=rubocop + env: CHECK="syntax lint metadata_lint check:symlinks check:git_ignore check:dot_underscore check:test_file rubocop" - - env: CHECK="syntax lint" + env: CHECK=parallel_spec - - env: CHECK=metadata_lint - - - env: CHECK=release_checks - - - env: CHECK=spec - - - env: PUPPET_GEM_VERSION="~> 4.0" CHECK=spec + env: PUPPET_GEM_VERSION="~> 4.0" CHECK=parallel_spec rvm: 2.1.9 branches: only: - master - /^v\d/ - release notifications: email: false deploy: provider: puppetforge user: puppet password: secure: "" on: tags: true all_branches: true condition: "$DEPLOY_TO_FORGE = yes" diff --git a/.yardopts b/.yardopts new file mode 100644 index 0000000..29c933b --- /dev/null +++ b/.yardopts @@ -0,0 +1 @@ +--markup markdown diff --git a/Gemfile b/Gemfile index 37597a3..a7ec820 100644 --- a/Gemfile +++ b/Gemfile @@ -1,136 +1,88 @@ source ENV['GEM_SOURCE'] || 'https://rubygems.org' def location_for(place_or_version, fake_version = nil) if place_or_version =~ %r{\A(git[:@][^#]*)#(.*)} [fake_version, { git: Regexp.last_match(1), branch: Regexp.last_match(2), require: false }].compact elsif place_or_version =~ %r{\Afile:\/\/(.*)} ['>= 0', { path: File.expand_path(Regexp.last_match(1)), require: false }] else [place_or_version, { require: false }] end end def gem_type(place_or_version) if place_or_version =~ %r{\Agit[:@]} :git elsif !place_or_version.nil? && place_or_version.start_with?('file:') :file else :gem end end ruby_version_segments = Gem::Version.new(RUBY_VERSION.dup).segments minor_version = ruby_version_segments[0..1].join('.') group :development do gem "fast_gettext", '1.1.0', require: false if Gem::Version.new(RUBY_VERSION.dup) < Gem::Version.new('2.1.0') gem "fast_gettext", require: false if Gem::Version.new(RUBY_VERSION.dup) >= Gem::Version.new('2.1.0') gem "json_pure", '<= 2.0.1', require: false if Gem::Version.new(RUBY_VERSION.dup) < Gem::Version.new('2.0.0') gem "json", '= 1.8.1', require: false if Gem::Version.new(RUBY_VERSION.dup) == Gem::Version.new('2.1.9') + gem "json", '<= 2.0.4', require: false if Gem::Version.new(RUBY_VERSION.dup) == Gem::Version.new('2.4.4') gem "puppet-module-posix-default-r#{minor_version}", require: false, platforms: [:ruby] gem "puppet-module-posix-dev-r#{minor_version}", require: false, platforms: [:ruby] gem "puppet-module-win-default-r#{minor_version}", require: false, platforms: [:mswin, :mingw, :x64_mingw] gem "puppet-module-win-dev-r#{minor_version}", require: false, platforms: [:mswin, :mingw, :x64_mingw] - gem "puppet-blacksmith", '~> 3.4', require: false + gem "puppet-blacksmith", '~> 3.4', require: false, platforms: [:ruby] end group :system_tests do gem "puppet-module-posix-system-r#{minor_version}", require: false, platforms: [:ruby] gem "puppet-module-win-system-r#{minor_version}", require: false, platforms: [:mswin, :mingw, :x64_mingw] gem "beaker", *location_for(ENV['BEAKER_VERSION'] || '~> 3.13') gem "beaker-abs", *location_for(ENV['BEAKER_ABS_VERSION'] || '~> 0.1') gem "beaker-pe", require: false gem "beaker-hostgenerator" gem "beaker-rspec" end puppet_version = ENV['PUPPET_GEM_VERSION'] puppet_type = gem_type(puppet_version) facter_version = ENV['FACTER_GEM_VERSION'] hiera_version = ENV['HIERA_GEM_VERSION'] -def puppet_older_than?(version) - puppet_version = ENV['PUPPET_GEM_VERSION'] - !puppet_version.nil? && - Gem::Version.correct?(puppet_version) && - Gem::Requirement.new("< #{version}").satisfied_by?(Gem::Version.new(puppet_version.dup)) -end - gems = {} gems['puppet'] = location_for(puppet_version) # If facter or hiera versions have been specified via the environment -# variables, use those versions. If not, and if the puppet version is < 3.5.0, -# use known good versions of both for puppet < 3.5.0. -if facter_version - gems['facter'] = location_for(facter_version) -elsif puppet_type == :gem && puppet_older_than?('3.5.0') - gems['facter'] = ['>= 1.6.11', '<= 1.7.5', require: false] -end - -if hiera_version - gems['hiera'] = location_for(ENV['HIERA_GEM_VERSION']) -elsif puppet_type == :gem && puppet_older_than?('3.5.0') - gems['hiera'] = ['>= 1.0.0', '<= 1.3.0', require: false] -end +# variables -if Gem.win_platform? && (puppet_type != :gem || puppet_older_than?('3.5.0')) - # For Puppet gems < 3.5.0 (tested as far back as 3.0.0) on Windows - if puppet_type == :gem - gems['ffi'] = ['1.9.0', require: false] - gems['minitar'] = ['0.5.4', require: false] - gems['win32-eventlog'] = ['0.5.3', '<= 0.6.5', require: false] - gems['win32-process'] = ['0.6.5', '<= 0.7.5', require: false] - gems['win32-security'] = ['~> 0.1.2', '<= 0.2.5', require: false] - gems['win32-service'] = ['0.7.2', '<= 0.8.8', require: false] - else - gems['ffi'] = ['~> 1.9.0', require: false] - gems['minitar'] = ['~> 0.5.4', require: false] - gems['win32-eventlog'] = ['~> 0.5', '<= 0.6.5', require: false] - gems['win32-process'] = ['~> 0.6', '<= 0.7.5', require: false] - gems['win32-security'] = ['~> 0.1', '<= 0.2.5', require: false] - gems['win32-service'] = ['~> 0.7', '<= 0.8.8', require: false] - end - - gems['win32-dir'] = ['~> 0.3', '<= 0.4.9', require: false] - - if RUBY_VERSION.start_with?('1.') - gems['win32console'] = ['1.3.2', require: false] - # sys-admin was removed in Puppet 3.7.0 and doesn't compile under Ruby 2.x - gems['sys-admin'] = ['1.5.6', require: false] - end +gems['facter'] = location_for(facter_version) if facter_version +gems['hiera'] = location_for(hiera_version) if hiera_version - # Puppet < 3.7.0 requires these. - # Puppet >= 3.5.0 gem includes these as requirements. - # The following versions are tested to work with 3.0.0 <= puppet < 3.7.0. - gems['win32-api'] = ['1.4.8', require: false] - gems['win32-taskscheduler'] = ['0.2.2', require: false] - gems['windows-api'] = ['0.4.3', require: false] - gems['windows-pr'] = ['1.2.3', require: false] -elsif Gem.win_platform? +if Gem.win_platform? && puppet_version =~ %r{^(file:///|git://)} # If we're using a Puppet gem on Windows which handles its own win32-xxx gem # dependencies (>= 3.5.0), set the maximum versions (see PUP-6445). gems['win32-dir'] = ['<= 0.4.9', require: false] gems['win32-eventlog'] = ['<= 0.6.5', require: false] gems['win32-process'] = ['<= 0.7.5', require: false] gems['win32-security'] = ['<= 0.2.5', require: false] - gems['win32-service'] = ['<= 0.8.8', require: false] + gems['win32-service'] = ['0.8.8', require: false] end gems.each do |gem_name, gem_params| gem gem_name, *gem_params end # Evaluate Gemfile.local and ~/.gemfile if they exist extra_gemfiles = [ "#{__FILE__}.local", File.join(Dir.home, '.gemfile'), ] extra_gemfiles.each do |gemfile| if File.file?(gemfile) && File.readable?(gemfile) eval(File.read(gemfile), binding) end end # vim: syntax=ruby diff --git a/Rakefile b/Rakefile index a39cae2..d4e36da 100644 --- a/Rakefile +++ b/Rakefile @@ -1,4 +1,6 @@ require 'puppetlabs_spec_helper/rake_tasks' require 'puppet-syntax/tasks/puppet-syntax' -require 'puppet_blacksmith/rake_tasks' -require 'puppet-lint/tasks/puppet-lint' +require 'puppet_blacksmith/rake_tasks' if Bundler.rubygems.find_name('puppet-blacksmith').any? + +PuppetLint.configuration.send('disable_relative') + diff --git a/lib/puppet/provider/postgresql_conf/parsed.rb b/lib/puppet/provider/postgresql_conf/parsed.rb index 40a9cd4..34709df 100644 --- a/lib/puppet/provider/postgresql_conf/parsed.rb +++ b/lib/puppet/provider/postgresql_conf/parsed.rb @@ -1,40 +1,40 @@ require 'puppet/provider/parsedfile' Puppet::Type.type(:postgresql_conf).provide( :parsed, parent: Puppet::Provider::ParsedFile, default_target: '/etc/postgresql.conf', filetype: :flat, ) do desc 'Set key/values in postgresql.conf.' text_line :comment, match: %r{^\s*#} text_line :blank, match: %r{^\s*$} record_line :parsed, - fields: %w[name value comment], - optional: %w[comment], + fields: ['name', 'value', 'comment'], + optional: ['comment'], match: %r{^\s*([\w\.]+)\s*=?\s*(.*?)(?:\s*#\s*(.*))?\s*$}, to_line: proc { |h| # simple string and numeric values don't need to be enclosed in quotes val = if h[:value].is_a?(Numeric) h[:value].to_s else h[:value] end dontneedquote = val.match(%r{^(\d+.?\d+|\w+)$}) dontneedequal = h[:name].match(%r{^(include|include_if_exists)$}i) str = h[:name].downcase # normalize case str += dontneedequal ? ' ' : ' = ' str += "'" unless dontneedquote && !dontneedequal str += val str += "'" unless dontneedquote && !dontneedequal str += " # #{h[:comment]}" unless h[:comment].nil? || h[:comment] == :absent str }, post_parse: proc { |h| h[:name].downcase! # normalize case h[:value].gsub!(%r{(^'|'$)}, '') # strip out quotes } end diff --git a/metadata.json b/metadata.json index 97085c8..b0cc4b8 100644 --- a/metadata.json +++ b/metadata.json @@ -1,81 +1,81 @@ { "name": "puppetlabs-postgresql", "version": "5.4.0", "author": "Inkling/Puppet Labs", "summary": "Offers support for basic management of PostgreSQL databases.", "license": "Apache-2.0", "source": "git://github.com/puppetlabs/puppetlabs-postgresql.git", "project_page": "https://github.com/puppetlabs/puppetlabs-postgresql", "issues_url": "https://tickets.puppetlabs.com/browse/MODULES", "dependencies": [ { "name": "puppetlabs/stdlib", "version_requirement": ">= 4.13.1 < 5.0.0" }, { "name": "puppetlabs/apt", "version_requirement": ">= 2.0.0 < 5.0.0" }, { "name": "puppetlabs/concat", "version_requirement": ">= 1.1.0 < 5.0.0" } ], "operatingsystem_support": [ { "operatingsystem": "RedHat", "operatingsystemrelease": [ "5", "6", "7" ] }, { "operatingsystem": "CentOS", "operatingsystemrelease": [ "5", "6", "7" ] }, { "operatingsystem": "OracleLinux", "operatingsystemrelease": [ "5", "6", "7" ] }, { "operatingsystem": "Scientific", "operatingsystemrelease": [ "5", "6", "7" ] }, { "operatingsystem": "Debian", "operatingsystemrelease": [ "7", "8" ] }, { "operatingsystem": "Ubuntu", "operatingsystemrelease": [ "14.04", "16.04" ] } ], "requirements": [ { "name": "puppet", "version_requirement": ">= 4.7.0 < 6.0.0" } ], - "pdk-version": "1.4.1", - "template-url": "file:///opt/puppetlabs/pdk/share/cache/pdk-templates.git", - "template-ref": "1.4.1-0-g52adbbb" + "pdk-version": "1.5.0", + "template-url": "https://github.com/puppetlabs/pdk-templates", + "template-ref": "heads/master-0-g34e3266" } diff --git a/spec/default_facts.yml b/spec/default_facts.yml new file mode 100644 index 0000000..3248be5 --- /dev/null +++ b/spec/default_facts.yml @@ -0,0 +1,8 @@ +# Use default_module_facts.yml for module specific facts. +# +# Facts specified here will override the values provided by rspec-puppet-facts. +--- +concat_basedir: "/tmp" +ipaddress: "172.16.254.254" +is_pe: false +macaddress: "AA:AA:AA:AA:AA:AA" diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index efd225b..e117192 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,30 +1,36 @@ + require 'puppetlabs_spec_helper/module_spec_helper' require 'rspec-puppet-facts' begin require 'spec_helper_local' if File.file?(File.join(File.dirname(__FILE__), 'spec_helper_local.rb')) rescue LoadError => loaderror warn "Could not require spec_helper_local: #{loaderror.message}" end include RspecPuppetFacts default_facts = { puppetversion: Puppet.version, facterversion: Facter.version, } default_facts_path = File.expand_path(File.join(File.dirname(__FILE__), 'default_facts.yml')) default_module_facts_path = File.expand_path(File.join(File.dirname(__FILE__), 'default_module_facts.yml')) if File.exist?(default_facts_path) && File.readable?(default_facts_path) default_facts.merge!(YAML.safe_load(File.read(default_facts_path))) end if File.exist?(default_module_facts_path) && File.readable?(default_module_facts_path) default_facts.merge!(YAML.safe_load(File.read(default_module_facts_path))) end RSpec.configure do |c| c.default_facts = default_facts + c.before :each do + # set to strictest setting for testing + # by default Puppet runs at warning level + Puppet.settings[:strict] = :warning + end end diff --git a/spec/spec_helper_acceptance.rb b/spec/spec_helper_acceptance.rb index 3332730..bce0da9 100644 --- a/spec/spec_helper_acceptance.rb +++ b/spec/spec_helper_acceptance.rb @@ -1,101 +1,101 @@ require 'puppet' require 'beaker-rspec/spec_helper' require 'beaker-rspec/helpers/serverspec' require 'beaker/puppet_install_helper' require 'beaker/module_install_helper' require 'beaker/task_helper' run_puppet_install_helper install_ca_certs unless pe_install? -UNSUPPORTED_PLATFORMS = %w[AIX windows Solaris Suse].freeze +UNSUPPORTED_PLATFORMS = ['AIX', 'windows', 'Solaris', 'Suse'].freeze install_bolt_on(hosts) unless pe_install? install_module_on(hosts) install_module_dependencies_on(hosts) DEFAULT_PASSWORD = if default[:hypervisor] == 'vagrant' 'vagrant' elsif default[:hypervisor] == 'vcloud' 'Qu@lity!' end +# Class String - unindent - Provide ability to remove indentation from strings, for the purpose of +# left justifying heredoc blocks. class String - # Provide ability to remove indentation from strings, for the purpose of - # left justifying heredoc blocks. def unindent gsub(%r{^#{scan(%r{^\s*}).min_by { |l| l.length }}}, '') end end def shellescape(str) str = str.to_s # An empty argument will be skipped, so return empty quotes. return "''" if str.empty? str = str.dup # Treat multibyte characters as is. It is caller's responsibility # to encode the string in the right encoding for the shell # environment. str.gsub!(%r{([^A-Za-z0-9_\-.,:\/@\n])}, '\\\\\\1') # A LF cannot be escaped with a backslash because a backslash + LF # combo is regarded as line continuation and simply ignored. str.gsub!(%r{\n}, "'\n'") str end def psql(psql_cmd, user = 'postgres', exit_codes = [0, 1], &block) psql = "psql #{psql_cmd}" shell("su #{shellescape(user)} -c #{shellescape(psql)}", acceptable_exit_codes: exit_codes, &block) end RSpec.configure do |c| # Readable test descriptions c.formatter = :documentation # Configure all nodes in nodeset c.before :suite do run_puppet_access_login(user: 'admin') if pe_install? && puppet_version =~ %r{(5\.\d\.\d)} # Set up selinux if appropriate. if fact('osfamily') == 'RedHat' && fact('selinux') == 'true' pp = <<-EOS if $::osfamily == 'RedHat' and $::selinux == 'true' { $semanage_package = $::operatingsystemmajrelease ? { '5' => 'policycoreutils', default => 'policycoreutils-python', } package { $semanage_package: ensure => installed } exec { 'set_postgres': command => 'semanage port -a -t postgresql_port_t -p tcp 5433', path => '/bin:/usr/bin/:/sbin:/usr/sbin', subscribe => Package[$semanage_package], } } EOS apply_manifest_on(agents, pp, catch_failures: false) end # net-tools required for netstat utility being used by be_listening if fact('osfamily') == 'RedHat' && fact('operatingsystemmajrelease') == '7' pp = <<-EOS package { 'net-tools': ensure => installed } EOS apply_manifest_on(agents, pp, catch_failures: false) end hosts.each do |host| on host, 'chmod 755 /root' next unless fact_on(host, 'osfamily') == 'Debian' on host, "echo \"en_US ISO-8859-1\nen_NG.UTF-8 UTF-8\nen_US.UTF-8 UTF-8\n\" > /etc/locale.gen" on host, '/usr/sbin/locale-gen' on host, '/usr/sbin/update-locale' end end end diff --git a/spec/unit/defines/server/grant_spec.rb b/spec/unit/defines/server/grant_spec.rb index 6e97294..850cd88 100644 --- a/spec/unit/defines/server/grant_spec.rb +++ b/spec/unit/defines/server/grant_spec.rb @@ -1,295 +1,295 @@ require 'spec_helper' describe 'postgresql::server::grant', type: :define do let :facts do { osfamily: 'Debian', operatingsystem: 'Debian', operatingsystemrelease: '6.0', kernel: 'Linux', concat_basedir: tmpfilename('contrib'), id: 'root', path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', } end let :title do 'test' end context 'plain' do let :params do { db: 'test', role: 'test', } end let :pre_condition do "class {'postgresql::server':}" end it { is_expected.to compile.with_all_deps } it { is_expected.to contain_postgresql__server__grant('test') } end context 'sequence' do let :params do { db: 'test', role: 'test', privilege: 'usage', object_type: 'sequence', } end let :pre_condition do "class {'postgresql::server':}" end it { is_expected.to compile.with_all_deps } it { is_expected.to contain_postgresql__server__grant('test') } it do is_expected.to contain_postgresql_psql('grant:test') .with_command(%r{GRANT USAGE ON SEQUENCE "test" TO\s* "test"}m) .with_unless(%r{SELECT 1 WHERE has_sequence_privilege\('test',\s* 'test', 'USAGE'\)}m) end end context 'SeQuEnCe case insensitive object_type match' do let :params do { db: 'test', role: 'test', privilege: 'usage', object_type: 'SeQuEnCe', } end let :pre_condition do "class {'postgresql::server':}" end it { is_expected.to compile.with_all_deps } it { is_expected.to contain_postgresql__server__grant('test') } it do is_expected.to contain_postgresql_psql('grant:test') .with_command(%r{GRANT USAGE ON SEQUENCE "test" TO\s* "test"}m) .with_unless(%r{SELECT 1 WHERE has_sequence_privilege\('test',\s* 'test', 'USAGE'\)}m) end end context 'all sequences' do let :params do { db: 'test', role: 'test', privilege: 'usage', object_type: 'all sequences in schema', object_name: 'public', } end let :pre_condition do "class {'postgresql::server':}" end it { is_expected.to compile.with_all_deps } it { is_expected.to contain_postgresql__server__grant('test') } it do is_expected.to contain_postgresql_psql('grant:test') .with_command(%r{GRANT USAGE ON ALL SEQUENCES IN SCHEMA "public" TO\s* "test"}m) .with_unless(%r{SELECT 1 WHERE NOT EXISTS \(\s*SELECT sequence_name\s* FROM information_schema\.sequences\s* WHERE sequence_schema='public'\s* EXCEPT DISTINCT\s* SELECT object_name as sequence_name\s* FROM .* WHERE .*grantee='test'\s* AND object_schema='public'\s* AND privilege_type='USAGE'\s*\)}m) # rubocop:disable Metrics/LineLength end end context 'with specific db connection settings - default port' do let :params do { db: 'test', role: 'test', connect_settings: { 'PGHOST' => 'postgres-db-server', 'DBVERSION' => '9.1' }, } end let :pre_condition do "class {'postgresql::server':}" end it { is_expected.to compile.with_all_deps } it { is_expected.to contain_postgresql__server__grant('test') } it { is_expected.to contain_postgresql_psql('grant:test').with_connect_settings('PGHOST' => 'postgres-db-server', 'DBVERSION' => '9.1').with_port(5432) } end context 'with specific db connection settings - including port' do let :params do { db: 'test', role: 'test', connect_settings: { 'PGHOST' => 'postgres-db-server', 'DBVERSION' => '9.1', 'PGPORT' => '1234' }, } end let :pre_condition do "class {'postgresql::server':}" end it { is_expected.to compile.with_all_deps } it { is_expected.to contain_postgresql__server__grant('test') } it { is_expected.to contain_postgresql_psql('grant:test').with_connect_settings('PGHOST' => 'postgres-db-server', 'DBVERSION' => '9.1', 'PGPORT' => '1234') } end context 'with specific db connection settings - port overriden by explicit parameter' do let :params do { db: 'test', role: 'test', connect_settings: { 'PGHOST' => 'postgres-db-server', 'DBVERSION' => '9.1', 'PGPORT' => '1234' }, port: 5678, } end let :pre_condition do "class {'postgresql::server':}" end it { is_expected.to compile.with_all_deps } it { is_expected.to contain_postgresql__server__grant('test') } it { is_expected.to contain_postgresql_psql('grant:test').with_connect_settings('PGHOST' => 'postgres-db-server', 'DBVERSION' => '9.1', 'PGPORT' => '1234').with_port('5678') } end context 'with specific schema name' do let :params do { db: 'test', role: 'test', privilege: 'all', - object_name: %w[myschema mytable], + object_name: ['myschema', 'mytable'], object_type: 'table', } end let :pre_condition do "class {'postgresql::server':}" end it { is_expected.to compile.with_all_deps } it { is_expected.to contain_postgresql__server__grant('test') } it do is_expected.to contain_postgresql_psql('grant:test') .with_command(%r{GRANT ALL ON TABLE "myschema"."mytable" TO\s* "test"}m) .with_unless(%r{SELECT 1 WHERE has_table_privilege\('test',\s*'myschema.mytable', 'INSERT'\)}m) end end context 'with a role defined' do let :params do { db: 'test', role: 'test', privilege: 'all', - object_name: %w[myschema mytable], + object_name: ['myschema', 'mytable'], object_type: 'table', } end let :pre_condition do <<-EOS class {'postgresql::server':} postgresql::server::role { 'test': } EOS end it { is_expected.to compile.with_all_deps } it { is_expected.to contain_postgresql__server__grant('test') } it { is_expected.to contain_postgresql__server__role('test') } it do is_expected.to contain_postgresql_psql('grant:test') \ .that_requires(['Class[postgresql::server::service]', 'Postgresql::Server::Role[test]']) end end context 'invalid object_type' do let :params do { db: 'test', role: 'test', privilege: 'usage', object_type: 'invalid', } end let :pre_condition do "class {'postgresql::server':}" end it { is_expected.to compile.and_raise_error(%r{parameter 'object_type' expects a match for Pattern}) } end context 'invalid object_name - wrong type' do let :params do { db: 'test', role: 'test', privilege: 'all', object_name: 1, object_type: 'table', } end let :pre_condition do "class {'postgresql::server':}" end it { is_expected.to compile.and_raise_error(%r{parameter 'object_name' expects a value of type (Array|Undef, Array,) or String, got Integer}) } end context 'invalid object_name - insufficent array elements' do let :params do { db: 'test', role: 'test', privilege: 'all', object_name: ['oops'], object_type: 'table', } end let :pre_condition do "class {'postgresql::server':}" end if Puppet::Util::Package.versioncmp(Puppet.version, '5.2.0') >= 0 it { is_expected.to compile.and_raise_error(%r{parameter 'object_name' variant 1 expects size to be 2, got 1}) } else it { is_expected.to compile.and_raise_error(%r{parameter 'object_name' variant 0 expects size to be 2, got 1}) } end end context 'invalid object_name - too many array elements' do let :params do { db: 'test', role: 'test', privilege: 'all', - object_name: %w[myschema mytable oops], + object_name: ['myschema', 'mytable', 'oops'], object_type: 'table', } end let :pre_condition do "class {'postgresql::server':}" end if Puppet::Util::Package.versioncmp(Puppet.version, '5.2.0') >= 0 it { is_expected.to compile.and_raise_error(%r{parameter 'object_name' variant 1 expects size to be 2, got 3}) } else it { is_expected.to compile.and_raise_error(%r{parameter 'object_name' variant 0 expects size to be 2, got 3}) } end end end diff --git a/spec/unit/puppet/provider/postgresql_psql/ruby_spec.rb b/spec/unit/puppet/provider/postgresql_psql/ruby_spec.rb index bc53367..93585bd 100644 --- a/spec/unit/puppet/provider/postgresql_psql/ruby_spec.rb +++ b/spec/unit/puppet/provider/postgresql_psql/ruby_spec.rb @@ -1,107 +1,107 @@ require 'spec_helper' describe Puppet::Type.type(:postgresql_psql).provider(:ruby) do let(:name) { 'rspec psql test' } let(:resource) do Puppet::Type.type(:postgresql_psql).new({ name: name, provider: :ruby }.merge(attributes)) end let(:provider) { resource.provider } context('#run_sql_command') do describe 'with default attributes' do let(:attributes) { { db: 'spec_db' } } it 'executes with the given psql_path on the given DB' do expect(provider).to receive(:run_command).with(['psql', '-d', attributes[:db], '-t', '-c', '"SELECT \'something\' as \"Custom column\""'], 'postgres', 'postgres', {}) provider.run_sql_command('SELECT \'something\' as "Custom column"') end end describe 'with psql_path and db' do let(:attributes) do { psql_path: '/opt/postgres/psql', psql_user: 'spec_user', psql_group: 'spec_group', cwd: '/spec', db: 'spec_db', } end it 'executes with the given psql_path on the given DB' do expect(Dir).to receive(:chdir).with(attributes[:cwd]).and_yield expect(provider).to receive(:run_command).with([attributes[:psql_path], '-d', attributes[:db], '-t', '-c', '"SELECT \'something\' as \"Custom column\""'], attributes[:psql_user], attributes[:psql_group], {}) provider.run_sql_command('SELECT \'something\' as "Custom column"') end end describe 'with search_path string' do let(:attributes) do { search_path: 'schema1', } end it 'executes with the given search_path' do expect(provider).to receive(:run_command).with(['psql', '-t', '-c', '"set search_path to schema1; SELECT \'something\' as \"Custom column\""'], 'postgres', 'postgres', {}) provider.run_sql_command('SELECT \'something\' as "Custom column"') end end describe 'with search_path array' do let(:attributes) do { - search_path: %w[schema1 schema2], + search_path: ['schema1', 'schema2'], } end it 'executes with the given search_path' do expect(provider).to receive(:run_command).with(['psql', '-t', '-c', '"set search_path to schema1,schema2; SELECT \'something\' as \"Custom column\""'], 'postgres', 'postgres', {}) provider.run_sql_command('SELECT \'something\' as "Custom column"') end end end describe 'with port string' do let(:attributes) { { port: '5555' } } it 'executes with the given port' do expect(provider).to receive(:run_command).with(['psql', '-p', '5555', '-t', '-c', '"SELECT something"'], 'postgres', 'postgres', {}) provider.run_sql_command('SELECT something') end end describe 'with connect_settings' do let(:attributes) { { connect_settings: { 'PGHOST' => '127.0.0.1' } } } it 'executes with the given host' do expect(provider).to receive(:run_command).with(['psql', '-t', '-c', '"SELECT something"'], 'postgres', 'postgres', 'PGHOST' => '127.0.0.1') provider.run_sql_command('SELECT something') end end context('#run_unless_sql_command') do let(:attributes) { {} } it 'calls #run_sql_command with SQL' do expect(provider).to receive(:run_sql_command).with('SELECT COUNT(*) FROM (SELECT 1) count') provider.run_unless_sql_command('SELECT 1') end end end diff --git a/spec/unit/puppet/provider/postgresql_replication_slot/ruby_spec.rb b/spec/unit/puppet/provider/postgresql_replication_slot/ruby_spec.rb index 8ac59f7..9b33b64 100644 --- a/spec/unit/puppet/provider/postgresql_replication_slot/ruby_spec.rb +++ b/spec/unit/puppet/provider/postgresql_replication_slot/ruby_spec.rb @@ -1,97 +1,99 @@ require 'spec_helper' type = Puppet::Type.type(:postgresql_replication_slot) describe type.provider(:ruby) do + # class SuccessStatus class SuccessStatus def success? true end end + # class FailStatus class FailStatus def success? false end end let(:name) { 'standby' } let(:resource) do type.new({ name: name, provider: :ruby }.merge(attributes)) end let(:sql_instances) do "abc | | physical | | | t | | | 0/3000420 def | | physical | | | t | | | 0/3000420\n" end let(:success_status) { SuccessStatus.new } let(:fail_status) { FailStatus.new } let(:provider) { resource.provider } context 'when listing instances' do before(:each) do provider.class.expects(:run_command).with(['psql', '-t', '-c', 'SELECT * FROM pg_replication_slots;'], 'postgres', 'postgres').returns([sql_instances, nil]) end let(:attributes) { {} } let(:instances) { provider.class.instances } - let(:expected) { %w[abc def] } + let(:expected) { ['abc', 'def'] } it 'lists instances #size' do expect(instances.size).to eq 2 end it 'lists instances #content' do expected.each_with_index do |expect, index| expect(instances[index].name).to eq expect end end end context 'when creating slot' do let(:attributes) { { ensure: 'present' } } context 'when creation works' do it 'calls psql and succeed' do provider.class.expects(:run_command).with( ['psql', '-t', '-c', "SELECT * FROM pg_create_physical_replication_slot('standby');"], 'postgres', 'postgres' ).returns([nil, success_status]) expect { provider.create }.not_to raise_error end end context 'when creation fails' do it 'calls psql and fail' do provider.class.expects(:run_command).with( ['psql', '-t', '-c', "SELECT * FROM pg_create_physical_replication_slot('standby');"], 'postgres', 'postgres' ).returns([nil, fail_status]) expect { provider.create }.to raise_error(Puppet::Error, %r{Failed to create replication slot standby:}) end end end context 'when destroying slot' do let(:attributes) { { ensure: 'absent' } } context 'when destruction works' do it 'calls psql and succeed' do provider.class.expects(:run_command).with( ['psql', '-t', '-c', "SELECT pg_drop_replication_slot('standby');"], 'postgres', 'postgres' ).returns([nil, success_status]) expect { provider.destroy }.not_to raise_error end end context 'when destruction fails' do it 'calls psql and fail' do provider.class.expects(:run_command).with( ['psql', '-t', '-c', "SELECT pg_drop_replication_slot('standby');"], 'postgres', 'postgres' ).returns([nil, fail_status]) expect { provider.destroy }.to raise_error(Puppet::Error, %r{Failed to destroy replication slot standby:}) end end end end diff --git a/spec/unit/puppet/type/postgresql_psql_spec.rb b/spec/unit/puppet/type/postgresql_psql_spec.rb index ff90022..d479df6 100644 --- a/spec/unit/puppet/type/postgresql_psql_spec.rb +++ b/spec/unit/puppet/type/postgresql_psql_spec.rb @@ -1,265 +1,265 @@ require 'spec_helper' describe Puppet::Type.type(:postgresql_psql) do # rubocop:disable RSpec/MultipleDescribes context 'when validating attributes' do [:name, :unless, :db, :psql_path, :psql_user, :psql_group, :connect_settings].each do |attr| it "should have a #{attr} parameter" do expect(Puppet::Type.type(:postgresql_psql).attrtype(attr)).to eq(:param) end end [:command].each do |attr| it "should have a #{attr} property" do expect(Puppet::Type.type(:postgresql_psql).attrtype(attr)).to eq(:property) end end end end describe Puppet::Type.type(:postgresql_psql), unless: Puppet.features.microsoft_windows? do subject do Puppet::Type.type(:postgresql_psql).new({ name: 'rspec' }.merge(attributes)) end describe 'available attributes' do { name: 'rspec', command: 'SELECT stuff', unless: 'SELECT other,stuff', db: 'postgres', psql_path: '/bin/false', psql_user: 'postgres', psql_group: 'postgres', cwd: '/var/lib', refreshonly: :true, - search_path: %w[schema1 schema2], + search_path: ['schema1', 'schema2'], connect_settings: { 'PGHOST' => 'postgres-db-server', 'DBVERSION' => '9.1' }, }.each do |attr, value| context attr do describe [attr] subject { super()[attr] } let(:attributes) { { attr => value } } it { is_expected.to eq(value) } end end let(:attributes) { {} } context 'default value: [:psql_path]' do subject { super()[:psql_path] } it { is_expected.to eq('psql') } end context 'default value: [:psql_user]' do subject { super()[:psql_user] } it { is_expected.to eq('postgres') } end context 'default value: [:psql_group]' do subject { super()[:psql_group] } it { is_expected.to eq('postgres') } end context 'default value: [:cwd]' do subject { super()[:cwd] } it { is_expected.to eq('/tmp') } end context 'default value: #refreshonly?' do subject { super().refreshonly? } it { is_expected.to be_falsey } end end # rubocop:disable RSpec/NamedSubject # rubocop:disable RSpec/SubjectStub describe '#command' do let(:attributes) { { command: 'SELECT stuff' } } it 'will have the value :notrun if the command should execute' do expect(subject).to receive(:should_run_sql).and_return(true) expect(subject.property(:command).retrieve).to eq(:notrun) end it "will be the 'should' value if the command should not execute" do expect(subject).to receive(:should_run_sql).and_return(false) expect(subject.property(:command).retrieve).to eq('SELECT stuff') end it 'will call provider#run_sql_command on sync' do expect(subject.provider).to receive(:run_sql_command).with('SELECT stuff').and_return(['done', 0]) subject.property(:command).sync end end describe '#unless' do let(:attributes) { { unless: 'SELECT something' } } describe '#matches' do it 'does not fail when the status is successful' do expect(subject.provider).to receive(:run_unless_sql_command).and_return ['1 row returned', 0] subject.parameter(:unless).matches('SELECT something') end it 'returns true when rows are returned' do expect(subject.provider).to receive(:run_unless_sql_command).and_return ['1 row returned', 0] expect(subject.parameter(:unless).matches('SELECT something')).to be_truthy end it 'returns false when no rows are returned' do expect(subject.provider).to receive(:run_unless_sql_command).and_return ['0 rows returned', 0] expect(subject.parameter(:unless).matches('SELECT something')).to be_falsey end it 'raises an error when the sql command fails' do allow(subject.provider).to receive(:run_unless_sql_command).and_return ['Something went wrong', 1] expect { subject.parameter(:unless).matches('SELECT something') }.to raise_error(Puppet::Error, %r{Something went wrong}) end end end describe "#should_run_sql without 'unless'" do [true, :true].each do |refreshonly| context "refreshonly => #{refreshonly.inspect}" do let(:attributes) do { refreshonly: refreshonly } end context 'not refreshing' it { expect(subject.should_run_sql).to be_falsey } end context "refreshonly => #{refreshonly.inspect}" do let(:attributes) do { refreshonly: refreshonly } end context 'refreshing' it { expect(subject.should_run_sql(true)).to be_truthy } end end [false, :false].each do |refreshonly| context "refreshonly => #{refreshonly.inspect}" do let(:attributes) do { refreshonly: refreshonly } end context 'not refreshing' it { expect(subject.should_run_sql).to be_truthy } end context "refreshonly => #{refreshonly.inspect}" do let(:attributes) do { refreshonly: refreshonly } end context 'refreshing' it { expect(subject.should_run_sql(true)).to be_truthy } end end end describe "#should_run_sql with matching 'unless'" do before(:each) { expect(subject.parameter(:unless)).to receive(:matches).with('SELECT something').and_return(true) } # rubocop:disable RSpec/ExpectInHook [true, :true].each do |refreshonly| context "refreshonly => #{refreshonly.inspect}" do let(:attributes) do { refreshonly: refreshonly, unless: 'SELECT something' } end context 'not refreshing' it { expect(subject.should_run_sql).to be_falsey } end context "refreshonly => #{refreshonly.inspect}" do let(:attributes) do { refreshonly: refreshonly, unless: 'SELECT something' } end context 'refreshing' it { expect(subject.should_run_sql(true)).to be_falsey } end end [false, :false].each do |refreshonly| context "refreshonly => #{refreshonly.inspect}" do let(:attributes) do { refreshonly: refreshonly, unless: 'SELECT something' } end context 'not refreshing' it { expect(subject.should_run_sql).to be_falsey } end context "refreshonly => #{refreshonly.inspect}" do let(:attributes) do { refreshonly: refreshonly, unless: 'SELECT something' } end context 'refreshing' it { expect(subject.should_run_sql(true)).to be_falsey } end end end describe "#should_run_sql when not matching 'unless'" do before(:each) { expect(subject.parameter(:unless)).to receive(:matches).with('SELECT something').and_return(false) } # rubocop:disable RSpec/ExpectInHook [true, :true].each do |refreshonly| context "refreshonly => #{refreshonly.inspect}" do let(:attributes) do { refreshonly: refreshonly, unless: 'SELECT something' } end context 'not refreshing' it { expect(subject.should_run_sql).to be_falsey } end context "refreshonly => #{refreshonly.inspect}" do let(:attributes) do { refreshonly: refreshonly, unless: 'SELECT something' } end context 'refreshing' it { expect(subject.should_run_sql(true)).to be_truthy } end end [false, :false].each do |refreshonly| context "refreshonly => #{refreshonly.inspect}" do let(:attributes) do { refreshonly: refreshonly, unless: 'SELECT something' } end context 'not refreshing' it { expect(subject.should_run_sql).to be_truthy } end context "refreshonly => #{refreshonly.inspect}" do let(:attributes) do { refreshonly: refreshonly, unless: 'SELECT something' } end context 'refreshing' it { expect(subject.should_run_sql(true)).to be_truthy } end end end describe '#refresh' do let(:attributes) { {} } it 'syncs command property when command should run' do expect(subject).to receive(:should_run_sql).with(true).and_return(true) expect(subject.property(:command)).to receive(:sync) subject.refresh end it 'does not sync command property when command should not run' do expect(subject).to receive(:should_run_sql).with(true).and_return(false) expect(subject.property(:command)).not_to receive(:sync) subject.refresh end end end