diff --git a/.sync.yml b/.sync.yml index 5850fed..436f1c4 100644 --- a/.sync.yml +++ b/.sync.yml @@ -1,7 +1,11 @@ --- NOTICE: unmanaged: true appveyor.yml: delete: true spec/spec_helper.rb: allow_deprecations: true +.travis.yml: + extras: + - rvm: 2.1.9 + script: bundle exec rake rubocop diff --git a/.travis.yml b/.travis.yml index b5d3180..47c6d8d 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,29 +1,31 @@ #This file is generated by ModuleSync, do not edit. --- sudo: false language: ruby cache: bundler script: "bundle exec rake release_checks" matrix: fast_finish: true include: - rvm: 2.3.1 dist: trusty env: PUPPET_INSTALL_TYPE=agent BEAKER_debug=true BEAKER_set=docker/ubuntu-14.04 script: bundle exec rake beaker services: docker sudo: required - rvm: 2.3.1 dist: trusty env: PUPPET_INSTALL_TYPE=agent BEAKER_debug=true BEAKER_set=docker/centos-7 script: bundle exec rake beaker services: docker sudo: required - rvm: 2.4.1 bundler_args: --without system_tests env: PUPPET_GEM_VERSION="~> 5.0" - rvm: 2.1.9 bundler_args: --without system_tests env: PUPPET_GEM_VERSION="~> 4.0" + - rvm: 2.1.9 + script: bundle exec rake rubocop notifications: email: false diff --git a/lib/puppet/parser/functions/postgresql_acls_to_resources_hash.rb b/lib/puppet/parser/functions/postgresql_acls_to_resources_hash.rb index 2508f85..e9112ca 100644 --- a/lib/puppet/parser/functions/postgresql_acls_to_resources_hash.rb +++ b/lib/puppet/parser/functions/postgresql_acls_to_resources_hash.rb @@ -1,76 +1,75 @@ +# postgresql_acls_to_resources_hash.rb module Puppet::Parser::Functions - newfunction(:postgresql_acls_to_resources_hash, :type => :rvalue, :doc => <<-EOS + newfunction(:postgresql_acls_to_resources_hash, type: :rvalue, doc: <<-EOS This internal function translates the ipv(4|6)acls format into a resource suitable for create_resources. It is not intended to be used outside of the postgresql internal classes/defined resources. This function accepts an array of strings that are pg_hba.conf rules. It will return a hash that can be fed into create_resources to create multiple individual pg_hba_rule resources. The second parameter is an identifier that will be included in the namevar to provide uniqueness. It must be a string. The third parameter is an order offset, so you can start the order at an arbitrary starting point. EOS - ) do |args| - func_name = "postgresql_acls_to_resources_hash()" + ) do |args| + func_name = 'postgresql_acls_to_resources_hash()' - raise(Puppet::ParseError, "#{func_name}: Wrong number of arguments " + - "given (#{args.size} for 3)") if args.size != 3 + if args.size != 3 + raise(Puppet::ParseError, "#{func_name}: Wrong number of arguments " \ + "given (#{args.size} for 3)") + end acls = args[0] raise(Puppet::ParseError, "#{func_name}: first argument must be an array") \ unless acls.instance_of? Array id = args[1] raise(Puppet::ParseError, "#{func_name}: second argument must be a string") \ unless id.instance_of? String offset = args[2].to_i raise(Puppet::ParseError, "#{func_name}: third argument must be a number") \ unless offset.is_a? Integer resources = {} acls.each do |acl| index = acls.index(acl) parts = acl.split - raise(Puppet::ParseError, "#{func_name}: acl line #{index} does not " + - "have enough parts") unless parts.length >= 4 + unless parts.length >= 4 + raise(Puppet::ParseError, "#{func_name}: acl line #{index} does not " \ + 'have enough parts') + end resource = { 'type' => parts[0], 'database' => parts[1], 'user' => parts[2], - 'order' => format('%03d', offset + index), + 'order' => format('%03d', offset + index), # rubocop:disable Style/FormatString } - if parts[0] == 'local' then + if parts[0] == 'local' resource['auth_method'] = parts[3] - if parts.length > 4 then - resource['auth_option'] = parts.last(parts.length - 4).join(" ") + if parts.length > 4 + resource['auth_option'] = parts.last(parts.length - 4).join(' ') end - else - if parts[4] =~ /^\d/ - resource['address'] = parts[3] + ' ' + parts[4] - resource['auth_method'] = parts[5] + elsif parts[4] =~ %r{^\d} + resource['address'] = parts[3] + ' ' + parts[4] + resource['auth_method'] = parts[5] - if parts.length > 6 then - resource['auth_option'] = parts.last(parts.length - 6).join(" ") - end - else - resource['address'] = parts[3] - resource['auth_method'] = parts[4] + resource['auth_option'] = parts.last(parts.length - 6).join(' ') if parts.length > 6 + else + resource['address'] = parts[3] + resource['auth_method'] = parts[4] - if parts.length > 5 then - resource['auth_option'] = parts.last(parts.length - 5).join(" ") - end - end + resource['auth_option'] = parts.last(parts.length - 5).join(' ') if parts.length > 5 end resources["postgresql class generated rule #{id} #{index}"] = resource end resources end end diff --git a/lib/puppet/parser/functions/postgresql_escape.rb b/lib/puppet/parser/functions/postgresql_escape.rb index 1ec11b8..49d6d7e 100644 --- a/lib/puppet/parser/functions/postgresql_escape.rb +++ b/lib/puppet/parser/functions/postgresql_escape.rb @@ -1,25 +1,28 @@ require 'digest/md5' +# postgresql_escape.rb module Puppet::Parser::Functions - newfunction(:postgresql_escape, :type => :rvalue, :doc => <<-EOS + newfunction(:postgresql_escape, type: :rvalue, doc: <<-EOS Safely escapes a string using $$ using a random tag which should be consistent EOS - ) do |args| + ) do |args| - raise(Puppet::ParseError, "postgresql_escape(): Wrong number of arguments " + - "given (#{args.size} for 1)") if args.size != 1 + if args.size != 1 + raise(Puppet::ParseError, 'postgresql_escape(): Wrong number of arguments ' \ + "given (#{args.size} for 1)") + end password = args[0] - if password !~ /\$\$/ and password[-1] != '$' + if password !~ %r{\$\$} && password[-1] != '$' retval = "$$#{password}$$" else - escape = Digest::MD5.hexdigest(password)[0..5].gsub(/\d/,'') - until password !~ /#{escape}/ - escape = Digest::MD5.hexdigest(escape)[0..5].gsub(/\d/,'') + escape = Digest::MD5.hexdigest(password)[0..5].gsub(%r{\d}, '') + until password !~ %r{#{escape}} + escape = Digest::MD5.hexdigest(escape)[0..5].gsub(%r{\d}, '') end retval = "$#{escape}$#{password}$#{escape}$" end retval end end diff --git a/lib/puppet/parser/functions/postgresql_password.rb b/lib/puppet/parser/functions/postgresql_password.rb index e5d2620..e53e5f9 100644 --- a/lib/puppet/parser/functions/postgresql_password.rb +++ b/lib/puppet/parser/functions/postgresql_password.rb @@ -1,18 +1,21 @@ # hash a string as mysql's "PASSWORD()" function would do it require 'digest/md5' +# postgresql_password.rb module Puppet::Parser::Functions - newfunction(:postgresql_password, :type => :rvalue, :doc => <<-EOS + newfunction(:postgresql_password, type: :rvalue, doc: <<-EOS Returns the postgresql password hash from the clear text username / password. EOS - ) do |args| + ) do |args| - raise(Puppet::ParseError, "postgresql_password(): Wrong number of arguments " + - "given (#{args.size} for 2)") if args.size != 2 + if args.size != 2 + raise(Puppet::ParseError, 'postgresql_password(): Wrong number of arguments ' \ + "given (#{args.size} for 2)") + end username = args[0] password = args[1] 'md5' + Digest::MD5.hexdigest(password.to_s + username.to_s) end end diff --git a/lib/puppet/provider/postgresql_conf/parsed.rb b/lib/puppet/provider/postgresql_conf/parsed.rb index 88bd303..40a9cd4 100644 --- a/lib/puppet/provider/postgresql_conf/parsed.rb +++ b/lib/puppet/provider/postgresql_conf/parsed.rb @@ -1,42 +1,40 @@ require 'puppet/provider/parsedfile' Puppet::Type.type(:postgresql_conf).provide( :parsed, - :parent => Puppet::Provider::ParsedFile, - :default_target => '/etc/postgresql.conf', - :filetype => :flat + parent: Puppet::Provider::ParsedFile, + default_target: '/etc/postgresql.conf', + filetype: :flat, ) do - desc "Set key/values in postgresql.conf." + desc 'Set key/values in postgresql.conf.' - text_line :comment, :match => /^\s*#/ - text_line :blank, :match => /^\s*$/ + text_line :comment, match: %r{^\s*#} + text_line :blank, match: %r{^\s*$} record_line :parsed, - :fields => %w{name value comment}, - :optional => %w{comment}, - :match => /^\s*([\w\.]+)\s*=?\s*(.*?)(?:\s*#\s*(.*))?\s*$/, - :to_line => proc { |h| - - # simple string and numeric values don't need to be enclosed in quotes - if h[:value].is_a?(Numeric) - val = h[:value].to_s - else - val = h[:value] - end - dontneedquote = val.match(/^(\d+.?\d+|\w+)$/) - dontneedequal = h[:name].match(/^(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? or h[:comment] == :absent) - str - }, - :post_parse => proc { |h| - h[:name].downcase! # normalize case - h[:value].gsub!(/(^'|'$)/, '') # strip out quotes - } + fields: %w[name value comment], + optional: %w[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/lib/puppet/provider/postgresql_conn_validator/ruby.rb b/lib/puppet/provider/postgresql_conn_validator/ruby.rb index f31b8b9..6e26e52 100644 --- a/lib/puppet/provider/postgresql_conn_validator/ruby.rb +++ b/lib/puppet/provider/postgresql_conn_validator/ruby.rb @@ -1,43 +1,41 @@ -$LOAD_PATH.unshift(File.join(File.dirname(__FILE__),"..","..","..")) +$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', '..', '..')) require 'puppet/util/postgresql_validator' # This file contains a provider for the resource type `postgresql_conn_validator`, # which validates the puppetdb connection by attempting an https connection. Puppet::Type.type(:postgresql_conn_validator).provide(:ruby) do desc "A provider for the resource type `postgresql_conn_validator`, which validates the PostgreSQL connection by attempting a query to the target PostgreSQL server." # Test to see if the resource exists, returns true if it does, false if it # does not. # # Here we simply monopolize the resource API, to execute a test to see if the # database is connectable. When we return a state of `false` it triggers the # create method where we can return an error message. # # @return [bool] did the test succeed? def exists? validator.attempt_connection(resource[:sleep], resource[:tries]) end # This method is called when the exists? method returns false. # # @return [void] def create # If `#create` is called, that means that `#exists?` returned false, which # means that the connection could not be established... so we need to # cause a failure here. raise Puppet::Error, "Unable to connect to PostgreSQL server! (#{resource[:host]}:#{resource[:port]})" end # Returns the existing validator, if one exists otherwise creates a new object # from the class. # # @api private def validator @validator ||= Puppet::Util::PostgresqlValidator.new(resource) end - end - diff --git a/lib/puppet/provider/postgresql_psql/ruby.rb b/lib/puppet/provider/postgresql_psql/ruby.rb index 166c8bc..45e7b07 100644 --- a/lib/puppet/provider/postgresql_psql/ruby.rb +++ b/lib/puppet/provider/postgresql_psql/ruby.rb @@ -1,80 +1,77 @@ Puppet::Type.type(:postgresql_psql).provide(:ruby) do - def run_unless_sql_command(sql) # for the 'unless' queries, we wrap the user's query in a 'SELECT COUNT', # which makes it easier to parse and process the output. - run_sql_command('SELECT COUNT(*) FROM (' << sql << ') count') + run_sql_command('SELECT COUNT(*) FROM (' << sql << ') count') end def run_sql_command(sql) if resource[:search_path] sql = "set search_path to #{Array(resource[:search_path]).join(',')}; #{sql}" end command = [resource[:psql_path]] - command.push("-d", resource[:db]) if resource[:db] - command.push("-p", resource[:port]) if resource[:port] - command.push("-t", "-c", '"' + sql.gsub('"', '\"') + '"') + command.push('-d', resource[:db]) if resource[:db] + command.push('-p', resource[:port]) if resource[:port] + command.push('-t', '-c', '"' + sql.gsub('"', '\"') + '"') environment = get_environment if resource[:cwd] Dir.chdir resource[:cwd] do run_command(command, resource[:psql_user], resource[:psql_group], environment) end else run_command(command, resource[:psql_user], resource[:psql_group], environment) end end private - def get_environment + def get_environment # rubocop:disable Style/AccessorMethodName : Refactor does not work correctly environment = (resource[:connect_settings] || {}).dup - if envlist = resource[:environment] - envlist = [envlist] unless envlist.is_a? Array - envlist.each do |setting| - if setting =~ /^(\w+)=((.|\n)+)$/ - env_name = $1 - value = $2 - if environment.include?(env_name) || environment.include?(env_name.to_sym) - if env_name == 'NEWPGPASSWD' - warning "Overriding environment setting '#{env_name}' with '****'" - else - warning "Overriding environment setting '#{env_name}' with '#{value}'" - end + envlist = resource[:environment] + return environment unless envlist + + envlist = [envlist] unless envlist.is_a? Array + envlist.each do |setting| + if setting =~ %r{^(\w+)=((.|\n)+)$} + env_name = Regexp.last_match(1) + value = Regexp.last_match(2) + if environment.include?(env_name) || environment.include?(env_name.to_sym) + if env_name == 'NEWPGPASSWD' + warning "Overriding environment setting '#{env_name}' with '****'" + else + warning "Overriding environment setting '#{env_name}' with '#{value}'" end - environment[env_name] = value - else - warning "Cannot understand environment setting #{setting.inspect}" end + environment[env_name] = value + else + warning "Cannot understand environment setting #{setting.inspect}" end end - return environment + environment end def run_command(command, user, group, environment) command = command.join ' ' if Puppet::PUPPETVERSION.to_f < 3.0 require 'puppet/util/execution' Puppet::Util::Execution.withenv environment do Puppet::Util::SUIDManager.run_and_capture(command, user, group) end elsif Puppet::PUPPETVERSION.to_f < 3.4 Puppet::Util.withenv environment do Puppet::Util::SUIDManager.run_and_capture(command, user, group) end else - output = Puppet::Util::Execution.execute(command, { - :uid => user, - :gid => group, - :failonfail => false, - :combine => true, - :override_locale => true, - :custom_environment => environment, - }) + output = Puppet::Util::Execution.execute(command, uid: user, + gid: group, + failonfail: false, + combine: true, + override_locale: true, + custom_environment: environment) [output, $CHILD_STATUS.dup] end end - end diff --git a/lib/puppet/provider/postgresql_replication_slot/ruby.rb b/lib/puppet/provider/postgresql_replication_slot/ruby.rb index cc49f7b..b120038 100644 --- a/lib/puppet/provider/postgresql_replication_slot/ruby.rb +++ b/lib/puppet/provider/postgresql_replication_slot/ruby.rb @@ -1,68 +1,59 @@ Puppet::Type.type(:postgresql_replication_slot).provide(:ruby) do # For confinement - commands :psql => 'psql' + commands psql: 'psql' def self.instances - run_sql_command('SELECT * FROM pg_replication_slots;')[0].split("\n").select { |l| l =~ /\|/ }.map do |l| - name, *others = l.strip.split(/\s+\|\s+/) - new({ - :name => name, - :ensure => :present, - }) + run_sql_command('SELECT * FROM pg_replication_slots;')[0].split("\n").select { |l| l =~ %r{\|} }.map do |l| + name, *_others = l.strip.split(%r{\s+\|\s+}) + new(name: name, + ensure: :present) end end def self.prefetch(resources) instances.each do |i| - if slot = resources[i.name] + slot = resources[i.name] + if slot slot.provider = i end end end def exists? @property_hash[:ensure] == :present end def create output = self.class.run_sql_command("SELECT * FROM pg_create_physical_replication_slot('#{resource[:name]}');") - if output[1].success? - @property_hash[:ensure] = :present - else - raise Puppet::Error, "Failed to create replication slot #{resource[:name]}:\n#{output[0]}" - end + raise Puppet::Error, "Failed to create replication slot #{resource[:name]}:\n#{output[0]}" unless output[1].success? + @property_hash[:ensure] = :present end def destroy output = self.class.run_sql_command("SELECT pg_drop_replication_slot('#{resource[:name]}');") - if output[1].success? - @property_hash[:ensure] = :absent - else - raise Puppet::Error, "Failed to destroy replication slot #{resource[:name]}:\n#{output[0]}" - end + raise Puppet::Error, "Failed to destroy replication slot #{resource[:name]}:\n#{output[0]}" unless output[1].success? + @property_hash[:ensure] = :absent end private def self.run_sql_command(sql) command = ['psql', '-t', '-c', sql] - self.run_command(command, 'postgres', 'postgres') + run_command(command, 'postgres', 'postgres') end def self.run_command(command, user, group) if Puppet::PUPPETVERSION.to_f < 3.4 Puppet::Util::SUIDManager.run_and_capture(command, user, group) else - output = Puppet::Util::Execution.execute(command, { - :uid => user, - :gid => group, - :failonfail => false, - :combine => true, - :override_locale => true, - :custom_environment => {} - }) + output = Puppet::Util::Execution.execute(command, uid: user, + gid: group, + failonfail: false, + combine: true, + override_locale: true, + custom_environment: {}) [output, $CHILD_STATUS.dup] end end end diff --git a/lib/puppet/type/postgresql_conf.rb b/lib/puppet/type/postgresql_conf.rb index 6dbaaee..bef52c2 100644 --- a/lib/puppet/type/postgresql_conf.rb +++ b/lib/puppet/type/postgresql_conf.rb @@ -1,29 +1,27 @@ Puppet::Type.newtype(:postgresql_conf) do - - @doc = "This type allows puppet to manage postgresql.conf parameters." + @doc = 'This type allows puppet to manage postgresql.conf parameters.' ensurable newparam(:name) do - desc "The postgresql parameter name to manage." + desc 'The postgresql parameter name to manage.' isnamevar - newvalues(/^[\w\.]+$/) + newvalues(%r{^[\w\.]+$}) end newproperty(:value) do - desc "The value to set for this parameter." + desc 'The value to set for this parameter.' end newproperty(:target) do - desc "The path to postgresql.conf" - defaultto { + desc 'The path to postgresql.conf' + defaultto do if @resource.class.defaultprovider.ancestors.include?(Puppet::Provider::ParsedFile) @resource.class.defaultprovider.default_target else nil end - } + end end - end diff --git a/lib/puppet/type/postgresql_conn_validator.rb b/lib/puppet/type/postgresql_conn_validator.rb index b9dc64e..8a07c6c 100644 --- a/lib/puppet/type/postgresql_conn_validator.rb +++ b/lib/puppet/type/postgresql_conn_validator.rb @@ -1,88 +1,87 @@ Puppet::Type.newtype(:postgresql_conn_validator) do - @doc = "Verify that a connection can be successfully established between a node and the PostgreSQL server. Its primary use is as a precondition to prevent configuration changes from being applied if the PostgreSQL server cannot be reached, but it could potentially be used for other purposes such as monitoring." ensurable do defaultvalues defaultto :present end - newparam(:name, :namevar => true) do + newparam(:name, namevar: true) do desc 'An arbitrary name used as the identity of the resource.' end newparam(:db_name) do - desc "The name of the database you are trying to validate a connection with." + desc 'The name of the database you are trying to validate a connection with.' end newparam(:db_username) do - desc "A user that has access to the target PostgreSQL database." + desc 'A user that has access to the target PostgreSQL database.' end newparam(:db_password) do - desc "The password required to access the target PostgreSQL database." + desc 'The password required to access the target PostgreSQL database.' end newparam(:host) do desc 'The DNS name or IP address of the server where PostgreSQL should be running.' end newparam(:port) do desc 'The port that the PostgreSQL server should be listening on.' validate do |value| Integer(value) end munge do |value| Integer(value) end end newparam(:connect_settings) do desc 'Hash of environment variables for connection to a db.' end newparam(:sleep) do - desc "The length of sleep time between connection tries." + desc 'The length of sleep time between connection tries.' validate do |value| Integer(value) end munge do |value| Integer(value) end defaultto 2 end newparam(:tries) do - desc "The number of tries to validate the connection to the target PostgreSQL database." + desc 'The number of tries to validate the connection to the target PostgreSQL database.' validate do |value| Integer(value) end munge do |value| Integer(value) end defaultto 10 end newparam(:psql_path) do - desc "Path to the psql command." + desc 'Path to the psql command.' end newparam(:run_as) do - desc "System user that will run the psql command." + desc 'System user that will run the psql command.' end newparam(:command) do - desc "Command to run against target database." + desc 'Command to run against target database.' - defaultto "SELECT 1" + defaultto 'SELECT 1' end end diff --git a/lib/puppet/type/postgresql_psql.rb b/lib/puppet/type/postgresql_psql.rb index 5b2702c..1e7b2c4 100644 --- a/lib/puppet/type/postgresql_psql.rb +++ b/lib/puppet/type/postgresql_psql.rb @@ -1,135 +1,135 @@ Puppet::Type.newtype(:postgresql_psql) do - newparam(:name) do - desc "An arbitrary tag for your own reference; the name of the message." + desc 'An arbitrary tag for your own reference; the name of the message.' isnamevar end newproperty(:command) do desc 'The SQL command to execute via psql.' defaultto { @resource[:name] } # If needing to run the SQL command, return a fake value that will trigger # a sync, else return the expected SQL command so no sync takes place def retrieve if @resource.should_run_sql - return :notrun + :notrun else - return self.should + should end end def sync output, status = provider.run_sql_command(value) - self.fail("Error executing SQL; psql returned #{status}: '#{output}'") unless status == 0 + raise("Error executing SQL; psql returned #{status}: '#{output}'") unless status == 0 # rubocop:disable Style/NumericPredicate end end newparam(:unless) do - desc "An optional SQL command to execute prior to the main :command; " + - "this is generally intended to be used for idempotency, to check " + - "for the existence of an object in the database to determine whether " + - "or not the main SQL command needs to be executed at all." + desc 'An optional SQL command to execute prior to the main :command; ' \ + 'this is generally intended to be used for idempotency, to check ' \ + 'for the existence of an object in the database to determine whether ' \ + 'or not the main SQL command needs to be executed at all.' # Return true if a matching row is found def matches(value) output, status = provider.run_unless_sql_command(value) - self.fail("Error evaluating 'unless' clause, returned #{status}: '#{output}'") unless status == 0 + # rubocop:disable Style/NumericPredicate + fail("Error evaluating 'unless' clause, returned #{status}: '#{output}'") unless status == 0 # rubocop:disable Style/SignalException + # rubocop:enable Style/NumericPredicate result_count = output.strip.to_i - self.debug("Found #{result_count} row(s) executing 'unless' clause") + debug("Found #{result_count} row(s) executing 'unless' clause") result_count > 0 end end newparam(:onlyif) do - desc "An optional SQL command to execute prior to the main :command; " + - "this is generally intended to be used for idempotency, to check " + - "for the existence of an object in the database to determine whether " + - "or not the main SQL command needs to be executed at all." + desc 'An optional SQL command to execute prior to the main :command; ' \ + 'this is generally intended to be used for idempotency, to check ' \ + 'for the existence of an object in the database to determine whether ' \ + 'or not the main SQL command needs to be executed at all.' # Return true if a matching row is found def matches(value) output, status = provider.run_unless_sql_command(value) status = output.exitcode if status.nil? - self.fail("Error evaluating 'onlyif' clause, returned #{status}: '#{output}'") unless status == 0 + raise("Error evaluating 'onlyif' clause, returned #{status}: '#{output}'") unless status == 0 # rubocop:disable Style/NumericPredicate result_count = output.strip.to_i - self.debug("Found #{result_count} row(s) executing 'onlyif' clause") + debug("Found #{result_count} row(s) executing 'onlyif' clause") result_count > 0 end end newparam(:connect_settings) do - desc "Connection settings that will be used when connecting to postgres" + desc 'Connection settings that will be used when connecting to postgres' end newparam(:db) do - desc "The name of the database to execute the SQL command against, this overrides any PGDATABASE value in connect_settings" + desc 'The name of the database to execute the SQL command against, this overrides any PGDATABASE value in connect_settings' end newparam(:port) do - desc "The port of the database server to execute the SQL command against, this overrides any PGPORT value in connect_settings." + desc 'The port of the database server to execute the SQL command against, this overrides any PGPORT value in connect_settings.' end newparam(:search_path) do - desc "The schema search path to use when executing the SQL command" + desc 'The schema search path to use when executing the SQL command' end newparam(:psql_path) do - desc "The path to psql executable." - defaultto("psql") + desc 'The path to psql executable.' + defaultto('psql') end newparam(:psql_user) do - desc "The system user account under which the psql command should be executed." - defaultto("postgres") + desc 'The system user account under which the psql command should be executed.' + defaultto('postgres') end newparam(:psql_group) do - desc "The system user group account under which the psql command should be executed." - defaultto("postgres") + desc 'The system user group account under which the psql command should be executed.' + defaultto('postgres') end - newparam(:cwd, :parent => Puppet::Parameter::Path) do - desc "The working directory under which the psql command should be executed." - defaultto("/tmp") + newparam(:cwd, parent: Puppet::Parameter::Path) do + desc 'The working directory under which the psql command should be executed.' + defaultto('/tmp') end newparam(:environment) do desc "Any additional environment variables you want to set for a SQL command. Multiple environment variables should be specified as an array." validate do |values| Array(values).each do |value| - unless value =~ /\w+=/ + unless value =~ %r{\w+=} raise ArgumentError, "Invalid environment setting '#{value}'" end end end end - newparam(:refreshonly, :boolean => true) do + newparam(:refreshonly, boolean: true) do desc "If 'true', then the SQL will only be executed via a notify/subscribe event." defaultto(:false) newvalues(:true, :false) end def should_run_sql(refreshing = false) onlyif_param = @parameters[:onlyif] unless_param = @parameters[:unless] return false if !onlyif_param.nil? && !onlyif_param.value.nil? && !onlyif_param.matches(onlyif_param.value) return false if !unless_param.nil? && !unless_param.value.nil? && unless_param.matches(unless_param.value) return false if !refreshing && @parameters[:refreshonly].value == :true true end def refresh - self.property(:command).sync if self.should_run_sql(true) + property(:command).sync if should_run_sql(true) end - end diff --git a/lib/puppet/type/postgresql_replication_slot.rb b/lib/puppet/type/postgresql_replication_slot.rb index b5b317c..c489cc3 100644 --- a/lib/puppet/type/postgresql_replication_slot.rb +++ b/lib/puppet/type/postgresql_replication_slot.rb @@ -1,16 +1,16 @@ Puppet::Type.newtype(:postgresql_replication_slot) do @doc = "Manages Postgresql replication slots. This type allows to create and destroy replication slots to register warm standby replication on a Postgresql master server. " ensurable newparam(:name) do - desc "The name of the slot to create. Must be a valid replication slot name." + desc 'The name of the slot to create. Must be a valid replication slot name.' isnamevar - newvalues /^[a-z0-9_]+$/ + newvalues %r{^[a-z0-9_]+$} end end diff --git a/lib/puppet/util/postgresql_validator.rb b/lib/puppet/util/postgresql_validator.rb index d737f12..972f936 100644 --- a/lib/puppet/util/postgresql_validator.rb +++ b/lib/puppet/util/postgresql_validator.rb @@ -1,65 +1,64 @@ -module Puppet - module Util - class PostgresqlValidator - attr_reader :resource +module Puppet::Util + # postgresql_validator.rb + class PostgresqlValidator + attr_reader :resource - def initialize(resource) - @resource = resource - end - - def build_psql_cmd - final_cmd = [] + def initialize(resource) + @resource = resource + end - cmd_init = "#{@resource[:psql_path]} --tuples-only --quiet --no-psqlrc" + def build_psql_cmd + final_cmd = [] - final_cmd.push cmd_init + cmd_init = "#{@resource[:psql_path]} --tuples-only --quiet --no-psqlrc" - cmd_parts = { - :host => "--host #{@resource[:host]}", - :port => "--port #{@resource[:port]}", - :db_username => "--username #{@resource[:db_username]}", - :db_name => "--dbname #{@resource[:db_name]}", - :command => "--command '#{@resource[:command]}'" - } + final_cmd.push cmd_init - cmd_parts.each do |k,v| - final_cmd.push v if @resource[k] - end + cmd_parts = { + host: "--host #{@resource[:host]}", + port: "--port #{@resource[:port]}", + db_username: "--username #{@resource[:db_username]}", + db_name: "--dbname #{@resource[:db_name]}", + command: "--command '#{@resource[:command]}'", + } - final_cmd.join ' ' + cmd_parts.each do |k, v| + final_cmd.push v if @resource[k] end - def parse_connect_settings - c_settings = @resource[:connect_settings] || {} - c_settings.merge! ({ 'PGPASSWORD' => @resource[:db_password] }) if @resource[:db_password] - return c_settings.map { |k,v| "#{k}=#{v}" } - end + final_cmd.join ' ' + end - def attempt_connection(sleep_length, tries) - (0..tries-1).each do |try| - Puppet.debug "PostgresqlValidator.attempt_connection: Attempting connection to #{@resource[:db_name]}" - Puppet.debug "PostgresqlValidator.attempt_connection: #{build_validate_cmd}" - result = execute_command - if result && result.length > 0 - Puppet.debug "PostgresqlValidator.attempt_connection: Connection to #{@resource[:db_name] || parse_connect_settings.select { |elem| elem.match /PGDATABASE/ }} successful!" - return true - else - Puppet.warning "PostgresqlValidator.attempt_connection: Sleeping for #{sleep_length} seconds" - sleep sleep_length - end + def parse_connect_settings + c_settings = @resource[:connect_settings] || {} + c_settings['PGPASSWORD'] = @resource[:db_password] if @resource[:db_password] + c_settings.map { |k, v| "#{k}=#{v}" } + end + + def attempt_connection(sleep_length, tries) + (0..tries - 1).each do |_try| + Puppet.debug "PostgresqlValidator.attempt_connection: Attempting connection to #{@resource[:db_name]}" + Puppet.debug "PostgresqlValidator.attempt_connection: #{build_validate_cmd}" + result = execute_command + if result && !result.empty? + Puppet.debug "PostgresqlValidator.attempt_connection: Connection to #{@resource[:db_name] || parse_connect_settings.select { |elem| elem.match %r{PGDATABASE} }} successful!" + return true + else + Puppet.warning "PostgresqlValidator.attempt_connection: Sleeping for #{sleep_length} seconds" + sleep sleep_length end - false end + false + end - private + private - def execute_command - Execution.execute(build_validate_cmd, :uid => @resource[:run_as]) - end + def execute_command + Execution.execute(build_validate_cmd, uid: @resource[:run_as]) + end - def build_validate_cmd - "#{parse_connect_settings.join(' ')} #{build_psql_cmd} " - end + def build_validate_cmd + "#{parse_connect_settings.join(' ')} #{build_psql_cmd} " end end end diff --git a/spec/acceptance/00-utf8_encoding_spec.rb b/spec/acceptance/00-utf8_encoding_spec.rb index 2e7770b..e98762c 100644 --- a/spec/acceptance/00-utf8_encoding_spec.rb +++ b/spec/acceptance/00-utf8_encoding_spec.rb @@ -1,37 +1,33 @@ -require 'spec_helper_acceptance' +require 'spec_helper_acceptance' # rubocop:disable Style/FileName # These tests are designed to ensure that the module, when ran with defaults, # sets up everything correctly and allows us to connect to Postgres. -describe 'postgresql::server', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do - it 'with defaults' do - pp = <<-EOS +describe 'postgresql::server', unless: UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do + pp = <<-MANIFEST class { 'postgresql::globals': encoding => 'UTF8', locale => 'en_NG', } -> class { 'postgresql::server': } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => true) + MANIFEST + it 'with defaults' do + apply_manifest(pp, catch_failures: true) + apply_manifest(pp, catch_changes: true) end describe port(5432) do it { is_expected.to be_listening } end it 'can connect with psql' do psql('--command="\l" postgres', 'postgres') do |r| - expect(r.stdout).to match(/List of databases/) + expect(r.stdout).to match(%r{List of databases}) end end it 'must set UTF8 as template1 encoding' do psql('--command="SELECT pg_encoding_to_char(encoding) FROM pg_database WHERE datname=\'template1\'"') do |r| - expect(r.stdout).to match(/UTF8/) + expect(r.stdout).to match(%r{UTF8}) end end end - - - diff --git a/spec/acceptance/alternative_port_spec.rb b/spec/acceptance/alternative_port_spec.rb index 11094d3..6bf56b7 100644 --- a/spec/acceptance/alternative_port_spec.rb +++ b/spec/acceptance/alternative_port_spec.rb @@ -1,28 +1,24 @@ require 'spec_helper_acceptance' # These tests ensure that postgres can change itself to an alternative port # properly. -describe 'postgresql::server', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do +describe 'postgresql::server', unless: UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do it 'on an alternative port' do - pp = <<-EOS + pp = <<-MANIFEST class { 'postgresql::server': port => '55433' } - EOS + MANIFEST - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => true) + apply_manifest(pp, catch_failures: true) + apply_manifest(pp, catch_changes: true) end - describe port(55433) do + describe port(55433) do # rubocop:disable Style/NumericLiterals it { is_expected.to be_listening } end it 'can connect with psql' do psql('-p 55433 --command="\l" postgres', 'postgres') do |r| - expect(r.stdout).to match(/List of databases/) + expect(r.stdout).to match(%r{List of databases}) end end - end - - - diff --git a/spec/acceptance/db_spec.rb b/spec/acceptance/db_spec.rb index 0285c3f..2e89d32 100644 --- a/spec/acceptance/db_spec.rb +++ b/spec/acceptance/db_spec.rb @@ -1,54 +1,57 @@ require 'spec_helper_acceptance' -describe 'postgresql::server::db', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do +describe 'postgresql::server::db', unless: UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do + # rubocop:disable RSpec/ExampleLength + # rubocop:disable RSpec/MultipleExpectations + # rubocop:disable Metrics/LineLength it 'creates a database' do begin tmpdir = default.tmpdir('postgresql') - pp = <<-EOS + pp = <<-MANIFEST class { 'postgresql::server': postgres_password => 'space password', } postgresql::server::tablespace { 'postgresql-test-db': location => '#{tmpdir}', } -> postgresql::server::db { 'postgresql-test-db': comment => 'testcomment', user => 'test-user', password => 'test1', tablespace => 'postgresql-test-db', } - EOS + MANIFEST - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => true) + apply_manifest(pp, catch_failures: true) + apply_manifest(pp, catch_changes: true) # Verify that the postgres password works shell("echo 'localhost:*:*:postgres:\'space password\'' > /root/.pgpass") - shell("chmod 600 /root/.pgpass") + shell('chmod 600 /root/.pgpass') shell("psql -U postgres -h localhost --command='\\l'") psql('--command="select datname from pg_database" "postgresql-test-db"') do |r| - expect(r.stdout).to match(/postgresql-test-db/) + expect(r.stdout).to match(%r{postgresql-test-db}) expect(r.stderr).to eq('') end psql('--command="SELECT 1 FROM pg_roles WHERE rolname=\'test-user\'"') do |r| - expect(r.stdout).to match(/\(1 row\)/) + expect(r.stdout).to match(%r{\(1 row\)}) end result = shell('psql --version') version = result.stdout.match(%r{\s(\d\.\d)})[1] - if version > "8.1" - comment_information_function = "shobj_description" - else - comment_information_function = "obj_description" - end + comment_information_function = if version > '8.1' + 'shobj_description' + else + 'obj_description' + end psql("--dbname postgresql-test-db --command=\"SELECT pg_catalog.#{comment_information_function}(d.oid, 'pg_database') FROM pg_catalog.pg_database d WHERE datname = 'postgresql-test-db' AND pg_catalog.#{comment_information_function}(d.oid, 'pg_database') = 'testcomment'\"") do |r| - expect(r.stdout).to match(/\(1 row\)/) + expect(r.stdout).to match(%r{\(1 row\)}) end ensure psql('--command=\'drop database "postgresql-test-db" postgres\'') psql('--command="DROP USER test"') end end end diff --git a/spec/acceptance/default_parameters_spec.rb b/spec/acceptance/default_parameters_spec.rb index 4763482..eb132e4 100644 --- a/spec/acceptance/default_parameters_spec.rb +++ b/spec/acceptance/default_parameters_spec.rb @@ -1,28 +1,24 @@ require 'spec_helper_acceptance' # These tests are designed to ensure that the module, when ran with defaults, # sets up everything correctly and allows us to connect to Postgres. -describe 'postgresql::server', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do +describe 'postgresql::server', unless: UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do it 'with defaults' do - pp = <<-EOS + pp = <<-MANIFEST class { 'postgresql::server': } - EOS + MANIFEST - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => true) + apply_manifest(pp, catch_failures: true) + apply_manifest(pp, catch_changes: true) end describe port(5432) do it { is_expected.to be_listening } end it 'can connect with psql' do psql('--command="\l" postgres', 'postgres') do |r| - expect(r.stdout).to match(/List of databases/) + expect(r.stdout).to match(%r{List of databases}) end end - end - - - diff --git a/spec/acceptance/postgresql_conn_validator_spec.rb b/spec/acceptance/postgresql_conn_validator_spec.rb index 20d8422..dfc116e 100644 --- a/spec/acceptance/postgresql_conn_validator_spec.rb +++ b/spec/acceptance/postgresql_conn_validator_spec.rb @@ -1,76 +1,73 @@ require 'spec_helper_acceptance' -describe 'postgresql_conn_validator', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do - - let(:install_pp) { <<-EOS - class { 'postgresql::server': - postgres_password => 'space password', - }-> - postgresql::server::role { 'testuser': - password_hash => postgresql_password('testuser','test1'), - }-> - postgresql::server::database { 'testdb': - owner => 'testuser', - require => Postgresql::Server::Role['testuser'] - }-> - postgresql::server::database_grant { 'allow connect for testuser': - privilege => 'ALL', - db => 'testdb', - role => 'testuser', - } - - EOS - - } +describe 'postgresql_conn_validator', unless: UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do + let(:install_pp) do + <<-MANIFEST + class { 'postgresql::server': + postgres_password => 'space password', + }-> + postgresql::server::role { 'testuser': + password_hash => postgresql_password('testuser','test1'), + }-> + postgresql::server::database { 'testdb': + owner => 'testuser', + require => Postgresql::Server::Role['testuser'] + }-> + postgresql::server::database_grant { 'allow connect for testuser': + privilege => 'ALL', + db => 'testdb', + role => 'testuser', + } + MANIFEST + end context 'local connection' do - it 'validates successfully with defaults' do - pp = <<-EOS + it 'validates successfully with defaults' do # rubocop:disable RSpec/ExampleLength + pp = <<-MANIFEST #{install_pp}-> postgresql_conn_validator { 'validate this': db_name => 'testdb', db_username => 'testuser', db_password => 'test1', host => 'localhost', psql_path => '/usr/bin/psql', } - EOS + MANIFEST - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => true) + apply_manifest(pp, catch_failures: true) + apply_manifest(pp, catch_changes: true) end - it 'works with connect settings hash' do - pp = <<-EOS + it 'works with connect settings hash' do # rubocop:disable RSpec/ExampleLength + pp = <<-MANIFEST #{install_pp}-> postgresql_conn_validator { 'validate this': connect_settings => { 'PGDATABASE' => 'testdb', 'PGPORT' => '5432', 'PGUSER' => 'testuser', 'PGPASSWORD' => 'test1', 'PGHOST' => 'localhost' }, psql_path => '/usr/bin/psql' } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => true) + MANIFEST + apply_manifest(pp, catch_failures: true) + apply_manifest(pp, catch_changes: true) end - it 'fails gracefully' do - pp = <<-EOS + it 'fails gracefully' do # rubocop:disable RSpec/ExampleLength + pp = <<-MANIFEST #{install_pp}-> postgresql_conn_validator { 'validate this': psql_path => '/usr/bin/psql', tries => 3 } - EOS + MANIFEST result = apply_manifest(pp) - expect(result.stderr).to match /Unable to connect to PostgreSQL server/ + expect(result.stderr).to match %r{Unable to connect to PostgreSQL server} end end end diff --git a/spec/acceptance/postgresql_psql_spec.rb b/spec/acceptance/postgresql_psql_spec.rb index 34a258c..6362bc9 100644 --- a/spec/acceptance/postgresql_psql_spec.rb +++ b/spec/acceptance/postgresql_psql_spec.rb @@ -1,183 +1,173 @@ require 'spec_helper_acceptance' -describe 'postgresql_psql', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do - - it 'should always run SQL' do - pp = <<-EOS - class { 'postgresql::server': } -> - postgresql_psql { 'foobar': - db => 'postgres', - psql_user => 'postgres', - command => 'select 1', - } - EOS +describe 'postgresql_psql', unless: UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do + pp_one = <<-MANIFEST + class { 'postgresql::server': } -> + postgresql_psql { 'foobar': + db => 'postgres', + psql_user => 'postgres', + command => 'select 1', + } + MANIFEST + it 'alwayses run SQL' do + apply_manifest(pp_one, catch_failures: true) + apply_manifest(pp_one, expect_changes: true) + end - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :expect_changes => true) + pp_two = <<-MANIFEST + class { 'postgresql::server': } -> + postgresql_psql { 'foobar': + db => 'postgres', + psql_user => 'postgres', + command => 'select 1', + unless => 'select 1 where 1=2', + } + MANIFEST + it 'runs some SQL when the unless query returns no rows' do + apply_manifest(pp_two, catch_failures: true) + apply_manifest(pp_two, expect_changes: true) end - it 'should run some SQL when the unless query returns no rows' do - pp = <<-EOS - class { 'postgresql::server': } -> - postgresql_psql { 'foobar': - db => 'postgres', - psql_user => 'postgres', - command => 'select 1', - unless => 'select 1 where 1=2', - } - EOS + pp_three = <<-MANIFEST + class { 'postgresql::server': } -> + postgresql_psql { 'foobar': + db => 'postgres', + psql_user => 'postgres', + command => 'select * from pg_database limit 1', + unless => 'select 1 where 1=1', + } + MANIFEST + it 'does not run SQL when the unless query returns rows' do + apply_manifest(pp_three, catch_failures: true) + apply_manifest(pp_three, catch_changes: true) + end - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :expect_changes => true) + pp_four = <<-MANIFEST + class { 'postgresql::server': } -> + notify { 'trigger': } ~> + postgresql_psql { 'foobar': + db => 'postgres', + psql_user => 'postgres', + command => 'invalid sql statement', + unless => 'select 1 where 1=1', + } + MANIFEST + it 'does not run SQL when refreshed and the unless query returns rows' do + apply_manifest(pp_four, catch_failures: true) + apply_manifest(pp_four, expect_changes: true) end - it 'should not run SQL when the unless query returns rows' do - pp = <<-EOS + context 'with refreshonly' do + pp_five = <<-MANIFEST class { 'postgresql::server': } -> postgresql_psql { 'foobar': - db => 'postgres', - psql_user => 'postgres', - command => 'select * from pg_database limit 1', - unless => 'select 1 where 1=1', + db => 'postgres', + psql_user => 'postgres', + command => 'select 1', + unless => 'select 1 where 1=2', + refreshonly => true, } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => true) - end + MANIFEST + it 'does not run SQL when the unless query returns no rows' do + apply_manifest(pp_five, catch_failures: true) + apply_manifest(pp_five, catch_changes: true) + end - it 'should not run SQL when refreshed and the unless query returns rows' do - pp = <<-EOS + pp_six = <<-MANIFEST.unindent class { 'postgresql::server': } -> notify { 'trigger': } ~> postgresql_psql { 'foobar': - db => 'postgres', - psql_user => 'postgres', - command => 'invalid sql statement', - unless => 'select 1 where 1=1', + db => 'postgres', + psql_user => 'postgres', + command => 'select 1', + unless => 'select 1 where 1=2', + refreshonly => true, } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :expect_changes => true) - end - - context 'with refreshonly' do - it 'should not run SQL when the unless query returns no rows' do - pp = <<-EOS - class { 'postgresql::server': } -> - postgresql_psql { 'foobar': - db => 'postgres', - psql_user => 'postgres', - command => 'select 1', - unless => 'select 1 where 1=2', - refreshonly => true, - } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => true) + MANIFEST + it 'runs SQL when refreshed and the unless query returns no rows' do + apply_manifest(pp_six, catch_failures: true) + apply_manifest(pp_six, expect_changes: true) end - it 'should run SQL when refreshed and the unless query returns no rows' do - pp = <<-EOS.unindent - class { 'postgresql::server': } -> - notify { 'trigger': } ~> - postgresql_psql { 'foobar': - db => 'postgres', - psql_user => 'postgres', - command => 'select 1', - unless => 'select 1 where 1=2', - refreshonly => true, - } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :expect_changes => true) - end - - it 'should not run SQL when refreshed and the unless query returns rows' do - pp = <<-EOS.unindent - class { 'postgresql::server': } -> - notify { 'trigger': } ~> - postgresql_psql { 'foobar': - db => 'postgres', - psql_user => 'postgres', - command => 'invalid sql query', - unless => 'select 1 where 1=1', - refreshonly => true, - } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :expect_changes => true) - end - end - - it 'should not run some SQL when the onlyif query returns no rows' do - pp = <<-EOS + pp_seven = <<-MANIFEST.unindent class { 'postgresql::server': } -> + notify { 'trigger': } ~> postgresql_psql { 'foobar': - db => 'postgres', - psql_user => 'postgres', - command => 'select 1', - onlyif => 'select 1 where 1=2', + db => 'postgres', + psql_user => 'postgres', + command => 'invalid sql query', + unless => 'select 1 where 1=1', + refreshonly => true, } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => true) + MANIFEST + it 'does not run SQL when refreshed and the unless query returns rows' do + apply_manifest(pp_seven, catch_failures: true) + apply_manifest(pp_seven, expect_changes: true) + end end - it 'should run SQL when the onlyif query returns rows' do - pp = <<-EOS - class { 'postgresql::server': } -> - postgresql_psql { 'foobar': - db => 'postgres', - psql_user => 'postgres', - command => 'select * from pg_database limit 1', - onlyif => 'select 1 where 1=1', - } - EOS + pp_eight = <<-MANIFEST + class { 'postgresql::server': } -> + postgresql_psql { 'foobar': + db => 'postgres', + psql_user => 'postgres', + command => 'select 1', + onlyif => 'select 1 where 1=2', + } + MANIFEST + it 'does not run some SQL when the onlyif query returns no rows' do + apply_manifest(pp_eight, catch_failures: true) + apply_manifest(pp_eight, catch_changes: true) + end - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :expect_changes => true) + pp_nine = <<-MANIFEST + class { 'postgresql::server': } -> + postgresql_psql { 'foobar': + db => 'postgres', + psql_user => 'postgres', + command => 'select * from pg_database limit 1', + onlyif => 'select 1 where 1=1', + } + MANIFEST + it 'runs SQL when the onlyif query returns rows' do + apply_manifest(pp_nine, catch_failures: true) + apply_manifest(pp_nine, expect_changes: true) end context 'with secure password passing by environment' do - it 'should run SQL that contanins password passed by environment' do + it 'runs SQL that contanins password passed by environment' do # rubocop:disable RSpec/ExampleLength select = "select \\'$PASS_TO_EMBED\\'" - pp = <<-EOS.unindent + pp = <<-MANIFEST.unindent class { 'postgresql::server': } -> postgresql_psql { 'password embedded by environment: #{select}': db => 'postgres', psql_user => 'postgres', command => '#{select}', environment => [ 'PASS_TO_EMBED=pa$swD', ], } - EOS - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :expect_changes => false) + MANIFEST + apply_manifest(pp, catch_failures: true) + apply_manifest(pp, expect_changes: false) end - it 'should run SQL that contanins password passed by environment in check' do + it 'runs SQL that contanins password passed by environment in check' do # rubocop:disable RSpec/ExampleLength select = "select 1 where \\'$PASS_TO_EMBED\\'=\\'passwD\\'" - pp = <<-EOS.unindent + pp = <<-MANIFEST.unindent class { 'postgresql::server': } -> postgresql_psql { 'password embedded by environment in check: #{select}': db => 'postgres', psql_user => 'postgres', command => 'invalid sql query', unless => '#{select}', environment => [ 'PASS_TO_EMBED=passwD', ], } - EOS + MANIFEST - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :expect_changes => false) + apply_manifest(pp, catch_failures: true) + apply_manifest(pp, expect_changes: false) end end end diff --git a/spec/acceptance/remote_access_spec.rb b/spec/acceptance/remote_access_spec.rb index 9dd31de..f801f37 100644 --- a/spec/acceptance/remote_access_spec.rb +++ b/spec/acceptance/remote_access_spec.rb @@ -1,72 +1,71 @@ require 'spec_helper_acceptance' -describe 'remote-access', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do - before do - skip "These tests require the spec/acceptance/nodesets/centos-64-x64-2-hosts nodeset" +describe 'remote-access', unless: UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do + before(:each) do + skip 'These tests require the spec/acceptance/nodesets/centos-64-x64-2-hosts nodeset' end - describe "configuring multi-node postgresql" do - + describe 'configuring multi-node postgresql' do # Get the database's IP to connect to from the database let(:database_ip_address) do - hosts_as('database').inject({}) do |memo,host| - fact_on host, "ipaddress_eth1" + hosts_as('database').reduce({}) do |_memo, host| + fact_on host, 'ipaddress_eth1' end end hosts_as('database').each do |host| - it "should be able to configure a host as database on #{host}" do - pp = <<-EOS + pp_one = <<-MANIFEST # Stop firewall so we can easily connect service {'iptables': ensure => 'stopped', } class { 'postgresql::server': ip_mask_allow_all_users => '0.0.0.0/0', listen_addresses => '*', } postgresql::server::db { 'puppet': user => 'puppet', password => postgresql_password('puppet', 'puppet'), } postgresql::server::pg_hba_rule { 'allow full yolo access password': type => 'host', database => 'all', user => 'all', address => '0.0.0.0/0', auth_method => 'password', order => '002', } - EOS - apply_manifest_on(host, pp, :catch_failures => true) + MANIFEST + it "should be able to configure a host as database on #{host}" do + apply_manifest_on(host, pp_one, catch_failures: true) end end hosts_as('client').each do |host| - it "should be able to configure a host as client on #{host} and then access database" do - pp = <<-EOS + pp_two = <<-MANIFEST class { 'postgresql::client':} $connection_settings = { 'PGUSER' => "puppet", 'PGPASSWORD' => "puppet", 'PGHOST' => "#{database_ip_address}", 'PGPORT' => "5432", 'PGDATABASE' => "puppet", } postgresql_psql { 'run using connection_settings': command => 'select 1', psql_user => 'root', psql_group => 'root', connect_settings => $connection_settings, } - EOS - apply_manifest_on(host, pp, :catch_failures => true) + MANIFEST + it "should be able to configure a host as client on #{host} and then access database" do + apply_manifest_on(host, pp_two, catch_failures: true) end end end end diff --git a/spec/acceptance/server/config_entry_spec.rb b/spec/acceptance/server/config_entry_spec.rb index 6e56259..c606a0d 100644 --- a/spec/acceptance/server/config_entry_spec.rb +++ b/spec/acceptance/server/config_entry_spec.rb @@ -1,38 +1,39 @@ require 'spec_helper_acceptance' describe 'postgresql::server::config_entry' do - - let(:pp_setup) { <<-EOS + let(:pp_setup) do + <<-MANIFEST class { 'postgresql::server': postgresql_conf_path => '/tmp/postgresql.conf', } - EOS - } + MANIFEST + end context 'unix_socket_directories' do - let(:pp_test) { pp_setup + <<-EOS + let(:pp_test) do + pp_setup + <<-MANIFEST postgresql::server::config_entry { 'unix_socket_directories': value => '/var/socket/, /root/' } - EOS - } + MANIFEST + end - #get postgresql version + # get postgresql version apply_manifest("class { 'postgresql::server': }") result = shell('psql --version') version = result.stdout.match(%r{\s(\d\.\d)})[1] if version >= '9.3' it 'is expected to run idempotently' do - apply_manifest(pp_test, :catch_failures => true) - apply_manifest(pp_test, :catch_changes => true) + apply_manifest(pp_test, catch_failures: true) + apply_manifest(pp_test, catch_changes: true) end it 'is expected to contain directories' do shell('cat /tmp/postgresql.conf') do |output| expect(output.stdout).to contain("unix_socket_directories = '/var/socket/, /root/'") end end end end end diff --git a/spec/acceptance/server/grant_role_spec.rb b/spec/acceptance/server/grant_role_spec.rb index 552c2f5..90d62ab 100644 --- a/spec/acceptance/server/grant_role_spec.rb +++ b/spec/acceptance/server/grant_role_spec.rb @@ -1,259 +1,263 @@ require 'spec_helper_acceptance' -describe 'postgresql::server::grant_role:', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do - +describe 'postgresql::server::grant_role:', unless: UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do let(:db) { 'grant_role_test' } let(:user) { 'psql_grant_role_tester' } let(:group) { 'test_group' } let(:password) { 'psql_grant_role_pw' } let(:version) do - if fact('osfamily') == 'RedHat' and fact('operatingsystemrelease') =~ /5/ + if fact('osfamily') == 'RedHat' && fact('operatingsystemrelease') =~ %r{5} '8.1' end end + let(:pp_one) do + <<-MANIFEST.unindent + $db = #{db} + $user = #{user} + $group = #{group} + $password = #{password} + $version = '#{version}' + + class { 'postgresql::server': } + + # Since we are not testing pg_hba or any of that, make a local user for ident auth + user { $user: + ensure => present, + } + + postgresql::server::role { $user: + password_hash => postgresql_password($user, $password), + } + + postgresql::server::database { $db: + owner => $user, + require => Postgresql::Server::Role[$user], + } + + # Lets setup the base rules + $local_auth_option = $version ? { + '8.1' => 'sameuser', + default => undef, + } + + # Create a rule for the user + postgresql::server::pg_hba_rule { "allow ${user}": + type => 'local', + database => $db, + user => $user, + auth_method => 'ident', + auth_option => $local_auth_option, + order => 1, + } + + # Create a role to grant to the user + postgresql::server::role { $group: + db => $db, + login => false, + require => Postgresql::Server::Database[$db], + } + + # Grant the role to the user + postgresql::server::grant_role { "grant_role ${group} to ${user}": + role => $user, + group => $group, + } + MANIFEST + end + let(:pp_two) do + <<-MANIFEST.unindent + $db = #{db} + $user = #{user} + $group = #{group} + $password = #{password} + $version = '#{version}' + + class { 'postgresql::server': } + + # Since we are not testing pg_hba or any of that, make a local user for ident auth + user { $user: + ensure => present, + } + + postgresql::server::role { $user: + password_hash => postgresql_password($user, $password), + } + + postgresql::server::database { $db: + owner => $user, + require => Postgresql::Server::Role[$user], + } + + # Lets setup the base rules + $local_auth_option = $version ? { + '8.1' => 'sameuser', + default => undef, + } + + # Create a rule for the user + postgresql::server::pg_hba_rule { "allow ${user}": + type => 'local', + database => $db, + user => $user, + auth_method => 'ident', + auth_option => $local_auth_option, + order => 1, + } + + # Create a role to grant to the user + postgresql::server::role { $group: + db => $db, + login => false, + require => Postgresql::Server::Database[$db], + } + + # Grant the role to the user + postgresql::server::grant_role { "grant_role ${group} to ${user}": + role => $user, + group => $group, + } + MANIFEST + end + let(:pp_three) do + <<-MANIFEST + $db = "#{db}" + $user = "#{user}" + $group = "#{group}" + $password = #{password} + $version = '#{version}' + + class { 'postgresql::server': } + + # Since we are not testing pg_hba or any of that, make a local user for ident auth + user { $user: + ensure => present, + } + + postgresql::server::role { $user: + password_hash => postgresql_password($user, $password), + } + + postgresql::server::database { $db: + owner => $user, + require => Postgresql::Server::Role[$user], + } + + # Lets setup the base rules + $local_auth_option = $version ? { + '8.1' => 'sameuser', + default => undef, + } + + # Create a rule for the user + postgresql::server::pg_hba_rule { "allow ${user}": + type => 'local', + database => $db, + user => $user, + auth_method => 'ident', + auth_option => $local_auth_option, + order => 1, + } + + # Create a role to grant to the user + postgresql::server::role { $group: + db => $db, + login => false, + require => Postgresql::Server::Database[$db], + } + + # Grant the role to the user + postgresql::server::grant_role { "grant_role ${group} to ${user}": + role => $user, + group => $group, + } + + postgresql::server::grant_role {"revoke ${group} from ${user}": + ensure => absent, + role => $user, + group => $group, + } + MANIFEST + end + let(:pp_four) do + <<-MANIFEST + $db = "#{db}" + $user = "#{user}" + $group = "#{group}" + $password = #{password} + + class { 'postgresql::server': } + + # Since we are not testing pg_hba or any of that, make a local user for ident auth + user { $user: + ensure => absent, + } + + postgresql::server::database { $db: + } + + # Create a role to grant to the nonexistent user + postgresql::server::role { $group: + db => $db, + login => false, + require => Postgresql::Server::Database[$db], + } + + # Grant the role to the nonexistent user + postgresql::server::grant_role { "grant_role ${group} to ${user}": + role => $user + group => $group, + } + MANIFEST + end - it 'should grant a role to a user' do + # rubocop:disable RSpec/ExampleLength + # rubocop:disable RSpec/MultipleExpectations + it 'grants a role to a user' do begin - pp = <<-EOS.unindent - $db = #{db} - $user = #{user} - $group = #{group} - $password = #{password} - $version = '#{version}' - - class { 'postgresql::server': } - - # Since we are not testing pg_hba or any of that, make a local user for ident auth - user { $user: - ensure => present, - } - - postgresql::server::role { $user: - password_hash => postgresql_password($user, $password), - } - - postgresql::server::database { $db: - owner => $user, - require => Postgresql::Server::Role[$user], - } - - # Lets setup the base rules - $local_auth_option = $version ? { - '8.1' => 'sameuser', - default => undef, - } - - # Create a rule for the user - postgresql::server::pg_hba_rule { "allow ${user}": - type => 'local', - database => $db, - user => $user, - auth_method => 'ident', - auth_option => $local_auth_option, - order => 1, - } - - # Create a role to grant to the user - postgresql::server::role { $group: - db => $db, - login => false, - require => Postgresql::Server::Database[$db], - } - - # Grant the role to the user - postgresql::server::grant_role { "grant_role ${group} to ${user}": - role => $user, - group => $group, - } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => true) + apply_manifest(pp_one, catch_failures: true) + apply_manifest(pp_one, catch_changes: true) ## Check that the role was granted to the user psql('--command="SELECT 1 WHERE pg_has_role(\'psql_grant_role_tester\', \'test_group\', \'MEMBER\') = true" grant_role_test', 'psql_grant_role_tester') do |r| - expect(r.stdout).to match(/\(1 row\)/) + expect(r.stdout).to match(%r{\(1 row\)}) expect(r.stderr).to eq('') end end end - it 'should grant a role to a superuser' do + it 'grants a role to a superuser' do begin - pp = <<-EOS.unindent - $db = "#{db}" - $user = "#{user}" - $group = "#{group}" - $password = #{password} - $version = '#{version}' - - class { 'postgresql::server': } - - # Since we are not testing pg_hba or any of that, make a local user for ident auth - user { $user: - ensure => present, - } - - postgresql::server::role { $user: - password_hash => postgresql_password($user, $password), - superuser => true, - } - - postgresql::server::database { $db: - owner => $user, - require => Postgresql::Server::Role[$user], - } - - # Lets setup the base rules - $local_auth_option = $version ? { - '8.1' => 'sameuser', - default => undef, - } - - # Create a rule for the user - postgresql::server::pg_hba_rule { "allow ${user}": - type => 'local', - database => $db, - user => $user, - auth_method => 'ident', - auth_option => $local_auth_option, - order => 1, - } - - # Create a role to grant to the user - postgresql::server::role { $group: - db => $db, - login => false, - require => Postgresql::Server::Database[$db], - } - - # Grant the role to the user - postgresql::server::grant_role { "grant_role ${group} to ${user}": - role => $user, - group => $group, - } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => true) + apply_manifest(pp_two, catch_failures: true) + apply_manifest(pp_two, catch_changes: true) ## Check that the role was granted to the user - psql('--command="SELECT 1 FROM pg_roles AS r_role JOIN pg_auth_members AS am ON r_role.oid = am.member JOIN pg_roles AS r_group ON r_group.oid = am.roleid WHERE r_group.rolname = \'test_group\' AND r_role.rolname = \'psql_grant_role_tester\'" grant_role_test', 'psql_grant_role_tester') do |r| - expect(r.stdout).to match(/\(1 row\)/) + psql('--command="SELECT 1 FROM pg_roles AS r_role JOIN pg_auth_members AS am ON r_role.oid = am.member JOIN pg_roles AS r_group ON r_group.oid = am.roleid WHERE r_group.rolname = \'test_group\' AND r_role.rolname = \'psql_grant_role_tester\'" grant_role_test', 'psql_grant_role_tester') do |r| # rubocop:disable Metrics/LineLength + expect(r.stdout).to match(%r{\(1 row\)}) expect(r.stderr).to eq('') end end end - it 'should revoke a role from a user' do + it 'revokes a role from a user' do begin - pp = <<-EOS - - $db = "#{db}" - $user = "#{user}" - $group = "#{group}" - $password = #{password} - $version = '#{version}' - - class { 'postgresql::server': } - - # Since we are not testing pg_hba or any of that, make a local user for ident auth - user { $user: - ensure => present, - } - - postgresql::server::role { $user: - password_hash => postgresql_password($user, $password), - } - - postgresql::server::database { $db: - owner => $user, - require => Postgresql::Server::Role[$user], - } - - # Lets setup the base rules - $local_auth_option = $version ? { - '8.1' => 'sameuser', - default => undef, - } - - # Create a rule for the user - postgresql::server::pg_hba_rule { "allow ${user}": - type => 'local', - database => $db, - user => $user, - auth_method => 'ident', - auth_option => $local_auth_option, - order => 1, - } - - # Create a role to grant to the user - postgresql::server::role { $group: - db => $db, - login => false, - require => Postgresql::Server::Database[$db], - } - - # Grant the role to the user - postgresql::server::grant_role { "grant_role ${group} to ${user}": - role => $user, - group => $group, - } - - postgresql::server::grant_role {"revoke ${group} from ${user}": - ensure => absent, - role => $user, - group => $group, - } - EOS - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :expect_changes => true) + apply_manifest(pp_three, catch_failures: true) + apply_manifest(pp_three, expect_changes: true) psql('--command="SELECT 1 WHERE pg_has_role(\'psql_grant_role_tester\', \'test_group\', \'MEMBER\') = true" grant_role_test', 'psql_grant_role_tester') do |r| - expect(r.stdout).to match(/\(0 rows\)/) + expect(r.stdout).to match(%r{\(0 rows\)}) expect(r.stderr).to eq('') end end end - it 'should not grant permission to a nonexistent user' do - begin - pp = <<-EOS - - $db = "#{db}" - $user = "#{user}" - $group = "#{group}" - $password = #{password} - - class { 'postgresql::server': } - - # Since we are not testing pg_hba or any of that, make a local user for ident auth - user { $user: - ensure => absent, - } - - postgresql::server::database { $db: - } - - # Create a role to grant to the nonexistent user - postgresql::server::role { $group: - db => $db, - login => false, - require => Postgresql::Server::Database[$db], - } - - # Grant the role to the nonexistent user - postgresql::server::grant_role { "grant_role ${group} to ${user}": - role => $user - group => $group, - } - EOS - apply_manifest(pp, :expect_failures => true) - - psql('--command="SELECT 1 WHERE pg_has_role(\'psql_grant_role_tester\', \'test_group\', \'MEMBER\') = true" grant_role_test', 'psql_grant_role_tester') do |r| - expect(r.stdout).to match(/\(0 rows\)/) - expect(r.stderr).to eq('') - end - end - end + it 'does not grant permission to a nonexistent user' do + begin + apply_manifest(pp_four, expect_failures: true) + + psql('--command="SELECT 1 WHERE pg_has_role(\'psql_grant_role_tester\', \'test_group\', \'MEMBER\') = true" grant_role_test', 'psql_grant_role_tester') do |r| + expect(r.stdout).to match(%r{\(0 rows\)}) + expect(r.stderr).to eq('') + end + end + end end diff --git a/spec/acceptance/server/grant_spec.rb b/spec/acceptance/server/grant_spec.rb index 63f2d7e..dd7f8a7 100644 --- a/spec/acceptance/server/grant_spec.rb +++ b/spec/acceptance/server/grant_spec.rb @@ -1,306 +1,307 @@ require 'spec_helper_acceptance' -describe 'postgresql::server::grant:', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do - +describe 'postgresql::server::grant:', unless: UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do + # rubocop:disable RSpec/ExampleLength + # rubocop:disable RSpec/MultipleExpectations let(:db) { 'grant_priv_test' } let(:owner) { 'psql_grant_priv_owner' } let(:user) { 'psql_grant_priv_tester' } let(:password) { 'psql_grant_role_pw' } - let(:pp_install) { "class {'postgresql::server': }"} - - let(:pp_setup) { pp_setup = <<-EOS.unindent - $db = #{db} - $owner = #{owner} - $user = #{user} - $password = #{password} - - class { 'postgresql::server': } - - postgresql::server::role { $owner: - password_hash => postgresql_password($owner, $password), - } - - # Since we are not testing pg_hba or any of that, make a local user for ident auth - user { $owner: - ensure => present, - } - - postgresql::server::database { $db: - owner => $owner, - require => Postgresql::Server::Role[$owner], - } - - # Create a user to grant privileges to - postgresql::server::role { $user: - db => $db, - require => Postgresql::Server::Database[$db], - } - - # Make a local user for ident auth - user { $user: - ensure => present, - } - - # Grant them connect to the database - postgresql::server::database_grant { "allow connect for ${user}": - privilege => 'CONNECT', - db => $db, - role => $user, - } - EOS - } + let(:pp_install) { "class {'postgresql::server': }" } + let(:pp_setup) do + <<-MANIFEST.unindent + $db = #{db} + $owner = #{owner} + $user = #{user} + $password = #{password} + + class { 'postgresql::server': } + + postgresql::server::role { $owner: + password_hash => postgresql_password($owner, $password), + } + + # Since we are not testing pg_hba or any of that, make a local user for ident auth + user { $owner: + ensure => present, + } + + postgresql::server::database { $db: + owner => $owner, + require => Postgresql::Server::Role[$owner], + } + + # Create a user to grant privileges to + postgresql::server::role { $user: + db => $db, + require => Postgresql::Server::Database[$db], + } + + # Make a local user for ident auth + user { $user: + ensure => present, + } + + # Grant them connect to the database + postgresql::server::database_grant { "allow connect for ${user}": + privilege => 'CONNECT', + db => $db, + role => $user, + } + MANIFEST + end context 'LANGUAGE' do describe 'GRANT * ON LANGUAGE' do - #testing grants on language requires a superuser + # testing grants on language requires a superuser let(:superuser) { 'postgres' } - let(:pp_lang) { pp_setup + <<-EOS.unindent - + let(:pp_lang) do + pp_setup + <<-MANIFEST.unindent postgresql_psql { 'make sure plpgsql exists': command => 'CREATE LANGUAGE plpgsql', db => $db, psql_user => '#{superuser}', unless => "SELECT 1 from pg_language where lanname = 'plpgsql'", require => Postgresql::Server::Database[$db], } postgresql::server::grant { 'grant usage on plpgsql': psql_user => '#{superuser}', privilege => 'USAGE', object_type => 'LANGUAGE', object_name => 'plpgsql', role => $user, db => $db, require => [ Postgresql_psql['make sure plpgsql exists'], Postgresql::Server::Role[$user], ] } - EOS - } - - it 'is expected to run idempotently' do - apply_manifest(pp_install) - - #postgres version - result = shell('psql --version') - version = result.stdout.match(%r{\s(\d\.\d)})[1] - - if version >= '8.4.0' - apply_manifest(pp_lang, :catch_failures => true) - apply_manifest(pp_lang, :catch_changes => true) - end - end - - it 'is expected to GRANT USAGE ON LANGUAGE plpgsql to ROLE' do - result = shell('psql --version') - version = result.stdout.match(%r{\s(\d\.\d)})[1] - - if version >= '8.4.0' - ## Check that the privilege was granted to the user - psql("-d #{db} --command=\"SELECT 1 WHERE has_language_privilege('#{user}', 'plpgsql', 'USAGE')\"", superuser) do |r| - expect(r.stdout).to match(/\(1 row\)/) - expect(r.stderr).to eq('') - end - end - end - - let(:pp_onlyif) { pp_setup + <<-EOS.unindent + MANIFEST + end + let(:pp_onlyif) do + pp_setup + <<-MANIFEST.unindent postgresql::server::grant { 'grant usage on BSql': psql_user => '#{superuser}', privilege => 'USAGE', object_type => 'LANGUAGE', object_name => 'bsql', role => $user, db => $db, onlyif_exists => true, } - EOS - } + MANIFEST + end + + it 'is expected to run idempotently' do + apply_manifest(pp_install) + + # postgres version + result = shell('psql --version') + version = result.stdout.match(%r{\s(\d\.\d)})[1] + + if version >= '8.4.0' + apply_manifest(pp_lang, catch_failures: true) + apply_manifest(pp_lang, catch_changes: true) + end + end - #test onlyif_exists function + it 'is expected to GRANT USAGE ON LANGUAGE plpgsql to ROLE' do + result = shell('psql --version') + version = result.stdout.match(%r{\s(\d\.\d)})[1] + + if version >= '8.4.0' + ## Check that the privilege was granted to the user + psql("-d #{db} --command=\"SELECT 1 WHERE has_language_privilege('#{user}', 'plpgsql', 'USAGE')\"", superuser) do |r| + expect(r.stdout).to match(%r{\(1 row\)}) + expect(r.stderr).to eq('') + end + end + end + + # test onlyif_exists function it 'is expected to not GRANT USAGE ON (dummy)LANGUAGE BSql to ROLE' do apply_manifest(pp_install) - #postgres version + # postgres version result = shell('psql --version') version = result.stdout.match(%r{\s(\d\.\d)})[1] if version >= '8.4.0' - apply_manifest(pp_onlyif, :catch_failures => true) - apply_manifest(pp_onlyif, :catch_changes => true) + apply_manifest(pp_onlyif, catch_failures: true) + apply_manifest(pp_onlyif, catch_changes: true) end end end end context 'sequence' do - it 'should grant usage on a sequence to a user' do - begin - pp = pp_setup + <<-EOS.unindent - + let(:pp_one) do + pp_setup + <<-MANIFEST.unindent postgresql_psql { 'create test sequence': command => 'CREATE SEQUENCE test_seq', db => $db, psql_user => $owner, unless => "SELECT 1 FROM information_schema.sequences WHERE sequence_name = 'test_seq'", require => Postgresql::Server::Database[$db], } postgresql::server::grant { 'grant usage on test_seq': privilege => 'USAGE', object_type => 'SEQUENCE', object_name => 'test_seq', db => $db, role => $user, require => [ Postgresql_psql['create test sequence'], Postgresql::Server::Role[$user], ] } - EOS - - apply_manifest(pp_install, :catch_failures => true) - - #postgres version - result = shell('psql --version') - version = result.stdout.match(%r{\s(\d\.\d)})[1] - - if version >= '9.0' - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => true) - - ## Check that the privilege was granted to the user - psql("-d #{db} --command=\"SELECT 1 WHERE has_sequence_privilege('#{user}', 'test_seq', 'USAGE')\"", user) do |r| - expect(r.stdout).to match(/\(1 row\)/) - expect(r.stderr).to eq('') - end - end - end + MANIFEST end - - it 'should grant update on a sequence to a user' do - begin - pp = pp_setup + <<-EOS.unindent - + let(:pp_two) do + pp_setup + <<-MANIFEST.unindent postgresql_psql { 'create test sequence': command => 'CREATE SEQUENCE test_seq', db => $db, psql_user => $owner, unless => "SELECT 1 FROM information_schema.sequences WHERE sequence_name = 'test_seq'", require => Postgresql::Server::Database[$db], } postgresql::server::grant { 'grant update on test_seq': privilege => 'UPDATE', object_type => 'SEQUENCE', object_name => 'test_seq', db => $db, role => $user, require => [ Postgresql_psql['create test sequence'], Postgresql::Server::Role[$user], ] } - EOS + MANIFEST + end + let(:result) do + shell('psql --version') + end + let(:version) do + result.stdout.match(%r{\s(\d\.\d)})[1] + end - apply_manifest(pp_install, :catch_failures => true) + before(:each) do + apply_manifest(pp_install, catch_failures: true) + end - #postgres version - result = shell('psql --version') - version = result.stdout.match(%r{\s(\d\.\d)})[1] + it 'grants usage on a sequence to a user' do + begin + if version >= '9.0' + apply_manifest(pp_one, catch_failures: true) + apply_manifest(pp_one, catch_changes: true) + ## Check that the privilege was granted to the user + psql("-d #{db} --command=\"SELECT 1 WHERE has_sequence_privilege('#{user}', 'test_seq', 'USAGE')\"", user) do |r| + expect(r.stdout).to match(%r{\(1 row\)}) + expect(r.stderr).to eq('') + end + end + end + end + + it 'grants update on a sequence to a user' do + begin if version >= '9.0' - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => true) + apply_manifest(pp_two, catch_failures: true) + apply_manifest(pp_two, catch_changes: true) ## Check that the privilege was granted to the user psql("-d #{db} --command=\"SELECT 1 WHERE has_sequence_privilege('#{user}', 'test_seq', 'UPDATE')\"", user) do |r| - expect(r.stdout).to match(/\(1 row\)/) + expect(r.stdout).to match(%r{\(1 row\)}) expect(r.stderr).to eq('') end end end end end context 'all sequences' do - it 'should grant usage on all sequences to a user' do - begin - pp = pp_setup + <<-EOS.unindent + let(:pp_one) do + pp_setup + <<-MANIFEST.unindent postgresql_psql { 'create test sequences': command => 'CREATE SEQUENCE test_seq2; CREATE SEQUENCE test_seq3;', db => $db, psql_user => $owner, unless => "SELECT 1 FROM information_schema.sequences WHERE sequence_name = 'test_seq2'", require => Postgresql::Server::Database[$db], } postgresql::server::grant { 'grant usage on all sequences': privilege => 'USAGE', object_type => 'ALL SEQUENCES IN SCHEMA', object_name => 'public', db => $db, role => $user, require => [ Postgresql_psql['create test sequences'], Postgresql::Server::Role[$user], ] } - EOS - - apply_manifest(pp_install, :catch_failures => true) - - #postgres version - result = shell('psql --version') - version = result.stdout.match(%r{\s(\d\.\d)})[1] - - if version >= '9.0' - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => true) - - ## Check that the privileges were granted to the user, this check is not available on version < 9.0 - psql("-d #{db} --command=\"SELECT 1 WHERE has_sequence_privilege('#{user}', 'test_seq2', 'USAGE') AND has_sequence_privilege('#{user}', 'test_seq3', 'USAGE')\"", user) do |r| - expect(r.stdout).to match(/\(1 row\)/) - expect(r.stderr).to eq('') - end - end - end + MANIFEST end - - it 'should grant update on all sequences to a user' do - begin - pp = pp_setup + <<-EOS.unindent + let(:pp_two) do + pp_setup + <<-MANIFEST.unindent postgresql_psql { 'create test sequences': command => 'CREATE SEQUENCE test_seq2; CREATE SEQUENCE test_seq3;', db => $db, psql_user => $owner, unless => "SELECT 1 FROM information_schema.sequences WHERE sequence_name = 'test_seq2'", require => Postgresql::Server::Database[$db], } postgresql::server::grant { 'grant usage on all sequences': privilege => 'UPDATE', object_type => 'ALL SEQUENCES IN SCHEMA', object_name => 'public', db => $db, role => $user, require => [ Postgresql_psql['create test sequences'], Postgresql::Server::Role[$user], ] } - EOS + MANIFEST + end + let(:result) do + shell('psql --version') + end + let(:version) do + result.stdout.match(%r{\s(\d\.\d)})[1] + end - apply_manifest(pp_install, :catch_failures => true) + before(:each) do + apply_manifest(pp_install, catch_failures: true) + end - #postgres version - result = shell('psql --version') - version = result.stdout.match(%r{\s(\d\.\d)})[1] + it 'grants usage on all sequences to a user' do + begin + if version >= '9.0' + apply_manifest(pp_one, catch_failures: true) + apply_manifest(pp_one, catch_changes: true) + + ## Check that the privileges were granted to the user, this check is not available on version < 9.0 + psql("-d #{db} --command=\"SELECT 1 WHERE has_sequence_privilege('#{user}', 'test_seq2', 'USAGE') AND has_sequence_privilege('#{user}', 'test_seq3', 'USAGE')\"", user) do |r| + expect(r.stdout).to match(%r{\(1 row\)}) + expect(r.stderr).to eq('') + end + end + end + end + it 'grants update on all sequences to a user' do + begin if version >= '9.0' - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => true) + apply_manifest(pp_two, catch_failures: true) + apply_manifest(pp_two, catch_changes: true) ## Check that the privileges were granted to the user psql("-d #{db} --command=\"SELECT 1 WHERE has_sequence_privilege('#{user}', 'test_seq2', 'UPDATE') AND has_sequence_privilege('#{user}', 'test_seq3', 'UPDATE')\"", user) do |r| - expect(r.stdout).to match(/\(1 row\)/) + expect(r.stdout).to match(%r{\(1 row\)}) expect(r.stderr).to eq('') end end end end end end diff --git a/spec/acceptance/server/reassign_owned_by_spec.rb b/spec/acceptance/server/reassign_owned_by_spec.rb index fc6c9cd..86db4c1 100644 --- a/spec/acceptance/server/reassign_owned_by_spec.rb +++ b/spec/acceptance/server/reassign_owned_by_spec.rb @@ -1,134 +1,140 @@ require 'spec_helper_acceptance' -describe 'postgresql::server::reassign_owned_by:', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do - +describe 'postgresql::server::reassign_owned_by:', unless: UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do let(:db) { 'reassign_test' } let(:old_owner) { 'psql_reassign_old_owner' } let(:new_owner) { 'psql_reassign_new_owner' } let(:password) { 'psql_reassign_pw' } let(:superuser) { 'postgres' } - let(:pp_setup) { pp_setup = <<-EOS.unindent - $db = #{db} - $old_owner = #{old_owner} - $new_owner = #{new_owner} - $password = #{password} - - class { 'postgresql::server': } - - postgresql::server::role { $old_owner: - password_hash => postgresql_password($old_owner, $password), - } - - # Since we are not testing pg_hba or any of that, make a local user for ident auth - user { $old_owner: - ensure => present, - } - - # Create a user to reassign ownership to - postgresql::server::role { $new_owner: - db => $db, - require => Postgresql::Server::Database[$db], - } - - # Make a local user for ident auth - user { $new_owner: - ensure => present, - } - - # Grant the new owner membership of the old owner (must have both for REASSIGN OWNED BY to work) - postgresql::server::grant_role { "grant_role to ${new_owner}": - role => $new_owner, - group => $old_owner, - } - - # Grant them connect to the database - postgresql::server::database_grant { "allow connect for ${old_owner}": - privilege => 'CONNECT', - db => $db, - role => $old_owner, - } - EOS - } - - let(:pp_db_old_owner) { <<-EOS.unindent - postgresql::server::database { $db: - owner => $old_owner, - require => Postgresql::Server::Role[$old_owner], - } - EOS - } - - let(:pp_db_no_owner) { <<-EOS.unindent - postgresql::server::database { $db: - } - EOS - } + let(:pp_setup) do + <<-MANIFEST.unindent + $db = #{db} + $old_owner = #{old_owner} + $new_owner = #{new_owner} + $password = #{password} + + class { 'postgresql::server': } + + postgresql::server::role { $old_owner: + password_hash => postgresql_password($old_owner, $password), + } + + # Since we are not testing pg_hba or any of that, make a local user for ident auth + user { $old_owner: + ensure => present, + } + + # Create a user to reassign ownership to + postgresql::server::role { $new_owner: + db => $db, + require => Postgresql::Server::Database[$db], + } + + # Make a local user for ident auth + user { $new_owner: + ensure => present, + } + + # Grant the new owner membership of the old owner (must have both for REASSIGN OWNED BY to work) + postgresql::server::grant_role { "grant_role to ${new_owner}": + role => $new_owner, + group => $old_owner, + } + + # Grant them connect to the database + postgresql::server::database_grant { "allow connect for ${old_owner}": + privilege => 'CONNECT', + db => $db, + role => $old_owner, + } + MANIFEST + end + + let(:pp_db_old_owner) do + <<-MANIFEST.unindent + postgresql::server::database { $db: + owner => $old_owner, + require => Postgresql::Server::Role[$old_owner], + } + MANIFEST + end + + let(:pp_db_no_owner) do + <<-MANIFEST.unindent + postgresql::server::database { $db: + } + MANIFEST + end context 'reassign_owned_by' do describe 'REASSIGN OWNED BY tests' do let(:db) { 'reassign_test' } let(:old_owner) { 'psql_reassign_old_owner' } let(:new_owner) { 'psql_reassign_new_owner' } - let(:pp_setup_objects) { <<-EOS.unindent + let(:pp_setup_objects) do + <<-MANIFEST.unindent postgresql_psql { 'create test table': command => 'CREATE TABLE test_tbl (col1 integer)', db => '#{db}', psql_user => '#{old_owner}', unless => "SELECT tablename FROM pg_catalog.pg_tables WHERE tablename = 'test_tbl'", require => Postgresql::Server::Database['#{db}'], } postgresql_psql { 'create test sequence': command => 'CREATE SEQUENCE test_seq', db => '#{db}', psql_user => '#{old_owner}', unless => "SELECT relname FROM pg_catalog.pg_class WHERE relkind='S' AND relname = 'test_seq'", require => [ Postgresql_psql['create test table'], Postgresql::Server::Database['#{db}'] ], } - EOS - } - let(:pp_reassign_owned_by) { <<-EOS.unindent + MANIFEST + end + let(:pp_reassign_owned_by) do + <<-MANIFEST.unindent postgresql::server::reassign_owned_by { 'test reassign to new_owner': db => '#{db}', old_role => '#{old_owner}', new_role => '#{new_owner}', psql_user => '#{new_owner}', } - EOS - } + MANIFEST + end - it 'should reassign all objects to new_owner' do + # rubocop:disable RSpec/ExampleLength + # rubocop:disable RSpec/MultipleExpectations + it 'reassigns all objects to new_owner' do begin - #postgres version + # postgres version result = shell('psql --version') version = result.stdout.match(%r{\s(\d\.\d)})[1] if version >= '9.0' - apply_manifest(pp_setup + pp_db_old_owner + pp_setup_objects, :catch_failures => true) + apply_manifest(pp_setup + pp_db_old_owner + pp_setup_objects, catch_failures: true) - apply_manifest(pp_setup + pp_db_no_owner + pp_reassign_owned_by, :catch_failures => true) - apply_manifest(pp_setup + pp_db_no_owner + pp_reassign_owned_by, :catch_changes => true) + apply_manifest(pp_setup + pp_db_no_owner + pp_reassign_owned_by, catch_failures: true) + apply_manifest(pp_setup + pp_db_no_owner + pp_reassign_owned_by, catch_changes: true) ## Check that the ownership was transferred psql("-d #{db} --tuples-only --no-align --command=\"SELECT tablename,tableowner FROM pg_catalog.pg_tables WHERE schemaname NOT IN ('pg_catalog', 'information_schema')\"", superuser) do |r| - expect(r.stdout).to match(/test_tbl.#{new_owner}/) + expect(r.stdout).to match(%r{test_tbl.#{new_owner}}) expect(r.stderr).to eq('') end psql("-d #{db} --tuples-only --no-align --command=\"SELECT relname,pg_get_userbyid(relowner) FROM pg_catalog.pg_class c WHERE relkind='S'\"", superuser) do |r| - expect(r.stdout).to match(/test_seq.#{new_owner}/) + expect(r.stdout).to match(%r{test_seq.#{new_owner}}) expect(r.stderr).to eq('') end if version >= '9.3' psql("-d #{db} --tuples-only --no-align --command=\"SELECT pg_get_userbyid(datdba) FROM pg_database WHERE datname = current_database()\"", superuser) do |r| - expect(r.stdout).to match(/#{new_owner}/) + expect(r.stdout).to match(%r{#{new_owner}}) expect(r.stderr).to eq('') end end end end - end # it should reassign all objects + end # it should reassign all objects end end ##################### end diff --git a/spec/acceptance/server/recovery_spec.rb b/spec/acceptance/server/recovery_spec.rb index b27a5c5..1ae5310 100644 --- a/spec/acceptance/server/recovery_spec.rb +++ b/spec/acceptance/server/recovery_spec.rb @@ -1,61 +1,58 @@ require 'spec_helper_acceptance' -describe 'postgresql::server::recovery', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do +describe 'postgresql::server::recovery', unless: UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do describe 'should manage recovery' do after(:all) do - pp = <<-EOS.unindent + pp = <<-MANIFEST.unindent file { '/tmp/recovery.conf': ensure => absent, } - EOS + MANIFEST - apply_manifest(pp, :catch_failures => true) + apply_manifest(pp, catch_failures: true) end - it 'adds conf file' do - pp = <<-EOS.unindent - class { 'postgresql::globals': - recovery_conf_path => '/tmp/recovery.conf', - manage_recovery_conf => true, - } + pp = <<-MANIFEST.unindent + class { 'postgresql::globals': + recovery_conf_path => '/tmp/recovery.conf', + manage_recovery_conf => true, + } - class { 'postgresql::server': } + class { 'postgresql::server': } - # Create a recovery.conf file - postgresql::server::recovery { "recovery.conf": - restore_command => 'restore_command', - recovery_target_timeline => 'recovery_target_timeline', - } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => true) + # Create a recovery.conf file + postgresql::server::recovery { "recovery.conf": + restore_command => 'restore_command', + recovery_target_timeline => 'recovery_target_timeline', + } + MANIFEST + it 'adds conf file' do + apply_manifest(pp, catch_failures: true) + apply_manifest(pp, catch_changes: true) end describe file('/tmp/recovery.conf') do it { is_expected.to be_file } - it { is_expected.to contain /restore_command = 'restore_command'/ } - it { is_expected.to contain /recovery_target_timeline = 'recovery_target_timeline'/ } + it { is_expected.to contain %r{restore_command = 'restore_command'} } + it { is_expected.to contain %r{recovery_target_timeline = 'recovery_target_timeline'} } end end describe 'should not manage recovery' do - it 'does not add conf file' do - pp = <<-EOS.unindent - class { 'postgresql::globals': - manage_recovery_conf => false, - } - - class { 'postgresql::server': } - EOS + pp = <<-MANIFEST.unindent + class { 'postgresql::globals': + manage_recovery_conf => false, + } - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => true) + class { 'postgresql::server': } + MANIFEST + it 'does not add conf file' do + apply_manifest(pp, catch_failures: true) + apply_manifest(pp, catch_changes: true) end describe file('/tmp/recovery.conf') do it { is_expected.not_to be_file } end end end - diff --git a/spec/acceptance/server/schema_spec.rb b/spec/acceptance/server/schema_spec.rb index 43b2c8a..1c10d1a 100644 --- a/spec/acceptance/server/schema_spec.rb +++ b/spec/acceptance/server/schema_spec.rb @@ -1,71 +1,72 @@ require 'spec_helper_acceptance' -describe 'postgresql::server::schema:', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do - +describe 'postgresql::server::schema:', unless: UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do let(:version) do - if fact('osfamily') == 'RedHat' and fact('operatingsystemrelease') =~ /5/ + if fact('osfamily') == 'RedHat' && fact('operatingsystemrelease') =~ %r{5} '8.1' end end + let(:pp) do + <<-MANIFEST.unindent + $db = 'schema_test' + $user = 'psql_schema_tester' + $password = 'psql_schema_pw' + $version = '#{version}' - it 'should create a schema for a user' do - begin - pp = <<-EOS.unindent - $db = 'schema_test' - $user = 'psql_schema_tester' - $password = 'psql_schema_pw' - $version = '#{version}' - - class { 'postgresql::server': } + class { 'postgresql::server': } - # Since we are not testing pg_hba or any of that, make a local user for ident auth - user { $user: - ensure => present, - } + # Since we are not testing pg_hba or any of that, make a local user for ident auth + user { $user: + ensure => present, + } - postgresql::server::role { $user: - password_hash => postgresql_password($user, $password), - } + postgresql::server::role { $user: + password_hash => postgresql_password($user, $password), + } - postgresql::server::database { $db: - owner => $user, - require => Postgresql::Server::Role[$user], - } + postgresql::server::database { $db: + owner => $user, + require => Postgresql::Server::Role[$user], + } - # Lets setup the base rules - $local_auth_option = $version ? { - '8.1' => 'sameuser', - default => undef, - } + # Lets setup the base rules + $local_auth_option = $version ? { + '8.1' => 'sameuser', + default => undef, + } - # Create a rule for the user - postgresql::server::pg_hba_rule { "allow ${user}": - type => 'local', - database => $db, - user => $user, - auth_method => 'ident', - auth_option => $local_auth_option, - order => 1, - } + # Create a rule for the user + postgresql::server::pg_hba_rule { "allow ${user}": + type => 'local', + database => $db, + user => $user, + auth_method => 'ident', + auth_option => $local_auth_option, + order => 1, + } - postgresql::server::schema { $user: - db => $db, - owner => $user, - require => Postgresql::Server::Database[$db], - } - EOS + postgresql::server::schema { $user: + db => $db, + owner => $user, + require => Postgresql::Server::Database[$db], + } + MANIFEST + end - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => true) + # rubocop:disable RSpec/ExampleLength + # rubocop:disable RSpec/MultipleExpectations + it 'creates a schema for a user' do + begin + apply_manifest(pp, catch_failures: true) + apply_manifest(pp, catch_changes: true) ## Check that the user can create a table in the database psql('--command="create table psql_schema_tester.foo (foo int)" schema_test', 'psql_schema_tester') do |r| - expect(r.stdout).to match(/CREATE TABLE/) + expect(r.stdout).to match(%r{CREATE TABLE}) expect(r.stderr).to eq('') end ensure psql('--command="drop table psql_schema_tester.foo" schema_test', 'psql_schema_tester') end end - end diff --git a/spec/acceptance/sql_task_spec.rb b/spec/acceptance/sql_task_spec.rb index 3b323c6..2cc4618 100644 --- a/spec/acceptance/sql_task_spec.rb +++ b/spec/acceptance/sql_task_spec.rb @@ -1,24 +1,24 @@ # run a test task require 'spec_helper_acceptance' describe 'postgresql task', if: puppet_version =~ %r{(5\.\d\.\d)} && !pe_install? do describe 'sql task' do - pp = <<-EOS + pp = <<-MANIFEST class { 'postgresql::server': } -> postgresql::server::db { 'spec1': user => 'root1', password => postgresql_password('root1', 'password'), } - EOS + MANIFEST it 'sets up a postgres db' do - apply_manifest(pp, :catch_failures => true) + apply_manifest(pp, catch_failures: true) end it 'execute some sql' do # equates to 'psql -c "SELECT table_name FROM information_schema.tables WHERE table_schema = 'information_schema';" --password --host localhost --dbname=spec1 --username root1' result = run_task(task_name: 'postgresql::sql', params: 'sql="SELECT count(table_name) FROM information_schema.tables;" host=localhost user=root1 password=password user=root1 database=spec1') expect_multiple_regexes(result: result, regexes: [%r{count}, %r{1 row}, %r{Job completed. 1/1 nodes succeeded|Ran on 1 node}]) end end end diff --git a/spec/acceptance/z_alternative_pgdata_spec.rb b/spec/acceptance/z_alternative_pgdata_spec.rb index 9f80f96..b893630 100644 --- a/spec/acceptance/z_alternative_pgdata_spec.rb +++ b/spec/acceptance/z_alternative_pgdata_spec.rb @@ -1,34 +1,33 @@ require 'spec_helper_acceptance' # These tests ensure that postgres can change itself to an alternative pgdata # location properly. # Allow postgresql to use /tmp/* as a datadir -if fact('osfamily') == 'RedHat' and fact('selinux') == 'true' +if fact('osfamily') == 'RedHat' && fact('selinux') == 'true' shell 'setenforce 0' end -describe 'postgresql::server', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do +describe 'postgresql::server', unless: UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do it 'on an alternative pgdata location' do - pp = <<-EOS + pp = <<-MAIFEST #file { '/var/lib/pgsql': ensure => directory, } -> # needs_initdb will be true by default for all OS's except Debian # in order to change the datadir we need to tell it explicitly to call initdb class { 'postgresql::server': datadir => '/tmp/data', needs_initdb => true } - EOS + MAIFEST - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => true) + apply_manifest(pp, catch_failures: true) + apply_manifest(pp, catch_changes: true) end describe file('/tmp/data') do - it { should be_directory } + it { is_expected.to be_directory } end it 'can connect with psql' do psql('--command="\l" postgres', 'postgres') do |r| - expect(r.stdout).to match(/List of databases/) + expect(r.stdout).to match(%r{List of databases}) end end - end diff --git a/spec/spec_helper_acceptance.rb b/spec/spec_helper_acceptance.rb index f1d9e3e..4a5d3ed 100644 --- a/spec/spec_helper_acceptance.rb +++ b/spec/spec_helper_acceptance.rb @@ -1,131 +1,129 @@ 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 = ['AIX','windows','Solaris','Suse'] +UNSUPPORTED_PLATFORMS = %w[AIX windows Solaris Suse].freeze # monkey patch to get around apt/forge issue (PUP-8008) module Beaker::ModuleInstallHelper include Beaker::DSL def module_dependencies_from_metadata metadata = module_metadata return [] unless metadata.key?('dependencies') dependencies = [] # get it outta here! - metadata['dependencies'].delete_if {|d| d['name'] == 'puppetlabs/apt' } + metadata['dependencies'].delete_if { |d| d['name'] == 'puppetlabs/apt' } metadata['dependencies'].each do |d| tmp = { module_name: d['name'].sub('/', '-') } if d.key?('version_requirement') tmp[:version] = module_version_from_requirement(tmp[:module_name], d['version_requirement']) end dependencies.push(tmp) end dependencies end end - install_bolt_on(hosts) unless pe_install? install_module_on(hosts) install_module_dependencies_on(hosts) -install_module_from_forge_on(hosts,'puppetlabs/apt','< 4.2.0') +install_module_from_forge_on(hosts, 'puppetlabs/apt', '< 4.2.0') DEFAULT_PASSWORD = if default[:hypervisor] == 'vagrant' 'vagrant' elsif default[:hypervisor] == 'vcloud' 'Qu@lity!' end class String # Provide ability to remove indentation from strings, for the purpose of # left justifying heredoc blocks. def unindent - gsub(/^#{scan(/^\s*/).min_by{|l|l.length}}/, "") + 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!(/([^A-Za-z0-9_\-.,:\/@\n])/, "\\\\\\1") + 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!(/\n/, "'\n'") + str.gsub!(%r{\n}, "'\n'") - return str + str end -def psql(psql_cmd, user = 'postgres', exit_codes = [0,1], &block) +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) + 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? # 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) + 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) + apply_manifest_on(agents, pp, catch_failures: false) end hosts.each do |host| on host, 'chmod 755 /root' - if 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 + 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/classes/client_spec.rb b/spec/unit/classes/client_spec.rb index 3f2e58f..0ecdef8 100644 --- a/spec/unit/classes/client_spec.rb +++ b/spec/unit/classes/client_spec.rb @@ -1,58 +1,53 @@ require 'spec_helper' -describe 'postgresql::client', :type => :class do +describe 'postgresql::client', type: :class do let :facts do { - :osfamily => 'Debian', - :operatingsystem => 'Debian', - :operatingsystemrelease => '6.0', + osfamily: 'Debian', + operatingsystem: 'Debian', + operatingsystemrelease: '6.0', } end describe 'with parameters' do let :params do { - :validcon_script_path => '/opt/bin/my-validate-con.sh', - :package_ensure => 'absent', - :package_name => 'mypackage', - :file_ensure => 'file' + validcon_script_path: '/opt/bin/my-validate-con.sh', + package_ensure: 'absent', + package_name: 'mypackage', + file_ensure: 'file', } end - it 'should modify package' do - is_expected.to contain_package("postgresql-client").with({ - :ensure => 'absent', - :name => 'mypackage', - :tag => 'postgresql', - }) + it 'modifies package' do + is_expected.to contain_package('postgresql-client').with(ensure: 'absent', + name: 'mypackage', + tag: 'postgresql') end - it 'should have specified validate connexion' do - should contain_file('/opt/bin/my-validate-con.sh').with({ - :ensure => 'file', - :owner => 0, - :group => 0, - :mode => '0755' - }) + it 'has specified validate connexion' do + is_expected.to contain_file('/opt/bin/my-validate-con.sh').with(ensure: 'file', + owner: 0, + group: 0, + mode: '0755') end end describe 'with no parameters' do - it 'should create package with postgresql tag' do - is_expected.to contain_package('postgresql-client').with({ - :tag => 'postgresql', - }) + it 'creates package with postgresql tag' do + is_expected.to contain_package('postgresql-client').with(tag: 'postgresql') end end describe 'with client package name explicitly set undef' do let :params do { - :package_name => 'UNSET' + package_name: 'UNSET', } end - it 'should not manage postgresql-client package' do + + it 'does not manage postgresql-client package' do is_expected.not_to contain_package('postgresql-client') end end end diff --git a/spec/unit/classes/globals_spec.rb b/spec/unit/classes/globals_spec.rb index 6789090..e3d87ce 100644 --- a/spec/unit/classes/globals_spec.rb +++ b/spec/unit/classes/globals_spec.rb @@ -1,95 +1,97 @@ require 'spec_helper' describe 'postgresql::globals', type: :class do context 'on a debian 6' do - let (:facts) do + let(:facts) do { - :os => { - :family => 'Debian', - :name => 'Debian', - :release => { - :full => '6.0', - :major => '6' - } + os: { + family: 'Debian', + name: 'Debian', + release: { + full: '6.0', + major: '6', + }, }, - :osfamily => 'Debian', - :operatingsystem => 'Debian', - :operatingsystemrelease => '6.0', - :lsbdistid => 'Debian', - :lsbdistcodename => 'squeeze' + osfamily: 'Debian', + operatingsystem: 'Debian', + operatingsystemrelease: '6.0', + lsbdistid: 'Debian', + lsbdistcodename: 'squeeze', } end describe 'with no parameters' do - it 'should work' do + it 'works' do is_expected.to contain_class('postgresql::globals') end end describe 'manage_package_repo => true' do let(:params) do { - manage_package_repo: true + manage_package_repo: true, } end - it 'should pull in class postgresql::repo' do + + it 'pulls in class postgresql::repo' do is_expected.to contain_class('postgresql::repo') end end end context 'on redhat family systems' do - let (:facts) do + let(:facts) do { osfamily: 'RedHat', operatingsystem: 'RedHat', - operatingsystemrelease: '7.1' + operatingsystemrelease: '7.1', } end + describe 'with no parameters' do - it 'should work' do + it 'works' do is_expected.to contain_class('postgresql::globals') end end describe 'manage_package_repo on RHEL => true' do let(:params) do { manage_package_repo: true, - repo_proxy: 'http://proxy-server:8080' + repo_proxy: 'http://proxy-server:8080', } end - it 'should pull in class postgresql::repo' do + it 'pulls in class postgresql::repo' do is_expected.to contain_class('postgresql::repo') end it do - should contain_yumrepo('yum.postgresql.org').with( + is_expected.to contain_yumrepo('yum.postgresql.org').with( 'enabled' => '1', - 'proxy' => 'http://proxy-server:8080' - ) + 'proxy' => 'http://proxy-server:8080', + ) end end describe 'repo_baseurl on RHEL => mirror.localrepo.com' do let(:params) do { manage_package_repo: true, - repo_baseurl: 'http://mirror.localrepo.com' + repo_baseurl: 'http://mirror.localrepo.com', } end - it 'should pull in class postgresql::repo' do + it 'pulls in class postgresql::repo' do is_expected.to contain_class('postgresql::repo') end it do - should contain_yumrepo('yum.postgresql.org').with( + is_expected.to contain_yumrepo('yum.postgresql.org').with( 'enabled' => '1', - 'baseurl' => 'http://mirror.localrepo.com' + 'baseurl' => 'http://mirror.localrepo.com', ) end end end end diff --git a/spec/unit/classes/lib/devel_spec.rb b/spec/unit/classes/lib/devel_spec.rb index ca0ebb3..8317a4d 100644 --- a/spec/unit/classes/lib/devel_spec.rb +++ b/spec/unit/classes/lib/devel_spec.rb @@ -1,73 +1,84 @@ require 'spec_helper' -describe 'postgresql::lib::devel', :type => :class do +describe 'postgresql::lib::devel', type: :class do let :facts do { - :osfamily => 'Debian', - :operatingsystem => 'Debian', - :operatingsystemrelease => '6.0', + osfamily: 'Debian', + operatingsystem: 'Debian', + operatingsystemrelease: '6.0', } end - it { is_expected.to contain_class("postgresql::lib::devel") } + + it { is_expected.to contain_class('postgresql::lib::devel') } describe 'link pg_config to /usr/bin' do - it { should_not contain_file('/usr/bin/pg_config') \ - .with_ensure('link') \ - .with_target('/usr/lib/postgresql/8.4/bin/pg_config') + it { + is_expected.not_to contain_file('/usr/bin/pg_config') \ + .with_ensure('link') \ + .with_target('/usr/lib/postgresql/8.4/bin/pg_config') } end describe 'disable link_pg_config' do - let(:params) {{ - :link_pg_config => false, - }} - it { should_not contain_file('/usr/bin/pg_config') } + let(:params) do + { + link_pg_config: false, + } + end + + it { is_expected.not_to contain_file('/usr/bin/pg_config') } end describe 'should not link pg_config on RedHat with default version' do - let(:facts) {{ - :osfamily => 'RedHat', - :operatingsystem => 'CentOS', - :operatingsystemrelease => '6.3', - :operatingsystemmajrelease => '6', - }} - it { should_not contain_file('/usr/bin/pg_config') } + let(:facts) do + { + osfamily: 'RedHat', + operatingsystem: 'CentOS', + operatingsystemrelease: '6.3', + operatingsystemmajrelease: '6', + } + end + + it { is_expected.not_to contain_file('/usr/bin/pg_config') } end describe 'link pg_config on RedHat with non-default version' do - let(:facts) {{ - :osfamily => 'RedHat', - :operatingsystem => 'CentOS', - :operatingsystemrelease => '6.3', - :operatingsystemmajrelease => '6', - }} + let(:facts) do + { + osfamily: 'RedHat', + operatingsystem: 'CentOS', + operatingsystemrelease: '6.3', + operatingsystemmajrelease: '6', + } + end let :pre_condition do - "class { '::postgresql::globals': version => '9.3' }" + "class { '::postgresql::globals': version => '9.3' }" end - it { should contain_file('/usr/bin/pg_config') \ - .with_ensure('link') \ - .with_target('/usr/pgsql-9.3/bin/pg_config') + it { + is_expected.to contain_file('/usr/bin/pg_config') \ + .with_ensure('link') \ + .with_target('/usr/pgsql-9.3/bin/pg_config') } end describe 'on Gentoo' do let :facts do { - :osfamily => 'Gentoo', - :operatingsystem => 'Gentoo', + osfamily: 'Gentoo', + operatingsystem: 'Gentoo', } end let :params do { - :link_pg_config => false, + link_pg_config: false, } end - it 'should fail to compile' do + it 'fails to compile' do # rubocop:disable RSpec/MultipleExpectations expect { is_expected.to compile - }.to raise_error(/is not supported/) + }.to raise_error(%r{is not supported}) end end end diff --git a/spec/unit/classes/lib/java_spec.rb b/spec/unit/classes/lib/java_spec.rb index 76dbbd9..58ec2f8 100644 --- a/spec/unit/classes/lib/java_spec.rb +++ b/spec/unit/classes/lib/java_spec.rb @@ -1,43 +1,52 @@ require 'spec_helper' -describe 'postgresql::lib::java', :type => :class do - +describe 'postgresql::lib::java', type: :class do describe 'on a debian based os' do - let :facts do { - :osfamily => 'Debian', - :operatingsystem => 'Debian', - :operatingsystemrelease => '6.0', - } + let :facts do + { + osfamily: 'Debian', + operatingsystem: 'Debian', + operatingsystemrelease: '6.0', + } end - it { is_expected.to contain_package('postgresql-jdbc').with( - :name => 'libpg-java', - :ensure => 'present', - :tag => 'postgresql' - )} + + it { + is_expected.to contain_package('postgresql-jdbc').with( + name: 'libpg-java', + ensure: 'present', + tag: 'postgresql', + ) + } end describe 'on a redhat based os' do - let :facts do { - :osfamily => 'RedHat', - :operatingsystem => 'RedHat', - :operatingsystemrelease => '6.4', - } + let :facts do + { + osfamily: 'RedHat', + operatingsystem: 'RedHat', + operatingsystemrelease: '6.4', + } end - it { is_expected.to contain_package('postgresql-jdbc').with( - :name => 'postgresql-jdbc', - :ensure => 'present', - :tag => 'postgresql' - )} + + it { + is_expected.to contain_package('postgresql-jdbc').with( + name: 'postgresql-jdbc', + ensure: 'present', + tag: 'postgresql', + ) + } describe 'when parameters are supplied' do let :params do - {:package_ensure => 'latest', :package_name => 'somepackage'} + { package_ensure: 'latest', package_name: 'somepackage' } end - it { is_expected.to contain_package('postgresql-jdbc').with( - :name => 'somepackage', - :ensure => 'latest', - :tag => 'postgresql' - )} + + it { + is_expected.to contain_package('postgresql-jdbc').with( + name: 'somepackage', + ensure: 'latest', + tag: 'postgresql', + ) + } end end - end diff --git a/spec/unit/classes/lib/perl_spec.rb b/spec/unit/classes/lib/perl_spec.rb index 922cfa0..d8c8a59 100644 --- a/spec/unit/classes/lib/perl_spec.rb +++ b/spec/unit/classes/lib/perl_spec.rb @@ -1,31 +1,37 @@ require 'spec_helper' -describe 'postgresql::lib::perl', :type => :class do - +describe 'postgresql::lib::perl', type: :class do describe 'on a redhat based os' do - let :facts do { - :osfamily => 'RedHat', - :operatingsystem => 'RedHat', - :operatingsystemrelease => '6.4', - } + let :facts do + { + osfamily: 'RedHat', + operatingsystem: 'RedHat', + operatingsystemrelease: '6.4', + } end - it { is_expected.to contain_package('perl-DBD-Pg').with( - :name => 'perl-DBD-Pg', - :ensure => 'present' - )} + + it { + is_expected.to contain_package('perl-DBD-Pg').with( + name: 'perl-DBD-Pg', + ensure: 'present', + ) + } end describe 'on a debian based os' do - let :facts do { - :osfamily => 'Debian', - :operatingsystem => 'Debian', - :operatingsystemrelease => '6.0', - } + let :facts do + { + osfamily: 'Debian', + operatingsystem: 'Debian', + operatingsystemrelease: '6.0', + } end - it { is_expected.to contain_package('perl-DBD-Pg').with( - :name => 'libdbd-pg-perl', - :ensure => 'present' - )} - end + it { + is_expected.to contain_package('perl-DBD-Pg').with( + name: 'libdbd-pg-perl', + ensure: 'present', + ) + } + end end diff --git a/spec/unit/classes/lib/pgdocs_spec.rb b/spec/unit/classes/lib/pgdocs_spec.rb index a751e98..878abac 100644 --- a/spec/unit/classes/lib/pgdocs_spec.rb +++ b/spec/unit/classes/lib/pgdocs_spec.rb @@ -1,29 +1,34 @@ require 'spec_helper' -describe 'postgresql::lib::docs', :type => :class do - +describe 'postgresql::lib::docs', type: :class do describe 'on a redhat based os' do - let :facts do { - :osfamily => 'RedHat', - :operatingsystem => 'RedHat', - :operatingsystemrelease => '6.4', - } + let :facts do + { + osfamily: 'RedHat', + operatingsystem: 'RedHat', + operatingsystemrelease: '6.4', + } end - it { is_expected.to contain_package('postgresql-docs').with( - :name => 'postgresql-docs', - :ensure => 'present', - :tag => 'postgresql' - )} + + it { + is_expected.to contain_package('postgresql-docs').with( + name: 'postgresql-docs', + ensure: 'present', + tag: 'postgresql', + ) + } describe 'when parameters are supplied' do let :params do - {:package_ensure => 'latest', :package_name => 'somepackage'} + { package_ensure: 'latest', package_name: 'somepackage' } end - it { is_expected.to contain_package('postgresql-docs').with( - :name => 'somepackage', - :ensure => 'latest', - :tag => 'postgresql' - )} + + it { + is_expected.to contain_package('postgresql-docs').with( + name: 'somepackage', + ensure: 'latest', + tag: 'postgresql', + ) + } end end - end diff --git a/spec/unit/classes/lib/python_spec.rb b/spec/unit/classes/lib/python_spec.rb index 095c2e1..bbf93b4 100644 --- a/spec/unit/classes/lib/python_spec.rb +++ b/spec/unit/classes/lib/python_spec.rb @@ -1,31 +1,37 @@ require 'spec_helper' -describe 'postgresql::lib::python', :type => :class do - +describe 'postgresql::lib::python', type: :class do describe 'on a redhat based os' do - let :facts do { - :osfamily => 'RedHat', - :operatingsystem => 'RedHat', - :operatingsystemrelease => '6.4', - } + let :facts do + { + osfamily: 'RedHat', + operatingsystem: 'RedHat', + operatingsystemrelease: '6.4', + } end - it { is_expected.to contain_package('python-psycopg2').with( - :name => 'python-psycopg2', - :ensure => 'present' - )} + + it { + is_expected.to contain_package('python-psycopg2').with( + name: 'python-psycopg2', + ensure: 'present', + ) + } end describe 'on a debian based os' do - let :facts do { - :osfamily => 'Debian', - :operatingsystem => 'Debian', - :operatingsystemrelease => '6.0', - } + let :facts do + { + osfamily: 'Debian', + operatingsystem: 'Debian', + operatingsystemrelease: '6.0', + } end - it { is_expected.to contain_package('python-psycopg2').with( - :name => 'python-psycopg2', - :ensure => 'present' - )} - end + it { + is_expected.to contain_package('python-psycopg2').with( + name: 'python-psycopg2', + ensure: 'present', + ) + } + end end diff --git a/spec/unit/classes/params_spec.rb b/spec/unit/classes/params_spec.rb index a415966..49dbb19 100644 --- a/spec/unit/classes/params_spec.rb +++ b/spec/unit/classes/params_spec.rb @@ -1,12 +1,13 @@ require 'spec_helper' -describe 'postgresql::params', :type => :class do +describe 'postgresql::params', type: :class do let :facts do { - :osfamily => 'Debian', - :operatingsystem => 'Debian', - :operatingsystemrelease => '6.0', + osfamily: 'Debian', + operatingsystem: 'Debian', + operatingsystemrelease: '6.0', } end - it { is_expected.to contain_class("postgresql::params") } + + it { is_expected.to contain_class('postgresql::params') } end diff --git a/spec/unit/classes/repo_spec.rb b/spec/unit/classes/repo_spec.rb index 3942d65..f066093 100644 --- a/spec/unit/classes/repo_spec.rb +++ b/spec/unit/classes/repo_spec.rb @@ -1,27 +1,27 @@ require 'spec_helper' -describe 'postgresql::repo', :type => :class do +describe 'postgresql::repo', type: :class do let :facts do { - :os => { - :name => 'Debian', - :family => 'Debian', - :release => { - :full => '6.0', - :major => '6' - } + os: { + name: 'Debian', + family: 'Debian', + release: { + full: '6.0', + major: '6', + }, }, - :osfamily => 'Debian', - :operatingsystem => 'Debian', - :operatingsystemrelease => '6.0', - :lsbdistid => 'Debian', - :lsbdistcodename => 'squeeze', + osfamily: 'Debian', + operatingsystem: 'Debian', + operatingsystemrelease: '6.0', + lsbdistid: 'Debian', + lsbdistcodename: 'squeeze', } end describe 'with no parameters' do - it 'should instantiate apt_postgresql_org class' do + it 'instantiates apt_postgresql_org class' do is_expected.to contain_class('postgresql::repo::apt_postgresql_org') end end end diff --git a/spec/unit/classes/server/config_spec.rb b/spec/unit/classes/server/config_spec.rb index fbf5529..5e22d05 100644 --- a/spec/unit/classes/server/config_spec.rb +++ b/spec/unit/classes/server/config_spec.rb @@ -1,171 +1,175 @@ require 'spec_helper' -describe 'postgresql::server::config', :type => :class do - let (:pre_condition) do - "include postgresql::server" +describe 'postgresql::server::config', type: :class do + let(:pre_condition) do + 'include postgresql::server' end describe 'on RedHat 7' do - let :facts do + let(:facts) do { - :osfamily => 'RedHat', - :operatingsystem => 'CentOS', - :operatingsystemrelease => '7.0', - :concat_basedir => tmpfilename('server'), - :kernel => 'Linux', - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', - :selinux => true, + osfamily: 'RedHat', + operatingsystem: 'CentOS', + operatingsystemrelease: '7.0', + concat_basedir: tmpfilename('server'), + kernel: 'Linux', + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + selinux: true, } end - it 'should have the correct systemd-override file' do - is_expected.to contain_file('systemd-override').with ({ - :ensure => 'present', - :path => '/etc/systemd/system/postgresql.service', - :owner => 'root', - :group => 'root', - }) + + it 'has the correct systemd-override file' do + is_expected.to contain_file('systemd-override').with( + ensure: 'present', path: '/etc/systemd/system/postgresql.service', + owner: 'root', group: 'root' + ) + end + it 'has the correct systemd-override file #content' do is_expected.to contain_file('systemd-override') \ - .with_content(/.include \/usr\/lib\/systemd\/system\/postgresql.service/) + .with_content(%r{.include \/usr\/lib\/systemd\/system\/postgresql.service}) end describe 'with manage_package_repo => true and a version' do - let (:pre_condition) do + let(:pre_condition) do <<-EOS class { 'postgresql::globals': manage_package_repo => true, version => '9.4', }-> class { 'postgresql::server': } EOS end - it 'should have the correct systemd-override file' do - is_expected.to contain_file('systemd-override').with ({ - :ensure => 'present', - :path => '/etc/systemd/system/postgresql-9.4.service', - :owner => 'root', - :group => 'root', - }) + it 'has the correct systemd-override file' do + is_expected.to contain_file('systemd-override').with( + ensure: 'present', path: '/etc/systemd/system/postgresql-9.4.service', + owner: 'root', group: 'root' + ) + end + it 'has the correct systemd-override file #regex' do is_expected.to contain_file('systemd-override') \ - .with_content(/.include \/usr\/lib\/systemd\/system\/postgresql-9.4.service/) + .with_content(%r{.include \/usr\/lib\/systemd\/system\/postgresql-9.4.service}) end end end describe 'on Fedora 21' do - let :facts do + let(:facts) do { - :osfamily => 'RedHat', - :operatingsystem => 'Fedora', - :operatingsystemrelease => '21', - :concat_basedir => tmpfilename('server'), - :kernel => 'Linux', - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', - :selinux => true, + osfamily: 'RedHat', + operatingsystem: 'Fedora', + operatingsystemrelease: '21', + concat_basedir: tmpfilename('server'), + kernel: 'Linux', + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + selinux: true, } end - it 'should have the correct systemd-override file' do - is_expected.to contain_file('systemd-override').with ({ - :ensure => 'present', - :path => '/etc/systemd/system/postgresql.service', - :owner => 'root', - :group => 'root', - }) + + it 'has the correct systemd-override file' do + is_expected.to contain_file('systemd-override').with( + ensure: 'present', path: '/etc/systemd/system/postgresql.service', + owner: 'root', group: 'root' + ) + end + it 'has the correct systemd-override file #regex' do is_expected.to contain_file('systemd-override') \ - .with_content(/.include \/lib\/systemd\/system\/postgresql.service/) + .with_content(%r{.include \/lib\/systemd\/system\/postgresql.service}) end describe 'with manage_package_repo => true and a version' do - let (:pre_condition) do + let(:pre_condition) do <<-EOS class { 'postgresql::globals': manage_package_repo => true, version => '9.4', }-> class { 'postgresql::server': } EOS end - it 'should have the correct systemd-override file' do - is_expected.to contain_file('systemd-override').with ({ - :ensure => 'present', - :path => '/etc/systemd/system/postgresql-9.4.service', - :owner => 'root', - :group => 'root', - }) + it 'has the correct systemd-override file' do + is_expected.to contain_file('systemd-override').with( + ensure: 'present', path: '/etc/systemd/system/postgresql-9.4.service', + owner: 'root', group: 'root' + ) + end + it 'has the correct systemd-override file #regex' do is_expected.to contain_file('systemd-override') \ - .with_content(/.include \/lib\/systemd\/system\/postgresql-9.4.service/) + .with_content(%r{.include \/lib\/systemd\/system\/postgresql-9.4.service}) end end end describe 'on Gentoo' do - let (:pre_condition) do + let(:pre_condition) do <<-EOS class { 'postgresql::globals': version => '9.5', }-> class { 'postgresql::server': } EOS end - let :facts do + let(:facts) do { - :osfamily => 'Gentoo', - :operatingsystem => 'Gentoo', - :operatingsystemrelease => 'unused', - :concat_basedir => tmpfilename('server'), - :kernel => 'Linux', - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', - :selinux => false, + osfamily: 'Gentoo', + operatingsystem: 'Gentoo', + operatingsystemrelease: 'unused', + concat_basedir: tmpfilename('server'), + kernel: 'Linux', + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + selinux: false, } end - it 'should have the correct systemd-override file' do - is_expected.to contain_file('systemd-override').with ({ - :ensure => 'present', - :path => '/etc/systemd/system/postgresql-9.5.service', - :owner => 'root', - :group => 'root', - }) + + it 'has the correct systemd-override file' do + is_expected.to contain_file('systemd-override').with( + ensure: 'present', path: '/etc/systemd/system/postgresql-9.5.service', + owner: 'root', group: 'root' + ) + end + it 'has the correct systemd-override file #regex' do is_expected.to contain_file('systemd-override') \ - .with_content(/.include \/usr\/lib64\/systemd\/system\/postgresql-9.5.service/) + .with_content(%r{.include \/usr\/lib64\/systemd\/system\/postgresql-9.5.service}) end end describe 'with managed pg_hba_conf and ipv4acls' do - let (:pre_condition) do + let(:pre_condition) do <<-EOS class { 'postgresql::globals': version => '9.5', }-> class { 'postgresql::server': manage_pg_hba_conf => true, ipv4acls => [ 'hostnossl all all 0.0.0.0/0 reject', 'hostssl all all 0.0.0.0/0 md5' ] } EOS end - let :facts do + let(:facts) do { - :osfamily => 'RedHat', - :operatingsystem => 'CentOS', - :operatingsystemrelease => '7.0', - :concat_basedir => tmpfilename('server'), - :kernel => 'Linux', - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', - :selinux => true, + osfamily: 'RedHat', + operatingsystem: 'CentOS', + operatingsystemrelease: '7.0', + concat_basedir: tmpfilename('server'), + kernel: 'Linux', + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + selinux: true, } end - it 'should have hba rule default' do + + it 'has hba rule default' do is_expected.to contain_postgresql__server__pg_hba_rule('local access as postgres user') end - it 'should have hba rule ipv4acls' do + it 'has hba rule ipv4acls' do is_expected.to contain_postgresql__server__pg_hba_rule('postgresql class generated rule ipv4acls 0') end end end diff --git a/spec/unit/classes/server/contrib_spec.rb b/spec/unit/classes/server/contrib_spec.rb index e268436..221c857 100644 --- a/spec/unit/classes/server/contrib_spec.rb +++ b/spec/unit/classes/server/contrib_spec.rb @@ -1,59 +1,55 @@ require 'spec_helper' -describe 'postgresql::server::contrib', :type => :class do +describe 'postgresql::server::contrib', type: :class do let :pre_condition do "class { 'postgresql::server': }" end 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', + 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 describe 'with parameters' do let(:params) do { - :package_name => 'mypackage', - :package_ensure => 'absent', + package_name: 'mypackage', + package_ensure: 'absent', } end - it 'should create package with correct params' do - is_expected.to contain_package('postgresql-contrib').with({ - :ensure => 'absent', - :name => 'mypackage', - :tag => 'postgresql', - }) + it 'creates package with correct params' do + is_expected.to contain_package('postgresql-contrib').with(ensure: 'absent', + name: 'mypackage', + tag: 'postgresql') end end describe 'with no parameters' do - it 'should create package with postgresql tag' do - is_expected.to contain_package('postgresql-contrib').with({ - :tag => 'postgresql', - }) + it 'creates package with postgresql tag' do + is_expected.to contain_package('postgresql-contrib').with(tag: 'postgresql') end end describe 'on Gentoo' do let :facts do { - :osfamily => 'Gentoo', - :operatingsystem => 'Gentoo', + osfamily: 'Gentoo', + operatingsystem: 'Gentoo', } end - it 'should fail to compile' do + it 'fails to compile' do # rubocop:disable RSpec/MultipleExpectations expect { is_expected.to compile - }.to raise_error(/is not supported/) + }.to raise_error(%r{is not supported}) end end end diff --git a/spec/unit/classes/server/initdb_spec.rb b/spec/unit/classes/server/initdb_spec.rb index 3482970..3c05d07 100644 --- a/spec/unit/classes/server/initdb_spec.rb +++ b/spec/unit/classes/server/initdb_spec.rb @@ -1,127 +1,127 @@ require 'spec_helper' -describe 'postgresql::server::initdb', :type => :class do - let (:pre_condition) do - "include postgresql::server" +describe 'postgresql::server::initdb', type: :class do + let(:pre_condition) do + 'include postgresql::server' end + describe 'on RedHat' do let :facts do { - :osfamily => 'RedHat', - :operatingsystem => 'CentOS', - :operatingsystemrelease => '6.0', - :concat_basedir => tmpfilename('server'), - :kernel => 'Linux', - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', - :selinux => true, + osfamily: 'RedHat', + operatingsystem: 'CentOS', + operatingsystemrelease: '6.0', + concat_basedir: tmpfilename('server'), + kernel: 'Linux', + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + selinux: true, } end + it { is_expected.to contain_file('/var/lib/pgsql/data').with_ensure('directory') } end describe 'on Amazon' do let :facts do { - :osfamily => 'RedHat', - :operatingsystem => 'Amazon', - :operatingsystemrelease => '1.0', - :concat_basedir => tmpfilename('server'), - :kernel => 'Linux', - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', - :selinux => true, + osfamily: 'RedHat', + operatingsystem: 'Amazon', + operatingsystemrelease: '1.0', + concat_basedir: tmpfilename('server'), + kernel: 'Linux', + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + selinux: true, } end + it { is_expected.to contain_file('/var/lib/pgsql92/data').with_ensure('directory') } end describe 'exec with module_workdir => /var/tmp' do let :facts do { - :osfamily => 'RedHat', - :operatingsystem => 'CentOS', - :operatingsystemrelease => '6.0', - :concat_basedir => tmpfilename('server'), - :kernel => 'Linux', - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', - :selinux => true, + osfamily: 'RedHat', + operatingsystem: 'CentOS', + operatingsystemrelease: '6.0', + concat_basedir: tmpfilename('server'), + kernel: 'Linux', + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + selinux: true, } end - let (:pre_condition) do + let(:pre_condition) do <<-EOS class { 'postgresql::globals': module_workdir => '/var/tmp', }-> class { 'postgresql::server': } EOS end - it 'should contain exec with specified working directory' do - is_expected.to contain_exec('postgresql_initdb').with ({ - :cwd => '/var/tmp', - }) + it 'contains exec with specified working directory' do + is_expected.to contain_exec('postgresql_initdb').with( + cwd: '/var/tmp', + ) end end describe 'exec with module_workdir => undef' do let :facts do { - :osfamily => 'RedHat', - :operatingsystem => 'CentOS', - :operatingsystemrelease => '6.0', - :concat_basedir => tmpfilename('server'), - :kernel => 'Linux', - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', - :selinux => true, + osfamily: 'RedHat', + operatingsystem: 'CentOS', + operatingsystemrelease: '6.0', + concat_basedir: tmpfilename('server'), + kernel: 'Linux', + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + selinux: true, } end - let (:pre_condition) do + let(:pre_condition) do <<-EOS class { 'postgresql::globals': }-> class { 'postgresql::server': } EOS end - it 'should contain exec with default working directory' do - is_expected.to contain_exec('postgresql_initdb').with ({ - :cwd => '/tmp', - }) + it 'contains exec with default working directory' do + is_expected.to contain_exec('postgresql_initdb').with( + cwd: '/tmp', + ) end end - describe 'postgresql_psql with module_workdir => /var/tmp' do let :facts do { - :osfamily => 'RedHat', - :operatingsystem => 'CentOS', - :operatingsystemrelease => '6.0', - :concat_basedir => tmpfilename('server'), - :kernel => 'Linux', - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', - :selinux => true, + osfamily: 'RedHat', + operatingsystem: 'CentOS', + operatingsystemrelease: '6.0', + concat_basedir: tmpfilename('server'), + kernel: 'Linux', + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + selinux: true, } end - let (:pre_condition) do + let(:pre_condition) do <<-EOS class { 'postgresql::globals': module_workdir => '/var/tmp', encoding => 'test', needs_initdb => false, }-> class { 'postgresql::server': } EOS end - it 'should contain postgresql_psql with specified working directory' do - is_expected.to contain_postgresql_psql('Set template1 encoding to test').with({ - :cwd => '/var/tmp', - }) + + it 'contains postgresql_psql with specified working directory' do + is_expected.to contain_postgresql_psql('Set template1 encoding to test').with(cwd: '/var/tmp') end end end - diff --git a/spec/unit/classes/server/plperl_spec.rb b/spec/unit/classes/server/plperl_spec.rb index 00ddf09..90d7d2d 100644 --- a/spec/unit/classes/server/plperl_spec.rb +++ b/spec/unit/classes/server/plperl_spec.rb @@ -1,47 +1,43 @@ require 'spec_helper' -describe 'postgresql::server::plperl', :type => :class do +describe 'postgresql::server::plperl', type: :class do let :facts do { - :osfamily => 'Debian', - :operatingsystem => 'Debian', - :operatingsystemrelease => '6.0', - :kernel => 'Linux', - :concat_basedir => tmpfilename('plperl'), - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + osfamily: 'Debian', + operatingsystem: 'Debian', + operatingsystemrelease: '6.0', + kernel: 'Linux', + concat_basedir: tmpfilename('plperl'), + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', } end let :pre_condition do "class { 'postgresql::server': }" end describe 'with no parameters' do - it { is_expected.to contain_class("postgresql::server::plperl") } - it 'should create package' do - is_expected.to contain_package('postgresql-plperl').with({ - :ensure => 'present', - :tag => 'postgresql', - }) + it { is_expected.to contain_class('postgresql::server::plperl') } + it 'creates package' do + is_expected.to contain_package('postgresql-plperl').with(ensure: 'present', + tag: 'postgresql') end end describe 'with parameters' do let :params do { - :package_ensure => 'absent', - :package_name => 'mypackage', + package_ensure: 'absent', + package_name: 'mypackage', } end - it { is_expected.to contain_class("postgresql::server::plperl") } - it 'should create package with correct params' do - is_expected.to contain_package('postgresql-plperl').with({ - :ensure => 'absent', - :name => 'mypackage', - :tag => 'postgresql', - }) + it { is_expected.to contain_class('postgresql::server::plperl') } + it 'creates package with correct params' do + is_expected.to contain_package('postgresql-plperl').with(ensure: 'absent', + name: 'mypackage', + tag: 'postgresql') end end end diff --git a/spec/unit/classes/server/plpython_spec.rb b/spec/unit/classes/server/plpython_spec.rb index 29a1440..ea87951 100644 --- a/spec/unit/classes/server/plpython_spec.rb +++ b/spec/unit/classes/server/plpython_spec.rb @@ -1,48 +1,44 @@ require 'spec_helper' -describe 'postgresql::server::plpython', :type => :class do +describe 'postgresql::server::plpython', type: :class do let :facts do { - :osfamily => 'RedHat', - :operatingsystem => 'CentOS', - :operatingsystemrelease => '6.0', - :concat_basedir => tmpfilename('plpython'), - :kernel => 'Linux', - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', - :selinux => true, + osfamily: 'RedHat', + operatingsystem: 'CentOS', + operatingsystemrelease: '6.0', + concat_basedir: tmpfilename('plpython'), + kernel: 'Linux', + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + selinux: true, } end let :pre_condition do "class { 'postgresql::server': }" end describe 'on RedHat with no parameters' do - it { is_expected.to contain_class("postgresql::server::plpython") } - it 'should create package' do - is_expected.to contain_package('postgresql-plpython').with({ - :ensure => 'present', - :tag => 'postgresql', - }) + it { is_expected.to contain_class('postgresql::server::plpython') } + it 'creates package' do + is_expected.to contain_package('postgresql-plpython').with(ensure: 'present', + tag: 'postgresql') end end - + describe 'with parameters' do - let :params do - { - :package_ensure => 'absent', - :package_name => 'mypackage', - } - end - - it { is_expected.to contain_class("postgresql::server::plpython") } - it 'should create package with correct params' do - is_expected.to contain_package('postgresql-plpython').with({ - :ensure => 'absent', - :name => 'mypackage', - :tag => 'postgresql', - }) - end + let :params do + { + package_ensure: 'absent', + package_name: 'mypackage', + } + end + + it { is_expected.to contain_class('postgresql::server::plpython') } + it 'creates package with correct params' do + is_expected.to contain_package('postgresql-plpython').with(ensure: 'absent', + name: 'mypackage', + tag: 'postgresql') end + end end diff --git a/spec/unit/classes/server/postgis_spec.rb b/spec/unit/classes/server/postgis_spec.rb index 1e53c21..b021bb3 100644 --- a/spec/unit/classes/server/postgis_spec.rb +++ b/spec/unit/classes/server/postgis_spec.rb @@ -1,44 +1,40 @@ require 'spec_helper' -describe 'postgresql::server::postgis', :type => :class do +describe 'postgresql::server::postgis', type: :class do let :pre_condition do "class { 'postgresql::server': }" end let :facts do { - :osfamily => 'Debian', - :operatingsystem => 'Debian', - :operatingsystemrelease => '6.0', - :kernel => 'Linux', - :concat_basedir => tmpfilename('postgis'), - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + osfamily: 'Debian', + operatingsystem: 'Debian', + operatingsystemrelease: '6.0', + kernel: 'Linux', + concat_basedir: tmpfilename('postgis'), + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', } end describe 'with parameters' do let(:params) do { - :package_name => 'mypackage', - :package_ensure => 'absent', + package_name: 'mypackage', + package_ensure: 'absent', } end - it 'should create package with correct params' do - is_expected.to contain_package('postgresql-postgis').with({ - :ensure => 'absent', - :name => 'mypackage', - :tag => 'postgresql', - }) + it 'creates package with correct params' do + is_expected.to contain_package('postgresql-postgis').with(ensure: 'absent', + name: 'mypackage', + tag: 'postgresql') end end describe 'with no parameters' do - it 'should create package with postgresql tag' do - is_expected.to contain_package('postgresql-postgis').with({ - :tag => 'postgresql', - }) + it 'creates package with postgresql tag' do + is_expected.to contain_package('postgresql-postgis').with(tag: 'postgresql') end end end diff --git a/spec/unit/classes/server_spec.rb b/spec/unit/classes/server_spec.rb index 18013d8..02d5a95 100644 --- a/spec/unit/classes/server_spec.rb +++ b/spec/unit/classes/server_spec.rb @@ -1,168 +1,166 @@ require 'spec_helper' -describe 'postgresql::server', :type => :class do +describe 'postgresql::server', type: :class do let :facts do { - :os => { - :family => 'Debian', - :name => 'Debian', - :release => { - :full => '6.0', - :major => '6' - } + os: { + family: 'Debian', + name: 'Debian', + release: { + full: '6.0', + major: '6', + }, }, - :osfamily => 'Debian', - :operatingsystem => 'Debian', - :lsbdistid => 'Debian', - :lsbdistcodename => 'jessie', - :operatingsystemrelease => '8.0', - :concat_basedir => tmpfilename('server'), - :kernel => 'Linux', - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + osfamily: 'Debian', + operatingsystem: 'Debian', + lsbdistid: 'Debian', + lsbdistcodename: 'jessie', + operatingsystemrelease: '8.0', + concat_basedir: tmpfilename('server'), + kernel: 'Linux', + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', } end describe 'with no parameters' do - it { is_expected.to contain_class("postgresql::params") } - it { is_expected.to contain_class("postgresql::server") } - it { is_expected.to contain_exec('postgresql_reload').with({ - 'command' => 'service postgresql reload', - }) + it { is_expected.to contain_class('postgresql::params') } + it { is_expected.to contain_class('postgresql::server') } + it { + is_expected.to contain_exec('postgresql_reload').with('command' => 'service postgresql reload') } - it 'should validate connection' do + it 'validates connection' do is_expected.to contain_postgresql_conn_validator('validate_service_is_running') end end describe 'service_ensure => running' do let(:params) do { - :service_ensure => 'running', - :postgres_password => 'new-p@s$word-to-set' + service_ensure: 'running', + postgres_password: 'new-p@s$word-to-set', } end - it { is_expected.to contain_class("postgresql::params") } - it { is_expected.to contain_class("postgresql::server") } - it { is_expected.to contain_class("postgresql::server::passwd") } - it 'should validate connection' do + + it { is_expected.to contain_class('postgresql::params') } + it { is_expected.to contain_class('postgresql::server') } + it { is_expected.to contain_class('postgresql::server::passwd') } + it 'validates connection' do is_expected.to contain_postgresql_conn_validator('validate_service_is_running') end - it 'should set postgres password' do - is_expected.to contain_exec('set_postgres_postgrespw').with({ - 'command' => '/usr/bin/psql -c "ALTER ROLE \"postgres\" PASSWORD ${NEWPASSWD_ESCAPED}"', - 'user' => 'postgres', - 'environment' => [ - "PGPASSWORD=new-p@s$word-to-set", - "PGPORT=5432", - "NEWPASSWD_ESCAPED=$$new-p@s$word-to-set$$" - ], - 'unless' => "/usr/bin/psql -h localhost -p 5432 -c 'select 1' > /dev/null", - }) + it 'sets postgres password' do + is_expected.to contain_exec('set_postgres_postgrespw').with('command' => '/usr/bin/psql -c "ALTER ROLE \"postgres\" PASSWORD ${NEWPASSWD_ESCAPED}"', + 'user' => 'postgres', + 'environment' => ['PGPASSWORD=new-p@s$word-to-set', 'PGPORT=5432', 'NEWPASSWD_ESCAPED=$$new-p@s$word-to-set$$'], + 'unless' => "/usr/bin/psql -h localhost -p 5432 -c 'select 1' > /dev/null") end end describe 'service_ensure => stopped' do - let(:params) {{ :service_ensure => 'stopped' }} - it { is_expected.to contain_class("postgresql::params") } - it { is_expected.to contain_class("postgresql::server") } + let(:params) { { service_ensure: 'stopped' } } + + it { is_expected.to contain_class('postgresql::params') } + it { is_expected.to contain_class('postgresql::server') } it 'shouldnt validate connection' do is_expected.not_to contain_postgresql_conn_validator('validate_service_is_running') end end describe 'service_restart_on_change => false' do - let(:params) {{ :service_restart_on_change => false }} - it { is_expected.to contain_class("postgresql::params") } - it { is_expected.to contain_class("postgresql::server") } - it { is_expected.to_not contain_Postgresql_conf('data_directory').that_notifies('Class[postgresql::server::service]') + let(:params) { { service_restart_on_change: false } } + + it { is_expected.to contain_class('postgresql::params') } + it { is_expected.to contain_class('postgresql::server') } + it { + is_expected.not_to contain_Postgresql_conf('data_directory').that_notifies('Class[postgresql::server::service]') } - it 'should validate connection' do + it 'validates connection' do is_expected.to contain_postgresql_conn_validator('validate_service_is_running') end end describe 'service_restart_on_change => true' do - let(:params) {{ :service_restart_on_change => true }} - it { is_expected.to contain_class("postgresql::params") } - it { is_expected.to contain_class("postgresql::server") } - it { is_expected.to contain_Postgresql_conf('data_directory').that_notifies('Class[postgresql::server::service]') + let(:params) { { service_restart_on_change: true } } + + it { is_expected.to contain_class('postgresql::params') } + it { is_expected.to contain_class('postgresql::server') } + it { + is_expected.to contain_Postgresql_conf('data_directory').that_notifies('Class[postgresql::server::service]') } - it 'should validate connection' do + it 'validates connection' do is_expected.to contain_postgresql_conn_validator('validate_service_is_running') end end describe 'service_reload => /bin/true' do - let(:params) {{ :service_reload => '/bin/true' }} - it { is_expected.to contain_class("postgresql::params") } - it { is_expected.to contain_class("postgresql::server") } - it { is_expected.to contain_exec('postgresql_reload').with({ - 'command' => '/bin/true', - }) + let(:params) { { service_reload: '/bin/true' } } + + it { is_expected.to contain_class('postgresql::params') } + it { is_expected.to contain_class('postgresql::server') } + it { + is_expected.to contain_exec('postgresql_reload').with('command' => '/bin/true') } - it 'should validate connection' do + it 'validates connection' do is_expected.to contain_postgresql_conn_validator('validate_service_is_running') end end describe 'service_manage => true' do - let(:params) {{ :service_manage => true }} + let(:params) { { service_manage: true } } + it { is_expected.to contain_service('postgresqld') } end describe 'service_manage => false' do - let(:params) {{ :service_manage => false }} + let(:params) { { service_manage: false } } + it { is_expected.not_to contain_service('postgresqld') } it 'shouldnt validate connection' do is_expected.not_to contain_postgresql_conn_validator('validate_service_is_running') end end describe 'package_ensure => absent' do let(:params) do { - :package_ensure => 'absent', + package_ensure: 'absent', } end - it 'should remove the package' do - is_expected.to contain_package('postgresql-server').with({ - :ensure => 'purged', - }) + it 'removes the package' do + is_expected.to contain_package('postgresql-server').with(ensure: 'purged') end - it 'should still enable the service' do - is_expected.to contain_service('postgresqld').with({ - :ensure => 'running', - }) + it 'stills enable the service' do + is_expected.to contain_service('postgresqld').with(ensure: 'running') end end describe 'needs_initdb => true' do let(:params) do { - :needs_initdb => true, + needs_initdb: true, } end - it 'should contain proper initdb exec' do + it 'contains proper initdb exec' do is_expected.to contain_exec('postgresql_initdb') end end describe 'postgresql_version' do let(:pre_condition) do <<-EOS class { 'postgresql::globals': manage_package_repo => true, version => '99.5', before => Class['postgresql::server'], } EOS end + it 'contains the correct package version' do is_expected.to contain_class('postgresql::repo').with_version('99.5') end end end diff --git a/spec/unit/defines/server/config_entry_spec.rb b/spec/unit/defines/server/config_entry_spec.rb index 34f0c70..852ced8 100644 --- a/spec/unit/defines/server/config_entry_spec.rb +++ b/spec/unit/defines/server/config_entry_spec.rb @@ -1,136 +1,144 @@ require 'spec_helper' -describe 'postgresql::server::config_entry', :type => :define do +describe 'postgresql::server::config_entry', type: :define do let :facts do { - :osfamily => 'RedHat', - :operatingsystem => 'RedHat', - :operatingsystemrelease => '6.4', - :kernel => 'Linux', - :concat_basedir => tmpfilename('contrib'), - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', - :selinux => true, + osfamily: 'RedHat', + operatingsystem: 'RedHat', + operatingsystemrelease: '6.4', + kernel: 'Linux', + concat_basedir: tmpfilename('contrib'), + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + selinux: true, } end - let(:title) { 'config_entry'} + let(:title) { 'config_entry' } let :target do tmpfilename('postgresql_conf') end let :pre_condition do "class {'postgresql::server':}" end - context "syntax check" do - let(:params) { { :ensure => 'present'} } + context 'syntax check' do + let(:params) { { ensure: 'present' } } + it { is_expected.to contain_postgresql__server__config_entry('config_entry') } end context 'ports' do context 'redhat 6' do let :facts do { - :osfamily => 'RedHat', - :operatingsystem => 'RedHat', - :operatingsystemrelease => '6.4', - :kernel => 'Linux', - :concat_basedir => tmpfilename('contrib'), - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', - :selinux => true, + osfamily: 'RedHat', + operatingsystem: 'RedHat', + operatingsystemrelease: '6.4', + kernel: 'Linux', + concat_basedir: tmpfilename('contrib'), + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + selinux: true, } end - let(:params) {{ :ensure => 'present', :name => 'port_spec', :value => '5432' }} + let(:params) { { ensure: 'present', name: 'port_spec', value: '5432' } } - it 'stops postgresql and changes the port' do + it 'stops postgresql and changes the port #exec' do is_expected.to contain_exec('postgresql_stop_port') + end + it 'stops postgresql and changes the port #augeas' do is_expected.to contain_augeas('override PGPORT in /etc/sysconfig/pgsql/postgresql') end end context 'redhat 7' do let :facts do { - :osfamily => 'RedHat', - :operatingsystem => 'RedHat', - :operatingsystemrelease => '7.0', - :kernel => 'Linux', - :concat_basedir => tmpfilename('contrib'), - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', - :selinux => true, + osfamily: 'RedHat', + operatingsystem: 'RedHat', + operatingsystemrelease: '7.0', + kernel: 'Linux', + concat_basedir: tmpfilename('contrib'), + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + selinux: true, } end - let(:params) {{ :ensure => 'present', :name => 'port_spec', :value => '5432' }} + let(:params) { { ensure: 'present', name: 'port_spec', value: '5432' } } - it 'stops postgresql and changes the port' do + it 'stops postgresql and changes the port #file' do is_expected.to contain_file('systemd-override') + end + it 'stops postgresql and changes the port #exec' do is_expected.to contain_exec('restart-systemd') end end context 'fedora 19' do let :facts do { - :osfamily => 'RedHat', - :operatingsystem => 'Fedora', - :operatingsystemrelease => '19', - :kernel => 'Linux', - :concat_basedir => tmpfilename('contrib'), - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', - :selinux => true, + osfamily: 'RedHat', + operatingsystem: 'Fedora', + operatingsystemrelease: '19', + kernel: 'Linux', + concat_basedir: tmpfilename('contrib'), + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + selinux: true, } end - let(:params) {{ :ensure => 'present', :name => 'port_spec', :value => '5432' }} + let(:params) { { ensure: 'present', name: 'port_spec', value: '5432' } } - it 'stops postgresql and changes the port' do + it 'stops postgresql and changes the port #file' do is_expected.to contain_file('systemd-override') + end + it 'stops postgresql and changes the port #exec' do is_expected.to contain_exec('restart-systemd') end end end - context "data_directory" do - let(:params) {{ :ensure => 'present', :name => 'data_directory_spec', :value => '/var/pgsql' }} + context 'data_directory' do + let(:params) { { ensure: 'present', name: 'data_directory_spec', value: '/var/pgsql' } } - it 'stops postgresql and changes the data directory' do + it 'stops postgresql and changes the data directory #exec' do is_expected.to contain_exec('postgresql_data_directory') + end + it 'stops postgresql and changes the data directory #augeas' do is_expected.to contain_augeas('override PGDATA in /etc/sysconfig/pgsql/postgresql') end end - context "passes values through appropriately" do - let(:params) {{ :ensure => 'present', :name => 'check_function_bodies', :value => 'off' }} + context 'passes values through appropriately' do + let(:params) { { ensure: 'present', name: 'check_function_bodies', value: 'off' } } it 'with no quotes' do - is_expected.to contain_postgresql_conf('check_function_bodies').with({ - :name => 'check_function_bodies', - :value => 'off' }) + is_expected.to contain_postgresql_conf('check_function_bodies').with(name: 'check_function_bodies', + value: 'off') end end context 'unix_socket_directories' do let :facts do { - :osfamily => 'RedHat', - :operatingsystem => 'RedHat', - :operatingsystemrelease => '7.0', - :kernel => 'Linux', - :concat_basedir => tmpfilename('contrib'), - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', - :selinux => true, + osfamily: 'RedHat', + operatingsystem: 'RedHat', + operatingsystemrelease: '7.0', + kernel: 'Linux', + concat_basedir: tmpfilename('contrib'), + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + selinux: true, } end - let(:params) {{ :ensure => 'present', :name => 'unix_socket_directories', :value => '/var/pgsql, /opt/postgresql, /root/' }} + let(:params) { { ensure: 'present', name: 'unix_socket_directories', value: '/var/pgsql, /opt/postgresql, /root/' } } - it 'should restart the server and change unix_socket_directories to the provided list' do + it 'restarts the server and change unix_socket_directories to the provided list' do is_expected.to contain_postgresql_conf('unix_socket_directories') - .with({ :name => 'unix_socket_directories', - :value => '/var/pgsql, /opt/postgresql, /root/'}) - .that_notifies('Class[postgresql::server::service]') + .with(name: 'unix_socket_directories', + value: '/var/pgsql, /opt/postgresql, /root/') + .that_notifies('Class[postgresql::server::service]') end end end diff --git a/spec/unit/defines/server/database_grant_spec.rb b/spec/unit/defines/server/database_grant_spec.rb index 19dfce9..d4c65b6 100644 --- a/spec/unit/defines/server/database_grant_spec.rb +++ b/spec/unit/defines/server/database_grant_spec.rb @@ -1,34 +1,34 @@ require 'spec_helper' -describe 'postgresql::server::database_grant', :type => :define do +describe 'postgresql::server::database_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', + 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 let :params do { - :privilege => 'ALL', - :db => 'test', - :role => 'test', + privilege: 'ALL', + db: 'test', + role: 'test', } end let :pre_condition do "class {'postgresql::server':}" end it { is_expected.to contain_postgresql__server__database_grant('test') } it { is_expected.to contain_postgresql__server__grant('database:test') } end diff --git a/spec/unit/defines/server/database_spec.rb b/spec/unit/defines/server/database_spec.rb index c9993f6..9880bbc 100644 --- a/spec/unit/defines/server/database_spec.rb +++ b/spec/unit/defines/server/database_spec.rb @@ -1,78 +1,80 @@ require 'spec_helper' -describe 'postgresql::server::database', :type => :define do +describe 'postgresql::server::database', 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', + 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 let :pre_condition do "class {'postgresql::server':}" end it { is_expected.to contain_postgresql__server__database('test') } it { is_expected.to contain_postgresql_psql('CREATE DATABASE "test"') } context "with comment set to 'test comment'" do - let (:params) {{ :comment => 'test comment' }} + let(:params) { { comment: 'test comment' } } - it { is_expected.to contain_postgresql_psql("COMMENT ON DATABASE \"test\" IS 'test comment'").with_connect_settings( {} ) } + it { is_expected.to contain_postgresql_psql("COMMENT ON DATABASE \"test\" IS 'test comment'").with_connect_settings({}) } end - context "with specific db connection settings - default port" do + context 'with specific db connection settings - default port' do let :pre_condition do "class {'postgresql::server':}" end - let (:params) {{ :connect_settings => { 'PGHOST' => 'postgres-db-server', - 'DBVERSION' => '9.1', }}} + let(:params) do + { connect_settings: { 'PGHOST' => 'postgres-db-server', + 'DBVERSION' => '9.1' } } + end - it { is_expected.to contain_postgresql_psql('CREATE DATABASE "test"').with_connect_settings( { 'PGHOST' => 'postgres-db-server','DBVERSION' => '9.1' } ).with_port( 5432 ) } + it { is_expected.to contain_postgresql_psql('CREATE DATABASE "test"').with_connect_settings('PGHOST' => 'postgres-db-server', 'DBVERSION' => '9.1').with_port(5432) } end - context "with specific db connection settings - including port" do + context 'with specific db connection settings - including port' do let :pre_condition do "class {'postgresql::globals':} class {'postgresql::server':}" end - let (:params) {{ :connect_settings => { 'PGHOST' => 'postgres-db-server', - 'DBVERSION' => '9.1', - 'PGPORT' => '1234' }}} - - it { is_expected.to contain_postgresql_psql('CREATE DATABASE "test"').with_connect_settings( { 'PGHOST' => 'postgres-db-server','DBVERSION' => '9.1','PGPORT' => '1234' } ).with_port( nil ) } + let(:params) do + { connect_settings: { 'PGHOST' => 'postgres-db-server', + 'DBVERSION' => '9.1', + 'PGPORT' => '1234' } } + end + it { is_expected.to contain_postgresql_psql('CREATE DATABASE "test"').with_connect_settings('PGHOST' => 'postgres-db-server', 'DBVERSION' => '9.1', 'PGPORT' => '1234').with_port(nil) } end - context "with global db connection settings - including port" do + context 'with global db connection settings - including port' do let :pre_condition do "class {'postgresql::globals': default_connect_settings => { 'PGHOST' => 'postgres-db-server', 'DBVERSION' => '9.2', 'PGPORT' => '1234' } } class {'postgresql::server':}" end - it { is_expected.to contain_postgresql_psql('CREATE DATABASE "test"').with_connect_settings( { 'PGHOST' => 'postgres-db-server','DBVERSION' => '9.2','PGPORT' => '1234' } ).with_port( nil ) } - + it { is_expected.to contain_postgresql_psql('CREATE DATABASE "test"').with_connect_settings('PGHOST' => 'postgres-db-server', 'DBVERSION' => '9.2', 'PGPORT' => '1234').with_port(nil) } end - context "with different owner" do - let (:params) {{ :owner => 'test_owner' }} + context 'with different owner' do + let(:params) { { owner: 'test_owner' } } it { is_expected.to contain_postgresql_psql('ALTER DATABASE "test" OWNER TO "test_owner"') } end end diff --git a/spec/unit/defines/server/db_spec.rb b/spec/unit/defines/server/db_spec.rb index 78e36b0..9dd9ad4 100644 --- a/spec/unit/defines/server/db_spec.rb +++ b/spec/unit/defines/server/db_spec.rb @@ -1,58 +1,55 @@ require 'spec_helper' -describe 'postgresql::server::db', :type => :define do +describe 'postgresql::server::db', 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', + 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 'without dbname param' do - let :params do { - :user => 'test', - :password => 'test', - :owner => 'tester', + user: 'test', + password: 'test', + owner: 'tester', } end let :pre_condition do "class {'postgresql::server':}" end it { is_expected.to contain_postgresql__server__db('test') } it { is_expected.to contain_postgresql__server__database('test').with_owner('tester') } it { is_expected.to contain_postgresql__server__role('test').that_comes_before('Postgresql::Server::Database[test]') } it { is_expected.to contain_postgresql__server__database_grant('GRANT test - ALL - test') } - end context 'dbname' do - let :params do { - :dbname => 'testtest', - :user => 'test', - :password => 'test', - :owner => 'tester', + dbname: 'testtest', + user: 'test', + password: 'test', + owner: 'tester', } end let :pre_condition do "class {'postgresql::server':}" end it { is_expected.to contain_postgresql__server__database('testtest') } end end diff --git a/spec/unit/defines/server/extension_spec.rb b/spec/unit/defines/server/extension_spec.rb index efb4b8b..84bd53d 100644 --- a/spec/unit/defines/server/extension_spec.rb +++ b/spec/unit/defines/server/extension_spec.rb @@ -1,166 +1,153 @@ require 'spec_helper' -describe 'postgresql::server::extension', :type => :define do +describe 'postgresql::server::extension', type: :define do # rubocop:disable RSpec/MultipleDescribes let :pre_condition do "class { 'postgresql::server': } postgresql::server::database { 'template_postgis': template => 'template1', }" end let :facts do { - :osfamily => 'Debian', - :operatingsystem => 'Debian', - :operatingsystemrelease => '6.0', - :kernel => 'Linux', - :concat_basedir => tmpfilename('postgis'), - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + osfamily: 'Debian', + operatingsystem: 'Debian', + operatingsystemrelease: '6.0', + kernel: 'Linux', + concat_basedir: tmpfilename('postgis'), + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', } end - let (:title) { 'postgis' } - let (:params) { { - :database => 'template_postgis', - } } + let(:title) { 'postgis' } + let(:params) do + { + database: 'template_postgis', + } + end - context "with mandatory arguments only" do + context 'with mandatory arguments only' do it { - is_expected.to contain_postgresql_psql('template_postgis: CREATE EXTENSION "postgis"').with({ - :db => 'template_postgis', - :command => 'CREATE EXTENSION "postgis"', - }).that_requires('Postgresql::Server::Database[template_postgis]') + is_expected.to contain_postgresql_psql('template_postgis: CREATE EXTENSION "postgis"') + .with(db: 'template_postgis', command: 'CREATE EXTENSION "postgis"').that_requires('Postgresql::Server::Database[template_postgis]') } end - context "when schema is specified" do - let (:params) { super().merge({ - :schema => 'pg_catalog', - }) } + context 'when schema is specified' do + let(:params) do + super().merge(schema: 'pg_catalog') + end it { is_expected.to contain_postgresql_psql('template_postgis: ALTER EXTENSION "postgis" SET SCHEMA "pg_catalog"') } end - context "when setting package name" do - let (:params) { super().merge({ - :package_name => 'postgis', - }) } + context 'when setting package name' do + let(:params) do + super().merge(package_name: 'postgis') + end it { - is_expected.to contain_package('postgis').with({ - :ensure => 'present', - :name => 'postgis', - }).that_comes_before('Postgresql_psql[template_postgis: CREATE EXTENSION "postgis"]') + is_expected.to contain_package('postgis') + .with(ensure: 'present', name: 'postgis').that_comes_before('Postgresql_psql[template_postgis: CREATE EXTENSION "postgis"]') } end - context "when ensuring absence" do - let (:params) { super().merge({ - :ensure => 'absent', - :package_name => 'postgis', - }) } + context 'when ensuring absence' do + let(:params) do + super().merge(ensure: 'absent', + package_name: 'postgis') + end it { - is_expected.to contain_postgresql_psql('template_postgis: DROP EXTENSION "postgis"').with({ - :db => 'template_postgis', - :command => 'DROP EXTENSION "postgis"', - }).that_requires('Postgresql::Server::Database[template_postgis]') + is_expected.to contain_postgresql_psql('template_postgis: DROP EXTENSION "postgis"') + .with(db: 'template_postgis', command: 'DROP EXTENSION "postgis"').that_requires('Postgresql::Server::Database[template_postgis]') } it { - is_expected.to contain_package('postgis').with({ - :ensure => 'absent', - :name => 'postgis', - }) + is_expected.to contain_package('postgis').with(ensure: 'absent', + name: 'postgis') } - context "when keeping package installed" do - let (:params) { super().merge({ - :package_ensure => 'present', - }) } + context 'when keeping package installed' do + let(:params) do + super().merge(package_ensure: 'present') + end it { - is_expected.to contain_postgresql_psql('template_postgis: DROP EXTENSION "postgis"').with({ - :db => 'template_postgis', - :command => 'DROP EXTENSION "postgis"', - }).that_requires('Postgresql::Server::Database[template_postgis]') + is_expected.to contain_postgresql_psql('template_postgis: DROP EXTENSION "postgis"') + .with(db: 'template_postgis', command: 'DROP EXTENSION "postgis"').that_requires('Postgresql::Server::Database[template_postgis]') } it { - is_expected.to contain_package('postgis').with({ - :ensure => 'present', - :name => 'postgis', - }).that_requires('Postgresql_psql[template_postgis: DROP EXTENSION "postgis"]') + is_expected.to contain_package('postgis') + .with(ensure: 'present', name: 'postgis').that_requires('Postgresql_psql[template_postgis: DROP EXTENSION "postgis"]') } end end - context "when extension version is specified" do - let (:params) { super().merge({ - :ensure => 'absent', - :package_name => 'postgis', - :version => '99.99.99', - }) } + context 'when extension version is specified' do + let(:params) do + super().merge(ensure: 'absent', + package_name: 'postgis', + version: '99.99.99') + end it { - is_expected.to contain_postgresql_psql('template_postgis: ALTER EXTENSION "postgis" UPDATE TO \'99.99.99\'').with({ - :db => 'template_postgis', - :unless => "SELECT 1 FROM pg_extension WHERE extname='postgis' AND extversion='99.99.99'", - }).that_requires('Postgresql::Server::Database[template_postgis]') + is_expected.to contain_postgresql_psql('template_postgis: ALTER EXTENSION "postgis" UPDATE TO \'99.99.99\'') + .with(db: 'template_postgis', unless: "SELECT 1 FROM pg_extension WHERE extname='postgis' AND extversion='99.99.99'").that_requires('Postgresql::Server::Database[template_postgis]') } end - context "when extension version is latest" do - let (:params) { super().merge({ - :ensure => 'absent', - :package_name => 'postgis', - :version => 'latest', - }) } + context 'when extension version is latest' do + let(:params) do + super().merge(ensure: 'absent', + package_name: 'postgis', + version: 'latest') + end it { - is_expected.to contain_postgresql_psql('template_postgis: ALTER EXTENSION "postgis" UPDATE').with({ - :db => 'template_postgis', - :unless => "SELECT 1 FROM pg_available_extensions WHERE name = 'postgis' AND default_version = installed_version", - }).that_requires('Postgresql::Server::Database[template_postgis]') + is_expected.to contain_postgresql_psql('template_postgis: ALTER EXTENSION "postgis" UPDATE') + .with(db: 'template_postgis', + unless: "SELECT 1 FROM pg_available_extensions WHERE name = 'postgis' AND default_version = installed_version").that_requires('Postgresql::Server::Database[template_postgis]') } end end -describe 'postgresql::server::extension', :type => :define do +describe 'postgresql::server::extension', type: :define do let :pre_condition do "class { 'postgresql::server': } postgresql::server::database { 'template_postgis2': template => 'template1', }" end let :facts do { - :osfamily => 'Debian', - :operatingsystem => 'Debian', - :operatingsystemrelease => '6.0', - :kernel => 'Linux', - :concat_basedir => tmpfilename('postgis'), - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + osfamily: 'Debian', + operatingsystem: 'Debian', + operatingsystemrelease: '6.0', + kernel: 'Linux', + concat_basedir: tmpfilename('postgis'), + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', } end - let (:title) { 'postgis_db2' } - let (:params) { { - :database => 'template_postgis2', - :extension => 'postgis', - } } + let(:title) { 'postgis_db2' } + let(:params) do + { + database: 'template_postgis2', + extension: 'postgis', + } + end - context "with mandatory arguments only" do + context 'with mandatory arguments only' do it { - is_expected.to contain_postgresql_psql('template_postgis2: CREATE EXTENSION "postgis"').with({ - :db => 'template_postgis2', - :command => 'CREATE EXTENSION "postgis"', - }).that_requires('Postgresql::Server::Database[template_postgis2]') + is_expected.to contain_postgresql_psql('template_postgis2: CREATE EXTENSION "postgis"') + .with(db: 'template_postgis2', command: 'CREATE EXTENSION "postgis"').that_requires('Postgresql::Server::Database[template_postgis2]') } end end diff --git a/spec/unit/defines/server/grant_role_spec.rb b/spec/unit/defines/server/grant_role_spec.rb index 12a41e2..6fbada8 100644 --- a/spec/unit/defines/server/grant_role_spec.rb +++ b/spec/unit/defines/server/grant_role_spec.rb @@ -1,105 +1,104 @@ require 'spec_helper' -describe 'postgresql::server::grant_role', :type => :define do +describe 'postgresql::server::grant_role', type: :define do let :pre_condition do "class { 'postgresql::server': }" end - let :facts do - {:osfamily => 'Debian', - :operatingsystem => 'Debian', - :operatingsystemrelease => '6.0', - :kernel => 'Linux', :concat_basedir => tmpfilename('postgis'), - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', - } + let(:facts) do + { osfamily: 'Debian', + operatingsystem: 'Debian', + operatingsystemrelease: '6.0', + kernel: 'Linux', concat_basedir: tmpfilename('postgis'), + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin' } end - let (:title) { 'test' } + let(:title) { 'test' } - let (:params) { { - :group => 'my_group', - :role => 'my_role', - } } + let(:params) do + { + group: 'my_group', + role: 'my_role', + } + end - context "with mandatory arguments only" do + context 'with mandatory arguments only' do it { - is_expected.to contain_postgresql_psql("grant_role:#{title}").with({ - :command => "GRANT \"#{params[:group]}\" TO \"#{params[:role]}\"", - :unless => "SELECT 1 WHERE EXISTS (SELECT 1 FROM pg_roles AS r_role JOIN pg_auth_members AS am ON r_role.oid = am.member JOIN pg_roles AS r_group ON r_group.oid = am.roleid WHERE r_group.rolname = '#{params[:group]}' AND r_role.rolname = '#{params[:role]}') = true", - }).that_requires('Class[postgresql::server]') + is_expected.to contain_postgresql_psql("grant_role:#{title}") + .with(command: "GRANT \"#{params[:group]}\" TO \"#{params[:role]}\"", + unless: "SELECT 1 WHERE EXISTS (SELECT 1 FROM pg_roles AS r_role JOIN pg_auth_members AS am ON r_role.oid = am.member JOIN pg_roles AS r_group ON r_group.oid = am.roleid WHERE r_group.rolname = '#{params[:group]}' AND r_role.rolname = '#{params[:role]}') = true") # rubocop:disable Metrics/LineLength + .that_requires('Class[postgresql::server]') } end - context "with db arguments" do - let (:params) { super().merge({ - :psql_db => 'postgres', - :psql_user => 'postgres', - :port => '5432', - }) } + context 'with db arguments' do + let(:params) do + super().merge(psql_db: 'postgres', + psql_user: 'postgres', + port: '5432') + end it { - is_expected.to contain_postgresql_psql("grant_role:#{title}").with({ - :command => "GRANT \"#{params[:group]}\" TO \"#{params[:role]}\"", - :unless => "SELECT 1 WHERE EXISTS (SELECT 1 FROM pg_roles AS r_role JOIN pg_auth_members AS am ON r_role.oid = am.member JOIN pg_roles AS r_group ON r_group.oid = am.roleid WHERE r_group.rolname = '#{params[:group]}' AND r_role.rolname = '#{params[:role]}') = true", - :db => params[:psql_db], - :psql_user => params[:psql_user], - :port => params[:port], - }).that_requires('Class[postgresql::server]') + is_expected.to contain_postgresql_psql("grant_role:#{title}") + .with(command: "GRANT \"#{params[:group]}\" TO \"#{params[:role]}\"", + unless: "SELECT 1 WHERE EXISTS (SELECT 1 FROM pg_roles AS r_role JOIN pg_auth_members AS am ON r_role.oid = am.member JOIN pg_roles AS r_group ON r_group.oid = am.roleid WHERE r_group.rolname = '#{params[:group]}' AND r_role.rolname = '#{params[:role]}') = true", # rubocop:disable Metrics/LineLength + db: params[:psql_db], psql_user: params[:psql_user], + port: params[:port]).that_requires('Class[postgresql::server]') } end - context "with ensure => absent" do - let (:params) { super().merge({ - :ensure => 'absent', - }) } + context 'with ensure => absent' do + let(:params) do + super().merge(ensure: 'absent') + end it { - is_expected.to contain_postgresql_psql("grant_role:#{title}").with({ - :command => "REVOKE \"#{params[:group]}\" FROM \"#{params[:role]}\"", - :unless => "SELECT 1 WHERE EXISTS (SELECT 1 FROM pg_roles AS r_role JOIN pg_auth_members AS am ON r_role.oid = am.member JOIN pg_roles AS r_group ON r_group.oid = am.roleid WHERE r_group.rolname = '#{params[:group]}' AND r_role.rolname = '#{params[:role]}') != true", - }).that_requires('Class[postgresql::server]') + is_expected.to contain_postgresql_psql("grant_role:#{title}") + .with(command: "REVOKE \"#{params[:group]}\" FROM \"#{params[:role]}\"", + unless: "SELECT 1 WHERE EXISTS (SELECT 1 FROM pg_roles AS r_role JOIN pg_auth_members AS am ON r_role.oid = am.member JOIN pg_roles AS r_group ON r_group.oid = am.roleid WHERE r_group.rolname = '#{params[:group]}' AND r_role.rolname = '#{params[:role]}') != true") # rubocop:disable Metrics/LineLength + .that_requires('Class[postgresql::server]') } end - context "with user defined" do - let :pre_condition do + context 'with user defined' do + let(:pre_condition) do "class { 'postgresql::server': } postgresql::server::role { '#{params[:role]}': }" end it { is_expected.to contain_postgresql_psql("grant_role:#{title}").that_requires("Postgresql::Server::Role[#{params[:role]}]") } it { is_expected.not_to contain_postgresql_psql("grant_role:#{title}").that_requires("Postgresql::Server::Role[#{params[:group]}]") } end - context "with group defined" do - let :pre_condition do + context 'with group defined' do + let(:pre_condition) do "class { 'postgresql::server': } postgresql::server::role { '#{params[:group]}': }" end it { is_expected.to contain_postgresql_psql("grant_role:#{title}").that_requires("Postgresql::Server::Role[#{params[:group]}]") } it { is_expected.not_to contain_postgresql_psql("grant_role:#{title}").that_requires("Postgresql::Server::Role[#{params[:role]}]") } end - context "with connect_settings" do - let (:params) { super().merge({ - :connect_settings => { 'PGHOST' => 'postgres-db-server' }, - }) } + context 'with connect_settings' do + let(:params) do + super().merge(connect_settings: { 'PGHOST' => 'postgres-db-server' }) + end it { - is_expected.to contain_postgresql_psql("grant_role:#{title}").with_connect_settings( { 'PGHOST' => 'postgres-db-server' } ) + is_expected.to contain_postgresql_psql("grant_role:#{title}").with_connect_settings('PGHOST' => 'postgres-db-server') } it { is_expected.not_to contain_postgresql_psql("grant_role:#{title}").that_requires('Class[postgresql::server]') } end end diff --git a/spec/unit/defines/server/grant_spec.rb b/spec/unit/defines/server/grant_spec.rb index 2244146..c221dc8 100644 --- a/spec/unit/defines/server/grant_spec.rb +++ b/spec/unit/defines/server/grant_spec.rb @@ -1,264 +1,264 @@ require 'spec_helper' -describe 'postgresql::server::grant', :type => :define do +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', + 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', + db: 'test', + role: 'test', } end let :pre_condition do "class {'postgresql::server':}" end 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', + db: 'test', + role: 'test', + privilege: 'usage', + object_type: 'sequence', } end let :pre_condition do "class {'postgresql::server':}" end it { is_expected.to contain_postgresql__server__grant('test') } - it { is_expected.to contain_postgresql_psql('grant:test').with( - { - 'command' => /GRANT USAGE ON SEQUENCE "test" TO\s* "test"/m, - 'unless' => /SELECT 1 WHERE has_sequence_privilege\('test',\s* 'test', 'USAGE'\)/m, - } - ) } + it { + is_expected.to contain_postgresql_psql('grant:test').with( + 'command' => %r{GRANT USAGE ON SEQUENCE "test" TO\s* "test"}m, + 'unless' => %r{SELECT 1 WHERE has_sequence_privilege\('test',\s* 'test', 'USAGE'\)}m, + ) + } end context 'SeQuEnCe case insensitive object_type match' do let :params do { - :db => 'test', - :role => 'test', - :privilege => 'usage', - :object_type => 'SeQuEnCe', + db: 'test', + role: 'test', + privilege: 'usage', + object_type: 'SeQuEnCe', } end let :pre_condition do "class {'postgresql::server':}" end it { is_expected.to contain_postgresql__server__grant('test') } - it { is_expected.to contain_postgresql_psql('grant:test').with( - { - 'command' => /GRANT USAGE ON SEQUENCE "test" TO\s* "test"/m, - 'unless' => /SELECT 1 WHERE has_sequence_privilege\('test',\s* 'test', 'USAGE'\)/m, - } - ) } + it { + is_expected.to contain_postgresql_psql('grant:test').with( + 'command' => %r{GRANT USAGE ON SEQUENCE "test" TO\s* "test"}m, + 'unless' => %r{SELECT 1 WHERE has_sequence_privilege\('test',\s* 'test', 'USAGE'\)}m, + ) + } end context 'all sequences' do let :params do { - :db => 'test', - :role => 'test', - :privilege => 'usage', - :object_type => 'all sequences in schema', - :object_name => 'public', + 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 contain_postgresql__server__grant('test') } - it { is_expected.to contain_postgresql_psql('grant:test').with( - { - 'command' => /GRANT USAGE ON ALL SEQUENCES IN SCHEMA "public" TO\s* "test"/m, - 'unless' => /SELECT 1 FROM \(\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*\) P\s* HAVING count\(P\.sequence_name\) = 0/m, - } - ) } + it { + is_expected.to contain_postgresql_psql('grant:test').with( + 'command' => %r{GRANT USAGE ON ALL SEQUENCES IN SCHEMA "public" TO\s* "test"}m, + 'unless' => %r{SELECT 1 FROM \(\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*\) P\s* HAVING count\(P\.sequence_name\) = 0}m, # rubocop:disable Metrics/LineLength + ) + } end - context "with specific db connection settings - default port" do + 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', }, + 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 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 ) } + 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 + 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', }, + 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 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' } ) } + 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 + 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, + 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 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' ) } + 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 => ['myschema', 'mytable'], - :object_type => 'table', + db: 'test', + role: 'test', + privilege: 'all', + object_name: %w[myschema mytable], + object_type: 'table', } end let :pre_condition do "class {'postgresql::server':}" end it { is_expected.to contain_postgresql__server__grant('test') } - it { is_expected.to contain_postgresql_psql('grant:test').with( - { - 'command' => /GRANT ALL ON TABLE "myschema"."mytable" TO\s* "test"/m, - 'unless' => /SELECT 1 WHERE has_table_privilege\('test',\s*'myschema.mytable', 'INSERT'\)/m, - } - ) } + it { + is_expected.to contain_postgresql_psql('grant:test').with( + 'command' => %r{GRANT ALL ON TABLE "myschema"."mytable" TO\s* "test"}m, + 'unless' => %r{SELECT 1 WHERE has_table_privilege\('test',\s*'myschema.mytable', 'INSERT'\)}m, + ) + } end context 'invalid object_type' do let :params do { - :db => 'test', - :role => 'test', - :privilege => 'usage', - :object_type => 'invalid', + 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(/parameter 'object_type' expects a match for Pattern/) } + 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', + 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(/parameter 'object_name' expects a value of type (Array|Undef, Array,) or String, got Integer/) } + 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', + 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(/parameter 'object_name' variant 1 expects size to be 2, got 1/) } + 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(/parameter 'object_name' variant 0 expects size to be 2, got 1/) } + 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 => ['myschema', 'mytable', 'oops'], - :object_type => 'table', + db: 'test', + role: 'test', + privilege: 'all', + object_name: %w[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(/parameter 'object_name' variant 1 expects size to be 2, got 3/) } + 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(/parameter 'object_name' variant 0 expects size to be 2, got 3/) } + 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/defines/server/pg_hba_rule_spec.rb b/spec/unit/defines/server/pg_hba_rule_spec.rb index 24ead07..44b854c 100644 --- a/spec/unit/defines/server/pg_hba_rule_spec.rb +++ b/spec/unit/defines/server/pg_hba_rule_spec.rb @@ -1,156 +1,148 @@ require 'spec_helper' -describe 'postgresql::server::pg_hba_rule', :type => :define do +describe 'postgresql::server::pg_hba_rule', type: :define do let :facts do { - :osfamily => 'Debian', - :operatingsystem => 'Debian', - :operatingsystemrelease => '6.0', - :kernel => 'Linux', - :concat_basedir => tmpfilename('pg_hba'), - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + osfamily: 'Debian', + operatingsystem: 'Debian', + operatingsystemrelease: '6.0', + kernel: 'Linux', + concat_basedir: tmpfilename('pg_hba'), + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', } end let :title do 'test' end let :target do tmpfilename('pg_hba_rule') end context 'test template 1' do let :pre_condition do - <<-EOS + <<-MANIFEST class { 'postgresql::server': } - EOS + MANIFEST end let :params do { - :type => 'host', - :database => 'all', - :user => 'all', - :address => '1.1.1.1/24', - :auth_method => 'md5', - :target => target, + type: 'host', + database: 'all', + user: 'all', + address: '1.1.1.1/24', + auth_method: 'md5', + target: target, } end + it do - is_expected.to contain_concat__fragment('pg_hba_rule_test').with({ - :content => /host\s+all\s+all\s+1\.1\.1\.1\/24\s+md5/ - }) + is_expected.to contain_concat__fragment('pg_hba_rule_test').with(content: %r{host\s+all\s+all\s+1\.1\.1\.1\/24\s+md5}) end end context 'test template 2' do let :pre_condition do - <<-EOS + <<-MANIFEST class { 'postgresql::server': } - EOS + MANIFEST end let :params do { - :type => 'local', - :database => 'all', - :user => 'all', - :auth_method => 'ident', - :target => target, + type: 'local', + database: 'all', + user: 'all', + auth_method: 'ident', + target: target, } end + it do - is_expected.to contain_concat__fragment('pg_hba_rule_test').with({ - :content => /local\s+all\s+all\s+ident/ - }) + is_expected.to contain_concat__fragment('pg_hba_rule_test').with(content: %r{local\s+all\s+all\s+ident}) end end context 'test template 3' do let :pre_condition do - <<-EOS + <<-MANIFEST class { 'postgresql::server': } - EOS + MANIFEST end let :params do { - :type => 'host', - :database => 'all', - :user => 'all', - :address => '0.0.0.0/0', - :auth_method => 'ldap', - :auth_option => 'foo=bar', - :target => target, + type: 'host', + database: 'all', + user: 'all', + address: '0.0.0.0/0', + auth_method: 'ldap', + auth_option: 'foo=bar', + target: target, } end + it do - is_expected.to contain_concat__fragment('pg_hba_rule_test').with({ - :content => /host\s+all\s+all\s+0\.0\.0\.0\/0\s+ldap\s+foo=bar/ - }) + is_expected.to contain_concat__fragment('pg_hba_rule_test').with(content: %r{host\s+all\s+all\s+0\.0\.0\.0\/0\s+ldap\s+foo=bar}) end end context 'validation' do context 'validate supported auth_method' do let :pre_condition do - <<-EOS + <<-MANIFEST class { 'postgresql::globals': version => '9.2', } class { 'postgresql::server': } - EOS + MANIFEST end let :params do { - :type => 'local', - :database => 'all', - :user => 'all', - :address => '0.0.0.0/0', - :auth_method => 'peer', - :target => target, + type: 'local', + database: 'all', + user: 'all', + address: '0.0.0.0/0', + auth_method: 'peer', + target: target, } end it do is_expected.to contain_concat__fragment('pg_hba_rule_test').with( - { - :content => /local\s+all\s+all\s+0\.0\.0\.0\/0\s+peer/ - } + content: %r{local\s+all\s+all\s+0\.0\.0\.0\/0\s+peer}, ) end end context 'allows scram-sha-256 on postgres 10' do let :pre_condition do - <<-EOS + <<-MANIFEST class { 'postgresql::globals': version => '10', } class { 'postgresql::server': } - EOS + MANIFEST end let :params do { - :type => 'local', - :database => 'all', - :user => 'all', - :address => '0.0.0.0/0', - :auth_method => 'scram-sha-256', - :target => target, + type: 'local', + database: 'all', + user: 'all', + address: '0.0.0.0/0', + auth_method: 'scram-sha-256', + target: target, } end it do is_expected.to contain_concat__fragment('pg_hba_rule_test').with( - { - :content => /local\s+all\s+all\s+0\.0\.0\.0\/0\s+scram-sha-256/ - } + content: %r{local\s+all\s+all\s+0\.0\.0\.0\/0\s+scram-sha-256}, ) end end - end end diff --git a/spec/unit/defines/server/pg_ident_rule_spec.rb b/spec/unit/defines/server/pg_ident_rule_spec.rb index 71dfff8..68bdfb2 100644 --- a/spec/unit/defines/server/pg_ident_rule_spec.rb +++ b/spec/unit/defines/server/pg_ident_rule_spec.rb @@ -1,66 +1,66 @@ require 'spec_helper' -describe 'postgresql::server::pg_ident_rule', :type => :define do +describe 'postgresql::server::pg_ident_rule', type: :define do let :facts do { - :osfamily => 'Debian', - :operatingsystem => 'Debian', - :operatingsystemrelease => '6.0', - :kernel => 'Linux', - :concat_basedir => tmpfilename('pg_ident'), - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + osfamily: 'Debian', + operatingsystem: 'Debian', + operatingsystemrelease: '6.0', + kernel: 'Linux', + concat_basedir: tmpfilename('pg_ident'), + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', } end let :title do 'test' end let :target do tmpfilename('pg_ident_rule') end context 'managing pg_ident' do let :pre_condition do - <<-EOS + <<-MANIFEST class { 'postgresql::globals': manage_pg_ident_conf => true, } class { 'postgresql::server': } - EOS + MANIFEST end let :params do { - :map_name => 'thatsmymap', - :system_username => 'systemuser', - :database_username => 'dbuser', + map_name: 'thatsmymap', + system_username: 'systemuser', + database_username: 'dbuser', } end + it do - is_expected.to contain_concat__fragment('pg_ident_rule_test').with({ - :content => /thatsmymap\s+systemuser\s+dbuser/ - }) + is_expected.to contain_concat__fragment('pg_ident_rule_test').with(content: %r{thatsmymap\s+systemuser\s+dbuser}) end end context 'not managing pg_ident' do let :pre_condition do - <<-EOS + <<-MANIFEST class { 'postgresql::globals': manage_pg_ident_conf => false, } class { 'postgresql::server': } - EOS + MANIFEST end let :params do { - :map_name => 'thatsmymap', - :system_username => 'systemuser', - :database_username => 'dbuser', + map_name: 'thatsmymap', + system_username: 'systemuser', + database_username: 'dbuser', } end - it 'should fail because $manage_pg_ident_conf is false' do + + it 'fails because $manage_pg_ident_conf is false' do expect { catalogue }.to raise_error(Puppet::Error, - /postgresql::server::manage_pg_ident_conf has been disabled/) + %r{postgresql::server::manage_pg_ident_conf has been disabled}) end end end diff --git a/spec/unit/defines/server/reassign_owned_by_spec.rb b/spec/unit/defines/server/reassign_owned_by_spec.rb index 72f67c3..1c8bd9f 100644 --- a/spec/unit/defines/server/reassign_owned_by_spec.rb +++ b/spec/unit/defines/server/reassign_owned_by_spec.rb @@ -1,44 +1,43 @@ require 'spec_helper' -describe 'postgresql::server::reassign_owned_by', :type => :define do +describe 'postgresql::server::reassign_owned_by', type: :define do let :facts do { - :osfamily => 'Debian', - :operatingsystem => 'Debian', - :operatingsystemrelease => '6.0', - :kernel => 'Linux', - :concat_basedir => tmpfilename('reassign_owned_by'), - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + osfamily: 'Debian', + operatingsystem: 'Debian', + operatingsystemrelease: '6.0', + kernel: 'Linux', + concat_basedir: tmpfilename('reassign_owned_by'), + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', } end let :title do 'test' end let :params do { - :db => 'test', - :old_role => 'test_old_role', - :new_role => 'test_new_role', + db: 'test', + old_role: 'test_old_role', + new_role: 'test_new_role', } end let :pre_condition do - <<-EOS + <<-MANIFEST class {'postgresql::server':} postgresql::server::role{ ['test_old_role','test_new_role']: } - EOS + MANIFEST end it { is_expected.to contain_postgresql__server__reassign_owned_by('test') } it { - is_expected.to contain_postgresql_psql('reassign_owned_by:test:REASSIGN OWNED BY "test_old_role" TO "test_new_role"').with({ - 'command' => "REASSIGN OWNED BY \"test_old_role\" TO \"test_new_role\"", - 'onlyif' => /SELECT tablename FROM pg_catalog.pg_tables WHERE\s*schemaname NOT IN \('pg_catalog', 'information_schema'\) AND\s*tableowner = 'test_old_role'.*/m, - }).that_requires('Class[postgresql::server]') + is_expected.to contain_postgresql_psql('reassign_owned_by:test:REASSIGN OWNED BY "test_old_role" TO "test_new_role"') + .with('command' => 'REASSIGN OWNED BY "test_old_role" TO "test_new_role"', + 'onlyif' => %r{SELECT tablename FROM pg_catalog.pg_tables WHERE\s*schemaname NOT IN \('pg_catalog', 'information_schema'\) AND\s*tableowner = 'test_old_role'.*}m) + .that_requires('Class[postgresql::server]') } - end diff --git a/spec/unit/defines/server/recovery_spec.rb b/spec/unit/defines/server/recovery_spec.rb index 8c78e3e..25bc132 100644 --- a/spec/unit/defines/server/recovery_spec.rb +++ b/spec/unit/defines/server/recovery_spec.rb @@ -1,113 +1,115 @@ require 'spec_helper' -describe 'postgresql::server::recovery', :type => :define do +describe 'postgresql::server::recovery', type: :define do let :facts do { - :osfamily => 'Debian', - :operatingsystem => 'Debian', - :operatingsystemrelease => '6.0', - :kernel => 'Linux', - :concat_basedir => tmpfilename('recovery'), - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + osfamily: 'Debian', + operatingsystem: 'Debian', + operatingsystemrelease: '6.0', + kernel: 'Linux', + concat_basedir: tmpfilename('recovery'), + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', } end - let :title do + let(:title) do 'test' end let :target do tmpfilename('recovery') end context 'managing recovery' do - let :pre_condition do - <<-EOS + let(:pre_condition) do + <<-MANIFEST class { 'postgresql::globals': manage_recovery_conf => true, } class { 'postgresql::server': } - EOS + MANIFEST end - let :params do + let(:params) do { - :restore_command => 'restore_command', - :recovery_target_timeline => 'recovery_target_timeline', + restore_command: 'restore_command', + recovery_target_timeline: 'recovery_target_timeline', } end + it do - is_expected.to contain_concat__fragment('recovery.conf').with({ - :content => /restore_command = 'restore_command'[\n]+recovery_target_timeline = 'recovery_target_timeline'/ - }) + is_expected.to contain_concat__fragment('recovery.conf') + .with(content: %r{restore_command = 'restore_command'[\n]+recovery_target_timeline = 'recovery_target_timeline'}) end end context 'not managing recovery' do - let :pre_condition do - <<-EOS + let(:pre_condition) do + <<-MANIFEST class { 'postgresql::globals': manage_recovery_conf => false, } class { 'postgresql::server': } - EOS + MANIFEST end - let :params do + let(:params) do { - :restore_command => '', + restore_command: '', } end - it 'should fail because $manage_recovery_conf is false' do + + it 'fails because $manage_recovery_conf is false' do expect { catalogue }.to raise_error(Puppet::Error, - /postgresql::server::manage_recovery_conf has been disabled/) + %r{postgresql::server::manage_recovery_conf has been disabled}) end end context 'not managing recovery, missing param' do - let :pre_condition do - <<-EOS + let(:pre_condition) do + <<-MANIFEST class { 'postgresql::globals': manage_recovery_conf => true, } class { 'postgresql::server': } - EOS + MANIFEST end - it 'should fail because no param set' do + + it 'fails because no param set' do expect { catalogue }.to raise_error(Puppet::Error, - /postgresql::server::recovery use this resource but do not pass a parameter will avoid creating the recovery.conf, because it makes no sense./) + %r{postgresql::server::recovery use this resource but do not pass a parameter will avoid creating the recovery.conf, because it makes no sense.}) end end context 'managing recovery with all params' do - let :pre_condition do - <<-EOS + let(:pre_condition) do + <<-MANIFEST class { 'postgresql::globals': manage_recovery_conf => true, } class { 'postgresql::server': } - EOS + MANIFEST end - let :params do + let(:params) do { - :restore_command => 'restore_command', - :archive_cleanup_command => 'archive_cleanup_command', - :recovery_end_command => 'recovery_end_command', - :recovery_target_name => 'recovery_target_name', - :recovery_target_time => 'recovery_target_time', - :recovery_target_xid => 'recovery_target_xid', - :recovery_target_inclusive => true, - :recovery_target => 'recovery_target', - :recovery_target_timeline => 'recovery_target_timeline', - :pause_at_recovery_target => true, - :standby_mode => 'on', - :primary_conninfo => 'primary_conninfo', - :primary_slot_name => 'primary_slot_name', - :trigger_file => 'trigger_file', - :recovery_min_apply_delay => 0, + restore_command: 'restore_command', + archive_cleanup_command: 'archive_cleanup_command', + recovery_end_command: 'recovery_end_command', + recovery_target_name: 'recovery_target_name', + recovery_target_time: 'recovery_target_time', + recovery_target_xid: 'recovery_target_xid', + recovery_target_inclusive: true, + recovery_target: 'recovery_target', + recovery_target_timeline: 'recovery_target_timeline', + pause_at_recovery_target: true, + standby_mode: 'on', + primary_conninfo: 'primary_conninfo', + primary_slot_name: 'primary_slot_name', + trigger_file: 'trigger_file', + recovery_min_apply_delay: 0, } end + it do - is_expected.to contain_concat__fragment('recovery.conf').with({ - :content => /restore_command = 'restore_command'[\n]+archive_cleanup_command = 'archive_cleanup_command'[\n]+recovery_end_command = 'recovery_end_command'[\n]+recovery_target_name = 'recovery_target_name'[\n]+recovery_target_time = 'recovery_target_time'[\n]+recovery_target_xid = 'recovery_target_xid'[\n]+recovery_target_inclusive = true[\n]+recovery_target = 'recovery_target'[\n]+recovery_target_timeline = 'recovery_target_timeline'[\n]+pause_at_recovery_target = true[\n]+standby_mode = on[\n]+primary_conninfo = 'primary_conninfo'[\n]+primary_slot_name = 'primary_slot_name'[\n]+trigger_file = 'trigger_file'[\n]+recovery_min_apply_delay = 0[\n]+/ - }) + is_expected.to contain_concat__fragment('recovery.conf') + .with(content: %r{restore_command = 'restore_command'[\n]+archive_cleanup_command = 'archive_cleanup_command'[\n]+recovery_end_command = 'recovery_end_command'[\n]+recovery_target_name = 'recovery_target_name'[\n]+recovery_target_time = 'recovery_target_time'[\n]+recovery_target_xid = 'recovery_target_xid'[\n]+recovery_target_inclusive = true[\n]+recovery_target = 'recovery_target'[\n]+recovery_target_timeline = 'recovery_target_timeline'[\n]+pause_at_recovery_target = true[\n]+standby_mode = on[\n]+primary_conninfo = 'primary_conninfo'[\n]+primary_slot_name = 'primary_slot_name'[\n]+trigger_file = 'trigger_file'[\n]+recovery_min_apply_delay = 0[\n]+}) # rubocop:disable Metrics/LineLength end end end diff --git a/spec/unit/defines/server/role_spec.rb b/spec/unit/defines/server/role_spec.rb index 6da904d..1cd2ca9 100644 --- a/spec/unit/defines/server/role_spec.rb +++ b/spec/unit/defines/server/role_spec.rb @@ -1,168 +1,143 @@ require 'spec_helper' -describe 'postgresql::server::role', :type => :define do +describe 'postgresql::server::role', 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', + 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 let :params do { - :password_hash => 'new-pa$s', + password_hash: 'new-pa$s', } end let :pre_condition do - "class {'postgresql::server':}" + "class {'postgresql::server':}" end it { is_expected.to contain_postgresql__server__role('test') } - it 'should have create role for "test" user with password as ****' do - is_expected.to contain_postgresql_psql('CREATE ROLE test ENCRYPTED PASSWORD ****').with({ - 'command' => "CREATE ROLE \"test\" ENCRYPTED PASSWORD '$NEWPGPASSWD' LOGIN NOCREATEROLE NOCREATEDB NOSUPERUSER CONNECTION LIMIT -1", - 'environment' => "NEWPGPASSWD=new-pa$s", - 'unless' => "SELECT 1 FROM pg_roles WHERE rolname = 'test'", - 'port' => "5432", - }) + it 'has create role for "test" user with password as ****' do + is_expected.to contain_postgresql_psql('CREATE ROLE test ENCRYPTED PASSWORD ****') + .with('command' => "CREATE ROLE \"test\" ENCRYPTED PASSWORD '$NEWPGPASSWD' LOGIN NOCREATEROLE NOCREATEDB NOSUPERUSER CONNECTION LIMIT -1", + 'environment' => 'NEWPGPASSWD=new-pa$s', + 'unless' => "SELECT 1 FROM pg_roles WHERE rolname = 'test'", + 'port' => '5432') end - it 'should have alter role for "test" user with password as ****' do - is_expected.to contain_postgresql_psql('ALTER ROLE test ENCRYPTED PASSWORD ****').with({ - 'command' => "ALTER ROLE \"test\" ENCRYPTED PASSWORD '$NEWPGPASSWD'", - 'environment' => "NEWPGPASSWD=new-pa$s", - 'unless' => "SELECT 1 FROM pg_shadow WHERE usename = 'test' AND passwd = 'md5b6f7fcbbabb4befde4588a26c1cfd2fa'", - 'port' => "5432", - }) + it 'has alter role for "test" user with password as ****' do + is_expected.to contain_postgresql_psql('ALTER ROLE test ENCRYPTED PASSWORD ****') + .with('command' => "ALTER ROLE \"test\" ENCRYPTED PASSWORD '$NEWPGPASSWD'", + 'environment' => 'NEWPGPASSWD=new-pa$s', + 'unless' => "SELECT 1 FROM pg_shadow WHERE usename = 'test' AND passwd = 'md5b6f7fcbbabb4befde4588a26c1cfd2fa'", + 'port' => '5432') end - context "with specific db connection settings - default port" do + context 'with specific db connection settings - default port' do let :params do { - :password_hash => 'new-pa$s', - :connect_settings => { 'PGHOST' => 'postgres-db-server', - 'DBVERSION' => '9.1', - 'PGUSER' => 'login-user', - 'PGPASSWORD' => 'login-pass' }, + password_hash: 'new-pa$s', + connect_settings: { 'PGHOST' => 'postgres-db-server', + 'DBVERSION' => '9.1', + 'PGUSER' => 'login-user', + 'PGPASSWORD' => 'login-pass' }, } end let :pre_condition do - "class {'postgresql::server':}" + "class {'postgresql::server':}" end it { is_expected.to contain_postgresql__server__role('test') } - it 'should have create role for "test" user with password as ****' do - is_expected.to contain_postgresql_psql('CREATE ROLE test ENCRYPTED PASSWORD ****').with({ - 'command' => "CREATE ROLE \"test\" ENCRYPTED PASSWORD '$NEWPGPASSWD' LOGIN NOCREATEROLE NOCREATEDB NOSUPERUSER CONNECTION LIMIT -1", - 'environment' => "NEWPGPASSWD=new-pa$s", - 'unless' => "SELECT 1 FROM pg_roles WHERE rolname = 'test'", - 'port' => "5432", - - 'connect_settings' => { 'PGHOST' => 'postgres-db-server', - 'DBVERSION' => '9.1', - 'PGUSER' => 'login-user', - 'PGPASSWORD' => 'login-pass' }, - }) + it 'has create role for "test" user with password as ****' do + is_expected.to contain_postgresql_psql('CREATE ROLE test ENCRYPTED PASSWORD ****') + .with('command' => "CREATE ROLE \"test\" ENCRYPTED PASSWORD '$NEWPGPASSWD' LOGIN NOCREATEROLE NOCREATEDB NOSUPERUSER CONNECTION LIMIT -1", 'environment' => 'NEWPGPASSWD=new-pa$s', + 'unless' => "SELECT 1 FROM pg_roles WHERE rolname = 'test'", 'port' => '5432', + 'connect_settings' => { 'PGHOST' => 'postgres-db-server', 'DBVERSION' => '9.1', + 'PGUSER' => 'login-user', 'PGPASSWORD' => 'login-pass' }) end - it 'should have alter role for "test" user with password as ****' do - is_expected.to contain_postgresql_psql('ALTER ROLE test ENCRYPTED PASSWORD ****').with({ - 'command' => "ALTER ROLE \"test\" ENCRYPTED PASSWORD '$NEWPGPASSWD'", - 'environment' => "NEWPGPASSWD=new-pa$s", - 'unless' => "SELECT 1 FROM pg_shadow WHERE usename = 'test' AND passwd = 'md5b6f7fcbbabb4befde4588a26c1cfd2fa'", - 'port' => "5432", - - 'connect_settings' => { 'PGHOST' => 'postgres-db-server', - 'DBVERSION' => '9.1', - 'PGUSER' => 'login-user', - 'PGPASSWORD' => 'login-pass' }, - }) + it 'has alter role for "test" user with password as ****' do + is_expected.to contain_postgresql_psql('ALTER ROLE test ENCRYPTED PASSWORD ****') + .with('command' => "ALTER ROLE \"test\" ENCRYPTED PASSWORD '$NEWPGPASSWD'", 'environment' => 'NEWPGPASSWD=new-pa$s', + 'unless' => "SELECT 1 FROM pg_shadow WHERE usename = 'test' AND passwd = 'md5b6f7fcbbabb4befde4588a26c1cfd2fa'", 'port' => '5432', + 'connect_settings' => { 'PGHOST' => 'postgres-db-server', 'DBVERSION' => '9.1', + 'PGUSER' => 'login-user', 'PGPASSWORD' => 'login-pass' }) end end - context "with specific db connection settings - including port" do + context 'with specific db connection settings - including port' do let :params do { - :password_hash => 'new-pa$s', - :connect_settings => { 'PGHOST' => 'postgres-db-server', - 'DBVERSION' => '9.1', - 'PGPORT' => '1234', - 'PGUSER' => 'login-user', - 'PGPASSWORD' => 'login-pass' }, + password_hash: 'new-pa$s', + connect_settings: { 'PGHOST' => 'postgres-db-server', + 'DBVERSION' => '9.1', + 'PGPORT' => '1234', + 'PGUSER' => 'login-user', + 'PGPASSWORD' => 'login-pass' }, } end let :pre_condition do - "class {'postgresql::server':}" + "class {'postgresql::server':}" end it { is_expected.to contain_postgresql__server__role('test') } - it 'should have create role for "test" user with password as ****' do - is_expected.to contain_postgresql_psql('CREATE ROLE test ENCRYPTED PASSWORD ****').with({ - 'command' => "CREATE ROLE \"test\" ENCRYPTED PASSWORD '$NEWPGPASSWD' LOGIN NOCREATEROLE NOCREATEDB NOSUPERUSER CONNECTION LIMIT -1", - 'environment' => "NEWPGPASSWD=new-pa$s", - 'unless' => "SELECT 1 FROM pg_roles WHERE rolname = 'test'", - 'connect_settings' => { 'PGHOST' => 'postgres-db-server', - 'DBVERSION' => '9.1', - 'PGPORT' => '1234', - 'PGUSER' => 'login-user', - 'PGPASSWORD' => 'login-pass' }, - }) + it 'has create role for "test" user with password as ****' do + is_expected.to contain_postgresql_psql('CREATE ROLE test ENCRYPTED PASSWORD ****') + .with('command' => "CREATE ROLE \"test\" ENCRYPTED PASSWORD '$NEWPGPASSWD' LOGIN NOCREATEROLE NOCREATEDB NOSUPERUSER CONNECTION LIMIT -1", + 'environment' => 'NEWPGPASSWD=new-pa$s', 'unless' => "SELECT 1 FROM pg_roles WHERE rolname = 'test'", + 'connect_settings' => { 'PGHOST' => 'postgres-db-server', 'DBVERSION' => '9.1', + 'PGPORT' => '1234', 'PGUSER' => 'login-user', 'PGPASSWORD' => 'login-pass' }) end - it 'should have alter role for "test" user with password as ****' do - is_expected.to contain_postgresql_psql('ALTER ROLE test ENCRYPTED PASSWORD ****').with({ - 'command' => "ALTER ROLE \"test\" ENCRYPTED PASSWORD '$NEWPGPASSWD'", - 'environment' => "NEWPGPASSWD=new-pa$s", - 'unless' => "SELECT 1 FROM pg_shadow WHERE usename = 'test' AND passwd = 'md5b6f7fcbbabb4befde4588a26c1cfd2fa'", - 'connect_settings' => { 'PGHOST' => 'postgres-db-server', - 'DBVERSION' => '9.1', - 'PGPORT' => '1234', - 'PGUSER' => 'login-user', - 'PGPASSWORD' => 'login-pass' }, - }) + it 'has alter role for "test" user with password as ****' do + is_expected.to contain_postgresql_psql('ALTER ROLE test ENCRYPTED PASSWORD ****') + .with('command' => "ALTER ROLE \"test\" ENCRYPTED PASSWORD '$NEWPGPASSWD'", 'environment' => 'NEWPGPASSWD=new-pa$s', + 'unless' => "SELECT 1 FROM pg_shadow WHERE usename = 'test' AND passwd = 'md5b6f7fcbbabb4befde4588a26c1cfd2fa'", + 'connect_settings' => { 'PGHOST' => 'postgres-db-server', 'DBVERSION' => '9.1', + 'PGPORT' => '1234', 'PGUSER' => 'login-user', 'PGPASSWORD' => 'login-pass' }) end end context 'with update_password set to false' do let :params do { - :password_hash => 'new-pa$s', - :update_password => false, + password_hash: 'new-pa$s', + update_password: false, } end let :pre_condition do "class {'postgresql::server':}" end - it 'should not have alter role for "test" user with password as **** if update_password is false' do + it 'does not have alter role for "test" user with password as **** if update_password is false' do is_expected.not_to contain_postgresql_psql('ALTER ROLE test ENCRYPTED PASSWORD ****') end end context 'with ensure set to absent' do let :params do { - :ensure => 'absent', + ensure: 'absent', } end let :pre_condition do "class {'postgresql::server':}" end - it 'should have drop role for "test" user if ensure absent' do + it 'has drop role for "test" user if ensure absent' do is_expected.to contain_postgresql_psql('DROP ROLE "test"') end end - end diff --git a/spec/unit/defines/server/schema_spec.rb b/spec/unit/defines/server/schema_spec.rb index c8fa3d9..a87f3dc 100644 --- a/spec/unit/defines/server/schema_spec.rb +++ b/spec/unit/defines/server/schema_spec.rb @@ -1,43 +1,43 @@ require 'spec_helper' -describe 'postgresql::server::schema', :type => :define do +describe 'postgresql::server::schema', type: :define do let :facts do { - :osfamily => 'Debian', - :operatingsystem => 'Debian', - :operatingsystemrelease => '6.0', - :kernel => 'Linux', - :concat_basedir => tmpfilename('schema'), - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + osfamily: 'Debian', + operatingsystem: 'Debian', + operatingsystemrelease: '6.0', + kernel: 'Linux', + concat_basedir: tmpfilename('schema'), + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', } end let :title do 'test' end let :params do { - :owner => 'jane', - :db => 'janedb', + owner: 'jane', + db: 'janedb', } end let :pre_condition do "class {'postgresql::server':}" end - it { should contain_postgresql__server__schema('test') } + it { is_expected.to contain_postgresql__server__schema('test') } - context "with different owner" do + context 'with different owner' do let :params do { - :owner => 'nate', - :db => 'natedb', + owner: 'nate', + db: 'natedb', } end it { is_expected.to contain_postgresql_psql('natedb: ALTER SCHEMA "test" OWNER TO "nate"') } end end diff --git a/spec/unit/defines/server/table_grant_spec.rb b/spec/unit/defines/server/table_grant_spec.rb index eac55bd..4314eb2 100644 --- a/spec/unit/defines/server/table_grant_spec.rb +++ b/spec/unit/defines/server/table_grant_spec.rb @@ -1,35 +1,35 @@ require 'spec_helper' -describe 'postgresql::server::table_grant', :type => :define do +describe 'postgresql::server::table_grant', type: :define do let :facts do { - :osfamily => 'Debian', - :operatingsystem => 'Debian', - :operatingsystemrelease => '6.0', - :kernel => 'Linux', - :concat_basedir => tmpfilename('table_grant'), - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + osfamily: 'Debian', + operatingsystem: 'Debian', + operatingsystemrelease: '6.0', + kernel: 'Linux', + concat_basedir: tmpfilename('table_grant'), + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', } end let :title do 'test' end let :params do { - :privilege => 'ALL', - :db => 'test', - :role => 'test', - :table => 'foo', + privilege: 'ALL', + db: 'test', + role: 'test', + table: 'foo', } end let :pre_condition do "class {'postgresql::server':}" end it { is_expected.to contain_postgresql__server__table_grant('test') } it { is_expected.to contain_postgresql__server__grant('table:test') } end diff --git a/spec/unit/defines/server/tablespace_spec.rb b/spec/unit/defines/server/tablespace_spec.rb index 50a93e2..96285d5 100644 --- a/spec/unit/defines/server/tablespace_spec.rb +++ b/spec/unit/defines/server/tablespace_spec.rb @@ -1,42 +1,42 @@ require 'spec_helper' -describe 'postgresql::server::tablespace', :type => :define do +describe 'postgresql::server::tablespace', type: :define do let :facts do { - :osfamily => 'Debian', - :operatingsystem => 'Debian', - :operatingsystemrelease => '6.0', - :kernel => 'Linux', - :concat_basedir => tmpfilename('tablespace'), - :id => 'root', - :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', + osfamily: 'Debian', + operatingsystem: 'Debian', + operatingsystemrelease: '6.0', + kernel: 'Linux', + concat_basedir: tmpfilename('tablespace'), + id: 'root', + path: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', } end let :title do 'test' end let :params do { - :location => '/srv/data/foo', + location: '/srv/data/foo', } end let :pre_condition do "class {'postgresql::server':}" end it { is_expected.to contain_postgresql__server__tablespace('test') } - context "with different owner" do + context 'with different owner' do let :params do { - :location => '/srv/data/foo', - :owner => 'test_owner', + location: '/srv/data/foo', + owner: 'test_owner', } end it { is_expected.to contain_postgresql_psql('ALTER TABLESPACE "test" OWNER TO "test_owner"') } end end diff --git a/spec/unit/defines/validate_db_connection_spec.rb b/spec/unit/defines/validate_db_connection_spec.rb index c7406dc..243c591 100644 --- a/spec/unit/defines/validate_db_connection_spec.rb +++ b/spec/unit/defines/validate_db_connection_spec.rb @@ -1,72 +1,66 @@ require 'spec_helper' -describe 'postgresql::validate_db_connection', :type => :define do +describe 'postgresql::validate_db_connection', type: :define do let :facts do { - :osfamily => 'Debian', - :operatingsystem => 'Debian', - :operatingsystemrelease => '6.0', + osfamily: 'Debian', + operatingsystem: 'Debian', + operatingsystemrelease: '6.0', } end let :title do 'test' end describe 'should work with only default parameters' do it { is_expected.to contain_postgresql__validate_db_connection('test') } end describe 'should work with all parameters' do let :params do { - :database_host => 'test', - :database_name => 'test', - :database_password => 'test', - :database_username => 'test', - :database_port => 5432, - :run_as => 'postgresq', - :sleep => 4, - :tries => 30, + database_host: 'test', + database_name: 'test', + database_password: 'test', + database_username: 'test', + database_port: 5432, + run_as: 'postgresq', + sleep: 4, + tries: 30, } end + it { is_expected.to contain_postgresql__validate_db_connection('test') } - it 'should have proper path for validate command' do - is_expected.to contain_exec('validate postgres connection for test@test:5432/test').with({ - :unless => %r'^/usr/local/bin/validate_postgresql_connection.sh\s+\d+' - }) + it 'has proper path for validate command' do + is_expected.to contain_exec('validate postgres connection for test@test:5432/test').with(unless: %r{^/usr/local/bin/validate_postgresql_connection.sh\s+\d+}) end end describe 'should work while specifying validate_connection in postgresql::client' do - let :params do { - :database_host => 'test', - :database_name => 'test', - :database_password => 'test', - :database_username => 'test', - :database_port => 5432 + database_host: 'test', + database_name: 'test', + database_password: 'test', + database_username: 'test', + database_port: 5432, } end let :pre_condition do - <<-EOS + <<-MANIFEST class { 'postgresql::globals': module_workdir => '/var/tmp', } -> class { 'postgresql::client': validcon_script_path => '/opt/something/validate.sh' } - EOS - end - - it 'should have proper path for validate command and correct cwd' do - is_expected.to contain_exec('validate postgres connection for test@test:5432/test').with({ - :unless => %r'^/opt/something/validate.sh\s+\d+', - :cwd => '/var/tmp', - }) + MANIFEST end + it 'has proper path for validate command and correct cwd' do + is_expected.to contain_exec('validate postgres connection for test@test:5432/test').with(unless: %r{^/opt/something/validate.sh\s+\d+}, + cwd: '/var/tmp') + end end - end diff --git a/spec/unit/functions/postgresql_acls_to_resources_hash_spec.rb b/spec/unit/functions/postgresql_acls_to_resources_hash_spec.rb index e21b521..76df663 100644 --- a/spec/unit/functions/postgresql_acls_to_resources_hash_spec.rb +++ b/spec/unit/functions/postgresql_acls_to_resources_hash_spec.rb @@ -1,137 +1,74 @@ require 'spec_helper' -describe 'postgresql_acls_to_resources_hash', :type => :puppet_function do +describe 'postgresql_acls_to_resources_hash', type: :puppet_function do context 'individual transform tests' do it do input = 'local all postgres ident' - result = { - "postgresql class generated rule test 0"=>{ - "type"=>"local", - "database"=>"all", - "user"=>"postgres", - "auth_method"=>"ident", - "order"=>"100", - }, - } + result = { 'postgresql class generated rule test 0' => { 'type' => 'local', 'database' => 'all', 'user' => 'postgres', + 'auth_method' => 'ident', 'order' => '100' } } is_expected.to run.with_params([input], 'test', 100).and_return(result) end it do input = 'local all root ident' - result = { - "postgresql class generated rule test 0"=>{ - "type"=>"local", - "database"=>"all", - "user"=>"root", - "auth_method"=>"ident", - "order"=>"100", - }, - } + result = { 'postgresql class generated rule test 0' => { 'type' => 'local', 'database' => 'all', 'user' => 'root', + 'auth_method' => 'ident', 'order' => '100' } } is_expected.to run.with_params([input], 'test', 100).and_return(result) end it do - input_array = [ - 'local all all ident', - ] - result = { - "postgresql class generated rule test 0"=>{ - "type"=>"local", - "database"=>"all", - "user"=>"all", - "auth_method"=>"ident", - "order"=>"100", - }, - } + input_array = ['local all all ident'] + result = { 'postgresql class generated rule test 0' => { 'type' => 'local', 'database' => 'all', 'user' => 'all', + 'auth_method' => 'ident', 'order' => '100' } } is_expected.to run.with_params(input_array, 'test', 100).and_return(result) end it do input = 'host all all 127.0.0.1/32 md5' - result = { - "postgresql class generated rule test 0"=>{ - "type"=>"host", - "database"=>"all", - "user"=>"all", - "address"=>"127.0.0.1/32", - "auth_method"=>"md5", - "order"=>"100", - }, - } + result = { 'postgresql class generated rule test 0' => { 'type' => 'host', 'database' => 'all', 'user' => 'all', 'address' => '127.0.0.1/32', + 'auth_method' => 'md5', 'order' => '100' } } is_expected.to run.with_params([input], 'test', 100).and_return(result) end it do input = 'host all all 0.0.0.0/0 md5' - result = { - "postgresql class generated rule test 0"=>{ - "type"=>"host", - "database"=>"all", - "user"=>"all", - "address"=>"0.0.0.0/0", - "auth_method"=>"md5", - "order"=>"100", - }, - } + result = { 'postgresql class generated rule test 0' => { 'type' => 'host', 'database' => 'all', 'user' => 'all', 'address' => '0.0.0.0/0', + 'auth_method' => 'md5', 'order' => '100' } } is_expected.to run.with_params([input], 'test', 100).and_return(result) end it do input = 'host all all ::1/128 md5' - result = { - "postgresql class generated rule test 0"=>{ - "type"=>"host", - "database"=>"all", - "user"=>"all", - "address"=>"::1/128", - "auth_method"=>"md5", - "order"=>"100", - }, - } + result = { 'postgresql class generated rule test 0' => { 'type' => 'host', 'database' => 'all', 'user' => 'all', 'address' => '::1/128', + 'auth_method' => 'md5', 'order' => '100' } } is_expected.to run.with_params([input], 'test', 100).and_return(result) end it do input = 'host all all 1.1.1.1 255.255.255.0 md5' - result = { - "postgresql class generated rule test 0"=>{ - "type"=>"host", - "database"=>"all", - "user"=>"all", - "address"=>"1.1.1.1 255.255.255.0", - "auth_method"=>"md5", - "order"=>"100", - }, - } + result = { 'postgresql class generated rule test 0' => { 'type' => 'host', 'database' => 'all', 'user' => 'all', 'address' => '1.1.1.1 255.255.255.0', + 'auth_method' => 'md5', 'order' => '100' } } is_expected.to run.with_params([input], 'test', 100).and_return(result) end it do input = 'host all all 1.1.1.1 255.255.255.0 ldap ldapserver=ldap.example.net ldapprefix="cn=" ldapsuffix=", dc=example, dc=net"' - result = { - "postgresql class generated rule test 0"=>{ - "type"=>"host", - "database"=>"all", - "user"=>"all", - "address"=>"1.1.1.1 255.255.255.0", - "auth_method"=>"ldap", - "auth_option"=>"ldapserver=ldap.example.net ldapprefix=\"cn=\" ldapsuffix=\", dc=example, dc=net\"", - "order"=>"100", - }, - } + result = { 'postgresql class generated rule test 0' => { 'type' => 'host', 'database' => 'all', 'user' => 'all', 'address' => '1.1.1.1 255.255.255.0', + 'auth_method' => 'ldap', 'auth_option' => 'ldapserver=ldap.example.net ldapprefix="cn=" ldapsuffix=", dc=example, dc=net"', + 'order' => '100' } } is_expected.to run.with_params([input], 'test', 100).and_return(result) end end - it 'should return an empty hash when input is empty array' do + it 'returns an empty hash when input is empty array' do is_expected.to run.with_params([], 'test', 100).and_return({}) end end diff --git a/spec/unit/functions/postgresql_escape_spec.rb b/spec/unit/functions/postgresql_escape_spec.rb index b4c9488..2edd388 100644 --- a/spec/unit/functions/postgresql_escape_spec.rb +++ b/spec/unit/functions/postgresql_escape_spec.rb @@ -1,14 +1,21 @@ require 'spec_helper' - -describe 'postgresql_escape', :type => :puppet_function do - it { is_expected.to run.with_params('foo'). - and_return('$$foo$$') } -end -describe 'postgresql_escape', :type => :puppet_function do - it { is_expected.to run.with_params('fo$$o'). - and_return('$ed$fo$$o$ed$') } -end -describe 'postgresql_escape', :type => :puppet_function do - it { is_expected.to run.with_params('foo$'). - and_return('$a$foo$$a$') } +describe 'postgresql_escape' do + describe 'postgresql_escape', type: :puppet_function do + it { + is_expected.to run.with_params('foo') + .and_return('$$foo$$') + } + end + describe 'postgresql_escape', type: :puppet_function do + it { + is_expected.to run.with_params('fo$$o') + .and_return('$ed$fo$$o$ed$') + } + end + describe 'postgresql_escape', type: :puppet_function do + it { + is_expected.to run.with_params('foo$') + .and_return('$a$foo$$a$') + } + end end diff --git a/spec/unit/functions/postgresql_password_spec.rb b/spec/unit/functions/postgresql_password_spec.rb index 89699f6..aef13ea 100644 --- a/spec/unit/functions/postgresql_password_spec.rb +++ b/spec/unit/functions/postgresql_password_spec.rb @@ -1,8 +1,12 @@ require 'spec_helper' -describe 'postgresql_password', :type => :puppet_function do - it { is_expected.to run.with_params('foo', 'bar'). - and_return('md596948aad3fcae80c08a35c9b5958cd89') } - it { is_expected.to run.with_params('foo', 1234). - and_return('md539a0e1b308278a8de5e007cd1f795920') } +describe 'postgresql_password', type: :puppet_function do + it { + is_expected.to run.with_params('foo', 'bar') + .and_return('md596948aad3fcae80c08a35c9b5958cd89') + } + it { + is_expected.to run.with_params('foo', 1234) + .and_return('md539a0e1b308278a8de5e007cd1f795920') + } end diff --git a/spec/unit/provider/postgresql_conf/parsed_spec.rb b/spec/unit/provider/postgresql_conf/parsed_spec.rb index 24e31c1..511f6c8 100644 --- a/spec/unit/provider/postgresql_conf/parsed_spec.rb +++ b/spec/unit/provider/postgresql_conf/parsed_spec.rb @@ -1,147 +1,146 @@ require 'spec_helper' -require "tempfile" +require 'tempfile' provider_class = Puppet::Type.type(:postgresql_conf).provider(:parsed) describe provider_class do let(:title) { 'postgresql_conf' } - let(:provider) { + let(:provider) do conf_class = Puppet::Type.type(:postgresql_conf) provider = conf_class.provider(:parsed) conffile = tmpfilename('postgresql.conf') - allow_any_instance_of(provider).to receive(:target).and_return conffile + allow_any_instance_of(provider).to receive(:target).and_return conffile # rubocop:disable RSpec/AnyInstance provider - } + end - before do + before(:each) do end after :each do provider.initvars end - describe "simple configuration that should be allowed" do - it "should parse a simple ini line" do + describe 'simple configuration that should be allowed' do + it 'parses a simple ini line' do expect(provider.parse_line("listen_addreses = '*'")).to eq( - { :name=>"listen_addreses", :value=>"*", :comment=>nil, :record_type=>:parsed } + name: 'listen_addreses', value: '*', comment: nil, record_type: :parsed, ) end - it "should parse a simple ini line (2)" do + it 'parses a simple ini line (2)' do expect(provider.parse_line(" listen_addreses = '*'")).to eq( - { :name=>"listen_addreses", :value=>"*", :comment=>nil, :record_type=>:parsed } + name: 'listen_addreses', value: '*', comment: nil, record_type: :parsed, ) end - it "should parse a simple ini line (3)" do + it 'parses a simple ini line (3)' do expect(provider.parse_line("listen_addreses = '*' # dont mind me")).to eq( - { :name=>"listen_addreses", :value=>"*", :comment=>"dont mind me", :record_type=>:parsed } + name: 'listen_addreses', value: '*', comment: 'dont mind me', record_type: :parsed, ) end - it "should parse a comment" do - expect(provider.parse_line("# dont mind me")).to eq( - { :line=>"# dont mind me", :record_type=>:comment } + it 'parses a comment' do + expect(provider.parse_line('# dont mind me')).to eq( + line: '# dont mind me', record_type: :comment, ) end - it "should parse a comment (2)" do + it 'parses a comment (2)' do expect(provider.parse_line(" \t# dont mind me")).to eq( - { :line=>" \t# dont mind me", :record_type=>:comment } + line: " \t# dont mind me", record_type: :comment, ) end - it "should allow includes" do - expect(provider.parse_line("include puppetextra")).to eq( - { :name=>"include", :value=>"puppetextra", :comment=>nil, :record_type=>:parsed } + it 'allows includes' do + expect(provider.parse_line('include puppetextra')).to eq( + name: 'include', value: 'puppetextra', comment: nil, record_type: :parsed, ) end - it "should allow numbers through without quotes" do - expect(provider.parse_line("wal_keep_segments = 32")).to eq( - { :name=>"wal_keep_segments", :value=>"32", :comment=>nil, :record_type=>:parsed } + it 'allows numbers through without quotes' do + expect(provider.parse_line('wal_keep_segments = 32')).to eq( + name: 'wal_keep_segments', value: '32', comment: nil, record_type: :parsed, ) end - it "should allow blanks through " do - expect(provider.parse_line("")).to eq( - { :line=>"", :record_type=>:blank } + it 'allows blanks through' do + expect(provider.parse_line('')).to eq( + line: '', record_type: :blank, ) end - it "should parse keys with dots " do - expect(provider.parse_line("auto_explain.log_min_duration = 1ms")).to eq( - { :name => "auto_explain.log_min_duration", :value => "1ms", :comment => nil, :record_type => :parsed } + it 'parses keys with dots' do + expect(provider.parse_line('auto_explain.log_min_duration = 1ms')).to eq( + name: 'auto_explain.log_min_duration', value: '1ms', comment: nil, record_type: :parsed, ) end end - describe "configuration that should be set" do - it "should set comment lines" do - expect(provider.to_line({ :line=>"# dont mind me", :record_type=>:comment })).to eq( - '# dont mind me' + describe 'configuration that should be set' do + it 'sets comment lines' do + expect(provider.to_line(line: '# dont mind me', record_type: :comment)).to eq( + '# dont mind me', ) end - it "should set blank lines" do - expect(provider.to_line({ :line=>"", :record_type=>:blank })).to eq( - '' + it 'sets blank lines' do + expect(provider.to_line(line: '', record_type: :blank)).to eq( + '', ) end - it "should set simple configuration" do - expect(provider.to_line({:name=>"listen_addresses", :value=>"*", :comment=>nil, :record_type=>:parsed })).to eq( - "listen_addresses = '*'" + it 'sets simple configuration' do + expect(provider.to_line(name: 'listen_addresses', value: '*', comment: nil, record_type: :parsed)).to eq( + "listen_addresses = '*'", ) end - it "should set simple configuration with period in name" do - expect(provider.to_line({:name => "auto_explain.log_min_duration", :value => '100ms', :comment => nil, :record_type => :parsed })).to eq( - "auto_explain.log_min_duration = 100ms" + it 'sets simple configuration with period in name' do + expect(provider.to_line(name: 'auto_explain.log_min_duration', value: '100ms', comment: nil, record_type: :parsed)).to eq( + 'auto_explain.log_min_duration = 100ms', ) end - it "should set simple configuration even with comments" do - expect(provider.to_line({:name=>"listen_addresses", :value=>"*", :comment=>'dont mind me', :record_type=>:parsed })).to eq( - "listen_addresses = '*' # dont mind me" + it 'sets simple configuration even with comments' do + expect(provider.to_line(name: 'listen_addresses', value: '*', comment: 'dont mind me', record_type: :parsed)).to eq( + "listen_addresses = '*' # dont mind me", ) end - it 'should quote includes' do - expect(provider.to_line( {:name=>"include", :value=>"puppetextra", :comment=>nil, :record_type=>:parsed })).to eq( - "include 'puppetextra'" + it 'quotes includes' do + expect(provider.to_line(name: 'include', value: 'puppetextra', comment: nil, record_type: :parsed)).to eq( + "include 'puppetextra'", ) end - it 'should quote multiple words' do - expect(provider.to_line( {:name=>"archive_command", :value=>"rsync up", :comment=>nil, :record_type=>:parsed })).to eq( - "archive_command = 'rsync up'" + it 'quotes multiple words' do + expect(provider.to_line(name: 'archive_command', value: 'rsync up', comment: nil, record_type: :parsed)).to eq( + "archive_command = 'rsync up'", ) end - it 'shouldn\'t quote numbers' do - expect(provider.to_line( {:name=>"wal_segments", :value=>"32", :comment=>nil, :record_type=>:parsed })).to eq( - "wal_segments = 32" + it 'does not quote numbers' do + expect(provider.to_line(name: 'wal_segments', value: '32', comment: nil, record_type: :parsed)).to eq( + 'wal_segments = 32', ) end - it "should allow numbers" do - expect(provider.to_line( {:name=>"integer", :value=>42, :comment=>nil, :record_type=>:parsed })).to eq( - "integer = 42" + it 'allows numbers' do + expect(provider.to_line(name: 'integer', value: 42, comment: nil, record_type: :parsed)).to eq( + 'integer = 42', ) end - it "should allow floats" do - expect(provider.to_line( {:name=>"float", :value=>2.71828182845, :comment=>nil, :record_type=>:parsed })).to eq( - "float = 2.71828182845" + it 'allows floats' do + expect(provider.to_line(name: 'float', value: 2.71828182845, comment: nil, record_type: :parsed)).to eq( + 'float = 2.71828182845', ) end - it "quotes addresses" do - expect(provider.to_line( {:name=>"listen_addresses", :value=>"0.0.0.0", :comment=>nil, :record_type=>:parsed })).to eq( - "listen_addresses = '0.0.0.0'" + it 'quotes addresses' do + expect(provider.to_line(name: 'listen_addresses', value: '0.0.0.0', comment: nil, record_type: :parsed)).to eq( + "listen_addresses = '0.0.0.0'", ) end end end - diff --git a/spec/unit/puppet/provider/postgresql_conn_validator/ruby_spec.rb b/spec/unit/puppet/provider/postgresql_conn_validator/ruby_spec.rb index 3d678ea..d4989ab 100644 --- a/spec/unit/puppet/provider/postgresql_conn_validator/ruby_spec.rb +++ b/spec/unit/puppet/provider/postgresql_conn_validator/ruby_spec.rb @@ -1,66 +1,65 @@ require 'spec_helper' describe Puppet::Type.type(:postgresql_conn_validator).provider(:ruby) do - - let(:resource) { Puppet::Type.type(:postgresql_conn_validator).new({ - :name => "testname" - }.merge attributes) } + let(:resource) do + Puppet::Type.type(:postgresql_conn_validator).new({ + name: 'testname', + }.merge(attributes)) + end let(:provider) { resource.provider } - let(:attributes) do { - :psql_path => '/usr/bin/psql', - :host => 'db.test.com', - :port => 4444, - :db_username => 'testuser', - :db_password => 'testpass' + psql_path: '/usr/bin/psql', + host: 'db.test.com', + port: 4444, + db_username: 'testuser', + db_password: 'testpass', + } + end + let(:connect_settings) do + { + connect_settings: { + PGPASSWORD: 'testpass', + PGHOST: 'db.test.com', + PGPORT: '1234', + }, } end describe '#build_psql_cmd' do it 'contains expected commandline options' do - expect(provider.validator.build_psql_cmd).to match /\/usr\/bin\/psql.*--host.*--port.*--username.*/ + expect(provider.validator.build_psql_cmd).to match %r{/usr/bin/psql.*--host.*--port.*--username.*} end end describe '#parse_connect_settings' do it 'returns array if password is present' do expect(provider.validator.parse_connect_settings).to eq(['PGPASSWORD=testpass']) end it 'returns an empty array if password is nil' do attributes.delete(:db_password) expect(provider.validator.parse_connect_settings).to eq([]) end - let(:connect_settings) do - { - :connect_settings => { - :PGPASSWORD => 'testpass', - :PGHOST => 'db.test.com', - :PGPORT => '1234' - } - } - end it 'returns an array of settings' do attributes.delete(:db_password) attributes.merge! connect_settings - expect(provider.validator.parse_connect_settings).to eq(['PGPASSWORD=testpass','PGHOST=db.test.com','PGPORT=1234']) + expect(provider.validator.parse_connect_settings).to eq(['PGPASSWORD=testpass', 'PGHOST=db.test.com', 'PGPORT=1234']) end end describe '#attempt_connection' do - let(:sleep_length) {1} - let(:tries) {3} - let(:exec) { + let(:sleep_length) { 1 } + let(:tries) { 3 } + let(:exec) do provider.validator.stub(:execute_command).and_return(true) - } + end it 'tries the correct number of times' do - expect(provider.validator).to receive(:execute_command).exactly(3).times - - provider.validator.attempt_connection(sleep_length,tries) + expect(provider.validator).to receive(:execute_command).exactly(3).times # rubocop:disable RSpec/MessageSpies + provider.validator.attempt_connection(sleep_length, tries) 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 b75bd98..ee1444f 100644 --- a/spec/unit/puppet/provider/postgresql_psql/ruby_spec.rb +++ b/spec/unit/puppet/provider/postgresql_psql/ruby_spec.rb @@ -1,104 +1,109 @@ require 'spec_helper' describe Puppet::Type.type(:postgresql_psql).provider(:ruby) do + # rubocop:disable RSpec/MessageSpies let(:name) { 'rspec psql test' } let(:resource) do - Puppet::Type.type(:postgresql_psql).new({ :name => name, :provider => :ruby }.merge attributes) + 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) do { :db => 'spec_db' } end + 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 + 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', {}) + 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 + 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 # rubocop:disable RSpec/MultipleExpectations 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], {}) + '-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 + describe 'with search_path string' do + let(:attributes) do + { + search_path: 'schema1', + } + end - it "executes with the given search_path" do + 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', {}) + '"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 => ['schema1','schema2'], - } end + describe 'with search_path array' do + let(:attributes) do + { + search_path: %w[schema1 schema2], + } + end - it "executes with the given search_path" do + 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', - {} - ) + '"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) do { :port => '5555' } 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", {} ) + 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 + provider.run_sql_command('SELECT something') end - describe "with connect_settings" do - let(:attributes) do { :connect_settings => { 'PGHOST' => '127.0.0.1' } } 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' } ) + 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 + provider.run_sql_command('SELECT something') end + end - context("#run_unless_sql_command") do - let(:attributes) do { } end + context('#run_unless_sql_command') do + let(:attributes) { {} } - it "calls #run_sql_command with SQL" do + 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 + # rubocop:enable RSpec/MessageSpies 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 4fc8b55..8ac59f7 100644 --- a/spec/unit/puppet/provider/postgresql_replication_slot/ruby_spec.rb +++ b/spec/unit/puppet/provider/postgresql_replication_slot/ruby_spec.rb @@ -1,92 +1,97 @@ require 'spec_helper' type = Puppet::Type.type(:postgresql_replication_slot) describe type.provider(:ruby) do - 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 - class SuccessStatus def success? true end end - let(:success_status) { SuccessStatus.new } - class FailStatus def success? false end end - let(:fail_status) { FailStatus.new } + 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 - let(:attributes) do { } end + 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] } - it 'should list instances' do - provider.class.expects(:run_command).with( - ['psql', '-t', '-c', 'SELECT * FROM pg_replication_slots;'], - 'postgres', 'postgres').returns([sql_instances, nil]) - instances = provider.class.instances + it 'lists instances #size' do expect(instances.size).to eq 2 - expect(instances[0].name).to eq 'abc' - expect(instances[1].name).to eq 'def' + 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) do { :ensure => 'present' } end + let(:attributes) { { ensure: 'present' } } context 'when creation works' do - it 'should call psql and succeed' 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]) + 'postgres', 'postgres' + ).returns([nil, success_status]) expect { provider.create }.not_to raise_error end end context 'when creation fails' do - it 'should call psql and fail' 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]) + 'postgres', 'postgres' + ).returns([nil, fail_status]) - expect { provider.create }.to raise_error(Puppet::Error, /Failed to create replication slot standby:/) + 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) do { :ensure => 'absent' } end + let(:attributes) { { ensure: 'absent' } } context 'when destruction works' do - it 'should call psql and succeed' 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]) + 'postgres', 'postgres' + ).returns([nil, success_status]) expect { provider.destroy }.not_to raise_error end end context 'when destruction fails' do - it 'should call psql and fail' 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]) + 'postgres', 'postgres' + ).returns([nil, fail_status]) - expect { provider.destroy }.to raise_error(Puppet::Error, /Failed to destroy replication slot standby:/) + 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_conn_validator.rb b/spec/unit/puppet/type/postgresql_conn_validator.rb index ef3a1ed..663ce3a 100644 --- a/spec/unit/puppet/type/postgresql_conn_validator.rb +++ b/spec/unit/puppet/type/postgresql_conn_validator.rb @@ -1,42 +1,44 @@ -#! /usr/bin/env ruby +#! /usr/bin/env ruby # rubocop:disable Lint/ScriptPermission require 'spec_helper' describe Puppet::Type.type(:postgresql_conn_validator) do - before do + before(:each) do @provider_class = described_class.provide(:simple) { mk_resource_methods } - @provider_class.stub(:suitable?).and_return true - described_class.stub(:defaultprovider).and_return @provider_class + @provider_class.stub(:suitable?).and_return true # rubocop:disable RSpec/InstanceVariable + described_class.stub(:defaultprovider).and_return @provider_class # rubocop:disable RSpec/InstanceVariable end - describe "when validating attributes" do + describe 'when validating attributes' do [:name, :db_name, :db_username, :command, :host, :port, :connect_settings, :sleep, :tries, :psql_path].each do |param| it "should have a #{param} parameter" do expect(described_class.attrtype(param)).to eq(:param) end end end - describe "when validating values" do - describe "tries and sleep" do + describe 'when validating values' do + describe 'tries and sleep' do [:tries, :sleep, :port].each do |param| - it "#{param} should be able to cast value as integer" do - expect { described_class.new(:name => 'test', param => '1') }.to_not raise_error - expect { described_class.new(:name => 'test', param => 1) }.to_not raise_error + it "#{param} should be able to cast value as integer #string" do + expect { described_class.new(:name => 'test', param => '1') }.not_to raise_error + end + it "#{param} should be able to cast value as integer #integer" do + expect { described_class.new(:name => 'test', param => 1) }.not_to raise_error end it "#{param} should not accept non-numeric string" do expect { described_class.new(:name => 'test', param => 'test') }.to raise_error Puppet::ResourceError end end end - describe "connect_settings" do - it "should accept a hash" do - expect { described_class.new(:name => 'test', :connect_settings => { "PGPASSWORD" => "test1" }) }.to_not raise_error + describe 'connect_settings' do + it 'accepts a hash' do + expect { described_class.new(name: 'test', connect_settings: { 'PGPASSWORD' => 'test1' }) }.not_to raise_error end end - describe "port" do - it "does not accept a word" do - expect { described_class.new(:name => 'test', :port => 'test')}.to raise_error Puppet::Error + describe 'port' do + it 'does not accept a word' do + expect { described_class.new(name: 'test', port: 'test') }.to raise_error Puppet::Error 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 3883327..85e844f 100644 --- a/spec/unit/puppet/type/postgresql_psql_spec.rb +++ b/spec/unit/puppet/type/postgresql_psql_spec.rb @@ -1,251 +1,268 @@ require 'spec_helper' -describe Puppet::Type.type(:postgresql_psql), "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) +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 - end - [:command].each do |attr| - it "should have a #{attr} property" do - expect(Puppet::Type.type(:postgresql_psql).attrtype(attr)).to eq(:property) + [: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 +describe Puppet::Type.type(:postgresql_psql), unless: Puppet.features.microsoft_windows? do subject do - Puppet::Type.type(:postgresql_psql).new({:name => 'rspec'}.merge attributes) + Puppet::Type.type(:postgresql_psql).new({ name: 'rspec' }.merge(attributes)) end - describe "available attributes" do + 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 => [ "schema1", "schema2"], - :connect_settings => { 'PGHOST' => 'postgres-db-server', - 'DBVERSION' => '9.1', }, + 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], + connect_settings: { 'PGHOST' => 'postgres-db-server', + 'DBVERSION' => '9.1' }, }.each do |attr, value| context attr do - let(:attributes) do { attr => value } end + describe [attr] + subject { super()[attr] } - describe [attr] do - subject { super()[attr] } - it { is_expected.to eq(value) } - end + let(:attributes) { { attr => value } } + + it { is_expected.to eq(value) } end end + let(:attributes) { {} } - context "default values" do - let(:attributes) do {} end + context 'default value: [:psql_path]' do + subject { super()[:psql_path] } - describe '[:psql_path]' do - subject { super()[:psql_path] } - it { is_expected.to eq("psql") } - end + it { is_expected.to eq('psql') } + end + context 'default value: [:psql_user]' do + subject { super()[:psql_user] } - describe '[:psql_user]' do - subject { super()[:psql_user] } - it { is_expected.to eq("postgres") } - end + it { is_expected.to eq('postgres') } + end + context 'default value: [:psql_group]' do + subject { super()[:psql_group] } - describe '[:psql_group]' do - subject { super()[:psql_group] } - it { is_expected.to eq("postgres") } - end + it { is_expected.to eq('postgres') } + end + context 'default value: [:cwd]' do + subject { super()[:cwd] } - describe '[:cwd]' do - subject { super()[:cwd] } - it { is_expected.to eq("/tmp") } - end + it { is_expected.to eq('/tmp') } + end + context 'default value: #refreshonly?' do + subject { super().refreshonly? } - describe '#refreshonly?' do - subject { super().refreshonly? } - it { is_expected.to be_falsey } - end + it { is_expected.to be_falsey } end end - describe "#command" do - let(:attributes) do {:command => 'SELECT stuff'} end + # rubocop:disable RSpec/MultipleExpectations + # rubocop:disable RSpec/MessageSpies + # 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 + 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]) + 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) do {:unless => 'SELECT something'} 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] + 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] + 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] + 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] + 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, /Something went wrong/) + }.to raise_error(Puppet::Error, %r{Something went wrong}) end end end + # rubocop:enable RSpec/MultipleExpectations - describe "#should_run_sql" do - context "without 'unless'" do - [true, :true].each do |refreshonly| - context "refreshonly => #{refreshonly.inspect}" do - let(:attributes) do { - :refreshonly => refreshonly, - } end - - context "not refreshing" do - it { expect(subject.should_run_sql).to be_falsey } - end - - context "refreshing" do - it { expect(subject.should_run_sql(true)).to be_truthy } - 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 - [false, :false].each do |refreshonly| - 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 - context "not refreshing" do - it { expect(subject.should_run_sql).to be_truthy } - end + [false, :false].each do |refreshonly| + context "refreshonly => #{refreshonly.inspect}" do + let(:attributes) do + { refreshonly: refreshonly } + end - context "refreshing" do - it { expect(subject.should_run_sql(true)).to be_truthy } - 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 - context "with matching 'unless'" do - before { expect(subject.parameter(:unless)).to receive(:matches).with('SELECT something').and_return(true) } - - [true, :true].each do |refreshonly| - context "refreshonly => #{refreshonly.inspect}" do - let(:attributes) do { - :refreshonly => refreshonly, - :unless => 'SELECT something', - } end - - context "not refreshing" do - it { expect(subject.should_run_sql).to be_falsey } - 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 - context "refreshing" do - it { expect(subject.should_run_sql(true)).to be_falsey } - end + [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 - [false, :false].each do |refreshonly| - 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 - context "not refreshing" do - it { expect(subject.should_run_sql).to be_falsey } - end + [false, :false].each do |refreshonly| + context "refreshonly => #{refreshonly.inspect}" do + let(:attributes) do + { refreshonly: refreshonly, unless: 'SELECT something' } + end - context "refreshing" do - it { expect(subject.should_run_sql(true)).to be_falsey } - 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 - context "when not matching 'unless'" do - before { expect(subject.parameter(:unless)).to receive(:matches).with('SELECT something').and_return(false) } - - [true, :true].each do |refreshonly| - context "refreshonly => #{refreshonly.inspect}" do - let(:attributes) do { - :refreshonly => refreshonly, - :unless => 'SELECT something', - } end - - context "not refreshing" do - it { expect(subject.should_run_sql).to be_falsey } - 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 - context "refreshing" do - it { expect(subject.should_run_sql(true)).to be_truthy } - end + [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 - [false, :false].each do |refreshonly| - 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 - context "not refreshing" do - it { expect(subject.should_run_sql).to be_truthy } - end + [false, :false].each do |refreshonly| + context "refreshonly => #{refreshonly.inspect}" do + let(:attributes) do + { refreshonly: refreshonly, unless: 'SELECT something' } + end - context "refreshing" do - it { expect(subject.should_run_sql(true)).to be_truthy } - 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) do {} end + describe '#refresh' do + let(:attributes) { {} } - it "syncs command property when command should run" do + it 'syncs command property when command should run' do # rubocop:disable RSpec/MultipleExpectations 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 + it 'does not sync command property when command should not run' do # rubocop:disable RSpec/MultipleExpectations 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 diff --git a/spec/unit/puppet/type/postgresql_replication_slot_spec.rb b/spec/unit/puppet/type/postgresql_replication_slot_spec.rb index 0d7c668..37d85a6 100644 --- a/spec/unit/puppet/type/postgresql_replication_slot_spec.rb +++ b/spec/unit/puppet/type/postgresql_replication_slot_spec.rb @@ -1,11 +1,11 @@ require 'spec_helper' describe Puppet::Type.type(:postgresql_replication_slot) do subject do - Puppet::Type.type(:postgresql_psql).new({:name => 'standby'}) + Puppet::Type.type(:postgresql_psql).new(name: 'standby') end - it 'should have a name parameter' do - expect(subject[:name]).to eq 'standby' + it 'has a name parameter' do + expect(subject[:name]).to eq 'standby' # rubocop:disable RSpec/NamedSubject end end diff --git a/spec/unit/type/postgresql_conf_spec.rb b/spec/unit/type/postgresql_conf_spec.rb index a406b0c..0cbab10 100644 --- a/spec/unit/type/postgresql_conf_spec.rb +++ b/spec/unit/type/postgresql_conf_spec.rb @@ -1,50 +1,50 @@ -#! /usr/bin/env ruby +#! /usr/bin/env ruby # rubocop:disable Lint/ScriptPermission require 'spec_helper' describe Puppet::Type.type(:postgresql_conf) do - before do + before(:each) do @provider_class = described_class.provide(:simple) { mk_resource_methods } - allow(@provider_class).to receive(:suitable?).and_return true - allow(described_class).to receive(:defaultprovider).and_return @provider_class + allow(@provider_class).to receive(:suitable?).and_return true # rubocop:disable RSpec/InstanceVariable + allow(described_class).to receive(:defaultprovider).and_return @provider_class # rubocop:disable RSpec/InstanceVariable end - describe "namevar validation" do - it "should have :name as its namevar" do + describe 'namevar validation' do + it 'has :name as its namevar' do expect(described_class.key_attributes).to eq([:name]) end - it "should not invalid names" do - expect { described_class.new(:name => 'foo bar') }.to raise_error(Puppet::Error, /Invalid value/) + it 'does not invalid names' do + expect { described_class.new(name: 'foo bar') }.to raise_error(Puppet::Error, %r{Invalid value}) end - it "should allow dots in names" do - expect { described_class.new(:name => 'foo.bar') }.to_not raise_error + it 'allows dots in names' do + expect { described_class.new(name: 'foo.bar') }.not_to raise_error end end - describe "when validating attributes" do + describe 'when validating attributes' do [:name, :provider].each do |param| it "should have a #{param} parameter" do expect(described_class.attrtype(param)).to eq(:param) end end [:value, :target].each do |property| it "should have a #{property} property" do expect(described_class.attrtype(property)).to eq(:property) end end end - describe "when validating values" do - describe "ensure" do - it "should support present as a value for ensure" do - expect { described_class.new(:name => 'foo', :ensure => :present) }.to_not raise_error + describe 'when validating values' do + describe 'ensure' do + it 'supports present as a value for ensure' do + expect { described_class.new(name: 'foo', ensure: :present) }.not_to raise_error end - it "should support absent as a value for ensure" do - expect { described_class.new(:name => 'foo', :ensure => :absent) }.to_not raise_error + it 'supports absent as a value for ensure' do + expect { described_class.new(name: 'foo', ensure: :absent) }.not_to raise_error end - it "should not support other values" do - expect { described_class.new(:name => 'foo', :ensure => :foo) }.to raise_error(Puppet::Error, /Invalid value/) + it 'does not support other values' do + expect { described_class.new(name: 'foo', ensure: :foo) }.to raise_error(Puppet::Error, %r{Invalid value}) end end end end diff --git a/tasks/sql.rb b/tasks/sql.rb index c706016..dc407c9 100755 --- a/tasks/sql.rb +++ b/tasks/sql.rb @@ -1,33 +1,33 @@ #!/opt/puppetlabs/puppet/bin/ruby require 'json' require 'open3' require 'puppet' def get(sql, database, user, port, password, host) - env_hash = {'PGPASSWORD' => password} unless password.nil? + env_hash = { 'PGPASSWORD' => password } unless password.nil? cmd_string = "psql -c \"#{sql}\"" cmd_string << " --dbname=#{database}" unless database.nil? cmd_string << " --username=#{user}" unless user.nil? cmd_string << " --port=#{port}" unless port.nil? cmd_string << " --host=#{host}" unless host.nil? stdout, stderr, status = Open3.capture3(env_hash, cmd_string) raise Puppet::Error, stderr if status != 0 { status: stdout.strip } end params = JSON.parse(STDIN.read) database = params['database'] host = params['host'] password = params['password'] port = params['port'] sql = params['sql'] user = params['user'] begin result = get(sql, database, user, port, password, host) puts result.to_json exit 0 rescue Puppet::Error => e puts({ status: 'failure', error: e.message }.to_json) exit 1 end