diff --git a/.rubocop.yml b/.rubocop.yml index 5aadd1b64..d973ebde8 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -1,508 +1,100 @@ -require: rubocop-rspec +--- +require: + - rubocop-rspec AllCops: - TargetRubyVersion: 1.9 + TargetRubyVersion: '2.1' Include: - - ./**/*.rb + - "./**/*.rb" Exclude: - - vendor/**/* - - .vendor/**/* - - pkg/**/* - - spec/fixtures/**/* -Lint/ConditionPosition: - Enabled: True - -Lint/ElseLayout: - Enabled: True - -Lint/UnreachableCode: - Enabled: True - -Lint/UselessComparison: - Enabled: True - -Lint/EnsureReturn: - Enabled: True - -Lint/HandleExceptions: - Enabled: True - -Lint/LiteralInCondition: - Enabled: True - -Lint/ShadowingOuterLocalVariable: - Enabled: True - -Lint/LiteralInInterpolation: - Enabled: True - -Style/HashSyntax: - Enabled: True - -Style/RedundantReturn: - Enabled: True - -Lint/AmbiguousOperator: - Enabled: True - -Lint/AssignmentInCondition: - Enabled: True - -Style/SpaceBeforeComment: - Enabled: True - -Style/AndOr: - Enabled: True - -Style/RedundantSelf: - Enabled: True - -# Method length is not necessarily an indicator of code quality -Metrics/MethodLength: - Enabled: False - -# Module length is not necessarily an indicator of code quality -Metrics/ModuleLength: - Enabled: False - -Style/WhileUntilModifier: - Enabled: True - -Lint/AmbiguousRegexpLiteral: - Enabled: True - -Lint/Eval: - Enabled: True - -Lint/BlockAlignment: - Enabled: True - -Lint/DefEndAlignment: - Enabled: True - -Lint/EndAlignment: - Enabled: True - -Lint/DeprecatedClassMethods: - Enabled: True - -Lint/Loop: - Enabled: True - -Lint/ParenthesesAsGroupedExpression: - Enabled: True - -Lint/RescueException: - Enabled: True - -Lint/StringConversionInInterpolation: - Enabled: True - -Lint/UnusedBlockArgument: - Enabled: True - -Lint/UnusedMethodArgument: - Enabled: True - -Lint/UselessAccessModifier: - Enabled: True - -Lint/UselessAssignment: - Enabled: True - -Lint/Void: - Enabled: True - -Style/AccessModifierIndentation: - Enabled: True - -Style/AccessorMethodName: - Enabled: True - -Style/Alias: - Enabled: True - -Style/AlignArray: - Enabled: True - -Style/AlignHash: - Enabled: True - -Style/AlignParameters: - Enabled: True - -Metrics/BlockNesting: - Enabled: True - -Style/AsciiComments: - Enabled: True - -Style/Attr: - Enabled: True - -Style/BracesAroundHashParameters: - Enabled: True - -Style/CaseEquality: - Enabled: True - -Style/CaseIndentation: - Enabled: True - -Style/CharacterLiteral: - Enabled: True - -Style/ClassAndModuleCamelCase: - Enabled: True - -Style/ClassAndModuleChildren: - Enabled: False - -Style/ClassCheck: - Enabled: True - -# Class length is not necessarily an indicator of code quality -Metrics/ClassLength: - Enabled: False - -Style/ClassMethods: - Enabled: True - -Style/ClassVars: - Enabled: True - -Style/WhenThen: - Enabled: True - -Style/WordArray: - Enabled: True - -Style/UnneededPercentQ: - Enabled: True - -Style/Tab: - Enabled: True - -Style/SpaceBeforeSemicolon: - Enabled: True - -Style/TrailingBlankLines: - Enabled: True - -Style/SpaceInsideBlockBraces: - Enabled: True - -Style/SpaceInsideBrackets: - Enabled: True - -Style/SpaceInsideHashLiteralBraces: - Enabled: True - -Style/SpaceInsideParens: - Enabled: True - -Style/LeadingCommentSpace: - Enabled: True - -Style/SpaceBeforeFirstArg: - Enabled: True - -Style/SpaceAfterColon: - Enabled: True - -Style/SpaceAfterComma: - Enabled: True - -Style/SpaceAfterMethodName: - Enabled: True - -Style/SpaceAfterNot: - Enabled: True - -Style/SpaceAfterSemicolon: - Enabled: True - -Style/SpaceAroundEqualsInParameterDefault: - Enabled: True - -Style/SpaceAroundOperators: - Enabled: True - -Style/SpaceBeforeBlockBraces: - Enabled: True - -Style/SpaceBeforeComma: - Enabled: True - -Style/CollectionMethods: - Enabled: True - -Style/CommentIndentation: - Enabled: True - -Style/ColonMethodCall: - Enabled: True - -Style/CommentAnnotation: - Enabled: True - -# 'Complexity' is very relative -Metrics/CyclomaticComplexity: - Enabled: False - -Style/ConstantName: - Enabled: True - -Style/Documentation: - Enabled: False - -Style/DefWithParentheses: - Enabled: True - -Style/PreferredHashMethods: - Enabled: True - -Style/DotPosition: - EnforcedStyle: trailing - -Style/DoubleNegation: - Enabled: True - -Style/EachWithObject: - Enabled: True - -Style/EmptyLineBetweenDefs: - Enabled: True - -Style/IndentArray: - Enabled: True - -Style/IndentHash: - Enabled: True - -Style/IndentationConsistency: - Enabled: True - -Style/IndentationWidth: - Enabled: True - -Style/EmptyLines: - Enabled: True - -Style/EmptyLinesAroundAccessModifier: - Enabled: True - -Style/EmptyLiteral: - Enabled: True - -# Configuration parameters: AllowURI, URISchemes. + - bin/* + - ".vendor/**/*" + - Gemfile + - Rakefile + - pkg/**/* + - spec/fixtures/**/* + - vendor/**/* +inherit_from: .rubocop_todo.yml Metrics/LineLength: - Enabled: False - -Style/MethodCallParentheses: - Enabled: True - -Style/MethodDefParentheses: - Enabled: True - -Style/LineEndConcatenation: - Enabled: True - -Style/TrailingWhitespace: - Enabled: True - -Style/StringLiterals: - Enabled: True - -Style/TrailingCommaInArguments: - Enabled: True - -Style/TrailingCommaInLiteral: - Enabled: True - -Style/GlobalVars: - Enabled: True - -Style/GuardClause: - Enabled: True - -Style/IfUnlessModifier: - Enabled: True - -Style/MultilineIfThen: - Enabled: True - -Style/NegatedIf: - Enabled: True - -Style/NegatedWhile: - Enabled: True - -Style/Next: - Enabled: True - -Style/SingleLineBlockParams: - Enabled: True - -Style/SingleLineMethods: - Enabled: True - -Style/SpecialGlobalVars: - Enabled: True - -Style/TrivialAccessors: - Enabled: True - -Style/UnlessElse: - Enabled: True - -Style/VariableInterpolation: - Enabled: True - -Style/VariableName: - Enabled: True - -Style/WhileUntilDo: - Enabled: True - -Style/EvenOdd: - Enabled: True - -Style/FileName: - Enabled: True - -Style/For: - Enabled: True - -Style/Lambda: - Enabled: True - -Style/MethodName: - Enabled: True - -Style/MultilineTernaryOperator: - Enabled: True - -Style/NestedTernaryOperator: - Enabled: True - -Style/NilComparison: - Enabled: True - + Description: People have wide screens, use them. + Max: 200 +RSpec/BeforeAfterAll: + Description: Beware of using after(:all) as it may cause state to leak between tests. + A necessary evil in acceptance testing. + Exclude: + - spec/acceptance/**/*.rb +RSpec/HookArgument: + Description: Prefer explicit :each argument, matching existing module's style + EnforcedStyle: each +Style/BlockDelimiters: + Description: Prefer braces for chaining. Mostly an aesthetical choice. Better to + be consistent then. + EnforcedStyle: braces_for_chaining +Style/ClassAndModuleChildren: + Description: Compact style reduces the required amount of indentation. + EnforcedStyle: compact +Style/EmptyElse: + Description: Enforce against empty else clauses, but allow `nil` for clarity. + EnforcedStyle: empty Style/FormatString: - Enabled: True - -Style/MultilineBlockChain: - Enabled: True - -Style/Semicolon: - Enabled: True - -Style/SignalException: - Enabled: True - -Style/NonNilCheck: - Enabled: True - -Style/Not: - Enabled: True - -Style/NumericLiterals: - Enabled: True - -Style/OneLineConditional: - Enabled: True - -Style/OpMethod: - Enabled: True - -Style/ParenthesesAroundCondition: - Enabled: True - -Style/PercentLiteralDelimiters: - Enabled: True - -Style/PerlBackrefs: - Enabled: True - -Style/PredicateName: - Enabled: True - -Style/RedundantException: - Enabled: True - -Style/SelfAssignment: - Enabled: True - -Style/Proc: - Enabled: True - -Style/RaiseArgs: - Enabled: True - -Style/RedundantBegin: - Enabled: True - -Style/RescueModifier: - Enabled: True - -# based on https://github.com/voxpupuli/modulesync_config/issues/168 + Description: Following the main puppet project's style, prefer the % format format. + EnforcedStyle: percent +Style/FormatStringToken: + Description: Following the main puppet project's style, prefer the simpler template + tokens over annotated ones. + EnforcedStyle: template +Style/Lambda: + Description: Prefer the keyword for easier discoverability. + EnforcedStyle: literal Style/RegexpLiteral: + Description: Community preference. See https://github.com/voxpupuli/modulesync_config/issues/168 EnforcedStyle: percent_r - Enabled: True - -Lint/UnderscorePrefixedVariableName: - Enabled: True - -Metrics/ParameterLists: - Enabled: False - -Lint/RequireParentheses: - Enabled: True - -Style/SpaceBeforeFirstArg: - Enabled: True - -Style/ModuleFunction: - Enabled: True - -Lint/Debugger: - Enabled: True - -Style/IfWithSemicolon: - Enabled: True - -Style/Encoding: - Enabled: True - -Style/BlockDelimiters: - Enabled: True - -Style/MultilineBlockLayout: - Enabled: True - -# 'Complexity' is very relative +Style/TernaryParentheses: + Description: Checks for use of parentheses around ternary conditions. Enforce parentheses + on complex expressions for better readability, but seriously consider breaking + it up. + EnforcedStyle: require_parentheses_when_complex +Style/TrailingCommaInArguments: + Description: Prefer always trailing comma on multiline argument lists. This makes + diffs, and re-ordering nicer. + EnforcedStyleForMultiline: comma +Style/TrailingCommaInLiteral: + Description: Prefer always trailing comma on multiline literals. This makes diffs, + and re-ordering nicer. + EnforcedStyleForMultiline: comma +Style/SymbolArray: + Description: Using percent style obscures symbolic intent of array's contents. + EnforcedStyle: brackets +Style/CollectionMethods: + Enabled: true +Style/MethodCalledOnDoEndBlock: + Enabled: true +Style/StringMethods: + Enabled: true Metrics/AbcSize: - Enabled: False - -# 'Complexity' is very relative + Enabled: false +Metrics/BlockLength: + Enabled: false +Metrics/ClassLength: + Enabled: false +Metrics/CyclomaticComplexity: + Enabled: false +Metrics/MethodLength: + Enabled: false +Metrics/ModuleLength: + Enabled: false +Metrics/ParameterLists: + Enabled: false Metrics/PerceivedComplexity: - Enabled: False - -Lint/UselessAssignment: - Enabled: True - -Style/ClosingParenthesisIndentation: - Enabled: False - -# RSpec - -# We don't use rspec in this way + Enabled: false RSpec/DescribeClass: - Enabled: False - -# Example length is not necessarily an indicator of code quality -RSpec/ExampleLength: - Enabled: False - + Enabled: false +RSpec/MessageExpectation: + Enabled: false +Style/AsciiComments: + Enabled: false +Style/IfUnlessModifier: + Enabled: false +Style/SymbolProc: + Enabled: false RSpec/NamedSubject: - Enabled: False + Enabled: false \ No newline at end of file diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml new file mode 100644 index 000000000..e69de29bb diff --git a/.sync.yml b/.sync.yml index a870bb710..6db07d826 100644 --- a/.sync.yml +++ b/.sync.yml @@ -18,3 +18,5 @@ spec/spec_helper.rb:   - rvm: 2.1.9     env: PUPPET_GEM_VERSION="~> 4.7.0"     bundler_args: --without system_tests + - rvm: 2.1.9 + script: bundle exec rake rubocop diff --git a/.travis.yml b/.travis.yml index 38d226395..6055eb19c 100644 --- a/.travis.yml +++ b/.travis.yml @@ -28,5 +28,7 @@ matrix: - 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/facter/facter_dot_d.rb b/lib/facter/facter_dot_d.rb index 5c5fb1fde..f1ef9bcc8 100644 --- a/lib/facter/facter_dot_d.rb +++ b/lib/facter/facter_dot_d.rb @@ -11,19 +11,18 @@ # The cache is stored in $libdir/facts_dot_d.cache as a mode # 600 file and will have the end result of not calling your # fact scripts more often than is needed - class Facter::Util::DotD require 'yaml' - def initialize(dir="/etc/facts.d", cache_file=File.join(Puppet[:libdir], "facts_dot_d.cache")) + def initialize(dir = '/etc/facts.d', cache_file = File.join(Puppet[:libdir], 'facts_dot_d.cache')) @dir = dir @cache_file = cache_file @cache = nil - @types = {".txt" => :txt, ".json" => :json, ".yaml" => :yaml} + @types = { '.txt' => :txt, '.json' => :json, '.yaml' => :yaml } end def entries - Dir.entries(@dir).reject { |f| f =~ /^\.|\.ttl$/ }.sort.map { |f| File.join(@dir, f) } + Dir.entries(@dir).reject { |f| f =~ %r{^\.|\.ttl$} }.sort.map { |f| File.join(@dir, f) } rescue [] end @@ -35,17 +34,17 @@ def fact_type(file) type = :script if type == :unknown && File.executable?(file) - return type + type end def txt_parser(file) File.readlines(file).each do |line| - if line =~ /^([^=]+)=(.+)$/ - var = $1; val = $2 + next unless line =~ %r{^([^=]+)=(.+)$} + var = Regexp.last_match(1) + val = Regexp.last_match(2) - Facter.add(var) do - setcode { val } - end + Facter.add(var) do + setcode { val } end end rescue StandardError => e @@ -60,7 +59,7 @@ def json_parser(file) raise end - JSON.load(File.read(file)).each_pair do |f, v| + JSON.parse(File.read(file)).each_pair do |f, v| Facter.add(f) do setcode { v } end @@ -85,7 +84,9 @@ def script_parser(file) result = cache_lookup(file) ttl = cache_time(file) - unless result + if result + Facter.debug("Using cached data for #{file}") + else result = Facter::Util::Resolution.exec(file) if ttl > 0 @@ -93,17 +94,15 @@ def script_parser(file) cache_store(file, result) cache_save! end - else - Facter.debug("Using cached data for #{file}") end result.split("\n").each do |line| - if line =~ /^(.+)=(.+)$/ - var = $1; val = $2 + next unless line =~ %r{^(.+)=(.+)$} + var = Regexp.last_match(1) + val = Regexp.last_match(2) - Facter.add(var) do - setcode { val } - end + Facter.add(var) do + setcode { val } end end rescue StandardError => e @@ -113,15 +112,15 @@ def script_parser(file) def cache_save! cache = load_cache - File.open(@cache_file, "w", 0600) { |f| f.write(YAML.dump(cache)) } - rescue + File.open(@cache_file, 'w', 0o600) { |f| f.write(YAML.dump(cache)) } + rescue # rubocop:disable Lint/HandleExceptions - Is meant to be suppressed end def cache_store(file, data) load_cache - @cache[file] = {:data => data, :stored => Time.now.to_i} - rescue + @cache[file] = { data: data, stored: Time.now.to_i } + rescue # rubocop:disable Lint/HandleExceptions - Is meant to be suppressed end def cache_lookup(file) @@ -131,21 +130,18 @@ def cache_lookup(file) ttl = cache_time(file) - if cache[file] - now = Time.now.to_i + return nil unless cache[file] + now = Time.now.to_i - return cache[file][:data] if ttl == -1 - return cache[file][:data] if (now - cache[file][:stored]) <= ttl - return nil - else - return nil - end + return cache[file][:data] if ttl == -1 + return cache[file][:data] if (now - cache[file][:stored]) <= ttl + return nil rescue return nil end def cache_time(file) - meta = file + ".ttl" + meta = file + '.ttl' return File.read(meta).chomp.to_i rescue @@ -154,11 +150,11 @@ def cache_time(file) def load_cache unless @cache - if File.exist?(@cache_file) - @cache = YAML.load_file(@cache_file) - else - @cache = {} - end + @cache = if File.exist?(@cache_file) + YAML.load_file(@cache_file) + else + {} + end end return @cache @@ -172,28 +168,26 @@ def create type = fact_type(fact) parser = "#{type}_parser" - if respond_to?("#{type}_parser") - Facter.debug("Parsing #{fact} using #{parser}") + next unless respond_to?("#{type}_parser") + Facter.debug("Parsing #{fact} using #{parser}") - send(parser, fact) - end + send(parser, fact) end end end - -mdata = Facter.version.match(/(\d+)\.(\d+)\.(\d+)/) +mdata = Facter.version.match(%r{(\d+)\.(\d+)\.(\d+)}) if mdata - (major, minor, patch) = mdata.captures.map { |v| v.to_i } + (major, minor, _patch) = mdata.captures.map { |v| v.to_i } if major < 2 # Facter 1.7 introduced external facts support directly - unless major == 1 and minor > 6 - Facter::Util::DotD.new("/etc/facter/facts.d").create - Facter::Util::DotD.new("/etc/puppetlabs/facter/facts.d").create + unless major == 1 && minor > 6 + Facter::Util::DotD.new('/etc/facter/facts.d').create + Facter::Util::DotD.new('/etc/puppetlabs/facter/facts.d').create # Windows has a different configuration directory that defaults to a vendor # specific sub directory of the %COMMON_APPDATA% directory. - if Dir.const_defined? 'COMMON_APPDATA' then + if Dir.const_defined? 'COMMON_APPDATA' # rubocop:disable Metrics/BlockNesting : Any attempt to alter this breaks it windows_facts_dot_d = File.join(Dir::COMMON_APPDATA, 'PuppetLabs', 'facter', 'facts.d') Facter::Util::DotD.new(windows_facts_dot_d).create end diff --git a/lib/facter/package_provider.rb b/lib/facter/package_provider.rb index 3a9117fdb..ae05d8185 100644 --- a/lib/facter/package_provider.rb +++ b/lib/facter/package_provider.rb @@ -12,10 +12,10 @@ Facter.add(:package_provider) do setcode do - if defined? Gem and Gem::Version.new(Facter.value(:puppetversion).split(' ')[0]) >= Gem::Version.new('3.6') - Puppet::Type.type(:package).newpackage(:name => 'dummy', :allow_virtual => 'true')[:provider].to_s + if defined? Gem && Gem::Version.new(Facter.value(:puppetversion).split(' ')[0]) >= Gem::Version.new('3.6') + Puppet::Type.type(:package).newpackage(name: 'dummy', allow_virtual: 'true')[:provider].to_s else - Puppet::Type.type(:package).newpackage(:name => 'dummy')[:provider].to_s + Puppet::Type.type(:package).newpackage(name: 'dummy')[:provider].to_s end end end diff --git a/lib/facter/pe_version.rb b/lib/facter/pe_version.rb index c9f2181c0..6ce7eac15 100644 --- a/lib/facter/pe_version.rb +++ b/lib/facter/pe_version.rb @@ -8,11 +8,11 @@ # # Caveats: # -Facter.add("pe_version") do +Facter.add('pe_version') do setcode do - puppet_ver = Facter.value("puppetversion") - if puppet_ver != nil - pe_ver = puppet_ver.match(/Puppet Enterprise (\d+\.\d+\.\d+)/) + puppet_ver = Facter.value('puppetversion') + if !puppet_ver.nil? + pe_ver = puppet_ver.match(%r{Puppet Enterprise (\d+\.\d+\.\d+)}) pe_ver[1] if pe_ver else nil @@ -20,9 +20,9 @@ end end -Facter.add("is_pe") do +Facter.add('is_pe') do setcode do - if Facter.value(:pe_version).to_s.empty? then + if Facter.value(:pe_version).to_s.empty? false else true @@ -30,28 +30,31 @@ end end -Facter.add("pe_major_version") do - confine :is_pe => true +Facter.add('pe_major_version') do + confine is_pe: true setcode do - if pe_version = Facter.value(:pe_version) + pe_version = Facter.value(:pe_version) + if pe_version pe_version.to_s.split('.')[0] end end end -Facter.add("pe_minor_version") do - confine :is_pe => true +Facter.add('pe_minor_version') do + confine is_pe: true setcode do - if pe_version = Facter.value(:pe_version) + pe_version = Facter.value(:pe_version) + if pe_version pe_version.to_s.split('.')[1] end end end -Facter.add("pe_patch_version") do - confine :is_pe => true +Facter.add('pe_patch_version') do + confine is_pe: true setcode do - if pe_version = Facter.value(:pe_version) + pe_version = Facter.value(:pe_version) + if pe_version pe_version.to_s.split('.')[2] end end diff --git a/lib/facter/puppet_settings.rb b/lib/facter/puppet_settings.rb index eac9e9753..b9321893f 100644 --- a/lib/facter/puppet_settings.rb +++ b/lib/facter/puppet_settings.rb @@ -13,10 +13,9 @@ # #4248). It should (in the future) but for the time being we need to be # defensive which is what this rescue block is doing. rb_file = File.join(File.dirname(__FILE__), 'util', 'puppet_settings.rb') - load rb_file if File.exists?(rb_file) or raise e + load rb_file if File.exist?(rb_file) || raise(e) end - # These will be nil if Puppet is not available. Facter.add(:puppet_vardir) do setcode do diff --git a/lib/facter/root_home.rb b/lib/facter/root_home.rb index 87c765718..35d6410af 100644 --- a/lib/facter/root_home.rb +++ b/lib/facter/root_home.rb @@ -1,30 +1,29 @@ # A facter fact to determine the root home directory. # This varies on PE supported platforms and may be # reconfigured by the end user. - module Facter::Util::RootHome class << self - def get_root_home - root_ent = Facter::Util::Resolution.exec("getent passwd root") + def returnt_root_home + root_ent = Facter::Util::Resolution.exec('getent passwd root') # The home directory is the sixth element in the passwd entry # If the platform doesn't have getent, root_ent will be nil and we should # return it straight away. - root_ent && root_ent.split(":")[5] + root_ent && root_ent.split(':')[5] end end end Facter.add(:root_home) do - setcode { Facter::Util::RootHome.get_root_home } + setcode { Facter::Util::RootHome.returnt_root_home } end Facter.add(:root_home) do - confine :kernel => :darwin + confine kernel: :darwin setcode do - str = Facter::Util::Resolution.exec("dscacheutil -q user -a name root") + str = Facter::Util::Resolution.exec('dscacheutil -q user -a name root') hash = {} str.split("\n").each do |pair| - key,value = pair.split(/:/) + key, value = pair.split(%r{:}) hash[key] = value end hash['dir'].strip @@ -32,13 +31,13 @@ def get_root_home end Facter.add(:root_home) do - confine :kernel => :aix + confine kernel: :aix root_home = nil setcode do - str = Facter::Util::Resolution.exec("lsuser -c -a home root") + str = Facter::Util::Resolution.exec('lsuser -c -a home root') str && str.split("\n").each do |line| - next if line =~ /^#/ - root_home = line.split(/:/)[1] + next if line =~ %r{^#} + root_home = line.split(%r{:})[1] end root_home end diff --git a/lib/facter/service_provider.rb b/lib/facter/service_provider.rb index a11792115..22167716b 100644 --- a/lib/facter/service_provider.rb +++ b/lib/facter/service_provider.rb @@ -12,6 +12,6 @@ Facter.add(:service_provider) do setcode do - Puppet::Type.type(:service).newservice(:name => 'dummy')[:provider].to_s + Puppet::Type.type(:service).newservice(name: 'dummy')[:provider].to_s end end diff --git a/lib/facter/util/puppet_settings.rb b/lib/facter/util/puppet_settings.rb index 1ad945218..d12e92c97 100644 --- a/lib/facter/util/puppet_settings.rb +++ b/lib/facter/util/puppet_settings.rb @@ -1,21 +1,16 @@ -module Facter - module Util - module PuppetSettings - # This method is intended to provide a convenient way to evaluate a - # Facter code block only if Puppet is loaded. This is to account for the - # situation where the fact happens to be in the load path, but Puppet is - # not loaded for whatever reason. Perhaps the user is simply running - # facter without the --puppet flag and they happen to be working in a lib - # directory of a module. - def self.with_puppet - begin - Module.const_get("Puppet") - rescue NameError - nil - else - yield - end - end - end +# A method to evaluate a Facter code block if puppet is loaded. +module Facter::Util::PuppetSettings + # This method is intended to provide a convenient way to evaluate a + # Facter code block only if Puppet is loaded. This is to account for the + # situation where the fact happens to be in the load path, but Puppet is + # not loaded for whatever reason. Perhaps the user is simply running + # facter without the --puppet flag and they happen to be working in a lib + # directory of a module. + def self.with_puppet + Module.const_get('Puppet') + rescue NameError + nil + else + yield end end diff --git a/lib/puppet/functions/deprecation.rb b/lib/puppet/functions/deprecation.rb index 39d9bc7fe..af6109d9d 100644 --- a/lib/puppet/functions/deprecation.rb +++ b/lib/puppet/functions/deprecation.rb @@ -1,4 +1,7 @@ -# Function to print deprecation warnings, Logs a warning once for a given key. The uniqueness key - can appear once. The msg is the message text including any positional information that is formatted by the user/caller of the method It is affected by the puppet setting 'strict', which can be set to :error (outputs as an error message), :off (no message / error is displayed) and :warning (default, outputs a warning) *Type*: String, String. +# Function to print deprecation warnings, Logs a warning once for a given key. The uniqueness key - can appear once. +# The msg is the message text including any positional information that is formatted by the user/caller of the method. +# It is affected by the puppet setting 'strict', which can be set to :error (outputs as an error message), +# :off (no message / error is displayed) and :warning (default, outputs a warning) *Type*: String, String. # Puppet::Functions.create_function(:deprecation) do @@ -8,7 +11,7 @@ end def deprecation(key, message) - if defined? Puppet::Pops::PuppetStack.stacktrace() + if defined? Puppet::Pops::PuppetStack.stacktrace stacktrace = Puppet::Pops::PuppetStack.stacktrace() file = stacktrace[0] line = stacktrace[1] @@ -16,10 +19,10 @@ def deprecation(key, message) end # depending on configuration setting of strict case Puppet.settings[:strict] - when :off + when :off # rubocop:disable Lint/EmptyWhen : Is required to prevent false errors # do nothing when :error - fail("deprecation. #{key}. #{message}") + raise("deprecation. #{key}. #{message}") else unless ENV['STDLIB_LOG_DEPRECATIONS'] == 'false' Puppet.deprecation_warning(message, key) diff --git a/lib/puppet/functions/fact.rb b/lib/puppet/functions/fact.rb index dfb048b5f..48736ad3f 100644 --- a/lib/puppet/functions/fact.rb +++ b/lib/puppet/functions/fact.rb @@ -19,9 +19,9 @@ end def to_dot_syntax(array_path) - array_path.map do |string| - string.include?('.') ? %Q{"#{string}"} : string - end.join('.') + array_path.map { |string| + string.include?('.') ? %("#{string}") : string + }.join('.') end def fact(fact_name) @@ -30,21 +30,20 @@ def fact(fact_name) # Transform the dot-notation string into an array of paths to walk. Make # sure to correctly extract double-quoted values containing dots as single # elements in the path. - path = fact_name.scan(/([^."]+)|(?:")([^"]+)(?:")/).map {|x| x.compact.first } + path = fact_name.scan(%r{([^."]+)|(?:")([^"]+)(?:")}).map { |x| x.compact.first } walked_path = [] path.reduce(facts) do |d, k| return nil if d.nil? || k.nil? - case - when d.is_a?(Array) + if d.is_a?(Array) begin result = d[Integer(k)] - rescue ArgumentError => e + rescue ArgumentError => e # rubocop:disable Lint/UselessAssignment : Causes errors if assigment is removed. Puppet.warning("fact request for #{fact_name} returning nil: '#{to_dot_syntax(walked_path)}' is an array; cannot index to '#{k}'") result = nil end - when d.is_a?(Hash) + elsif d.is_a?(Hash) result = d[k] else Puppet.warning("fact request for #{fact_name} returning nil: '#{to_dot_syntax(walked_path)}' is not a collection; cannot walk to '#{k}'") diff --git a/lib/puppet/functions/is_a.rb b/lib/puppet/functions/is_a.rb index da98b0352..24b97441c 100644 --- a/lib/puppet/functions/is_a.rb +++ b/lib/puppet/functions/is_a.rb @@ -25,7 +25,7 @@ param 'Type', :type end - def is_a(value, type) + def is_a(value, type) # rubocop:disable Style/PredicateName : Used in to many other places to rename at this time, attempting to refactor caused Rubocop to crash. # See puppet's lib/puppet/pops/evaluator/evaluator_impl.rb eval_MatchExpression Puppet::Pops::Types::TypeCalculator.instance?(type, value) end diff --git a/lib/puppet/functions/is_absolute_path.rb b/lib/puppet/functions/is_absolute_path.rb index b61064a79..c9d92ebd7 100644 --- a/lib/puppet/functions/is_absolute_path.rb +++ b/lib/puppet/functions/is_absolute_path.rb @@ -3,13 +3,15 @@ param 'Any', :scope repeated_param 'Any', :args end - # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff-c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. + # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff + # -c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. def call(scope, *args) manipulated_args = [scope] + args self.class.dispatcher.dispatch(self, scope, manipulated_args) end + def deprecation_gen(scope, *args) - call_function('deprecation', 'is_absolute_path', "This method is deprecated, please use match expressions with Stdlib::Compat::Absolute_Path instead. They are described at https://docs.puppet.com/puppet/latest/reference/lang_data_type.html#match-expressions.") - scope.send("function_is_absolute_path", args) + call_function('deprecation', 'is_absolute_path', 'This method is deprecated, please use match expressions with Stdlib::Compat::Absolute_Path instead. They are described at https://docs.puppet.com/puppet/latest/reference/lang_data_type.html#match-expressions.') + scope.send('function_is_absolute_path', args) end end diff --git a/lib/puppet/functions/is_array.rb b/lib/puppet/functions/is_array.rb index a29fe8a25..fdc60dd5d 100644 --- a/lib/puppet/functions/is_array.rb +++ b/lib/puppet/functions/is_array.rb @@ -3,13 +3,15 @@ param 'Any', :scope repeated_param 'Any', :args end - # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff-c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. + # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff + # -c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. def call(scope, *args) manipulated_args = [scope] + args self.class.dispatcher.dispatch(self, scope, manipulated_args) end + def deprecation_gen(scope, *args) - call_function('deprecation', 'is_array', "This method is deprecated, please use match expressions with Stdlib::Compat::Array instead. They are described at https://docs.puppet.com/puppet/latest/reference/lang_data_type.html#match-expressions.") - scope.send("function_is_array", args) + call_function('deprecation', 'is_array', 'This method is deprecated, please use match expressions with Stdlib::Compat::Array instead. They are described at https://docs.puppet.com/puppet/latest/reference/lang_data_type.html#match-expressions.') + scope.send('function_is_array', args) end end diff --git a/lib/puppet/functions/is_bool.rb b/lib/puppet/functions/is_bool.rb index 6e2c22ba4..1672f0a3d 100644 --- a/lib/puppet/functions/is_bool.rb +++ b/lib/puppet/functions/is_bool.rb @@ -3,13 +3,15 @@ param 'Any', :scope repeated_param 'Any', :args end - # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff-c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. + # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff + # -c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. def call(scope, *args) manipulated_args = [scope] + args self.class.dispatcher.dispatch(self, scope, manipulated_args) end + def deprecation_gen(scope, *args) - call_function('deprecation', 'is_bool', "This method is deprecated, please use match expressions with Stdlib::Compat::Bool instead. They are described at https://docs.puppet.com/puppet/latest/reference/lang_data_type.html#match-expressions.") - scope.send("function_is_bool", args) + call_function('deprecation', 'is_bool', 'This method is deprecated, please use match expressions with Stdlib::Compat::Bool instead. They are described at https://docs.puppet.com/puppet/latest/reference/lang_data_type.html#match-expressions.') + scope.send('function_is_bool', args) end end diff --git a/lib/puppet/functions/is_float.rb b/lib/puppet/functions/is_float.rb index c91aa5d54..03e94d3a4 100644 --- a/lib/puppet/functions/is_float.rb +++ b/lib/puppet/functions/is_float.rb @@ -3,13 +3,15 @@ param 'Any', :scope repeated_param 'Any', :args end - # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff-c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. + # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff + # -c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. def call(scope, *args) manipulated_args = [scope] + args self.class.dispatcher.dispatch(self, scope, manipulated_args) end + def deprecation_gen(scope, *args) - call_function('deprecation', 'is_float', "This method is deprecated, please use match expressions with Stdlib::Compat::Float instead. They are described at https://docs.puppet.com/puppet/latest/reference/lang_data_type.html#match-expressions.") - scope.send("function_is_float", args) + call_function('deprecation', 'is_float', 'This method is deprecated, please use match expressions with Stdlib::Compat::Float instead. They are described at https://docs.puppet.com/puppet/latest/reference/lang_data_type.html#match-expressions.') + scope.send('function_is_float', args) end end diff --git a/lib/puppet/functions/is_ip_address.rb b/lib/puppet/functions/is_ip_address.rb index 4c72037fc..1ab67e7a7 100644 --- a/lib/puppet/functions/is_ip_address.rb +++ b/lib/puppet/functions/is_ip_address.rb @@ -3,13 +3,15 @@ param 'Any', :scope repeated_param 'Any', :args end - # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff-c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. + # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff + # -c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. def call(scope, *args) manipulated_args = [scope] + args self.class.dispatcher.dispatch(self, scope, manipulated_args) end + def deprecation_gen(scope, *args) - call_function('deprecation', 'is_ip_address', "This method is deprecated, please use match expressions with Stdlib::Compat::Ip_address instead. They are described at https://docs.puppet.com/puppet/latest/reference/lang_data_type.html#match-expressions.") - scope.send("function_is_ip_address", args) + call_function('deprecation', 'is_ip_address', 'This method is deprecated, please use match expressions with Stdlib::Compat::Ip_address instead. They are described at https://docs.puppet.com/puppet/latest/reference/lang_data_type.html#match-expressions.') + scope.send('function_is_ip_address', args) end end diff --git a/lib/puppet/functions/is_ipv4_address.rb b/lib/puppet/functions/is_ipv4_address.rb index 97b01ae77..034f9ba10 100644 --- a/lib/puppet/functions/is_ipv4_address.rb +++ b/lib/puppet/functions/is_ipv4_address.rb @@ -3,13 +3,15 @@ param 'Any', :scope repeated_param 'Any', :args end - # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff-c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. + # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff + # -c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. def call(scope, *args) manipulated_args = [scope] + args self.class.dispatcher.dispatch(self, scope, manipulated_args) end + def deprecation_gen(scope, *args) - call_function('deprecation', 'is_ipv4_address', "This method is deprecated, please use match expressions with Stdlib::Compat::Ipv4 instead. They are described at https://docs.puppet.com/puppet/latest/reference/lang_data_type.html#match-expressions.") - scope.send("function_is_ipv4_address", args) + call_function('deprecation', 'is_ipv4_address', 'This method is deprecated, please use match expressions with Stdlib::Compat::Ipv4 instead. They are described at https://docs.puppet.com/puppet/latest/reference/lang_data_type.html#match-expressions.') + scope.send('function_is_ipv4_address', args) end end diff --git a/lib/puppet/functions/is_ipv6_address.rb b/lib/puppet/functions/is_ipv6_address.rb index be0c98a8d..c8fb3ab67 100644 --- a/lib/puppet/functions/is_ipv6_address.rb +++ b/lib/puppet/functions/is_ipv6_address.rb @@ -3,13 +3,15 @@ param 'Any', :scope repeated_param 'Any', :args end - # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff-c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. + # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff + # -c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. def call(scope, *args) manipulated_args = [scope] + args self.class.dispatcher.dispatch(self, scope, manipulated_args) end + def deprecation_gen(scope, *args) - call_function('deprecation', 'is_ipv4_address', "This method is deprecated, please use match expressions with Stdlib::Compat::Ipv6 instead. They are described at https://docs.puppet.com/puppet/latest/reference/lang_data_type.html#match-expressions.") - scope.send("function_is_ipv6_address", args) + call_function('deprecation', 'is_ipv4_address', 'This method is deprecated, please use match expressions with Stdlib::Compat::Ipv6 instead. They are described at https://docs.puppet.com/puppet/latest/reference/lang_data_type.html#match-expressions.') + scope.send('function_is_ipv6_address', args) end end diff --git a/lib/puppet/functions/is_numeric.rb b/lib/puppet/functions/is_numeric.rb index f5e9d412e..79a6bbf82 100644 --- a/lib/puppet/functions/is_numeric.rb +++ b/lib/puppet/functions/is_numeric.rb @@ -3,13 +3,15 @@ param 'Any', :scope repeated_param 'Any', :args end - # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff-c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. + # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff + # -c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. def call(scope, *args) manipulated_args = [scope] + args self.class.dispatcher.dispatch(self, scope, manipulated_args) end + def deprecation_gen(scope, *args) - call_function('deprecation', 'is_numeric', "This method is deprecated, please use match expressions with Stdlib::Compat::Numeric instead. They are described at https://docs.puppet.com/puppet/latest/reference/lang_data_type.html#match-expressions.") - scope.send("function_is_numeric", args) + call_function('deprecation', 'is_numeric', 'This method is deprecated, please use match expressions with Stdlib::Compat::Numeric instead. They are described at https://docs.puppet.com/puppet/latest/reference/lang_data_type.html#match-expressions.') + scope.send('function_is_numeric', args) end end diff --git a/lib/puppet/functions/is_string.rb b/lib/puppet/functions/is_string.rb index a05a7963b..a32216c05 100644 --- a/lib/puppet/functions/is_string.rb +++ b/lib/puppet/functions/is_string.rb @@ -3,13 +3,15 @@ param 'Any', :scope repeated_param 'Any', :args end - # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff-c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. + # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff + # -c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. def call(scope, *args) manipulated_args = [scope] + args self.class.dispatcher.dispatch(self, scope, manipulated_args) end + def deprecation_gen(scope, *args) - call_function('deprecation', 'is_string', "This method is deprecated, please use match expressions with Stdlib::Compat::String instead. They are described at https://docs.puppet.com/puppet/latest/reference/lang_data_type.html#match-expressions.") - scope.send("function_is_string", args) + call_function('deprecation', 'is_string', 'This method is deprecated, please use match expressions with Stdlib::Compat::String instead. They are described at https://docs.puppet.com/puppet/latest/reference/lang_data_type.html#match-expressions.') + scope.send('function_is_string', args) end end diff --git a/lib/puppet/functions/length.rb b/lib/puppet/functions/length.rb index 5ebd4551e..8cd43e5f4 100644 --- a/lib/puppet/functions/length.rb +++ b/lib/puppet/functions/length.rb @@ -1,4 +1,4 @@ -#A function to eventually replace the old size() function for stdlib - The original size function did not handle Puppets new type capabilities, so this function is a Puppet 4 compatible solution. +# A function to eventually replace the old size() function for stdlib - The original size function did not handle Puppets new type capabilities, so this function is a Puppet 4 compatible solution. Puppet::Functions.create_function(:length) do dispatch :length do param 'Variant[String,Array,Hash]', :value @@ -9,6 +9,6 @@ def length(value) elsif value.is_a?(Array) || value.is_a?(Hash) result = value.size end - return result + result end end diff --git a/lib/puppet/functions/type_of.rb b/lib/puppet/functions/type_of.rb index 01f1f49ef..5bed6d5a5 100644 --- a/lib/puppet/functions/type_of.rb +++ b/lib/puppet/functions/type_of.rb @@ -10,7 +10,7 @@ # See the documentation for "The Puppet Type System" for more information about types. # See the `assert_type()` function for flexible ways to assert the type of a value. # -# The built-in type() function in puppet is generally preferred over this function +# The built-in type() function in puppet is generally preferred over this function # this function is provided for backwards compatibility. Puppet::Functions.create_function(:type_of) do def type_of(value) diff --git a/lib/puppet/functions/validate_absolute_path.rb b/lib/puppet/functions/validate_absolute_path.rb index a3c696d0f..44f600fd9 100644 --- a/lib/puppet/functions/validate_absolute_path.rb +++ b/lib/puppet/functions/validate_absolute_path.rb @@ -3,13 +3,16 @@ param 'Any', :scope repeated_param 'Any', :args end - # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff-c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. + # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff + # -c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. def call(scope, *args) manipulated_args = [scope] + args self.class.dispatcher.dispatch(self, scope, manipulated_args) end + def deprecation_gen(scope, *args) - call_function('deprecation', 'validate_absolute_path', "This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Absolute_Path. There is further documentation for validate_legacy function in the README.") - scope.send("function_validate_absolute_path", args) + call_function('deprecation', 'validate_absolute_path', 'This method is deprecated, please use the stdlib validate_legacy function, + with Stdlib::Compat::Absolute_Path. There is further documentation for validate_legacy function in the README.') + scope.send('function_validate_absolute_path', args) end end diff --git a/lib/puppet/functions/validate_array.rb b/lib/puppet/functions/validate_array.rb index f59c6b447..2bedd3fee 100644 --- a/lib/puppet/functions/validate_array.rb +++ b/lib/puppet/functions/validate_array.rb @@ -3,13 +3,16 @@ param 'Any', :scope repeated_param 'Any', :args end - # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff-c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. + # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff + # -c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. def call(scope, *args) manipulated_args = [scope] + args self.class.dispatcher.dispatch(self, scope, manipulated_args) end + def deprecation_gen(scope, *args) - call_function('deprecation', 'validate_array', "This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Array. There is further documentation for validate_legacy function in the README.") - scope.send("function_validate_array", args) + call_function('deprecation', 'validate_array', 'This method is deprecated, please use the stdlib validate_legacy function, + with Stdlib::Compat::Array. There is further documentation for validate_legacy function in the README.') + scope.send('function_validate_array', args) end end diff --git a/lib/puppet/functions/validate_bool.rb b/lib/puppet/functions/validate_bool.rb index 5cfb2accc..907eed371 100644 --- a/lib/puppet/functions/validate_bool.rb +++ b/lib/puppet/functions/validate_bool.rb @@ -3,13 +3,16 @@ param 'Any', :scope repeated_param 'Any', :args end - # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff-c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. + # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff + # -c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. def call(scope, *args) manipulated_args = [scope] + args self.class.dispatcher.dispatch(self, scope, manipulated_args) end + def deprecation_gen(scope, *args) - call_function('deprecation', 'validate_bool', "This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Bool. There is further documentation for validate_legacy function in the README.") - scope.send("function_validate_bool", args) + call_function('deprecation', 'validate_bool', 'This method is deprecated, please use the stdlib validate_legacy function, + with Stdlib::Compat::Bool. There is further documentation for validate_legacy function in the README.') + scope.send('function_validate_bool', args) end end diff --git a/lib/puppet/functions/validate_hash.rb b/lib/puppet/functions/validate_hash.rb index 89ad9ab53..c6a61a4bd 100644 --- a/lib/puppet/functions/validate_hash.rb +++ b/lib/puppet/functions/validate_hash.rb @@ -3,13 +3,16 @@ param 'Any', :scope repeated_param 'Any', :args end - # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff-c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. + # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff + # -c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. def call(scope, *args) manipulated_args = [scope] + args self.class.dispatcher.dispatch(self, scope, manipulated_args) end + def deprecation_gen(scope, *args) - call_function('deprecation', 'validate_hash', "This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Hash. There is further documentation for validate_legacy function in the README.") - scope.send("function_validate_hash", args) + call_function('deprecation', 'validate_hash', 'This method is deprecated, please use the stdlib validate_legacy function, + with Stdlib::Compat::Hash. There is further documentation for validate_legacy function in the README.') + scope.send('function_validate_hash', args) end end diff --git a/lib/puppet/functions/validate_integer.rb b/lib/puppet/functions/validate_integer.rb index 475ea0fa1..487dcf725 100644 --- a/lib/puppet/functions/validate_integer.rb +++ b/lib/puppet/functions/validate_integer.rb @@ -3,13 +3,16 @@ param 'Any', :scope repeated_param 'Any', :args end - # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff-c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. + # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff + # -c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. def call(scope, *args) manipulated_args = [scope] + args self.class.dispatcher.dispatch(self, scope, manipulated_args) end + def deprecation_gen(scope, *args) - call_function('deprecation', 'validate_integer', "This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Integer. There is further documentation for validate_legacy function in the README.") - scope.send("function_validate_integer", args) + call_function('deprecation', 'validate_integer', 'This method is deprecated, please use the stdlib validate_legacy function, + with Stdlib::Compat::Integer. There is further documentation for validate_legacy function in the README.') + scope.send('function_validate_integer', args) end end diff --git a/lib/puppet/functions/validate_ip_address.rb b/lib/puppet/functions/validate_ip_address.rb index 1521c089e..68e7f7f88 100644 --- a/lib/puppet/functions/validate_ip_address.rb +++ b/lib/puppet/functions/validate_ip_address.rb @@ -3,13 +3,16 @@ param 'Any', :scope repeated_param 'Any', :args end - # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff-c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. + # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff + # -c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. def call(scope, *args) manipulated_args = [scope] + args self.class.dispatcher.dispatch(self, scope, manipulated_args) end + def deprecation_gen(scope, *args) - call_function('deprecation', 'validate_ip_address', "This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Ip_Address. There is further documentation for validate_legacy function in the README.") - scope.send("function_validate_ip_address", args) + call_function('deprecation', 'validate_ip_address', 'This method is deprecated, please use the stdlib validate_legacy function, + with Stdlib::Compat::Ip_Address. There is further documentation for validate_legacy function in the README.') + scope.send('function_validate_ip_address', args) end end diff --git a/lib/puppet/functions/validate_ipv4_address.rb b/lib/puppet/functions/validate_ipv4_address.rb index fe66ab3ba..caeeacaa9 100644 --- a/lib/puppet/functions/validate_ipv4_address.rb +++ b/lib/puppet/functions/validate_ipv4_address.rb @@ -3,13 +3,16 @@ param 'Any', :scope repeated_param 'Any', :args end - # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff-c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. + # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff + # -c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. def call(scope, *args) manipulated_args = [scope] + args self.class.dispatcher.dispatch(self, scope, manipulated_args) end + def deprecation_gen(scope, *args) - call_function('deprecation', 'validate_ipv4_address', "This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Ipv4_Address. There is further documentation for validate_legacy function in the README.") - scope.send("function_validate_ipv4_address", args) + call_function('deprecation', 'validate_ipv4_address', 'This method is deprecated, please use the stdlib validate_legacy function, + with Stdlib::Compat::Ipv4_Address. There is further documentation for validate_legacy function in the README.') + scope.send('function_validate_ipv4_address', args) end end diff --git a/lib/puppet/functions/validate_ipv6_address.rb b/lib/puppet/functions/validate_ipv6_address.rb index 7cc3cbdd2..c0353571a 100644 --- a/lib/puppet/functions/validate_ipv6_address.rb +++ b/lib/puppet/functions/validate_ipv6_address.rb @@ -3,13 +3,16 @@ param 'Any', :scope repeated_param 'Any', :args end - # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff-c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. + # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff + # -c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. def call(scope, *args) manipulated_args = [scope] + args self.class.dispatcher.dispatch(self, scope, manipulated_args) end + def deprecation_gen(scope, *args) - call_function('deprecation', 'validate_ipv6_address', "This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Ipv6_address. There is further documentation for validate_legacy function in the README.") - scope.send("function_validate_ipv6_address", args) + call_function('deprecation', 'validate_ipv6_address', 'This method is deprecated, please use the stdlib validate_legacy function, + with Stdlib::Compat::Ipv6_address. There is further documentation for validate_legacy function in the README.') + scope.send('function_validate_ipv6_address', args) end end diff --git a/lib/puppet/functions/validate_legacy.rb b/lib/puppet/functions/validate_legacy.rb index c9d1f5611..21646ade3 100644 --- a/lib/puppet/functions/validate_legacy.rb +++ b/lib/puppet/functions/validate_legacy.rb @@ -17,7 +17,8 @@ repeated_param 'Any', :args end - # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff-c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. + # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff- + # c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. def call(scope, *args) manipulated_args = [scope] + args self.class.dispatcher.dispatch(self, scope, manipulated_args) @@ -48,12 +49,11 @@ def validate_legacy(scope, target_type, function_name, value, *prev_args) def previous_validation(scope, function_name, value, *prev_args) # Call the previous validation function and catch any errors. Return true if no errors are thrown. - begin - scope.send("function_#{function_name}".to_s, [value, *prev_args]) - true - rescue Puppet::ParseError - false - end + + scope.send("function_#{function_name}".to_s, [value, *prev_args]) + true + rescue Puppet::ParseError + false end def assert_type(type, value) diff --git a/lib/puppet/functions/validate_numeric.rb b/lib/puppet/functions/validate_numeric.rb index 3052d3515..3adb0a87b 100644 --- a/lib/puppet/functions/validate_numeric.rb +++ b/lib/puppet/functions/validate_numeric.rb @@ -3,13 +3,16 @@ param 'Any', :scope repeated_param 'Any', :args end - # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff-c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. + # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff- + # c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. def call(scope, *args) manipulated_args = [scope] + args self.class.dispatcher.dispatch(self, scope, manipulated_args) end + def deprecation_gen(scope, *args) - call_function('deprecation', 'validate_numeric', "This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Numeric. There is further documentation for validate_legacy function in the README.") - scope.send("function_validate_numeric", args) + call_function('deprecation', 'validate_numeric', 'This method is deprecated, please use the stdlib validate_legacy function, + with Stdlib::Compat::Numeric. There is further documentation for validate_legacy function in the README.') + scope.send('function_validate_numeric', args) end end diff --git a/lib/puppet/functions/validate_re.rb b/lib/puppet/functions/validate_re.rb index 19443a8ac..d357aab31 100644 --- a/lib/puppet/functions/validate_re.rb +++ b/lib/puppet/functions/validate_re.rb @@ -3,13 +3,16 @@ param 'Any', :scope repeated_param 'Any', :args end - # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff-c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. + # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff- + # c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. def call(scope, *args) manipulated_args = [scope] + args self.class.dispatcher.dispatch(self, scope, manipulated_args) end + def deprecation_gen(scope, *args) - call_function('deprecation', 'validate_re', "This method is deprecated, please use the stdlib validate_legacy function, with Pattern[]. There is further documentation for validate_legacy function in the README.") - scope.send("function_validate_re", args) + call_function('deprecation', 'validate_re', 'This method is deprecated, please use the stdlib validate_legacy function, + with Pattern[]. There is further documentation for validate_legacy function in the README.') + scope.send('function_validate_re', args) end end diff --git a/lib/puppet/functions/validate_slength.rb b/lib/puppet/functions/validate_slength.rb index 584232ac1..ad6f7b3ad 100644 --- a/lib/puppet/functions/validate_slength.rb +++ b/lib/puppet/functions/validate_slength.rb @@ -3,13 +3,16 @@ param 'Any', :scope repeated_param 'Any', :args end - # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff-c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. + # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff- + # c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. def call(scope, *args) manipulated_args = [scope] + args self.class.dispatcher.dispatch(self, scope, manipulated_args) end + def deprecation_gen(scope, *args) - call_function('deprecation', 'validate_slength', "This method is deprecated, please use the stdlib validate_legacy function, with String[]. There is further documentation for validate_legacy function in the README.") - scope.send("function_validate_slength", args) + call_function('deprecation', 'validate_slength', 'This method is deprecated, please use the stdlib validate_legacy function, + with String[]. There is further documentation for validate_legacy function in the README.') + scope.send('function_validate_slength', args) end end diff --git a/lib/puppet/functions/validate_string.rb b/lib/puppet/functions/validate_string.rb index 91ff00460..a908c1974 100644 --- a/lib/puppet/functions/validate_string.rb +++ b/lib/puppet/functions/validate_string.rb @@ -3,13 +3,16 @@ param 'Any', :scope repeated_param 'Any', :args end - # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff-c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. + # Workaround PUP-4438 (fixed: https://github.com/puppetlabs/puppet/commit/e01c4dc924cd963ff6630008a5200fc6a2023b08#diff- + # c937cc584953271bb3d3b3c2cb141790R221) to support puppet < 4.1.0 and puppet < 3.8.1. def call(scope, *args) manipulated_args = [scope] + args self.class.dispatcher.dispatch(self, scope, manipulated_args) end + def deprecation_gen(scope, *args) - call_function('deprecation', 'validate_string', "This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::String. There is further documentation for validate_legacy function in the README.") - scope.send("function_validate_string", args) + call_function('deprecation', 'validate_string', 'This method is deprecated, please use the stdlib validate_legacy function, + with Stdlib::Compat::String. There is further documentation for validate_legacy function in the README.') + scope.send('function_validate_string', args) end end diff --git a/lib/puppet/parser/functions/abs.rb b/lib/puppet/parser/functions/abs.rb index 222a902ee..1b6d2baac 100644 --- a/lib/puppet/parser/functions/abs.rb +++ b/lib/puppet/parser/functions/abs.rb @@ -1,23 +1,22 @@ # # abs.rb # - module Puppet::Parser::Functions - newfunction(:abs, :type => :rvalue, :doc => <<-EOS + newfunction(:abs, type: :rvalue, doc: <<-EOS Returns the absolute value of a number, for example -34.56 becomes 34.56. Takes a single integer and float value as an argument. EOS - ) do |arguments| + ) do |arguments| - raise(Puppet::ParseError, "abs(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size < 1 + raise(Puppet::ParseError, "abs(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? value = arguments[0] # Numbers in Puppet are often string-encoded which is troublesome ... if value.is_a?(String) - if value.match(/^-?(?:\d+)(?:\.\d+){1}$/) + if value =~ %r{^-?(?:\d+)(?:\.\d+){1}$} value = value.to_f - elsif value.match(/^-?\d+$/) + elsif value =~ %r{^-?\d+$} value = value.to_i else raise(Puppet::ParseError, 'abs(): Requires float or integer to work with') diff --git a/lib/puppet/parser/functions/any2array.rb b/lib/puppet/parser/functions/any2array.rb index e71407e89..4c47a4e68 100644 --- a/lib/puppet/parser/functions/any2array.rb +++ b/lib/puppet/parser/functions/any2array.rb @@ -1,31 +1,27 @@ # # any2array.rb # - module Puppet::Parser::Functions - newfunction(:any2array, :type => :rvalue, :doc => <<-EOS -This converts any object to an array containing that object. Empty argument -lists are converted to an empty array. Arrays are left untouched. Hashes are -converted to arrays of alternating keys and values. - EOS - ) do |arguments| + newfunction(:any2array, type: :rvalue, doc: <<-EOS + This converts any object to an array containing that object. Empty argument + lists are converted to an empty array. Arrays are left untouched. Hashes are + converted to arrays of alternating keys and values. + EOS + ) do |arguments| if arguments.empty? - return [] + return [] end - if arguments.length == 1 - if arguments[0].kind_of?(Array) - return arguments[0] - elsif arguments[0].kind_of?(Hash) - result = [] - arguments[0].each do |key, value| - result << key << value - end - return result - end + return arguments unless arguments.length == 1 + return arguments[0] if arguments[0].is_a?(Array) + if arguments[0].is_a?(Hash) + result = [] + arguments[0].each do |key, value| + result << key << value + end + return result end - return arguments end end diff --git a/lib/puppet/parser/functions/any2bool.rb b/lib/puppet/parser/functions/any2bool.rb index 17612bf80..0d86477da 100644 --- a/lib/puppet/parser/functions/any2bool.rb +++ b/lib/puppet/parser/functions/any2bool.rb @@ -1,30 +1,29 @@ # # any2bool.rb # - module Puppet::Parser::Functions - newfunction(:any2bool, :type => :rvalue, :doc => <<-EOS -This converts 'anything' to a boolean. In practise it does the following: + newfunction(:any2bool, type: :rvalue, doc: <<-EOS + This converts 'anything' to a boolean. In practise it does the following: -* Strings such as Y,y,1,T,t,TRUE,yes,'true' will return true -* Strings such as 0,F,f,N,n,FALSE,no,'false' will return false -* Booleans will just return their original value -* Number (or a string representation of a number) > 0 will return true, otherwise false -* undef will return false -* Anything else will return true - EOS - ) do |arguments| + * Strings such as Y,y,1,T,t,TRUE,yes,'true' will return true + * Strings such as 0,F,f,N,n,FALSE,no,'false' will return false + * Booleans will just return their original value + * Number (or a string representation of a number) > 0 will return true, otherwise false + * undef will return false + * Anything else will return true + EOS + ) do |arguments| - raise(Puppet::ParseError, "any2bool(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size < 1 + raise(Puppet::ParseError, "any2bool(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? # If argument is already Boolean, return it - if !!arguments[0] == arguments[0] + if !!arguments[0] == arguments[0] # rubocop:disable Style/DoubleNegation : Could not find a better way to check if a boolean return arguments[0] end arg = arguments[0] - if arg == nil + if arg.nil? return false end @@ -32,22 +31,22 @@ module Puppet::Parser::Functions return false end - valid_float = !!Float(arg) rescue false + valid_float = begin + !!Float(arg) # rubocop:disable Style/DoubleNegation : Could not find a better way to check if a boolean + rescue + false + end if arg.is_a?(Numeric) - return function_num2bool( [ arguments[0] ] ) + return function_num2bool([arguments[0]]) end if arg.is_a?(String) - if valid_float - return function_num2bool( [ arguments[0] ] ) - else - return function_str2bool( [ arguments[0] ] ) - end + return function_num2bool([arguments[0]]) if valid_float + return function_str2bool([arguments[0]]) end return true - end end diff --git a/lib/puppet/parser/functions/assert_private.rb b/lib/puppet/parser/functions/assert_private.rb index 62e2c6b08..a61686024 100644 --- a/lib/puppet/parser/functions/assert_private.rb +++ b/lib/puppet/parser/functions/assert_private.rb @@ -1,20 +1,19 @@ # # assert_private.rb # - module Puppet::Parser::Functions - newfunction(:assert_private, :doc => <<-'EOS' + newfunction(:assert_private, doc: <<-'EOS' Sets the current class or definition as private. Calling the class or definition from outside the current module will fail. EOS - ) do |args| + ) do |args| raise(Puppet::ParseError, "assert_private(): Wrong number of arguments given (#{args.size}}) for 0 or 1)") if args.size > 1 scope = self if scope.lookupvar('module_name') != scope.lookupvar('caller_module_name') message = nil - if args[0] and args[0].is_a? String + if args[0] && args[0].is_a?(String) message = args[0] else manifest_name = scope.source.name diff --git a/lib/puppet/parser/functions/base64.rb b/lib/puppet/parser/functions/base64.rb index d61014607..9847cd920 100644 --- a/lib/puppet/parser/functions/base64.rb +++ b/lib/puppet/parser/functions/base64.rb @@ -1,10 +1,6 @@ - # Please note: This function is an implementation of a Ruby class and as such may not be entirely UTF8 compatible. To ensure compatibility please use this function with Ruby 2.4.0 or greater - https://bugs.ruby-lang.org/issues/10085. - module Puppet::Parser::Functions - - newfunction(:base64, :type => :rvalue, :doc => <<-'ENDHEREDOC') do |args| - + newfunction(:base64, type: :rvalue, doc: <<-'ENDHEREDOC') do |args| Base64 encode or decode a string based on the command and the string submitted Usage: @@ -21,49 +17,49 @@ module Puppet::Parser::Functions require 'base64' - raise Puppet::ParseError, ("base64(): Wrong number of arguments (#{args.length}; must be >= 2)") unless args.length >= 2 + raise Puppet::ParseError, "base64(): Wrong number of arguments (#{args.length}; must be >= 2)" unless args.length >= 2 - actions = ['encode','decode'] + actions = %w[encode decode] unless actions.include?(args[0]) - raise Puppet::ParseError, ("base64(): the first argument must be one of 'encode' or 'decode'") + raise Puppet::ParseError, "base64(): the first argument must be one of 'encode' or 'decode'" end unless args[1].is_a?(String) - raise Puppet::ParseError, ("base64(): the second argument must be a string to base64") + raise Puppet::ParseError, 'base64(): the second argument must be a string to base64' end - method = ['default','strict','urlsafe'] + method = %w[default strict urlsafe] - if args.length <= 2 - chosenMethod = 'default' - else - chosenMethod = args[2] - end + chosen_method = if args.length <= 2 + 'default' + else + args[2] + end - unless method.include?(chosenMethod) - raise Puppet::ParseError, ("base64(): the third argument must be one of 'default', 'strict', or 'urlsafe'") + unless method.include?(chosen_method) + raise Puppet::ParseError, "base64(): the third argument must be one of 'default', 'strict', or 'urlsafe'" end case args[0] - when 'encode' - case chosenMethod - when 'default' - result = Base64.encode64(args[1]) - when 'strict' - result = Base64.strict_encode64(args[1]) - when 'urlsafe' - result = Base64.urlsafe_encode64(args[1]) - end - when 'decode' - case chosenMethod - when 'default' - result = Base64.decode64(args[1]) - when 'strict' - result = Base64.strict_decode64(args[1]) - when 'urlsafe' - result = Base64.urlsafe_decode64(args[1]) - end + when 'encode' + case chosen_method + when 'default' + result = Base64.encode64(args[1]) + when 'strict' + result = Base64.strict_encode64(args[1]) + when 'urlsafe' + result = Base64.urlsafe_encode64(args[1]) + end + when 'decode' + case chosen_method + when 'default' + result = Base64.decode64(args[1]) + when 'strict' + result = Base64.strict_decode64(args[1]) + when 'urlsafe' + result = Base64.urlsafe_decode64(args[1]) + end end return result diff --git a/lib/puppet/parser/functions/basename.rb b/lib/puppet/parser/functions/basename.rb index f7e443847..a134f7f55 100644 --- a/lib/puppet/parser/functions/basename.rb +++ b/lib/puppet/parser/functions/basename.rb @@ -1,30 +1,20 @@ +# +# basename.rb +# module Puppet::Parser::Functions - newfunction(:basename, :type => :rvalue, :doc => <<-EOS + newfunction(:basename, type: :rvalue, doc: <<-EOS Strips directory (and optional suffix) from a filename EOS - ) do |arguments| + ) do |arguments| - if arguments.size < 1 then - raise(Puppet::ParseError, "basename(): No arguments given") - elsif arguments.size > 2 then - raise(Puppet::ParseError, "basename(): Too many arguments given (#{arguments.size})") - else - - unless arguments[0].is_a?(String) - raise(Puppet::ParseError, 'basename(): Requires string as first argument') - end - - if arguments.size == 1 then - rv = File.basename(arguments[0]) - elsif arguments.size == 2 then - - unless arguments[1].is_a?(String) - raise(Puppet::ParseError, 'basename(): Requires string as second argument') - end - - rv = File.basename(arguments[0], arguments[1]) - end + raise(Puppet::ParseError, 'basename(): No arguments given') if arguments.empty? + raise(Puppet::ParseError, "basename(): Too many arguments given (#{arguments.size})") if arguments.size > 2 + raise(Puppet::ParseError, 'basename(): Requires string as first argument') unless arguments[0].is_a?(String) + rv = File.basename(arguments[0]) if arguments.size == 1 + if arguments.size == 2 + raise(Puppet::ParseError, 'basename(): Requires string as second argument') unless arguments[1].is_a?(String) + rv = File.basename(arguments[0], arguments[1]) end return rv diff --git a/lib/puppet/parser/functions/bool2num.rb b/lib/puppet/parser/functions/bool2num.rb index 92e4ddef3..a6abb44e5 100644 --- a/lib/puppet/parser/functions/bool2num.rb +++ b/lib/puppet/parser/functions/bool2num.rb @@ -1,17 +1,16 @@ # # bool2num.rb # - module Puppet::Parser::Functions - newfunction(:bool2num, :type => :rvalue, :doc => <<-EOS + newfunction(:bool2num, type: :rvalue, doc: <<-EOS Converts a boolean to a number. Converts the values: false, f, 0, n, and no to 0 true, t, 1, y, and yes to 1 Requires a single boolean or string as an input. EOS - ) do |arguments| + ) do |arguments| - raise(Puppet::ParseError, "bool2num(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size < 1 + raise(Puppet::ParseError, "bool2num(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? value = function_str2bool([arguments[0]]) diff --git a/lib/puppet/parser/functions/bool2str.rb b/lib/puppet/parser/functions/bool2str.rb index 37d4a4ef2..6cd833220 100644 --- a/lib/puppet/parser/functions/bool2str.rb +++ b/lib/puppet/parser/functions/bool2str.rb @@ -1,9 +1,8 @@ # # bool2str.rb # - module Puppet::Parser::Functions - newfunction(:bool2str, :type => :rvalue, :doc => <<-EOS + newfunction(:bool2str, type: :rvalue, doc: <<-EOS Converts a boolean to a string using optionally supplied arguments. The optional second and third arguments represent what true and false will be converted to respectively. If only one argument is given, it will be @@ -17,9 +16,9 @@ module Puppet::Parser::Functions Requires a single boolean as an input. EOS - ) do |arguments| + ) do |arguments| - unless arguments.size == 1 or arguments.size == 3 + unless arguments.size == 1 || arguments.size == 3 raise(Puppet::ParseError, "bool2str(): Wrong number of arguments given (#{arguments.size} for 3)") end @@ -33,8 +32,8 @@ module Puppet::Parser::Functions raise(Puppet::ParseError, 'bool2str(): Requires a boolean to work with') end - unless [true_string, false_string].all?{|x| x.kind_of?(String)} - raise(Puppet::ParseError, "bool2str(): Requires strings to convert to" ) + unless [true_string, false_string].all? { |x| x.is_a?(String) } + raise(Puppet::ParseError, 'bool2str(): Requires strings to convert to') end return value ? true_string : false_string diff --git a/lib/puppet/parser/functions/camelcase.rb b/lib/puppet/parser/functions/camelcase.rb index 085b3c6d8..32a31856a 100644 --- a/lib/puppet/parser/functions/camelcase.rb +++ b/lib/puppet/parser/functions/camelcase.rb @@ -2,14 +2,13 @@ # camelcase.rb # Please note: This function is an implementation of a Ruby class and as such may not be entirely UTF8 compatible. To ensure compatibility please use this function with Ruby 2.4.0 or greater - https://bugs.ruby-lang.org/issues/10085. # - module Puppet::Parser::Functions - newfunction(:camelcase, :type => :rvalue, :doc => <<-EOS -Converts the case of a string or all strings in an array to camel case. - EOS - ) do |arguments| + newfunction(:camelcase, type: :rvalue, doc: <<-EOS + Converts the case of a string or all strings in an array to camel case. + EOS + ) do |arguments| - raise(Puppet::ParseError, "camelcase(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size < 1 + raise(Puppet::ParseError, "camelcase(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? value = arguments[0] klass = value.class @@ -18,12 +17,12 @@ module Puppet::Parser::Functions raise(Puppet::ParseError, 'camelcase(): Requires either array or string to work with') end - if value.is_a?(Array) - # Numbers in Puppet are often string-encoded which is troublesome ... - result = value.collect { |i| i.is_a?(String) ? i.split('_').map{|e| e.capitalize}.join : i } - else - result = value.split('_').map{|e| e.capitalize}.join - end + result = if value.is_a?(Array) + # Numbers in Puppet are often string-encoded which is troublesome ... + value.map { |i| i.is_a?(String) ? i.split('_').map { |e| e.capitalize }.join : i } + else + value.split('_').map { |e| e.capitalize }.join + end return result end diff --git a/lib/puppet/parser/functions/capitalize.rb b/lib/puppet/parser/functions/capitalize.rb index 096bc5dc5..47db566f9 100644 --- a/lib/puppet/parser/functions/capitalize.rb +++ b/lib/puppet/parser/functions/capitalize.rb @@ -2,15 +2,14 @@ # capitalize.rb # Please note: This function is an implementation of a Ruby class and as such may not be entirely UTF8 compatible. To ensure compatibility please use this function with Ruby 2.4.0 or greater - https://bugs.ruby-lang.org/issues/10085. # - module Puppet::Parser::Functions - newfunction(:capitalize, :type => :rvalue, :doc => <<-EOS + newfunction(:capitalize, type: :rvalue, doc: <<-EOS Capitalizes the first letter of a string or array of strings. Requires either a single string or an array as an input. EOS - ) do |arguments| + ) do |arguments| - raise(Puppet::ParseError, "capitalize(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size < 1 + raise(Puppet::ParseError, "capitalize(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? value = arguments[0] @@ -18,12 +17,12 @@ module Puppet::Parser::Functions raise(Puppet::ParseError, 'capitalize(): Requires either array or string to work with') end - if value.is_a?(Array) - # Numbers in Puppet are often string-encoded which is troublesome ... - result = value.collect { |i| i.is_a?(String) ? i.capitalize : i } - else - result = value.capitalize - end + result = if value.is_a?(Array) + # Numbers in Puppet are often string-encoded which is troublesome ... + value.map { |i| i.is_a?(String) ? i.capitalize : i } + else + value.capitalize + end return result end diff --git a/lib/puppet/parser/functions/ceiling.rb b/lib/puppet/parser/functions/ceiling.rb index bec42661b..51c163a05 100644 --- a/lib/puppet/parser/functions/ceiling.rb +++ b/lib/puppet/parser/functions/ceiling.rb @@ -1,15 +1,18 @@ +# +# ceiling.rb +# module Puppet::Parser::Functions - newfunction(:ceiling, :type => :rvalue, :doc => <<-EOS + newfunction(:ceiling, type: :rvalue, doc: <<-EOS Returns the smallest integer greater or equal to the argument. Takes a single numeric value as an argument. EOS - ) do |arguments| + ) do |arguments| raise(Puppet::ParseError, "ceiling(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size != 1 begin arg = Float(arguments[0]) - rescue TypeError, ArgumentError => e + rescue TypeError, ArgumentError => _e raise(Puppet::ParseError, "ceiling(): Wrong argument type given (#{arguments[0]} for Numeric)") end diff --git a/lib/puppet/parser/functions/chomp.rb b/lib/puppet/parser/functions/chomp.rb index f9da50f58..f950d9c06 100644 --- a/lib/puppet/parser/functions/chomp.rb +++ b/lib/puppet/parser/functions/chomp.rb @@ -1,16 +1,15 @@ # # chomp.rb # - module Puppet::Parser::Functions - newfunction(:chomp, :type => :rvalue, :doc => <<-'EOS' + newfunction(:chomp, type: :rvalue, doc: <<-'EOS' Removes the record separator from the end of a string or an array of strings, for example `hello\n` becomes `hello`. Requires a single string or array as an input. EOS - ) do |arguments| + ) do |arguments| - raise(Puppet::ParseError, "chomp(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size < 1 + raise(Puppet::ParseError, "chomp(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? value = arguments[0] @@ -18,12 +17,12 @@ module Puppet::Parser::Functions raise(Puppet::ParseError, 'chomp(): Requires either array or string to work with') end - if value.is_a?(Array) - # Numbers in Puppet are often string-encoded which is troublesome ... - result = value.collect { |i| i.is_a?(String) ? i.chomp : i } - else - result = value.chomp - end + result = if value.is_a?(Array) + # Numbers in Puppet are often string-encoded which is troublesome ... + value.map { |i| i.is_a?(String) ? i.chomp : i } + else + value.chomp + end return result end diff --git a/lib/puppet/parser/functions/chop.rb b/lib/puppet/parser/functions/chop.rb index 809349d9d..e5b258d0d 100644 --- a/lib/puppet/parser/functions/chop.rb +++ b/lib/puppet/parser/functions/chop.rb @@ -1,18 +1,17 @@ # # chop.rb # - module Puppet::Parser::Functions - newfunction(:chop, :type => :rvalue, :doc => <<-'EOS' + newfunction(:chop, type: :rvalue, doc: <<-'EOS' Returns a new string with the last character removed. If the string ends with `\r\n`, both characters are removed. Applying chop to an empty string returns an empty string. If you wish to merely remove record separators then you should use the `chomp` function. Requires a string or array of strings as input. EOS - ) do |arguments| + ) do |arguments| - raise(Puppet::ParseError, "chop(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size < 1 + raise(Puppet::ParseError, "chop(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? value = arguments[0] @@ -20,12 +19,12 @@ module Puppet::Parser::Functions raise(Puppet::ParseError, 'chop(): Requires either an array or string to work with') end - if value.is_a?(Array) - # Numbers in Puppet are often string-encoded which is troublesome ... - result = value.collect { |i| i.is_a?(String) ? i.chop : i } - else - result = value.chop - end + result = if value.is_a?(Array) + # Numbers in Puppet are often string-encoded which is troublesome ... + value.map { |i| i.is_a?(String) ? i.chop : i } + else + value.chop + end return result end diff --git a/lib/puppet/parser/functions/clamp.rb b/lib/puppet/parser/functions/clamp.rb index c4503fe5b..f5e33c621 100644 --- a/lib/puppet/parser/functions/clamp.rb +++ b/lib/puppet/parser/functions/clamp.rb @@ -1,12 +1,11 @@ # # clamp.rb # - module Puppet::Parser::Functions - newfunction(:clamp, :type => :rvalue, :arity => -2, :doc => <<-EOS + newfunction(:clamp, type: :rvalue, arity: -2, doc: <<-EOS Clamps value to a range. EOS - ) do |args| + ) do |args| args.flatten! @@ -15,15 +14,15 @@ module Puppet::Parser::Functions # check values out args.each do |value| case [value.class] - when [String] - raise(Puppet::ParseError, "clamp(): Required explicit numeric (#{value}:String)") unless value =~ /^\d+$/ - when [Hash] - raise(Puppet::ParseError, "clamp(): The Hash type is not allowed (#{value})") + when [String] + raise(Puppet::ParseError, "clamp(): Required explicit numeric (#{value}:String)") unless value =~ %r{^\d+$} + when [Hash] + raise(Puppet::ParseError, "clamp(): The Hash type is not allowed (#{value})") end end # convert to numeric each element # then sort them and get a middle value - args.map{ |n| n.to_i }.sort[1] + args.map { |n| n.to_i }.sort[1] end end diff --git a/lib/puppet/parser/functions/concat.rb b/lib/puppet/parser/functions/concat.rb index 0a49cfef7..401006999 100644 --- a/lib/puppet/parser/functions/concat.rb +++ b/lib/puppet/parser/functions/concat.rb @@ -1,20 +1,19 @@ # # concat.rb # - module Puppet::Parser::Functions - newfunction(:concat, :type => :rvalue, :doc => <<-EOS -Appends the contents of multiple arrays into array 1. + newfunction(:concat, type: :rvalue, doc: <<-EOS + Appends the contents of multiple arrays into array 1. -*Example:* + *Example:* - concat(['1','2','3'],['4','5','6'],['7','8','9']) + concat(['1','2','3'],['4','5','6'],['7','8','9']) -Would result in: + Would result in: - ['1','2','3','4','5','6','7','8','9'] - EOS - ) do |arguments| + ['1','2','3','4','5','6','7','8','9'] + EOS + ) do |arguments| # Check that more than 2 arguments have been given ... raise(Puppet::ParseError, "concat(): Wrong number of arguments given (#{arguments.size} for < 2)") if arguments.size < 2 @@ -30,7 +29,7 @@ module Puppet::Parser::Functions arguments.shift arguments.each do |x| - result = result + (x.is_a?(Array) ? x : [x]) + result += (x.is_a?(Array) ? x : [x]) end return result diff --git a/lib/puppet/parser/functions/convert_base.rb b/lib/puppet/parser/functions/convert_base.rb index 0fcbafeaf..b5b10d875 100644 --- a/lib/puppet/parser/functions/convert_base.rb +++ b/lib/puppet/parser/functions/convert_base.rb @@ -1,7 +1,8 @@ +# +# convert_base.rb +# module Puppet::Parser::Functions - - newfunction(:convert_base, :type => :rvalue, :arity => 2, :doc => <<-'ENDHEREDOC') do |args| - + newfunction(:convert_base, type: :rvalue, arity: 2, doc: <<-'ENDHEREDOC') do |args| Converts a given integer or base 10 string representing an integer to a specified base, as a string. Usage: @@ -11,24 +12,24 @@ module Puppet::Parser::Functions ENDHEREDOC - raise Puppet::ParseError, ("convert_base(): First argument must be either a string or an integer") unless (args[0].is_a?(Integer) or args[0].is_a?(String)) - raise Puppet::ParseError, ("convert_base(): Second argument must be either a string or an integer") unless (args[1].is_a?(Integer) or args[1].is_a?(String)) + raise Puppet::ParseError, 'convert_base(): First argument must be either a string or an integer' unless args[0].is_a?(Integer) || args[0].is_a?(String) + raise Puppet::ParseError, 'convert_base(): Second argument must be either a string or an integer' unless args[1].is_a?(Integer) || args[1].is_a?(String) if args[0].is_a?(String) - raise Puppet::ParseError, ("convert_base(): First argument must be an integer or a string corresponding to an integer in base 10") unless args[0] =~ /^[0-9]+$/ + raise Puppet::ParseError, 'convert_base(): First argument must be an integer or a string corresponding to an integer in base 10' unless args[0] =~ %r{^[0-9]+$} end if args[1].is_a?(String) - raise Puppet::ParseError, ("convert_base(): First argument must be an integer or a string corresponding to an integer in base 10") unless args[1] =~ /^[0-9]+$/ + raise Puppet::ParseError, 'convert_base(): First argument must be an integer or a string corresponding to an integer in base 10' unless args[1] =~ %r{^[0-9]+$} end number_to_convert = args[0] new_base = args[1] - number_to_convert = number_to_convert.to_i() - new_base = new_base.to_i() + number_to_convert = number_to_convert.to_i + new_base = new_base.to_i - raise Puppet::ParseError, ("convert_base(): base must be at least 2 and must not be greater than 36") unless new_base >= 2 and new_base <= 36 + raise Puppet::ParseError, 'convert_base(): base must be at least 2 and must not be greater than 36' unless new_base >= 2 && new_base <= 36 return number_to_convert.to_s(new_base) end diff --git a/lib/puppet/parser/functions/count.rb b/lib/puppet/parser/functions/count.rb index cef263735..1206ffee2 100644 --- a/lib/puppet/parser/functions/count.rb +++ b/lib/puppet/parser/functions/count.rb @@ -1,21 +1,24 @@ +# +# count.rb +# module Puppet::Parser::Functions - newfunction(:count, :type => :rvalue, :arity => -2, :doc => <<-EOS -Takes an array as first argument and an optional second argument. -Count the number of elements in array that matches second argument. -If called with only an array it counts the number of elements that are not nil/undef. - EOS - ) do |args| + newfunction(:count, type: :rvalue, arity: -2, doc: <<-EOS + Takes an array as first argument and an optional second argument. + Count the number of elements in array that matches second argument. + If called with only an array it counts the number of elements that are not nil/undef. + EOS + ) do |args| - if (args.size > 2) then + if args.size > 2 raise(ArgumentError, "count(): Wrong number of arguments given #{args.size} for 1 or 2.") end collection, item = args - if item then + if item collection.count item else - collection.count { |obj| obj != nil && obj != :undef && obj != '' } + collection.count { |obj| !obj.nil? && obj != :undef && obj != '' } end end end diff --git a/lib/puppet/parser/functions/deep_merge.rb b/lib/puppet/parser/functions/deep_merge.rb index 6df32e9c5..af982a20e 100644 --- a/lib/puppet/parser/functions/deep_merge.rb +++ b/lib/puppet/parser/functions/deep_merge.rb @@ -1,5 +1,8 @@ +# +# deep_merge.rb +# module Puppet::Parser::Functions - newfunction(:deep_merge, :type => :rvalue, :doc => <<-'ENDHEREDOC') do |args| + newfunction(:deep_merge, type: :rvalue, doc: <<-'ENDHEREDOC') do |args| Recursively merges two or more hashes together and returns the resulting hash. For example: @@ -16,11 +19,11 @@ module Puppet::Parser::Functions ENDHEREDOC if args.length < 2 - raise Puppet::ParseError, ("deep_merge(): wrong number of arguments (#{args.length}; must be at least 2)") + raise Puppet::ParseError, "deep_merge(): wrong number of arguments (#{args.length}; must be at least 2)" end - deep_merge = Proc.new do |hash1,hash2| - hash1.merge(hash2) do |key,old_value,new_value| + deep_merge = proc do |hash1, hash2| + hash1.merge(hash2) do |_key, old_value, new_value| if old_value.is_a?(Hash) && new_value.is_a?(Hash) deep_merge.call(old_value, new_value) else @@ -29,9 +32,9 @@ module Puppet::Parser::Functions end end - result = Hash.new + result = {} args.each do |arg| - next if arg.is_a? String and arg.empty? # empty string is synonym for puppet's undef + next if arg.is_a?(String) && arg.empty? # empty string is synonym for puppet's undef # If the argument was not a hash, skip it. unless arg.is_a?(Hash) raise Puppet::ParseError, "deep_merge: unexpected argument type #{arg.class}, only expects hash arguments" @@ -39,6 +42,6 @@ module Puppet::Parser::Functions result = deep_merge.call(result, arg) end - return( result ) + return(result) end end diff --git a/lib/puppet/parser/functions/defined_with_params.rb b/lib/puppet/parser/functions/defined_with_params.rb index c45a9dfa8..430fcdb91 100644 --- a/lib/puppet/parser/functions/defined_with_params.rb +++ b/lib/puppet/parser/functions/defined_with_params.rb @@ -2,25 +2,25 @@ require 'puppet/parser/functions' Puppet::Parser::Functions.newfunction(:defined_with_params, - :type => :rvalue, - :doc => <<-'ENDOFDOC' -Takes a resource reference and an optional hash of attributes. + type: :rvalue, + doc: <<-'ENDOFDOC' + Takes a resource reference and an optional hash of attributes. -Returns true if a resource with the specified attributes has already been added -to the catalog, and false otherwise. + Returns true if a resource with the specified attributes has already been added + to the catalog, and false otherwise. - user { 'dan': - ensure => present, - } + user { 'dan': + ensure => present, + } - if ! defined_with_params(User[dan], {'ensure' => 'present' }) { - user { 'dan': ensure => present, } - } + if ! defined_with_params(User[dan], {'ensure' => 'present' }) { + user { 'dan': ensure => present, } + } ENDOFDOC -) do |vals| + ) do |vals| reference, params = vals raise(ArgumentError, 'Must specify a reference') unless reference - if (! params) || params == '' + if !params || params == '' params = {} end ret = false @@ -36,14 +36,15 @@ else raise(ArgumentError, "Reference is not understood: '#{reference.class}'") end - #end workaround + # end workaround else type = reference.to_s title = nil end - if resource = findresource(type, title) - matches = params.collect do |key, value| + resource = findresource(type, title) + if resource + matches = params.map do |key, value| # eql? avoids bugs caused by monkeypatching in puppet resource_is_undef = resource[key].eql?(:undef) || resource[key].nil? value_is_undef = value.eql?(:undef) || value.nil? diff --git a/lib/puppet/parser/functions/delete.rb b/lib/puppet/parser/functions/delete.rb index 9dd5164de..ee7885a24 100644 --- a/lib/puppet/parser/functions/delete.rb +++ b/lib/puppet/parser/functions/delete.rb @@ -1,39 +1,38 @@ # # delete.rb # - module Puppet::Parser::Functions - newfunction(:delete, :type => :rvalue, :doc => <<-EOS -Deletes all instances of a given element from an array, substring from a -string, or key from a hash. + newfunction(:delete, type: :rvalue, doc: <<-EOS + Deletes all instances of a given element from an array, substring from a + string, or key from a hash. -*Examples:* + *Examples:* - delete(['a','b','c','b'], 'b') - Would return: ['a','c'] + delete(['a','b','c','b'], 'b') + Would return: ['a','c'] - delete({'a'=>1,'b'=>2,'c'=>3}, 'b') - Would return: {'a'=>1,'c'=>3} + delete({'a'=>1,'b'=>2,'c'=>3}, 'b') + Would return: {'a'=>1,'c'=>3} - delete({'a'=>1,'b'=>2,'c'=>3}, ['b','c']) - Would return: {'a'=>1} + delete({'a'=>1,'b'=>2,'c'=>3}, ['b','c']) + Would return: {'a'=>1} - delete('abracadabra', 'bra') - Would return: 'acada' + delete('abracadabra', 'bra') + Would return: 'acada' EOS - ) do |arguments| + ) do |arguments| raise(Puppet::ParseError, "delete(): Wrong number of arguments given #{arguments.size} for 2") unless arguments.size == 2 collection = arguments[0].dup Array(arguments[1]).each do |item| case collection - when Array, Hash - collection.delete item - when String - collection.gsub! item, '' - else - raise(TypeError, "delete(): First argument must be an Array, String, or Hash. Given an argument of class #{collection.class}.") + when Array, Hash + collection.delete item + when String + collection.gsub! item, '' + else + raise(TypeError, "delete(): First argument must be an Array, String, or Hash. Given an argument of class #{collection.class}.") end end collection diff --git a/lib/puppet/parser/functions/delete_at.rb b/lib/puppet/parser/functions/delete_at.rb index daf37212e..871c3512c 100644 --- a/lib/puppet/parser/functions/delete_at.rb +++ b/lib/puppet/parser/functions/delete_at.rb @@ -1,18 +1,17 @@ # # delete_at.rb # - module Puppet::Parser::Functions - newfunction(:delete_at, :type => :rvalue, :doc => <<-EOS -Deletes a determined indexed value from an array. + newfunction(:delete_at, type: :rvalue, doc: <<-EOS + Deletes a determined indexed value from an array. -*Examples:* + *Examples:* - delete_at(['a','b','c'], 1) + delete_at(['a','b','c'], 1) -Would return: ['a','c'] - EOS - ) do |arguments| + Would return: ['a','c'] + EOS + ) do |arguments| raise(Puppet::ParseError, "delete_at(): Wrong number of arguments given (#{arguments.size} for 2)") if arguments.size < 2 @@ -24,7 +23,7 @@ module Puppet::Parser::Functions index = arguments[1] - if index.is_a?(String) and not index.match(/^\d+$/) + if index.is_a?(String) && !index.match(%r{^\d+$}) raise(Puppet::ParseError, 'delete_at(): You must provide non-negative numeric index') end diff --git a/lib/puppet/parser/functions/delete_regex.rb b/lib/puppet/parser/functions/delete_regex.rb index e5dc1fdcd..76fca4d20 100644 --- a/lib/puppet/parser/functions/delete_regex.rb +++ b/lib/puppet/parser/functions/delete_regex.rb @@ -2,39 +2,38 @@ # delete_regex.rb # Please note: This function is an implementation of a Ruby class and as such may not be entirely UTF8 compatible. To ensure compatibility please use this function with Ruby 2.4.0 or greater - https://bugs.ruby-lang.org/issues/10085. # - module Puppet::Parser::Functions - newfunction(:delete_regex, :type => :rvalue, :doc => <<-EOS -deletes all instances of a given element that match a regular expression -from an array or key from a hash. Multiple regular expressions are assumed -to be matched as an OR. + newfunction(:delete_regex, type: :rvalue, doc: <<-EOS + deletes all instances of a given element that match a regular expression + from an array or key from a hash. Multiple regular expressions are assumed + to be matched as an OR. -*Examples:* + *Examples:* - delete_regex(['a','b','c','b'], 'b') - Would return: ['a','c'] + delete_regex(['a','b','c','b'], 'b') + Would return: ['a','c'] - delete_regex(['a','b','c','b'], ['b', 'c']) - Would return: ['a'] + delete_regex(['a','b','c','b'], ['b', 'c']) + Would return: ['a'] - delete_regex({'a'=>1,'b'=>2,'c'=>3}, 'b') - Would return: {'a'=>1,'c'=>3} + delete_regex({'a'=>1,'b'=>2,'c'=>3}, 'b') + Would return: {'a'=>1,'c'=>3} - delete_regex({'a'=>1,'b'=>2,'c'=>3}, '^a$') - Would return: {'b'=>2,'c'=>3} + delete_regex({'a'=>1,'b'=>2,'c'=>3}, '^a$') + Would return: {'b'=>2,'c'=>3} EOS - ) do |arguments| + ) do |arguments| raise(Puppet::ParseError, "delete_regex(): Wrong number of arguments given #{arguments.size} for 2") unless arguments.size == 2 collection = arguments[0].dup Array(arguments[1]).each do |item| case collection - when Array, Hash, String - collection.reject! { |coll_item| (coll_item =~ %r{\b#{item}\b}) } - else - raise(TypeError, "delete_regex(): First argument must be an Array, Hash, or String. Given an argument of class #{collection.class}.") + when Array, Hash, String + collection.reject! { |coll_item| (coll_item =~ %r{\b#{item}\b}) } + else + raise(TypeError, "delete_regex(): First argument must be an Array, Hash, or String. Given an argument of class #{collection.class}.") end end collection diff --git a/lib/puppet/parser/functions/delete_undef_values.rb b/lib/puppet/parser/functions/delete_undef_values.rb index 00bd25213..b43601be7 100644 --- a/lib/puppet/parser/functions/delete_undef_values.rb +++ b/lib/puppet/parser/functions/delete_undef_values.rb @@ -1,28 +1,31 @@ +# +# delete_undef_values.rb +# module Puppet::Parser::Functions - newfunction(:delete_undef_values, :type => :rvalue, :doc => <<-EOS -Returns a copy of input hash or array with all undefs deleted. + newfunction(:delete_undef_values, type: :rvalue, doc: <<-EOS + Returns a copy of input hash or array with all undefs deleted. -*Examples:* + *Examples:* - $hash = delete_undef_values({a=>'A', b=>'', c=>undef, d => false}) + $hash = delete_undef_values({a=>'A', b=>'', c=>undef, d => false}) -Would return: {a => 'A', b => '', d => false} + Would return: {a => 'A', b => '', d => false} - $array = delete_undef_values(['A','',undef,false]) + $array = delete_undef_values(['A','',undef,false]) -Would return: ['A','',false] + Would return: ['A','',false] EOS - ) do |args| + ) do |args| - raise(Puppet::ParseError, "delete_undef_values(): Wrong number of arguments given (#{args.size})") if args.size < 1 + raise(Puppet::ParseError, "delete_undef_values(): Wrong number of arguments given (#{args.size})") if args.empty? - unless args[0].is_a? Array or args[0].is_a? Hash + unless args[0].is_a?(Array) || args[0].is_a?(Hash) raise(Puppet::ParseError, "delete_undef_values(): expected an array or hash, got #{args[0]} type #{args[0].class} ") end result = args[0].dup if result.is_a?(Hash) - result.delete_if {|key, val| val.equal? :undef} + result.delete_if { |_key, val| val.equal? :undef } elsif result.is_a?(Array) result.delete :undef end diff --git a/lib/puppet/parser/functions/delete_values.rb b/lib/puppet/parser/functions/delete_values.rb index e799aef0e..dcb608b9b 100644 --- a/lib/puppet/parser/functions/delete_values.rb +++ b/lib/puppet/parser/functions/delete_values.rb @@ -1,23 +1,26 @@ +# +# delete_values.rb +# module Puppet::Parser::Functions - newfunction(:delete_values, :type => :rvalue, :doc => <<-EOS -Deletes all instances of a given value from a hash. + newfunction(:delete_values, type: :rvalue, doc: <<-EOS + Deletes all instances of a given value from a hash. -*Examples:* + *Examples:* - delete_values({'a'=>'A','b'=>'B','c'=>'C','B'=>'D'}, 'B') + delete_values({'a'=>'A','b'=>'B','c'=>'C','B'=>'D'}, 'B') -Would return: {'a'=>'A','c'=>'C','B'=>'D'} + Would return: {'a'=>'A','c'=>'C','B'=>'D'} EOS - ) do |arguments| + ) do |arguments| raise(Puppet::ParseError, "delete_values(): Wrong number of arguments given (#{arguments.size} of 2)") if arguments.size != 2 hash, item = arguments - if not hash.is_a?(Hash) + unless hash.is_a?(Hash) raise(TypeError, "delete_values(): First argument must be a Hash. Given an argument of class #{hash.class}.") end - hash.dup.delete_if { |key, val| item == val } + hash.dup.delete_if { |_key, val| item == val } end end diff --git a/lib/puppet/parser/functions/deprecation.rb b/lib/puppet/parser/functions/deprecation.rb index 39d306a0a..4b587904d 100644 --- a/lib/puppet/parser/functions/deprecation.rb +++ b/lib/puppet/parser/functions/deprecation.rb @@ -1,15 +1,18 @@ +# +# deprecation.rb +# module Puppet::Parser::Functions - newfunction(:deprecation, :doc => <<-EOS + newfunction(:deprecation, doc: <<-EOS Function to print deprecation warnings (this is the 3.X version of it), The uniqueness key - can appear once. The msg is the message text including any positional information that is formatted by the user/caller of the method.). EOS - ) do |arguments| + ) do |arguments| raise(Puppet::ParseError, "deprecation: Wrong number of arguments given (#{arguments.size} for 2)") unless arguments.size == 2 key = arguments[0] message = arguments[1] - if ENV['STDLIB_LOG_DEPRECATIONS'] == "true" + if ENV['STDLIB_LOG_DEPRECATIONS'] == 'true' warning("deprecation. #{key}. #{message}") end end diff --git a/lib/puppet/parser/functions/difference.rb b/lib/puppet/parser/functions/difference.rb index c9ac47873..01e7f832b 100644 --- a/lib/puppet/parser/functions/difference.rb +++ b/lib/puppet/parser/functions/difference.rb @@ -1,20 +1,19 @@ # # difference.rb # - module Puppet::Parser::Functions - newfunction(:difference, :type => :rvalue, :doc => <<-EOS -This function returns the difference between two arrays. -The returned array is a copy of the original array, removing any items that -also appear in the second array. + newfunction(:difference, type: :rvalue, doc: <<-EOS + This function returns the difference between two arrays. + The returned array is a copy of the original array, removing any items that + also appear in the second array. -*Examples:* + *Examples:* - difference(["a","b","c"],["b","c","d"]) + difference(["a","b","c"],["b","c","d"]) -Would return: ["a"] + Would return: ["a"] EOS - ) do |arguments| + ) do |arguments| # Two arguments are required raise(Puppet::ParseError, "difference(): Wrong number of arguments given (#{arguments.size} for 2)") if arguments.size != 2 diff --git a/lib/puppet/parser/functions/dig.rb b/lib/puppet/parser/functions/dig.rb index 34fa701c6..44002b106 100644 --- a/lib/puppet/parser/functions/dig.rb +++ b/lib/puppet/parser/functions/dig.rb @@ -1,14 +1,13 @@ # # dig.rb # - module Puppet::Parser::Functions - newfunction(:dig, :type => :rvalue, :doc => <<-EOS + newfunction(:dig, type: :rvalue, doc: <<-EOS DEPRECATED: This function has been replaced in Puppet 4.5.0, please use dig44() for backwards compatibility or use the new version. EOS - ) do |arguments| - warning("dig() DEPRECATED: This function has been replaced in Puppet 4.5.0, please use dig44() for backwards compatibility or use the new version.") - if ! Puppet::Parser::Functions.autoloader.loaded?(:dig44) + ) do |arguments| + warning('dig() DEPRECATED: This function has been replaced in Puppet 4.5.0, please use dig44() for backwards compatibility or use the new version.') + unless Puppet::Parser::Functions.autoloader.loaded?(:dig44) Puppet::Parser::Functions.autoloader.load(:dig44) end function_dig44(arguments) diff --git a/lib/puppet/parser/functions/dig44.rb b/lib/puppet/parser/functions/dig44.rb index 21c0a8ce2..0fe5f0295 100644 --- a/lib/puppet/parser/functions/dig44.rb +++ b/lib/puppet/parser/functions/dig44.rb @@ -1,44 +1,43 @@ # # dig44.rb # - module Puppet::Parser::Functions newfunction( - :dig44, - :type => :rvalue, - :arity => -2, - :doc => <<-eos -DEPRECATED: This function has been replaced in puppet 4.5.0. + :dig44, + type: :rvalue, + arity: -2, + doc: <<-eos + DEPRECATED: This function has been replaced in puppet 4.5.0. -Looks up into a complex structure of arrays and hashes and returns a value -or the default value if nothing was found. + Looks up into a complex structure of arrays and hashes and returns a value + or the default value if nothing was found. -Key can contain slashes to describe path components. The function will go down -the structure and try to extract the required value. + Key can contain slashes to describe path components. The function will go down + the structure and try to extract the required value. -$data = { - 'a' => { - 'b' => [ - 'b1', - 'b2', - 'b3', - ] - } -} + $data = { + 'a' => { + 'b' => [ + 'b1', + 'b2', + 'b3', + ] + } + } -$value = dig44($data, ['a', 'b', '2'], 'not_found') -=> $value = 'b3' + $value = dig44($data, ['a', 'b', '2'], 'not_found') + => $value = 'b3' -a -> first hash key -b -> second hash key -2 -> array index starting with 0 + a -> first hash key + b -> second hash key + 2 -> array index starting with 0 -not_found -> (optional) will be returned if there is no value or the path -did not match. Defaults to nil. + not_found -> (optional) will be returned if there is no value or the path + did not match. Defaults to nil. -In addition to the required "key" argument, the function accepts a default -argument. It will be returned if no value was found or a path component is -missing. And the fourth argument can set a variable path separator. + In addition to the required "key" argument, the function accepts a default + argument. It will be returned if no value was found or a path component is + missing. And the fourth argument can set a variable path separator. eos ) do |arguments| # Two arguments are required @@ -46,24 +45,20 @@ module Puppet::Parser::Functions data, path, default = *arguments - unless data.is_a?(Hash) or data.is_a?(Array) - raise(Puppet::ParseError, "dig44(): first argument must be a hash or an array, given #{data.class.name}") - end - - unless path.is_a? Array - raise(Puppet::ParseError, "dig44(): second argument must be an array, given #{path.class.name}") - end + raise(Puppet::ParseError, "dig44(): first argument must be a hash or an array, given #{data.class.name}") unless data.is_a?(Hash) || data.is_a?(Array) + raise(Puppet::ParseError, "dig44(): second argument must be an array, given #{path.class.name}") unless path.is_a? Array value = path.reduce(data) do |structure, key| - if structure.is_a? Hash or structure.is_a? Array - if structure.is_a? Array - key = Integer key rescue break + break unless structure.is_a?(Hash) || structure.is_a?(Array) + if structure.is_a? Array + begin + key = Integer key + rescue + break end - break if structure[key].nil? or structure[key] == :undef - structure[key] - else - break end + break if structure[key].nil? || structure[key] == :undef + structure[key] end value.nil? ? default : value end diff --git a/lib/puppet/parser/functions/dirname.rb b/lib/puppet/parser/functions/dirname.rb index 40b300d89..e02433e3d 100644 --- a/lib/puppet/parser/functions/dirname.rb +++ b/lib/puppet/parser/functions/dirname.rb @@ -1,13 +1,16 @@ +# +# dirname.rb +# module Puppet::Parser::Functions - newfunction(:dirname, :type => :rvalue, :doc => <<-EOS + newfunction(:dirname, type: :rvalue, doc: <<-EOS Returns the dirname of a path. EOS - ) do |arguments| + ) do |arguments| - if arguments.size < 1 then - raise(Puppet::ParseError, "dirname(): No arguments given") + if arguments.empty? + raise(Puppet::ParseError, 'dirname(): No arguments given') end - if arguments.size > 1 then + if arguments.size > 1 raise(Puppet::ParseError, "dirname(): Too many arguments given (#{arguments.size})") end unless arguments[0].is_a?(String) diff --git a/lib/puppet/parser/functions/dos2unix.rb b/lib/puppet/parser/functions/dos2unix.rb index ccac89933..33df5e592 100644 --- a/lib/puppet/parser/functions/dos2unix.rb +++ b/lib/puppet/parser/functions/dos2unix.rb @@ -1,15 +1,15 @@ # Custom Puppet function to convert dos to unix format module Puppet::Parser::Functions - newfunction(:dos2unix, :type => :rvalue, :arity => 1, :doc => <<-EOS + newfunction(:dos2unix, type: :rvalue, arity: 1, doc: <<-EOS Returns the Unix version of the given string. Takes a single string argument. EOS - ) do |arguments| + ) do |arguments| unless arguments[0].is_a?(String) raise(Puppet::ParseError, 'dos2unix(): Requires string as argument') end - arguments[0].gsub(/\r\n/, "\n") + arguments[0].gsub(%r{\r\n}, "\n") end end diff --git a/lib/puppet/parser/functions/downcase.rb b/lib/puppet/parser/functions/downcase.rb index ab04f8a21..e56df7501 100644 --- a/lib/puppet/parser/functions/downcase.rb +++ b/lib/puppet/parser/functions/downcase.rb @@ -2,14 +2,13 @@ # downcase.rb # Please note: This function is an implementation of a Ruby class and as such may not be entirely UTF8 compatible. To ensure compatibility please use this function with Ruby 2.4.0 or greater - https://bugs.ruby-lang.org/issues/10085. # - module Puppet::Parser::Functions - newfunction(:downcase, :type => :rvalue, :doc => <<-EOS -Converts the case of a string or all strings in an array to lower case. - EOS - ) do |arguments| + newfunction(:downcase, type: :rvalue, doc: <<-EOS + Converts the case of a string or all strings in an array to lower case. + EOS + ) do |arguments| - raise(Puppet::ParseError, "downcase(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size < 1 + raise(Puppet::ParseError, "downcase(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? value = arguments[0] @@ -17,12 +16,12 @@ module Puppet::Parser::Functions raise(Puppet::ParseError, 'downcase(): Requires either array or string to work with') end - if value.is_a?(Array) - # Numbers in Puppet are often string-encoded which is troublesome ... - result = value.collect { |i| i.is_a?(String) ? i.downcase : i } - else - result = value.downcase - end + result = if value.is_a?(Array) + # Numbers in Puppet are often string-encoded which is troublesome ... + value.map { |i| i.is_a?(String) ? i.downcase : i } + else + value.downcase + end return result end diff --git a/lib/puppet/parser/functions/empty.rb b/lib/puppet/parser/functions/empty.rb index 4f77ad300..f4c4af2f4 100644 --- a/lib/puppet/parser/functions/empty.rb +++ b/lib/puppet/parser/functions/empty.rb @@ -1,28 +1,22 @@ # # empty.rb # - module Puppet::Parser::Functions - newfunction(:empty, :type => :rvalue, :doc => <<-EOS -Returns true if the variable is empty. - EOS - ) do |arguments| - - raise(Puppet::ParseError, "empty(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size < 1 + newfunction(:empty, type: :rvalue, doc: <<-EOS + Returns true if the variable is empty. + EOS + ) do |arguments| + raise(Puppet::ParseError, "empty(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? value = arguments[0] unless value.is_a?(Array) || value.is_a?(Hash) || value.is_a?(String) || value.is_a?(Numeric) raise(Puppet::ParseError, 'empty(): Requires either array, hash, string or integer to work with') end - if value.is_a?(Numeric) - return false - else - result = value.empty? - - return result - end + return false if value.is_a?(Numeric) + result = value.empty? + return result end end diff --git a/lib/puppet/parser/functions/enclose_ipv6.rb b/lib/puppet/parser/functions/enclose_ipv6.rb index 1f8a45493..3b288d375 100644 --- a/lib/puppet/parser/functions/enclose_ipv6.rb +++ b/lib/puppet/parser/functions/enclose_ipv6.rb @@ -1,24 +1,23 @@ # # enclose_ipv6.rb # - module Puppet::Parser::Functions - newfunction(:enclose_ipv6, :type => :rvalue, :doc => <<-EOS -Takes an array of ip addresses and encloses the ipv6 addresses with square brackets. - EOS - ) do |arguments| + newfunction(:enclose_ipv6, type: :rvalue, doc: <<-EOS + Takes an array of ip addresses and encloses the ipv6 addresses with square brackets. + EOS + ) do |arguments| require 'ipaddr' - rescuable_exceptions = [ ArgumentError ] + rescuable_exceptions = [ArgumentError] if defined?(IPAddr::InvalidAddressError) - rescuable_exceptions << IPAddr::InvalidAddressError + rescuable_exceptions << IPAddr::InvalidAddressError end - if (arguments.size != 1) then + if arguments.size != 1 raise(Puppet::ParseError, "enclose_ipv6(): Wrong number of arguments given #{arguments.size} for 1") end - unless arguments[0].is_a?(String) or arguments[0].is_a?(Array) then + unless arguments[0].is_a?(String) || arguments[0].is_a?(Array) raise(Puppet::ParseError, "enclose_ipv6(): Wrong argument type given #{arguments[0].class} expected String or Array") end @@ -32,7 +31,7 @@ module Puppet::Parser::Functions rescue *rescuable_exceptions raise(Puppet::ParseError, "enclose_ipv6(): Wrong argument given #{val} is not an ip address.") end - val = "[#{ip.to_s}]" if ip.ipv6? + val = "[#{ip}]" if ip.ipv6? end result << val end diff --git a/lib/puppet/parser/functions/ensure_packages.rb b/lib/puppet/parser/functions/ensure_packages.rb index 1bf8bf18b..9fcf06b4d 100644 --- a/lib/puppet/parser/functions/ensure_packages.rb +++ b/lib/puppet/parser/functions/ensure_packages.rb @@ -1,20 +1,16 @@ # # ensure_packages.rb # - module Puppet::Parser::Functions - newfunction(:ensure_packages, :type => :statement, :doc => <<-EOS -Takes a list of packages and only installs them if they don't already exist. -It optionally takes a hash as a second parameter that will be passed as the -third argument to the ensure_resource() function. - EOS - ) do |arguments| + newfunction(:ensure_packages, type: :statement, doc: <<-EOS + Takes a list of packages and only installs them if they don't already exist. + It optionally takes a hash as a second parameter that will be passed as the + third argument to the ensure_resource() function. + EOS + ) do |arguments| - if arguments.size > 2 or arguments.size == 0 - raise(Puppet::ParseError, "ensure_packages(): Wrong number of arguments given (#{arguments.size} for 1 or 2)") - elsif arguments.size == 2 and !arguments[1].is_a?(Hash) - raise(Puppet::ParseError, 'ensure_packages(): Requires second argument to be a Hash') - end + raise(Puppet::ParseError, "ensure_packages(): Wrong number of arguments given (#{arguments.size} for 1 or 2)") if arguments.size > 2 || arguments.empty? + raise(Puppet::ParseError, 'ensure_packages(): Requires second argument to be a Hash') if arguments.size == 2 && !arguments[1].is_a?(Hash) if arguments[0].is_a?(Hash) if arguments[1] @@ -27,7 +23,7 @@ module Puppet::Parser::Functions end Puppet::Parser::Functions.function(:ensure_resources) - function_ensure_resources(['package', arguments[0].dup, defaults ]) + function_ensure_resources(['package', arguments[0].dup, defaults]) else packages = Array(arguments[0]) @@ -41,12 +37,12 @@ module Puppet::Parser::Functions end Puppet::Parser::Functions.function(:ensure_resource) - packages.each { |package_name| - raise(Puppet::ParseError, 'ensure_packages(): Empty String provided for package name') if package_name.length == 0 - if !findresource("Package[#{package_name}]") - function_ensure_resource(['package', package_name, defaults ]) + packages.each do |package_name| + raise(Puppet::ParseError, 'ensure_packages(): Empty String provided for package name') if package_name.empty? + unless findresource("Package[#{package_name}]") + function_ensure_resource(['package', package_name, defaults]) + end end - } end end end diff --git a/lib/puppet/parser/functions/ensure_resource.rb b/lib/puppet/parser/functions/ensure_resource.rb index 1ba6a4478..8d9902aec 100644 --- a/lib/puppet/parser/functions/ensure_resource.rb +++ b/lib/puppet/parser/functions/ensure_resource.rb @@ -2,30 +2,30 @@ require 'puppet/parser/functions' Puppet::Parser::Functions.newfunction(:ensure_resource, - :type => :statement, - :doc => <<-'ENDOFDOC' -Takes a resource type, title, and a list of attributes that describe a -resource. + type: :statement, + doc: <<-'ENDOFDOC' + Takes a resource type, title, and a list of attributes that describe a + resource. - user { 'dan': - ensure => present, - } + user { 'dan': + ensure => present, + } -This example only creates the resource if it does not already exist: + This example only creates the resource if it does not already exist: - ensure_resource('user', 'dan', {'ensure' => 'present' }) + ensure_resource('user', 'dan', {'ensure' => 'present' }) -If the resource already exists but does not match the specified parameters, -this function will attempt to recreate the resource leading to a duplicate -resource definition error. + If the resource already exists but does not match the specified parameters, + this function will attempt to recreate the resource leading to a duplicate + resource definition error. -An array of resources can also be passed in and each will be created with -the type and parameters specified if it doesn't already exist. + An array of resources can also be passed in and each will be created with + the type and parameters specified if it doesn't already exist. - ensure_resource('user', ['dan','alex'], {'ensure' => 'present'}) + ensure_resource('user', ['dan','alex'], {'ensure' => 'present'}) ENDOFDOC -) do |vals| + ) do |vals| type, title, params = vals raise(ArgumentError, 'Must specify a type') unless type raise(ArgumentError, 'Must specify a title') unless title diff --git a/lib/puppet/parser/functions/ensure_resources.rb b/lib/puppet/parser/functions/ensure_resources.rb index b3c51e650..f925f8162 100644 --- a/lib/puppet/parser/functions/ensure_resources.rb +++ b/lib/puppet/parser/functions/ensure_resources.rb @@ -1,54 +1,50 @@ require 'puppet/parser/functions' Puppet::Parser::Functions.newfunction(:ensure_resources, - :type => :statement, - :doc => <<-'ENDOFDOC' -Takes a resource type, title (only hash), and a list of attributes that describe a -resource. + type: :statement, + doc: <<-'ENDOFDOC' + Takes a resource type, title (only hash), and a list of attributes that describe a + resource. - user { 'dan': - gid => 'mygroup', - ensure => present, - } + user { 'dan': + gid => 'mygroup', + ensure => present, + } -An hash of resources should be passed in and each will be created with -the type and parameters specified if it doesn't already exist. + An hash of resources should be passed in and each will be created with + the type and parameters specified if it doesn't already exist. - ensure_resources('user', {'dan' => { gid => 'mygroup', uid => '600' } , 'alex' => { gid => 'mygroup' }}, {'ensure' => 'present'}) + ensure_resources('user', {'dan' => { gid => 'mygroup', uid => '600' } , 'alex' => { gid => 'mygroup' }}, {'ensure' => 'present'}) -From Hiera Backend: + From Hiera Backend: -userlist: - dan: - gid: 'mygroup' - uid: '600' - alex: - gid: 'mygroup' - -Call: -ensure_resources('user', hiera_hash('userlist'), {'ensure' => 'present'}) + userlist: + dan: + gid: 'mygroup' + uid: '600' + alex: + gid: 'mygroup' + Call: + ensure_resources('user', hiera_hash('userlist'), {'ensure' => 'present'}) ENDOFDOC -) do |vals| + ) do |vals| type, title, params = vals raise(ArgumentError, 'Must specify a type') unless type raise(ArgumentError, 'Must specify a title') unless title params ||= {} - if title.is_a?(Hash) - resource_hash = title.dup - resources = resource_hash.keys - - Puppet::Parser::Functions.function(:ensure_resource) - resources.each { |resource_name| - if resource_hash[resource_name] - params_merged = params.merge(resource_hash[resource_name]) - else - params_merged = params - end - function_ensure_resource([ type, resource_name, params_merged ]) - } - else - raise(Puppet::ParseError, 'ensure_resources(): Requires second argument to be a Hash') + raise(Puppet::ParseError, 'ensure_resources(): Requires second argument to be a Hash') unless title.is_a?(Hash) + resource_hash = title.dup + resources = resource_hash.keys + + Puppet::Parser::Functions.function(:ensure_resource) + resources.each do |resource_name| + params_merged = if resource_hash[resource_name] + params.merge(resource_hash[resource_name]) + else + params + end + function_ensure_resource([type, resource_name, params_merged]) end end diff --git a/lib/puppet/parser/functions/flatten.rb b/lib/puppet/parser/functions/flatten.rb index 4401bdb35..694694465 100644 --- a/lib/puppet/parser/functions/flatten.rb +++ b/lib/puppet/parser/functions/flatten.rb @@ -1,19 +1,18 @@ # # flatten.rb # - module Puppet::Parser::Functions - newfunction(:flatten, :type => :rvalue, :doc => <<-EOS -This function flattens any deeply nested arrays and returns a single flat array -as a result. + newfunction(:flatten, type: :rvalue, doc: <<-EOS + This function flattens any deeply nested arrays and returns a single flat array + as a result. -*Examples:* + *Examples:* - flatten(['a', ['b', ['c']]]) + flatten(['a', ['b', ['c']]]) -Would return: ['a','b','c'] - EOS - ) do |arguments| + Would return: ['a','b','c'] + EOS + ) do |arguments| raise(Puppet::ParseError, "flatten(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size != 1 diff --git a/lib/puppet/parser/functions/floor.rb b/lib/puppet/parser/functions/floor.rb index 9e4b5044b..99836b4ab 100644 --- a/lib/puppet/parser/functions/floor.rb +++ b/lib/puppet/parser/functions/floor.rb @@ -1,15 +1,18 @@ +# +# floor.rb +# module Puppet::Parser::Functions - newfunction(:floor, :type => :rvalue, :doc => <<-EOS + newfunction(:floor, type: :rvalue, doc: <<-EOS Returns the largest integer less or equal to the argument. Takes a single numeric value as an argument. EOS - ) do |arguments| + ) do |arguments| raise(Puppet::ParseError, "floor(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size != 1 begin arg = Float(arguments[0]) - rescue TypeError, ArgumentError => e + rescue TypeError, ArgumentError => _e raise(Puppet::ParseError, "floor(): Wrong argument type given (#{arguments[0]} for Numeric)") end diff --git a/lib/puppet/parser/functions/fqdn_rand_string.rb b/lib/puppet/parser/functions/fqdn_rand_string.rb index 2bb1287e0..f404d69f0 100644 --- a/lib/puppet/parser/functions/fqdn_rand_string.rb +++ b/lib/puppet/parser/functions/fqdn_rand_string.rb @@ -1,8 +1,8 @@ -Puppet::Parser::Functions::newfunction( +Puppet::Parser::Functions.newfunction( :fqdn_rand_string, - :arity => -2, - :type => :rvalue, - :doc => "Usage: `fqdn_rand_string(LENGTH, [CHARSET], [SEED])`. LENGTH is + arity: -2, + type: :rvalue, + doc: "Usage: `fqdn_rand_string(LENGTH, [CHARSET], [SEED])`. LENGTH is required and must be a positive integer. CHARSET is optional and may be `undef` or a string. SEED is optional and may be any number or string. @@ -12,23 +12,24 @@ string from this function, but a given node's result will be the same every time unless its hostname changes.) Adding a SEED can be useful if you need more than one unrelated string. CHARSET will default to alphanumeric if - `undef` or an empty string.") do |args| - raise(ArgumentError, "fqdn_rand_string(): wrong number of arguments (0 for 1)") if args.size == 0 - Puppet::Parser::Functions.function('is_integer') - raise(ArgumentError, "fqdn_rand_string(): first argument must be a positive integer") unless function_is_integer([args[0]]) and args[0].to_i > 0 - raise(ArgumentError, "fqdn_rand_string(): second argument must be undef or a string") unless args[1].nil? or args[1].is_a? String + `undef` or an empty string.", +) do |args| + raise(ArgumentError, 'fqdn_rand_string(): wrong number of arguments (0 for 1)') if args.empty? + Puppet::Parser::Functions.function('is_integer') + raise(ArgumentError, 'fqdn_rand_string(): first argument must be a positive integer') unless function_is_integer([args[0]]) && args[0].to_i > 0 + raise(ArgumentError, 'fqdn_rand_string(): second argument must be undef or a string') unless args[1].nil? || args[1].is_a?(String) - Puppet::Parser::Functions.function('fqdn_rand') + Puppet::Parser::Functions.function('fqdn_rand') - length = args.shift.to_i - charset = args.shift.to_s.chars.to_a + length = args.shift.to_i + charset = args.shift.to_s.chars.to_a - charset = (0..9).map { |i| i.to_s } + ('A'..'Z').to_a + ('a'..'z').to_a if charset.empty? + charset = (0..9).map { |i| i.to_s } + ('A'..'Z').to_a + ('a'..'z').to_a if charset.empty? - rand_string = '' - for current in 1..length - rand_string << charset[function_fqdn_rand([charset.size, (args + [current.to_s]).join(':')]).to_i] - end + rand_string = '' + for current in 1..length # rubocop:disable Style/For : An each loop would not work correctly in this circumstance + rand_string << charset[function_fqdn_rand([charset.size, (args + [current.to_s]).join(':')]).to_i] + end - rand_string + rand_string end diff --git a/lib/puppet/parser/functions/fqdn_rotate.rb b/lib/puppet/parser/functions/fqdn_rotate.rb index 05bdcc74f..3c201fdbe 100644 --- a/lib/puppet/parser/functions/fqdn_rotate.rb +++ b/lib/puppet/parser/functions/fqdn_rotate.rb @@ -1,11 +1,10 @@ # # fqdn_rotate.rb # - Puppet::Parser::Functions.newfunction( :fqdn_rotate, - :type => :rvalue, - :doc => "Usage: `fqdn_rotate(VALUE, [SEED])`. VALUE is required and + type: :rvalue, + doc: "Usage: `fqdn_rotate(VALUE, [SEED])`. VALUE is required and must be an array or a string. SEED is optional and may be any number or string. @@ -13,49 +12,48 @@ the value of SEED for repeatable randomness. (That is, each node will get a different random rotation from this function, but a given node's result will be the same every time unless its hostname changes.) Adding - a SEED can be useful if you need more than one unrelated rotation.") do |args| + a SEED can be useful if you need more than one unrelated rotation.", +) do |args| + + raise(Puppet::ParseError, "fqdn_rotate(): Wrong number of arguments given (#{args.size} for 1)") if args.empty? - raise(Puppet::ParseError, "fqdn_rotate(): Wrong number of arguments given (#{args.size} for 1)") if args.size < 1 + value = args.shift + require 'digest/md5' - value = args.shift - require 'digest/md5' + unless value.is_a?(Array) || value.is_a?(String) + raise(Puppet::ParseError, 'fqdn_rotate(): Requires either array or string to work with') + end - unless value.is_a?(Array) || value.is_a?(String) - raise(Puppet::ParseError, 'fqdn_rotate(): Requires either array or string to work with') - end + result = value.clone - result = value.clone + string = value.is_a?(String) ? true : false - string = value.is_a?(String) ? true : false + # Check whether it makes sense to rotate ... + return result if result.size <= 1 - # Check whether it makes sense to rotate ... - return result if result.size <= 1 + # We turn any string value into an array to be able to rotate ... + result = string ? result.split('') : result - # We turn any string value into an array to be able to rotate ... - result = string ? result.split('') : result + elements = result.size - elements = result.size + seed = Digest::MD5.hexdigest([lookupvar('::fqdn'), args].join(':')).hex + # deterministic_rand() was added in Puppet 3.2.0; reimplement if necessary + if Puppet::Util.respond_to?(:deterministic_rand) + offset = Puppet::Util.deterministic_rand(seed, elements).to_i + else + return offset = Random.new(seed).rand(elements) if defined?(Random) == 'constant' && Random.class == Class - seed = Digest::MD5.hexdigest([lookupvar('::fqdn'),args].join(':')).hex - # deterministic_rand() was added in Puppet 3.2.0; reimplement if necessary - if Puppet::Util.respond_to?(:deterministic_rand) - offset = Puppet::Util.deterministic_rand(seed, elements).to_i - else - if defined?(Random) == 'constant' && Random.class == Class - offset = Random.new(seed).rand(elements) - else - old_seed = srand(seed) - offset = rand(elements) - srand(old_seed) - end - end - offset.times { - result.push result.shift - } + old_seed = srand(seed) + offset = rand(elements) + srand(old_seed) + end + offset.times do + result.push result.shift + end - result = string ? result.join : result + result = string ? result.join : result - return result + return result end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/fqdn_uuid.rb b/lib/puppet/parser/functions/fqdn_uuid.rb index 30205d0c8..c40112250 100644 --- a/lib/puppet/parser/functions/fqdn_uuid.rb +++ b/lib/puppet/parser/functions/fqdn_uuid.rb @@ -1,8 +1,9 @@ require 'digest/sha1' - +# +# fqdn_uuid.rb +# module Puppet::Parser::Functions - newfunction(:fqdn_uuid, :type => :rvalue, :doc => <<-END) do |args| - + newfunction(:fqdn_uuid, type: :rvalue, doc: <<-END) do |args| Creates a UUID based on a given string, assumed to be the FQDN For example, to generate a UUID based on the FQDN of a system: @@ -32,16 +33,11 @@ module Puppet::Parser::Functions is in fact a correct fully-qualified domain name. Therefore any arbitrary string and/or alpha-numeric value can subside for a domain name. EOS + END - END - - if args.length == 0 - raise(ArgumentError, "fqdn_uuid: No arguments given") - elsif args.length == 1 - fqdn = args[0] - else - raise(ArgumentError, "fqdn_uuid: Too many arguments given (#{args.length})") - end + raise(ArgumentError, 'fqdn_uuid: No arguments given') if args.empty? + raise(ArgumentError, "fqdn_uuid: Too many arguments given (#{args.length})") unless args.length == 1 + fqdn = args[0] # Code lovingly taken from # https://github.com/puppetlabs/marionette-collective/blob/master/lib/mcollective/ssl.rb @@ -51,22 +47,21 @@ module Puppet::Parser::Functions # 6ba7b810-9dad-11d1-80b4-00c04fd430c8 # uuid_name_space_dns = [0x6b, - 0xa7, - 0xb8, - 0x10, - 0x9d, - 0xad, - 0x11, - 0xd1, - 0x80, - 0xb4, - 0x00, - 0xc0, - 0x4f, - 0xd4, - 0x30, - 0xc8 - ].map {|b| b.chr}.join + 0xa7, + 0xb8, + 0x10, + 0x9d, + 0xad, + 0x11, + 0xd1, + 0x80, + 0xb4, + 0x00, + 0xc0, + 0x4f, + 0xd4, + 0x30, + 0xc8].map { |b| b.chr }.join sha1 = Digest::SHA1.new sha1.update(uuid_name_space_dns) @@ -83,7 +78,7 @@ module Puppet::Parser::Functions bytes[8] &= 0x3f bytes[8] |= 0x80 - bytes = [4, 2, 2, 2, 6].collect do |i| + bytes = [4, 2, 2, 2, 6].map do |i| bytes.slice!(0, i).pack('C*').unpack('H*') end diff --git a/lib/puppet/parser/functions/get_module_path.rb b/lib/puppet/parser/functions/get_module_path.rb index 1421b91f5..215d97886 100644 --- a/lib/puppet/parser/functions/get_module_path.rb +++ b/lib/puppet/parser/functions/get_module_path.rb @@ -1,17 +1,18 @@ +# +# get_module_path.rb +# module Puppet::Parser::Functions - newfunction(:get_module_path, :type =>:rvalue, :doc => <<-EOT + newfunction(:get_module_path, type: :rvalue, doc: <<-EOT Returns the absolute path of the specified module for the current environment. Example: $module_path = get_module_path('stdlib') EOT - ) do |args| - raise(Puppet::ParseError, "get_module_path(): Wrong number of arguments, expects one") unless args.size == 1 - if module_path = Puppet::Module.find(args[0], compiler.environment.to_s) - module_path.path - else - raise(Puppet::ParseError, "Could not find module #{args[0]} in environment #{compiler.environment}") - end + ) do |args| + raise(Puppet::ParseError, 'get_module_path(): Wrong number of arguments, expects one') unless args.size == 1 + module_path = Puppet::Module.find(args[0], compiler.environment.to_s) + raise(Puppet::ParseError, "Could not find module #{args[0]} in environment #{compiler.environment}") unless module_path + module_path.path end end diff --git a/lib/puppet/parser/functions/getparam.rb b/lib/puppet/parser/functions/getparam.rb index 0a5cbe0f7..0431b88dc 100644 --- a/lib/puppet/parser/functions/getparam.rb +++ b/lib/puppet/parser/functions/getparam.rb @@ -2,32 +2,33 @@ require 'puppet/parser/functions' Puppet::Parser::Functions.newfunction(:getparam, - :type => :rvalue, - :doc => <<-'ENDOFDOC' -Takes a resource reference and name of the parameter and -returns value of resource's parameter. + type: :rvalue, + doc: <<-'ENDOFDOC' + Takes a resource reference and name of the parameter and + returns value of resource's parameter. -*Examples:* + *Examples:* - define example_resource($param) { - } + define example_resource($param) { + } - example_resource { "example_resource_instance": - param => "param_value" - } + example_resource { "example_resource_instance": + param => "param_value" + } - getparam(Example_resource["example_resource_instance"], "param") + getparam(Example_resource["example_resource_instance"], "param") -Would return: param_value -ENDOFDOC -) do |vals| + Would return: param_value + ENDOFDOC + ) do |vals| reference, param = vals raise(ArgumentError, 'Must specify a reference') unless reference - raise(ArgumentError, 'Must specify name of a parameter') unless param and param.instance_of? String + raise(ArgumentError, 'Must specify name of a parameter') unless param && param.instance_of?(String) return '' if param.empty? - if resource = findresource(reference.to_s) + resource = findresource(reference.to_s) + if resource return resource[param] unless resource[param].nil? end diff --git a/lib/puppet/parser/functions/getvar.rb b/lib/puppet/parser/functions/getvar.rb index 3af8d4810..935ca8d6c 100644 --- a/lib/puppet/parser/functions/getvar.rb +++ b/lib/puppet/parser/functions/getvar.rb @@ -1,6 +1,8 @@ +# +# getvar.rb +# module Puppet::Parser::Functions - - newfunction(:getvar, :type => :rvalue, :doc => <<-'ENDHEREDOC') do |args| + newfunction(:getvar, type: :rvalue, doc: <<-'ENDHEREDOC') do |args| Lookup a variable in a remote namespace. For example: @@ -16,20 +18,18 @@ module Puppet::Parser::Functions ENDHEREDOC unless args.length == 1 - raise Puppet::ParseError, ("getvar(): wrong number of arguments (#{args.length}; must be 1)") + raise Puppet::ParseError, "getvar(): wrong number of arguments (#{args.length}; must be 1)" end begin result = nil catch(:undefined_variable) do - result = self.lookupvar("#{args[0]}") + result = lookupvar((args[0]).to_s) end # avoid relying on incosistent behaviour around ruby return values from catch result - rescue Puppet::ParseError # Eat the exception if strict_variables = true is set + rescue Puppet::ParseError # rubocop:disable Lint/HandleExceptions : Eat the exception if strict_variables = true is set end - end - end diff --git a/lib/puppet/parser/functions/glob.rb b/lib/puppet/parser/functions/glob.rb index 54cdda61d..dd803a995 100644 --- a/lib/puppet/parser/functions/glob.rb +++ b/lib/puppet/parser/functions/glob.rb @@ -1,21 +1,24 @@ # # glob.rb # - module Puppet::Parser::Functions - newfunction(:glob, :type => :rvalue, :doc => <<-'EOS' + newfunction(:glob, type: :rvalue, doc: <<-'EOS' Returns an Array of file entries of a directory or an Array of directories. Uses same patterns as Dir#glob EOS - ) do |arguments| + ) do |arguments| - raise(Puppet::ParseError, "glob(): Wrong number of arguments given " + - "(#{arguments.size} for 1)") unless arguments.size == 1 + unless arguments.size == 1 + raise(Puppet::ParseError, 'glob(): Wrong number of arguments given ' \ + "(#{arguments.size} for 1)") + end pattern = arguments[0] - raise(Puppet::ParseError, 'glob(): Requires either array or string ' + - 'to work') unless pattern.is_a?(String) || pattern.is_a?(Array) + unless pattern.is_a?(String) || pattern.is_a?(Array) + raise(Puppet::ParseError, 'glob(): Requires either array or string ' \ + 'to work') + end Dir.glob(pattern) end diff --git a/lib/puppet/parser/functions/grep.rb b/lib/puppet/parser/functions/grep.rb index c611a7e02..3aec06ec6 100644 --- a/lib/puppet/parser/functions/grep.rb +++ b/lib/puppet/parser/functions/grep.rb @@ -1,23 +1,22 @@ # # grep.rb # - module Puppet::Parser::Functions - newfunction(:grep, :type => :rvalue, :doc => <<-EOS -This function searches through an array and returns any elements that match -the provided regular expression. + newfunction(:grep, type: :rvalue, doc: <<-EOS + This function searches through an array and returns any elements that match + the provided regular expression. -*Examples:* + *Examples:* - grep(['aaa','bbb','ccc','aaaddd'], 'aaa') + grep(['aaa','bbb','ccc','aaaddd'], 'aaa') -Would return: + Would return: - ['aaa','aaaddd'] + ['aaa','aaaddd'] EOS - ) do |arguments| + ) do |arguments| - if (arguments.size != 2) then + if arguments.size != 2 raise(Puppet::ParseError, "grep(): Wrong number of arguments given #{arguments.size} for 2") end @@ -25,7 +24,6 @@ module Puppet::Parser::Functions pattern = Regexp.new(arguments[1]) a.grep(pattern) - end end diff --git a/lib/puppet/parser/functions/has_interface_with.rb b/lib/puppet/parser/functions/has_interface_with.rb index f6cb74b2b..aa3c3b0c7 100644 --- a/lib/puppet/parser/functions/has_interface_with.rb +++ b/lib/puppet/parser/functions/has_interface_with.rb @@ -1,30 +1,29 @@ # # has_interface_with # - module Puppet::Parser::Functions - newfunction(:has_interface_with, :type => :rvalue, :doc => <<-EOS -Returns boolean based on kind and value: - * macaddress - * netmask - * ipaddress - * network + newfunction(:has_interface_with, type: :rvalue, doc: <<-EOS + Returns boolean based on kind and value: + * macaddress + * netmask + * ipaddress + * network -has_interface_with("macaddress", "x:x:x:x:x:x") -has_interface_with("ipaddress", "127.0.0.1") => true -etc. + has_interface_with("macaddress", "x:x:x:x:x:x") + has_interface_with("ipaddress", "127.0.0.1") => true + etc. -If no "kind" is given, then the presence of the interface is checked: -has_interface_with("lo") => true + If no "kind" is given, then the presence of the interface is checked: + has_interface_with("lo") => true EOS - ) do |args| + ) do |args| - raise(Puppet::ParseError, "has_interface_with(): Wrong number of arguments given (#{args.size} for 1 or 2)") if args.size < 1 or args.size > 2 + raise(Puppet::ParseError, "has_interface_with(): Wrong number of arguments given (#{args.size} for 1 or 2)") if args.empty? || args.size > 2 interfaces = lookupvar('interfaces') # If we do not have any interfaces, then there are no requested attributes - return false if (interfaces == :undefined || interfaces.nil?) + return false if interfaces == :undefined || interfaces.nil? interfaces = interfaces.split(',') @@ -41,7 +40,7 @@ module Puppet::Parser::Functions catch :undefined_variable do factval = lookupvar(kind) end - rescue Puppet::ParseError # Eat the exception if strict_variables = true is set + rescue Puppet::ParseError # rubocop:disable Lint/HandleExceptions : Eat the exception if strict_variables = true is set end if factval == value return true @@ -57,7 +56,7 @@ module Puppet::Parser::Functions catch :undefined_variable do factval = lookupvar("#{kind}_#{iface}") end - rescue Puppet::ParseError # Eat the exception if strict_variables = true is set + rescue Puppet::ParseError # rubocop:disable Lint/HandleExceptions : Eat the exception if strict_variables = true is set end if value == factval result = true diff --git a/lib/puppet/parser/functions/has_ip_address.rb b/lib/puppet/parser/functions/has_ip_address.rb index a0071c8d2..ac069c821 100644 --- a/lib/puppet/parser/functions/has_ip_address.rb +++ b/lib/puppet/parser/functions/has_ip_address.rb @@ -1,15 +1,14 @@ # # has_ip_address # - module Puppet::Parser::Functions - newfunction(:has_ip_address, :type => :rvalue, :doc => <<-EOS -Returns true if the client has the requested IP address on some interface. + newfunction(:has_ip_address, type: :rvalue, doc: <<-EOS + Returns true if the client has the requested IP address on some interface. -This function iterates through the 'interfaces' fact and checks the -'ipaddress_IFACE' facts, performing a simple string comparison. + This function iterates through the 'interfaces' fact and checks the + 'ipaddress_IFACE' facts, performing a simple string comparison. EOS - ) do |args| + ) do |args| raise(Puppet::ParseError, "has_ip_address(): Wrong number of arguments given (#{args.size} for 1)") if args.size != 1 @@ -17,7 +16,6 @@ module Puppet::Parser::Functions unless Puppet::Parser::Functions.autoloader.loaded?(:has_interface_with) function_has_interface_with(['ipaddress', args[0]]) - end end diff --git a/lib/puppet/parser/functions/has_ip_network.rb b/lib/puppet/parser/functions/has_ip_network.rb index b02c0c027..f8e8e85fc 100644 --- a/lib/puppet/parser/functions/has_ip_network.rb +++ b/lib/puppet/parser/functions/has_ip_network.rb @@ -1,15 +1,14 @@ # # has_ip_network # - module Puppet::Parser::Functions - newfunction(:has_ip_network, :type => :rvalue, :doc => <<-EOS -Returns true if the client has an IP address within the requested network. + newfunction(:has_ip_network, type: :rvalue, doc: <<-EOS + Returns true if the client has an IP address within the requested network. -This function iterates through the 'interfaces' fact and checks the -'network_IFACE' facts, performing a simple string comparision. + This function iterates through the 'interfaces' fact and checks the + 'network_IFACE' facts, performing a simple string comparision. EOS - ) do |args| + ) do |args| raise(Puppet::ParseError, "has_ip_network(): Wrong number of arguments given (#{args.size} for 1)") if args.size != 1 @@ -17,7 +16,6 @@ module Puppet::Parser::Functions unless Puppet::Parser::Functions.autoloader.loaded?(:has_interface_with) function_has_interface_with(['network', args[0]]) - end end diff --git a/lib/puppet/parser/functions/has_key.rb b/lib/puppet/parser/functions/has_key.rb index 4657cc29c..b80923db0 100644 --- a/lib/puppet/parser/functions/has_key.rb +++ b/lib/puppet/parser/functions/has_key.rb @@ -1,6 +1,8 @@ +# +# has_key.rb +# module Puppet::Parser::Functions - - newfunction(:has_key, :type => :rvalue, :doc => <<-'ENDHEREDOC') do |args| + newfunction(:has_key, type: :rvalue, doc: <<-'ENDHEREDOC') do |args| Determine if a hash has a certain key value. Example: @@ -16,13 +18,11 @@ module Puppet::Parser::Functions ENDHEREDOC unless args.length == 2 - raise Puppet::ParseError, ("has_key(): wrong number of arguments (#{args.length}; must be 2)") + raise Puppet::ParseError, "has_key(): wrong number of arguments (#{args.length}; must be 2)" end unless args[0].is_a?(Hash) raise Puppet::ParseError, "has_key(): expects the first argument to be a hash, got #{args[0].inspect} which is of type #{args[0].class}" end - args[0].has_key?(args[1]) - + args[0].key?(args[1]) end - end diff --git a/lib/puppet/parser/functions/hash.rb b/lib/puppet/parser/functions/hash.rb index 22763f311..472afb6aa 100644 --- a/lib/puppet/parser/functions/hash.rb +++ b/lib/puppet/parser/functions/hash.rb @@ -1,20 +1,19 @@ # # hash.rb # - module Puppet::Parser::Functions - newfunction(:hash, :type => :rvalue, :doc => <<-EOS -This function converts an array into a hash. + newfunction(:hash, type: :rvalue, doc: <<-EOS + This function converts an array into a hash. -*Examples:* + *Examples:* - hash(['a',1,'b',2,'c',3]) + hash(['a',1,'b',2,'c',3]) -Would return: {'a'=>1,'b'=>2,'c'=>3} + Would return: {'a'=>1,'b'=>2,'c'=>3} EOS - ) do |arguments| + ) do |arguments| - raise(Puppet::ParseError, "hash(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size < 1 + raise(Puppet::ParseError, "hash(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? array = arguments[0] diff --git a/lib/puppet/parser/functions/intersection.rb b/lib/puppet/parser/functions/intersection.rb index 8a438f480..338daf8fb 100644 --- a/lib/puppet/parser/functions/intersection.rb +++ b/lib/puppet/parser/functions/intersection.rb @@ -1,18 +1,16 @@ # # intersection.rb # - module Puppet::Parser::Functions - newfunction(:intersection, :type => :rvalue, :doc => <<-EOS -This function returns an array of the intersection of two. - -*Examples:* + newfunction(:intersection, type: :rvalue, doc: <<-EOS + This function returns an array of the intersection of two. - intersection(["a","b","c"],["b","c","d"]) # returns ["b","c"] - intersection(["a","b","c"],[1,2,3,4]) # returns [] (true, when evaluated as a Boolean) + *Examples:* + intersection(["a","b","c"],["b","c","d"]) # returns ["b","c"] + intersection(["a","b","c"],[1,2,3,4]) # returns [] (true, when evaluated as a Boolean) EOS - ) do |arguments| + ) do |arguments| # Two arguments are required raise(Puppet::ParseError, "intersection(): Wrong number of arguments given (#{arguments.size} for 2)") if arguments.size != 2 diff --git a/lib/puppet/parser/functions/is_absolute_path.rb b/lib/puppet/parser/functions/is_absolute_path.rb index e64777f73..ebb913e4e 100644 --- a/lib/puppet/parser/functions/is_absolute_path.rb +++ b/lib/puppet/parser/functions/is_absolute_path.rb @@ -1,5 +1,8 @@ +# +# is_absolute_path.rb +# module Puppet::Parser::Functions - newfunction(:is_absolute_path, :type => :rvalue, :arity => 1, :doc => <<-'ENDHEREDOC') do |args| + newfunction(:is_absolute_path, type: :rvalue, arity: 1, doc: <<-'ENDHEREDOC') do |args| Returns boolean true if the string represents an absolute path in the filesystem. This function works for windows and unix style paths. @@ -23,15 +26,16 @@ module Puppet::Parser::Functions is_absolute_path($undefined) ENDHEREDOC - function_deprecation([:is_absolute_path, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Absolute_path. There is further documentation for validate_legacy function in the README.']) + function_deprecation([:is_absolute_path, 'This method is deprecated, please use the stdlib validate_legacy function, + with Stdlib::Compat::Absolute_path. There is further documentation for validate_legacy function in the README.']) require 'puppet/util' path = args[0] # This logic was borrowed from # [lib/puppet/file_serving/base.rb](https://github.com/puppetlabs/puppet/blob/master/lib/puppet/file_serving/base.rb) # Puppet 2.7 and beyond will have Puppet::Util.absolute_path? Fall back to a back-ported implementation otherwise. - if Puppet::Util.respond_to?(:absolute_path?) then - value = (Puppet::Util.absolute_path?(path, :posix) or Puppet::Util.absolute_path?(path, :windows)) + if Puppet::Util.respond_to?(:absolute_path?) + value = (Puppet::Util.absolute_path?(path, :posix) || Puppet::Util.absolute_path?(path, :windows)) else # This code back-ported from 2.7.x's lib/puppet/util.rb Puppet::Util.absolute_path? # Determine in a platform-specific way whether a path is absolute. This @@ -40,10 +44,10 @@ module Puppet::Parser::Functions slash = '[\\\\/]' name = '[^\\\\/]+' regexes = { - :windows => %r!^(([A-Z]:#{slash})|(#{slash}#{slash}#{name}#{slash}#{name})|(#{slash}#{slash}\?#{slash}#{name}))!i, - :posix => %r!^/! + windows: %r{^(([A-Z]:#{slash})|(#{slash}#{slash}#{name}#{slash}#{name})|(#{slash}#{slash}\?#{slash}#{name}))}i, + posix: %r{^/}, } - value = (!!(path =~ regexes[:posix])) || (!!(path =~ regexes[:windows])) + value = !!(path =~ regexes[:posix]) || !!(path =~ regexes[:windows]) # rubocop:disable Style/DoubleNegation : No alternative known end value end diff --git a/lib/puppet/parser/functions/is_array.rb b/lib/puppet/parser/functions/is_array.rb index a33afe41a..3a394382f 100644 --- a/lib/puppet/parser/functions/is_array.rb +++ b/lib/puppet/parser/functions/is_array.rb @@ -1,16 +1,16 @@ # # is_array.rb # - module Puppet::Parser::Functions - newfunction(:is_array, :type => :rvalue, :doc => <<-EOS -Returns true if the variable passed to this function is an array. + newfunction(:is_array, type: :rvalue, doc: <<-EOS + Returns true if the variable passed to this function is an array. EOS - ) do |arguments| + ) do |arguments| - function_deprecation([:is_array, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Array. There is further documentation for validate_legacy function in the README.']) + function_deprecation([:is_array, 'This method is deprecated, please use the stdlib validate_legacy function, + with Stdlib::Compat::Array. There is further documentation for validate_legacy function in the README.']) - raise(Puppet::ParseError, "is_array(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size < 1 + raise(Puppet::ParseError, "is_array(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? type = arguments[0] diff --git a/lib/puppet/parser/functions/is_bool.rb b/lib/puppet/parser/functions/is_bool.rb index 2ebe430cd..6897605d0 100644 --- a/lib/puppet/parser/functions/is_bool.rb +++ b/lib/puppet/parser/functions/is_bool.rb @@ -1,14 +1,14 @@ # # is_bool.rb # - module Puppet::Parser::Functions - newfunction(:is_bool, :type => :rvalue, :doc => <<-EOS -Returns true if the variable passed to this function is a boolean. + newfunction(:is_bool, type: :rvalue, doc: <<-EOS + Returns true if the variable passed to this function is a boolean. EOS - ) do |arguments| + ) do |arguments| - function_deprecation([:is_bool, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Bool. There is further documentation for validate_legacy function in the README.']) + function_deprecation([:is_bool, 'This method is deprecated, please use the stdlib validate_legacy function, + with Stdlib::Compat::Bool. There is further documentation for validate_legacy function in the README.']) raise(Puppet::ParseError, "is_bool(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size != 1 diff --git a/lib/puppet/parser/functions/is_domain_name.rb b/lib/puppet/parser/functions/is_domain_name.rb index 247db3b59..38aeecf9d 100644 --- a/lib/puppet/parser/functions/is_domain_name.rb +++ b/lib/puppet/parser/functions/is_domain_name.rb @@ -1,14 +1,13 @@ # # is_domain_name.rb # - module Puppet::Parser::Functions - newfunction(:is_domain_name, :type => :rvalue, :doc => <<-EOS -Returns true if the string passed to this function is a syntactically correct domain name. + newfunction(:is_domain_name, type: :rvalue, doc: <<-EOS + Returns true if the string passed to this function is a syntactically correct domain name. EOS - ) do |arguments| + ) do |arguments| - if (arguments.size != 1) then + if arguments.size != 1 raise(Puppet::ParseError, "is_domain_name(): Wrong number of arguments given #{arguments.size} for 1") end @@ -18,9 +17,9 @@ module Puppet::Parser::Functions domain = arguments[0].dup # Limits (rfc1035, 3.1) - domain_max_length=255 - label_min_length=1 - label_max_length=63 + domain_max_length = 255 + label_min_length = 1 + label_max_length = 63 # Allow ".", it is the top level domain return true if domain == '.' @@ -34,7 +33,7 @@ module Puppet::Parser::Functions # The top level domain must be alphabetic if there are multiple labels. # See rfc1123, 2.1 - return false if domain.include? '.' and not /\.[A-Za-z]+$/.match(domain) + return false if domain.include?('.') && !%r{\.[A-Za-z]+$}.match(domain) # Check each label in the domain labels = domain.split('.') @@ -43,10 +42,9 @@ module Puppet::Parser::Functions break if label.length > label_max_length break if label[-1..-1] == '-' break if label[0..0] == '-' - break unless /^[a-z\d-]+$/i.match(label) + break unless %r{^[a-z\d-]+$}i =~ label end return vlabels == labels - end end diff --git a/lib/puppet/parser/functions/is_email_address.rb b/lib/puppet/parser/functions/is_email_address.rb index bcd79217b..c47f31664 100644 --- a/lib/puppet/parser/functions/is_email_address.rb +++ b/lib/puppet/parser/functions/is_email_address.rb @@ -1,10 +1,9 @@ # # is_email_address.rb # - module Puppet::Parser::Functions - newfunction(:is_email_address, :type => :rvalue, :doc => <<-EOS -Returns true if the string passed to this function is a valid email address. + newfunction(:is_email_address, type: :rvalue, doc: <<-EOS + Returns true if the string passed to this function is a valid email address. EOS ) do |arguments| if arguments.size != 1 @@ -13,7 +12,7 @@ module Puppet::Parser::Functions # Taken from http://emailregex.com/ (simpler regex) valid_email_regex = %r{\A([\w+\-].?)+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z} - return (arguments[0] =~ valid_email_regex) == 0 + return (arguments[0] =~ valid_email_regex) == 0 # rubocop:disable Style/NumericPredicate : Changing to '.zero?' breaks the code end end diff --git a/lib/puppet/parser/functions/is_float.rb b/lib/puppet/parser/functions/is_float.rb index aa84a2b1a..fcce6ed32 100644 --- a/lib/puppet/parser/functions/is_float.rb +++ b/lib/puppet/parser/functions/is_float.rb @@ -1,30 +1,26 @@ # # is_float.rb # - module Puppet::Parser::Functions - newfunction(:is_float, :type => :rvalue, :doc => <<-EOS -Returns true if the variable passed to this function is a float. + newfunction(:is_float, type: :rvalue, doc: <<-EOS + Returns true if the variable passed to this function is a float. EOS - ) do |arguments| + ) do |arguments| - function_deprecation([:is_float, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Float. There is further documentation for validate_legacy function in the README.']) + function_deprecation([:is_float, 'This method is deprecated, please use the stdlib validate_legacy function, + with Stdlib::Compat::Float. There is further documentation for validate_legacy function in the README.']) - if (arguments.size != 1) then + if arguments.size != 1 raise(Puppet::ParseError, "is_float(): Wrong number of arguments given #{arguments.size} for 1") end value = arguments[0] # Only allow Numeric or String types - return false unless value.is_a?(Numeric) or value.is_a?(String) - - if value != value.to_f.to_s and !value.is_a? Float then - return false - else - return true - end + return false unless value.is_a?(Numeric) || value.is_a?(String) + return false if value != value.to_f.to_s && !value.is_a?(Float) + return true end end diff --git a/lib/puppet/parser/functions/is_function_available.rb b/lib/puppet/parser/functions/is_function_available.rb index 50cd5e170..a1e958df1 100644 --- a/lib/puppet/parser/functions/is_function_available.rb +++ b/lib/puppet/parser/functions/is_function_available.rb @@ -1,16 +1,15 @@ # # is_function_available.rb # - module Puppet::Parser::Functions - newfunction(:is_function_available, :type => :rvalue, :doc => <<-EOS -This function accepts a string as an argument, determines whether the -Puppet runtime has access to a function by that name. It returns a -true if the function exists, false if not. + newfunction(:is_function_available, type: :rvalue, doc: <<-EOS + This function accepts a string as an argument, determines whether the + Puppet runtime has access to a function by that name. It returns a + true if the function exists, false if not. EOS - ) do |arguments| + ) do |arguments| - if (arguments.size != 1) then + if arguments.size != 1 raise(Puppet::ParseError, "is_function_available?(): Wrong number of arguments given #{arguments.size} for 1") end @@ -18,7 +17,7 @@ module Puppet::Parser::Functions return false unless arguments[0].is_a?(String) function = Puppet::Parser::Functions.function(arguments[0].to_sym) - function.is_a?(String) and not function.empty? + function.is_a?(String) && !function.empty? end end diff --git a/lib/puppet/parser/functions/is_hash.rb b/lib/puppet/parser/functions/is_hash.rb index 3162f7dde..3362c71d8 100644 --- a/lib/puppet/parser/functions/is_hash.rb +++ b/lib/puppet/parser/functions/is_hash.rb @@ -1,12 +1,11 @@ # # is_hash.rb # - module Puppet::Parser::Functions - newfunction(:is_hash, :type => :rvalue, :doc => <<-EOS -Returns true if the variable passed to this function is a hash. + newfunction(:is_hash, type: :rvalue, doc: <<-EOS + Returns true if the variable passed to this function is a hash. EOS - ) do |arguments| + ) do |arguments| raise(Puppet::ParseError, "is_hash(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size != 1 diff --git a/lib/puppet/parser/functions/is_integer.rb b/lib/puppet/parser/functions/is_integer.rb index 8965b157d..509921950 100644 --- a/lib/puppet/parser/functions/is_integer.rb +++ b/lib/puppet/parser/functions/is_integer.rb @@ -1,21 +1,21 @@ # # is_integer.rb # - module Puppet::Parser::Functions - newfunction(:is_integer, :type => :rvalue, :doc => <<-EOS -Returns true if the variable passed to this function is an Integer or -a decimal (base 10) integer in String form. The string may -start with a '-' (minus). A value of '0' is allowed, but a leading '0' digit may not -be followed by other digits as this indicates that the value is octal (base 8). + newfunction(:is_integer, type: :rvalue, doc: <<-EOS + Returns true if the variable passed to this function is an Integer or + a decimal (base 10) integer in String form. The string may + start with a '-' (minus). A value of '0' is allowed, but a leading '0' digit may not + be followed by other digits as this indicates that the value is octal (base 8). -If given any other argument `false` is returned. + If given any other argument `false` is returned. EOS - ) do |arguments| + ) do |arguments| - function_deprecation([:is_integer, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Integer. There is further documentation for validate_legacy function in the README.']) + function_deprecation([:is_integer, 'This method is deprecated, please use the stdlib validate_legacy function, + with Stdlib::Compat::Integer. There is further documentation for validate_legacy function in the README.']) - if (arguments.size != 1) then + if arguments.size != 1 raise(Puppet::ParseError, "is_integer(): Wrong number of arguments given #{arguments.size} for 1") end @@ -35,11 +35,8 @@ module Puppet::Parser::Functions # 47291 numeric = %r{^-?(?:(?:[1-9]\d*)|0)$} - if value.is_a? Integer or (value.is_a? String and value.match numeric) - return true - else - return false - end + return true if value.is_a?(Integer) || (value.is_a?(String) && value.match(numeric)) + return false end end diff --git a/lib/puppet/parser/functions/is_ip_address.rb b/lib/puppet/parser/functions/is_ip_address.rb index 79ddb986c..697537ad8 100644 --- a/lib/puppet/parser/functions/is_ip_address.rb +++ b/lib/puppet/parser/functions/is_ip_address.rb @@ -1,18 +1,18 @@ # # is_ip_address.rb # - module Puppet::Parser::Functions - newfunction(:is_ip_address, :type => :rvalue, :doc => <<-EOS -Returns true if the string passed to this function is a valid IP address. + newfunction(:is_ip_address, type: :rvalue, doc: <<-EOS + Returns true if the string passed to this function is a valid IP address. EOS - ) do |arguments| + ) do |arguments| require 'ipaddr' - function_deprecation([:is_ip_address, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Ip_address. There is further documentation for validate_legacy function in the README.']) + function_deprecation([:is_ip_address, 'This method is deprecated, please use the stdlib validate_legacy function, + with Stdlib::Compat::Ip_address. There is further documentation for validate_legacy function in the README.']) - if (arguments.size != 1) then + if arguments.size != 1 raise(Puppet::ParseError, "is_ip_address(): Wrong number of arguments given #{arguments.size} for 1") end @@ -22,11 +22,8 @@ module Puppet::Parser::Functions return false end - if ip.ipv4? or ip.ipv6? then - return true - else - return false - end + return true if ip.ipv4? || ip.ipv6? + return false end end diff --git a/lib/puppet/parser/functions/is_ipv4_address.rb b/lib/puppet/parser/functions/is_ipv4_address.rb index 91869b65f..93dcb24f7 100644 --- a/lib/puppet/parser/functions/is_ipv4_address.rb +++ b/lib/puppet/parser/functions/is_ipv4_address.rb @@ -1,18 +1,18 @@ # # is_ipv4_address.rb # - module Puppet::Parser::Functions - newfunction(:is_ipv4_address, :type => :rvalue, :doc => <<-EOS -Returns true if the string passed to this function is a valid IPv4 address. + newfunction(:is_ipv4_address, type: :rvalue, doc: <<-EOS + Returns true if the string passed to this function is a valid IPv4 address. EOS - ) do |arguments| + ) do |arguments| require 'ipaddr' - function_deprecation([:is_ipv4_address, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Ipv4. There is further documentation for validate_legacy function in the README.']) + function_deprecation([:is_ipv4_address, 'This method is deprecated, please use the stdlib validate_legacy function, + with Stdlib::Compat::Ipv4. There is further documentation for validate_legacy function in the README.']) - if (arguments.size != 1) then + if arguments.size != 1 raise(Puppet::ParseError, "is_ipv4_address(): Wrong number of arguments given #{arguments.size} for 1") end diff --git a/lib/puppet/parser/functions/is_ipv6_address.rb b/lib/puppet/parser/functions/is_ipv6_address.rb index 4d96202ab..d898f949e 100644 --- a/lib/puppet/parser/functions/is_ipv6_address.rb +++ b/lib/puppet/parser/functions/is_ipv6_address.rb @@ -1,18 +1,18 @@ # # is_ipv6_address.rb # - module Puppet::Parser::Functions - newfunction(:is_ipv6_address, :type => :rvalue, :doc => <<-EOS -Returns true if the string passed to this function is a valid IPv6 address. + newfunction(:is_ipv6_address, type: :rvalue, doc: <<-EOS + Returns true if the string passed to this function is a valid IPv6 address. EOS - ) do |arguments| + ) do |arguments| - function_deprecation([:is_ipv6_address, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Ipv6. There is further documentation for validate_legacy function in the README.']) + function_deprecation([:is_ipv6_address, 'This method is deprecated, please use the stdlib validate_legacy function, + with Stdlib::Compat::Ipv6. There is further documentation for validate_legacy function in the README.']) require 'ipaddr' - if (arguments.size != 1) then + if arguments.size != 1 raise(Puppet::ParseError, "is_ipv6_address(): Wrong number of arguments given #{arguments.size} for 1") end diff --git a/lib/puppet/parser/functions/is_mac_address.rb b/lib/puppet/parser/functions/is_mac_address.rb index 5993ed234..f110edf52 100644 --- a/lib/puppet/parser/functions/is_mac_address.rb +++ b/lib/puppet/parser/functions/is_mac_address.rb @@ -1,25 +1,20 @@ # # is_mac_address.rb # - module Puppet::Parser::Functions - newfunction(:is_mac_address, :type => :rvalue, :doc => <<-EOS -Returns true if the string passed to this function is a valid mac address. + newfunction(:is_mac_address, type: :rvalue, doc: <<-EOS + Returns true if the string passed to this function is a valid mac address. EOS - ) do |arguments| + ) do |arguments| - if (arguments.size != 1) then + if arguments.size != 1 raise(Puppet::ParseError, "is_mac_address(): Wrong number of arguments given #{arguments.size} for 1") end mac = arguments[0] - if /^[a-f0-9]{1,2}(:[a-f0-9]{1,2}){5}$/i.match(mac) then - return true - else - return false - end - + return true if %r{^[a-f0-9]{1,2}(:[a-f0-9]{1,2}){5}$}i =~ mac + return false end end diff --git a/lib/puppet/parser/functions/is_numeric.rb b/lib/puppet/parser/functions/is_numeric.rb index 7800edd57..30105a997 100644 --- a/lib/puppet/parser/functions/is_numeric.rb +++ b/lib/puppet/parser/functions/is_numeric.rb @@ -1,32 +1,32 @@ # # is_numeric.rb # - module Puppet::Parser::Functions - newfunction(:is_numeric, :type => :rvalue, :doc => <<-EOS -Returns true if the given argument is a Numeric (Integer or Float), -or a String containing either a valid integer in decimal base 10 form, or -a valid floating point string representation. + newfunction(:is_numeric, type: :rvalue, doc: <<-EOS + Returns true if the given argument is a Numeric (Integer or Float), + or a String containing either a valid integer in decimal base 10 form, or + a valid floating point string representation. -The function recognizes only decimal (base 10) integers and float but not -integers in hex (base 16) or octal (base 8) form. + The function recognizes only decimal (base 10) integers and float but not + integers in hex (base 16) or octal (base 8) form. -The string representation may start with a '-' (minus). If a decimal '.' is used, -it must be followed by at least one digit. + The string representation may start with a '-' (minus). If a decimal '.' is used, + it must be followed by at least one digit. -Valid examples: + Valid examples: - 77435 - 10e-12 - -8475 - 0.2343 - -23.561e3 + 77435 + 10e-12 + -8475 + 0.2343 + -23.561e3 EOS - ) do |arguments| + ) do |arguments| - function_deprecation([:is_numeric, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Numeric. There is further documentation for validate_legacy function in the README.']) + function_deprecation([:is_numeric, 'This method is deprecated, please use the stdlib validate_legacy function, + with Stdlib::Compat::Numeric. There is further documentation for validate_legacy function in the README.']) - if (arguments.size != 1) then + if arguments.size != 1 raise(Puppet::ParseError, "is_numeric(): Wrong number of arguments given #{arguments.size} for 1") end @@ -41,19 +41,19 @@ module Puppet::Parser::Functions # if there is no risk to declare them inside of the module # Puppet::Parser::Functions - # TODO decide if this should be used + # TODO: decide if this should be used # HEX numbers like # 0xaa230F # 0X1234009C # 0x0012 # -12FcD - #numeric_hex = %r{^-?0[xX][0-9A-Fa-f]+$} + # numeric_hex = %r{^-?0[xX][0-9A-Fa-f]+$} - # TODO decide if this should be used + # TODO: decide if this should be used # OCTAL numbers like # 01234567 # -045372 - #numeric_oct = %r{^-?0[1-7][0-7]*$} + # numeric_oct = %r{^-?0[1-7][0-7]*$} # Integer/Float numbers like # -0.1234568981273 @@ -61,11 +61,11 @@ module Puppet::Parser::Functions # 42.12345e-12 numeric = %r{^-?(?:(?:[1-9]\d*)|0)(?:\.\d+)?(?:[eE]-?\d+)?$} - if value.is_a? Numeric or (value.is_a? String and ( - value.match(numeric) #or - # value.match(numeric_hex) or - # value.match(numeric_oct) - )) + if value.is_a?(Numeric) || (value.is_a?(String) && + value.match(numeric) # or + # value.match(numeric_hex) or + # value.match(numeric_oct) + ) return true else return false diff --git a/lib/puppet/parser/functions/is_string.rb b/lib/puppet/parser/functions/is_string.rb index 0ed6aec71..9e0e47d47 100644 --- a/lib/puppet/parser/functions/is_string.rb +++ b/lib/puppet/parser/functions/is_string.rb @@ -1,23 +1,23 @@ # # is_string.rb # - module Puppet::Parser::Functions - newfunction(:is_string, :type => :rvalue, :doc => <<-EOS -Returns true if the variable passed to this function is a string. + newfunction(:is_string, type: :rvalue, doc: <<-EOS + Returns true if the variable passed to this function is a string. EOS - ) do |arguments| + ) do |arguments| - function_deprecation([:is_string, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::String. There is further documentation for validate_legacy function in the README.']) + function_deprecation([:is_string, 'This method is deprecated, please use the stdlib validate_legacy function, + with Stdlib::Compat::String. There is further documentation for validate_legacy function in the README.']) - raise(Puppet::ParseError, "is_string(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size < 1 + raise(Puppet::ParseError, "is_string(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? type = arguments[0] # when called through the v4 API shim, undef gets translated to nil result = type.is_a?(String) || type.nil? - if result and (type == type.to_f.to_s or type == type.to_i.to_s) then + if result && (type == type.to_f.to_s || type == type.to_i.to_s) return false end diff --git a/lib/puppet/parser/functions/join.rb b/lib/puppet/parser/functions/join.rb index 1c179974c..0fdc0013b 100644 --- a/lib/puppet/parser/functions/join.rb +++ b/lib/puppet/parser/functions/join.rb @@ -1,21 +1,20 @@ # # join.rb # - module Puppet::Parser::Functions - newfunction(:join, :type => :rvalue, :doc => <<-EOS -This function joins an array into a string using a separator. + newfunction(:join, type: :rvalue, doc: <<-EOS + This function joins an array into a string using a separator. -*Examples:* + *Examples:* - join(['a','b','c'], ",") + join(['a','b','c'], ",") -Would result in: "a,b,c" + Would result in: "a,b,c" EOS - ) do |arguments| + ) do |arguments| # Technically we support two arguments but only first is mandatory ... - raise(Puppet::ParseError, "join(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size < 1 + raise(Puppet::ParseError, "join(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? array = arguments[0] diff --git a/lib/puppet/parser/functions/join_keys_to_values.rb b/lib/puppet/parser/functions/join_keys_to_values.rb index d8966bac7..8c6a83648 100644 --- a/lib/puppet/parser/functions/join_keys_to_values.rb +++ b/lib/puppet/parser/functions/join_keys_to_values.rb @@ -1,25 +1,24 @@ # # join.rb # - module Puppet::Parser::Functions - newfunction(:join_keys_to_values, :type => :rvalue, :doc => <<-EOS -This function joins each key of a hash to that key's corresponding value with a -separator. Keys are cast to strings. If values are arrays, multiple keys -are added for each element. The return value is an array in -which each element is one joined key/value pair. + newfunction(:join_keys_to_values, type: :rvalue, doc: <<-EOS + This function joins each key of a hash to that key's corresponding value with a + separator. Keys are cast to strings. If values are arrays, multiple keys + are added for each element. The return value is an array in + which each element is one joined key/value pair. -*Examples:* + *Examples:* - join_keys_to_values({'a'=>1,'b'=>2}, " is ") + join_keys_to_values({'a'=>1,'b'=>2}, " is ") -Would result in: ["a is 1","b is 2"] + Would result in: ["a is 1","b is 2"] - join_keys_to_values({'a'=>1,'b'=>[2,3]}, " is ") + join_keys_to_values({'a'=>1,'b'=>[2,3]}, " is ") -Would result in: ["a is 1","b is 2","b is 3"] + Would result in: ["a is 1","b is 2","b is 3"] EOS - ) do |arguments| + ) do |arguments| # Validate the number of arguments. if arguments.size != 2 @@ -28,25 +27,24 @@ module Puppet::Parser::Functions # Validate the first argument. hash = arguments[0] - if not hash.is_a?(Hash) + unless hash.is_a?(Hash) raise(TypeError, "join_keys_to_values(): The first argument must be a hash, but a #{hash.class} was given.") end # Validate the second argument. separator = arguments[1] - if not separator.is_a?(String) + unless separator.is_a?(String) raise(TypeError, "join_keys_to_values(): The second argument must be a string, but a #{separator.class} was given.") end # Join the keys to their values. - hash.map do |k,v| + hash.map { |k, v| if v.is_a?(Array) v.map { |va| String(k) + separator + String(va) } else String(k) + separator + String(v) end - end.flatten - + }.flatten end end diff --git a/lib/puppet/parser/functions/keys.rb b/lib/puppet/parser/functions/keys.rb index 199e31906..ccf5c6270 100644 --- a/lib/puppet/parser/functions/keys.rb +++ b/lib/puppet/parser/functions/keys.rb @@ -1,14 +1,13 @@ # # keys.rb # - module Puppet::Parser::Functions - newfunction(:keys, :type => :rvalue, :doc => <<-EOS -Returns the keys of a hash as an array. + newfunction(:keys, type: :rvalue, doc: <<-EOS + Returns the keys of a hash as an array. EOS - ) do |arguments| + ) do |arguments| - raise(Puppet::ParseError, "keys(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size < 1 + raise(Puppet::ParseError, "keys(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? hash = arguments[0] diff --git a/lib/puppet/parser/functions/load_module_metadata.rb b/lib/puppet/parser/functions/load_module_metadata.rb index c9b84885b..a2c5fa088 100644 --- a/lib/puppet/parser/functions/load_module_metadata.rb +++ b/lib/puppet/parser/functions/load_module_metadata.rb @@ -1,22 +1,23 @@ +# +# load_module_metadata.rb +# module Puppet::Parser::Functions - newfunction(:load_module_metadata, :type => :rvalue, :doc => <<-EOT + newfunction(:load_module_metadata, type: :rvalue, doc: <<-EOT + This function loads the metadata of a given module. EOT - ) do |args| - raise(Puppet::ParseError, "load_module_metadata(): Wrong number of arguments, expects one or two") unless [1,2].include?(args.size) + ) do |args| + raise(Puppet::ParseError, 'load_module_metadata(): Wrong number of arguments, expects one or two') unless [1, 2].include?(args.size) mod = args[0] allow_empty_metadata = args[1] module_path = function_get_module_path([mod]) metadata_json = File.join(module_path, 'metadata.json') - metadata_exists = File.exists?(metadata_json) + metadata_exists = File.exists?(metadata_json) # rubocop:disable Lint/DeprecatedClassMethods : Changing to .exist? breaks the code if metadata_exists metadata = PSON.load(File.read(metadata_json)) else - if allow_empty_metadata - metadata = {} - else - raise(Puppet::ParseError, "load_module_metadata(): No metadata.json file for module #{mod}") - end + metadata = {} + raise(Puppet::ParseError, "load_module_metadata(): No metadata.json file for module #{mod}") unless allow_empty_metadata end return metadata diff --git a/lib/puppet/parser/functions/loadjson.rb b/lib/puppet/parser/functions/loadjson.rb index 3a3372b97..535152d51 100644 --- a/lib/puppet/parser/functions/loadjson.rb +++ b/lib/puppet/parser/functions/loadjson.rb @@ -1,34 +1,32 @@ +# +# loadjson.rb +# module Puppet::Parser::Functions - newfunction(:loadjson, :type => :rvalue, :arity => -2, :doc => <<-'ENDHEREDOC') do |args| -Load a JSON file containing an array, string, or hash, and return the data -in the corresponding native data type. -The second parameter is the default value. It will be returned if the file -was not found or could not be parsed. + newfunction(:loadjson, type: :rvalue, arity: -2, doc: <<-'ENDHEREDOC') do |args| + Load a JSON file containing an array, string, or hash, and return the data + in the corresponding native data type. + The second parameter is the default value. It will be returned if the file + was not found or could not be parsed. -For example: + For example: - $myhash = loadjson('/etc/puppet/data/myhash.json') - $myhash = loadjson('no-file.json', {'default' => 'value'}) + $myhash = loadjson('/etc/puppet/data/myhash.json') + $myhash = loadjson('no-file.json', {'default' => 'value'}) ENDHEREDOC raise ArgumentError, 'Wrong number of arguments. 1 or 2 arguments should be provided.' unless args.length >= 1 - if File.exists?(args[0]) + if File.exists?(args[0]) # rubocop:disable Lint/DeprecatedClassMethods : Changing to .exist? breaks the code begin content = File.read(args[0]) - PSON::load(content) || args[1] - rescue Exception => e - if args[1] - args[1] - else - raise e - end + PSON.load(content) || args[1] + rescue StandardError => e + raise e unless args[1] + args[1] end else warning("Can't load '#{args[0]}' File does not exist!") args[1] end - end - end diff --git a/lib/puppet/parser/functions/loadyaml.rb b/lib/puppet/parser/functions/loadyaml.rb index 969636246..3cfed4bde 100644 --- a/lib/puppet/parser/functions/loadyaml.rb +++ b/lib/puppet/parser/functions/loadyaml.rb @@ -1,34 +1,32 @@ +# +# loadyaml.rb +# module Puppet::Parser::Functions - newfunction(:loadyaml, :type => :rvalue, :arity => -2, :doc => <<-'ENDHEREDOC') do |args| -Load a YAML file containing an array, string, or hash, and return the data -in the corresponding native data type. -The second parameter is the default value. It will be returned if the file -was not found or could not be parsed. + newfunction(:loadyaml, type: :rvalue, arity: -2, doc: <<-'ENDHEREDOC') do |args| + Load a YAML file containing an array, string, or hash, and return the data + in the corresponding native data type. + The second parameter is the default value. It will be returned if the file + was not found or could not be parsed. -For example: + For example: - $myhash = loadyaml('/etc/puppet/data/myhash.yaml') - $myhash = loadyaml('no-file.yaml', {'default' => 'value'}) + $myhash = loadyaml('/etc/puppet/data/myhash.yaml') + $myhash = loadyaml('no-file.yaml', {'default' => 'value'}) ENDHEREDOC raise ArgumentError, 'Wrong number of arguments. 1 or 2 arguments should be provided.' unless args.length >= 1 require 'yaml' - if File.exists?(args[0]) + if File.exists?(args[0]) # rubocop:disable Lint/DeprecatedClassMethods : Changing to .exist? breaks the code begin - YAML::load_file(args[0]) || args[1] - rescue Exception => e - if args[1] - args[1] - else - raise e - end + YAML.load_file(args[0]) || args[1] + rescue StandardError => e + raise e unless args[1] + args[1] end else warning("Can't load '#{args[0]}' File does not exist!") args[1] end - end - end diff --git a/lib/puppet/parser/functions/lstrip.rb b/lib/puppet/parser/functions/lstrip.rb index 9a9ee2984..b729bed97 100644 --- a/lib/puppet/parser/functions/lstrip.rb +++ b/lib/puppet/parser/functions/lstrip.rb @@ -1,14 +1,13 @@ # # lstrip.rb # - module Puppet::Parser::Functions - newfunction(:lstrip, :type => :rvalue, :doc => <<-EOS -Strips leading spaces to the left of a string. + newfunction(:lstrip, type: :rvalue, doc: <<-EOS + Strips leading spaces to the left of a string. EOS - ) do |arguments| + ) do |arguments| - raise(Puppet::ParseError, "lstrip(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size < 1 + raise(Puppet::ParseError, "lstrip(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? value = arguments[0] @@ -16,12 +15,12 @@ module Puppet::Parser::Functions raise(Puppet::ParseError, 'lstrip(): Requires either array or string to work with') end - if value.is_a?(Array) - # Numbers in Puppet are often string-encoded which is troublesome ... - result = value.collect { |i| i.is_a?(String) ? i.lstrip : i } - else - result = value.lstrip - end + result = if value.is_a?(Array) + # Numbers in Puppet are often string-encoded which is troublesome ... + value.map { |i| i.is_a?(String) ? i.lstrip : i } + else + value.lstrip + end return result end diff --git a/lib/puppet/parser/functions/max.rb b/lib/puppet/parser/functions/max.rb index 758c42cd6..df594d92d 100644 --- a/lib/puppet/parser/functions/max.rb +++ b/lib/puppet/parser/functions/max.rb @@ -1,16 +1,19 @@ +# +# max.rb +# module Puppet::Parser::Functions - newfunction(:max, :type => :rvalue, :doc => <<-EOS + newfunction(:max, type: :rvalue, doc: <<-EOS Returns the highest value of all arguments. Requires at least one argument. EOS - ) do |args| + ) do |args| - raise(Puppet::ParseError, "max(): Wrong number of arguments need at least one") if args.size == 0 + raise(Puppet::ParseError, 'max(): Wrong number of arguments need at least one') if args.empty? # Sometimes we get numbers as numerics and sometimes as strings. # We try to compare them as numbers when possible - return args.max do |a,b| - if a.to_s =~ /\A-?\d+(.\d+)?\z/ and b.to_s =~ /\A-?\d+(.\d+)?\z/ then + return args.max do |a, b| + if a.to_s =~ %r{\A-?\d+(.\d+)?\z} && b.to_s =~ %r{\A-?\d+(.\d+)?\z} a.to_f <=> b.to_f else a.to_s <=> b.to_s diff --git a/lib/puppet/parser/functions/member.rb b/lib/puppet/parser/functions/member.rb index fb9345218..0bd408465 100644 --- a/lib/puppet/parser/functions/member.rb +++ b/lib/puppet/parser/functions/member.rb @@ -1,34 +1,32 @@ +# TODO(Krzysztof Wilczynski): We need to add support for regular expression ... +# TODO(Krzysztof Wilczynski): Support for strings and hashes too ... # # member.rb # - -# TODO(Krzysztof Wilczynski): We need to add support for regular expression ... -# TODO(Krzysztof Wilczynski): Support for strings and hashes too ... - module Puppet::Parser::Functions - newfunction(:member, :type => :rvalue, :doc => <<-EOS -This function determines if a variable is a member of an array. -The variable can be a string, fixnum, or array. + newfunction(:member, type: :rvalue, doc: <<-EOS + This function determines if a variable is a member of an array. + The variable can be a string, fixnum, or array. -*Examples:* + *Examples:* - member(['a','b'], 'b') + member(['a','b'], 'b') -Would return: true + Would return: true - member(['a', 'b', 'c'], ['a', 'b']) + member(['a', 'b', 'c'], ['a', 'b']) -would return: true + would return: true - member(['a','b'], 'c') + member(['a','b'], 'c') -Would return: false + Would return: false - member(['a', 'b', 'c'], ['d', 'b']) + member(['a', 'b', 'c'], ['d', 'b']) -would return: false + would return: false EOS - ) do |arguments| + ) do |arguments| raise(Puppet::ParseError, "member(): Wrong number of arguments given (#{arguments.size} for 2)") if arguments.size < 2 @@ -38,16 +36,15 @@ module Puppet::Parser::Functions raise(Puppet::ParseError, 'member(): Requires array to work with') end - unless arguments[1].is_a? String or arguments[1].is_a? Fixnum or arguments[1].is_a? Array + unless arguments[1].is_a?(String) || arguments[1].is_a?(Integer) || arguments[1].is_a?(Array) raise(Puppet::ParseError, 'member(): Item to search for must be a string, fixnum, or array') end - if arguments[1].is_a? String or arguments[1].is_a? Fixnum - item = [arguments[1]] - else - item = arguments[1] - end - + item = if arguments[1].is_a?(String) || arguments[1].is_a?(Integer) + [arguments[1]] + else + arguments[1] + end raise(Puppet::ParseError, 'member(): You must provide item to search for within array given') if item.respond_to?('empty?') && item.empty? diff --git a/lib/puppet/parser/functions/merge.rb b/lib/puppet/parser/functions/merge.rb index 1b39f2060..37154bc3d 100644 --- a/lib/puppet/parser/functions/merge.rb +++ b/lib/puppet/parser/functions/merge.rb @@ -1,5 +1,8 @@ +# +# merge.rb +# module Puppet::Parser::Functions - newfunction(:merge, :type => :rvalue, :doc => <<-'ENDHEREDOC') do |args| + newfunction(:merge, type: :rvalue, doc: <<-'ENDHEREDOC') do |args| Merges two or more hashes together and returns the resulting hash. For example: @@ -15,14 +18,14 @@ module Puppet::Parser::Functions ENDHEREDOC if args.length < 2 - raise Puppet::ParseError, ("merge(): wrong number of arguments (#{args.length}; must be at least 2)") + raise Puppet::ParseError, "merge(): wrong number of arguments (#{args.length}; must be at least 2)" end # The hash we accumulate into - accumulator = Hash.new + accumulator = {} # Merge into the accumulator hash args.each do |arg| - next if arg.is_a? String and arg.empty? # empty string is synonym for puppet's undef + next if arg.is_a?(String) && arg.empty? # empty string is synonym for puppet's undef unless arg.is_a?(Hash) raise Puppet::ParseError, "merge: unexpected argument type #{arg.class}, only expects hash arguments" end diff --git a/lib/puppet/parser/functions/min.rb b/lib/puppet/parser/functions/min.rb index f10a2b211..a2ec99f44 100644 --- a/lib/puppet/parser/functions/min.rb +++ b/lib/puppet/parser/functions/min.rb @@ -1,20 +1,20 @@ +# +# min.rb +# module Puppet::Parser::Functions - newfunction(:min, :type => :rvalue, :doc => <<-EOS + newfunction(:min, type: :rvalue, doc: <<-EOS Returns the lowest value of all arguments. Requires at least one argument. EOS - ) do |args| + ) do |args| - raise(Puppet::ParseError, "min(): Wrong number of arguments need at least one") if args.size == 0 + raise(Puppet::ParseError, 'min(): Wrong number of arguments need at least one') if args.empty? # Sometimes we get numbers as numerics and sometimes as strings. # We try to compare them as numbers when possible - return args.min do |a,b| - if a.to_s =~ /\A^-?\d+(.\d+)?\z/ and b.to_s =~ /\A-?\d+(.\d+)?\z/ then - a.to_f <=> b.to_f - else - a.to_s <=> b.to_s - end + return args.min do |a, b| + a.to_f <=> b.to_f if a.to_s =~ %r{\A^-?\d+(.\d+)?\z} && b.to_s =~ %r{\A-?\d+(.\d+)?\z} + a.to_s <=> b.to_s end end end diff --git a/lib/puppet/parser/functions/num2bool.rb b/lib/puppet/parser/functions/num2bool.rb index 9ad59b254..1860c8bbc 100644 --- a/lib/puppet/parser/functions/num2bool.rb +++ b/lib/puppet/parser/functions/num2bool.rb @@ -1,21 +1,20 @@ # # num2bool.rb # - module Puppet::Parser::Functions - newfunction(:num2bool, :type => :rvalue, :doc => <<-EOS -This function converts a number or a string representation of a number into a -true boolean. Zero or anything non-numeric becomes false. Numbers higher then 0 -become true. + newfunction(:num2bool, type: :rvalue, doc: <<-EOS + This function converts a number or a string representation of a number into a + true boolean. Zero or anything non-numeric becomes false. Numbers higher then 0 + become true. EOS - ) do |arguments| + ) do |arguments| raise(Puppet::ParseError, "num2bool(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size != 1 number = arguments[0] case number - when Numeric + when Numeric # rubocop:disable Lint/EmptyWhen : Required for the module to work # Yay, it's a number when String begin diff --git a/lib/puppet/parser/functions/parsejson.rb b/lib/puppet/parser/functions/parsejson.rb index f7c2896ed..1117d03da 100644 --- a/lib/puppet/parser/functions/parsejson.rb +++ b/lib/puppet/parser/functions/parsejson.rb @@ -1,28 +1,23 @@ # # parsejson.rb # - module Puppet::Parser::Functions - newfunction(:parsejson, :type => :rvalue, :doc => <<-EOS -This function accepts JSON as a string and converts it into the correct -Puppet structure. + newfunction(:parsejson, type: :rvalue, doc: <<-EOS + This function accepts JSON as a string and converts it into the correct + Puppet structure. -The optional second argument can be used to pass a default value that will -be returned if the parsing of YAML string have failed. + The optional second argument can be used to pass a default value that will + be returned if the parsing of YAML string have failed. EOS - ) do |arguments| + ) do |arguments| raise ArgumentError, 'Wrong number of arguments. 1 or 2 arguments should be provided.' unless arguments.length >= 1 begin - PSON::load(arguments[0]) || arguments[1] + PSON.load(arguments[0]) || arguments[1] rescue StandardError => e - if arguments[1] - arguments[1] - else - raise e - end + raise e unless arguments[1] + arguments[1] end - end end diff --git a/lib/puppet/parser/functions/parseyaml.rb b/lib/puppet/parser/functions/parseyaml.rb index ba9d98aa9..33c86961e 100644 --- a/lib/puppet/parser/functions/parseyaml.rb +++ b/lib/puppet/parser/functions/parseyaml.rb @@ -1,32 +1,27 @@ # # parseyaml.rb # - module Puppet::Parser::Functions - newfunction(:parseyaml, :type => :rvalue, :doc => <<-EOS -This function accepts YAML as a string and converts it into the correct -Puppet structure. + newfunction(:parseyaml, type: :rvalue, doc: <<-EOS + This function accepts YAML as a string and converts it into the correct + Puppet structure. -The optional second argument can be used to pass a default value that will -be returned if the parsing of YAML string have failed. + The optional second argument can be used to pass a default value that will + be returned if the parsing of YAML string have failed. EOS - ) do |arguments| + ) do |arguments| raise ArgumentError, 'Wrong number of arguments. 1 or 2 arguments should be provided.' unless arguments.length >= 1 require 'yaml' begin - YAML::load(arguments[0]) || arguments[1] + YAML.load(arguments[0]) || arguments[1] # rubocop:disable Security/YAMLLoad : using YAML.safe_load causes the code to break # in ruby 1.9.3 Psych::SyntaxError is a RuntimeException # this still needs to catch that and work also on rubies that # do not have Psych available. - rescue StandardError, Psych::SyntaxError => e - if arguments[1] - arguments[1] - else - raise e - end + rescue StandardError, Psych::SyntaxError => e # rubocop:disable Lint/ShadowedException : See above + raise e unless arguments[1] + arguments[1] end - end end diff --git a/lib/puppet/parser/functions/pick.rb b/lib/puppet/parser/functions/pick.rb index fdd0aefd7..d68791cd8 100644 --- a/lib/puppet/parser/functions/pick.rb +++ b/lib/puppet/parser/functions/pick.rb @@ -1,29 +1,27 @@ +# +# pick.rb +# module Puppet::Parser::Functions - newfunction(:pick, :type => :rvalue, :doc => <<-EOS + newfunction(:pick, type: :rvalue, doc: <<-EOS + This function is similar to a coalesce function in SQL in that it will return + the first value in a list of values that is not undefined or an empty string + (two things in Puppet that will return a boolean false value). Typically, + this function is used to check for a value in the Puppet Dashboard/Enterprise + Console, and failover to a default value like the following: -This function is similar to a coalesce function in SQL in that it will return -the first value in a list of values that is not undefined or an empty string -(two things in Puppet that will return a boolean false value). Typically, -this function is used to check for a value in the Puppet Dashboard/Enterprise -Console, and failover to a default value like the following: - - $real_jenkins_version = pick($::jenkins_version, '1.449') - -The value of $real_jenkins_version will first look for a top-scope variable -called 'jenkins_version' (note that parameters set in the Puppet Dashboard/ -Enterprise Console are brought into Puppet as top-scope variables), and, -failing that, will use a default value of 1.449. + $real_jenkins_version = pick($::jenkins_version, '1.449') + The value of $real_jenkins_version will first look for a top-scope variable + called 'jenkins_version' (note that parameters set in the Puppet Dashboard/ + Enterprise Console are brought into Puppet as top-scope variables), and, + failing that, will use a default value of 1.449. EOS -) do |args| - args = args.compact - args.delete(:undef) - args.delete(:undefined) - args.delete("") - if args[0].to_s.empty? then - fail Puppet::ParseError, "pick(): must receive at least one non empty value" - else - return args[0] - end - end + ) do |args| + args = args.compact + args.delete(:undef) + args.delete(:undefined) + args.delete('') + raise Puppet::ParseError, 'pick(): must receive at least one non empty value' if args[0].to_s.empty? + return args[0] + end end diff --git a/lib/puppet/parser/functions/pick_default.rb b/lib/puppet/parser/functions/pick_default.rb index 36e33abfa..05ac8ca4a 100644 --- a/lib/puppet/parser/functions/pick_default.rb +++ b/lib/puppet/parser/functions/pick_default.rb @@ -1,35 +1,36 @@ +# +# pick_default.rb +# module Puppet::Parser::Functions - newfunction(:pick_default, :type => :rvalue, :doc => <<-EOS + newfunction(:pick_default, type: :rvalue, doc: <<-EOS + This function is similar to a coalesce function in SQL in that it will return + the first value in a list of values that is not undefined or an empty string + (two things in Puppet that will return a boolean false value). If no value is + found, it will return the last argument. -This function is similar to a coalesce function in SQL in that it will return -the first value in a list of values that is not undefined or an empty string -(two things in Puppet that will return a boolean false value). If no value is -found, it will return the last argument. + Typically, this function is used to check for a value in the Puppet + Dashboard/Enterprise Console, and failover to a default value like the + following: -Typically, this function is used to check for a value in the Puppet -Dashboard/Enterprise Console, and failover to a default value like the -following: + $real_jenkins_version = pick_default($::jenkins_version, '1.449') - $real_jenkins_version = pick_default($::jenkins_version, '1.449') - -The value of $real_jenkins_version will first look for a top-scope variable -called 'jenkins_version' (note that parameters set in the Puppet Dashboard/ -Enterprise Console are brought into Puppet as top-scope variables), and, -failing that, will use a default value of 1.449. - -Note that, contrary to the pick() function, the pick_default does not fail if -all arguments are empty. This allows pick_default to use an empty value as -default. + The value of $real_jenkins_version will first look for a top-scope variable + called 'jenkins_version' (note that parameters set in the Puppet Dashboard/ + Enterprise Console are brought into Puppet as top-scope variables), and, + failing that, will use a default value of 1.449. + Note that, contrary to the pick() function, the pick_default does not fail if + all arguments are empty. This allows pick_default to use an empty value as + default. EOS -) do |args| - fail "Must receive at least one argument." if args.empty? - default = args.last - args = args[0..-2].compact - args.delete(:undef) - args.delete(:undefined) - args.delete("") - args << default - return args[0] - end + ) do |args| + raise 'Must receive at least one argument.' if args.empty? + default = args.last + args = args[0..-2].compact + args.delete(:undef) + args.delete(:undefined) + args.delete('') + args << default + return args[0] + end end diff --git a/lib/puppet/parser/functions/prefix.rb b/lib/puppet/parser/functions/prefix.rb index b1c1e3539..285a3ceec 100644 --- a/lib/puppet/parser/functions/prefix.rb +++ b/lib/puppet/parser/functions/prefix.rb @@ -1,25 +1,24 @@ # # prefix.rb # - module Puppet::Parser::Functions - newfunction(:prefix, :type => :rvalue, :doc => <<-EOS -This function applies a prefix to all elements in an array or a hash. + newfunction(:prefix, type: :rvalue, doc: <<-EOS + This function applies a prefix to all elements in an array or a hash. -*Examples:* + *Examples:* - prefix(['a','b','c'], 'p') + prefix(['a','b','c'], 'p') -Will return: ['pa','pb','pc'] + Will return: ['pa','pb','pc'] EOS - ) do |arguments| + ) do |arguments| # Technically we support two arguments but only first is mandatory ... - raise(Puppet::ParseError, "prefix(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size < 1 + raise(Puppet::ParseError, "prefix(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? enumerable = arguments[0] - unless enumerable.is_a?(Array) or enumerable.is_a?(Hash) + unless enumerable.is_a?(Array) || enumerable.is_a?(Hash) raise Puppet::ParseError, "prefix(): expected first argument to be an Array or a Hash, got #{enumerable.inspect}" end @@ -31,18 +30,18 @@ module Puppet::Parser::Functions end end - if enumerable.is_a?(Array) - # Turn everything into string same as join would do ... - result = enumerable.collect do |i| - i = i.to_s - prefix ? prefix + i : i - end - else - result = Hash[enumerable.map do |k,v| - k = k.to_s - [ prefix ? prefix + k : k, v ] - end] - end + result = if enumerable.is_a?(Array) + # Turn everything into string same as join would do ... + enumerable.map do |i| + i = i.to_s + prefix ? prefix + i : i + end + else + Hash[enumerable.map do |k, v| + k = k.to_s + [prefix ? prefix + k : k, v] + end] + end return result end diff --git a/lib/puppet/parser/functions/private.rb b/lib/puppet/parser/functions/private.rb index 3b00ba12f..79d1f468d 100644 --- a/lib/puppet/parser/functions/private.rb +++ b/lib/puppet/parser/functions/private.rb @@ -1,17 +1,16 @@ # # private.rb # - module Puppet::Parser::Functions - newfunction(:private, :doc => <<-'EOS' + newfunction(:private, doc: <<-'EOS' DEPRECATED: Sets the current class or definition as private. Calling the class or definition from outside the current module will fail. EOS - ) do |args| - warning("private() DEPRECATED: This function will cease to function on Puppet 4; please use assert_private() before upgrading to puppet 4 for backwards-compatibility, or migrate to the new parser's typing system.") - if !Puppet::Parser::Functions.autoloader.loaded?(:assert_private) + ) do |args| + warning("private() DEPRECATED: This function will cease to function on Puppet 4; please use assert_private() before upgrading to puppet 4 for backwards-compatibility, or migrate to the new parser's typing system.") # rubocop:disable Lint/LineLength : Cannot shorten this line + unless Puppet::Parser::Functions.autoloader.loaded?(:assert_private) Puppet::Parser::Functions.autoloader.load(:assert_private) end - function_assert_private([(args[0] unless args.size < 1)]) + function_assert_private([(args[0] unless args.empty?)]) end end diff --git a/lib/puppet/parser/functions/pry.rb b/lib/puppet/parser/functions/pry.rb index c18ef7ef8..7a6b91735 100644 --- a/lib/puppet/parser/functions/pry.rb +++ b/lib/puppet/parser/functions/pry.rb @@ -1,16 +1,15 @@ # # pry.rb # - module Puppet::Parser::Functions - newfunction(:pry, :type => :statement, :doc => <<-EOS -This function invokes a pry debugging session in the current scope object. This is useful for debugging manifest code at specific points during a compilation. + newfunction(:pry, type: :statement, doc: <<-EOS + This function invokes a pry debugging session in the current scope object. This is useful for debugging manifest code at specific points during a compilation. -*Examples:* + *Examples:* - pry() + pry() EOS - ) do |arguments| + ) do |arguments| begin require 'pry' rescue LoadError diff --git a/lib/puppet/parser/functions/pw_hash.rb b/lib/puppet/parser/functions/pw_hash.rb index adcc719a5..9fe5c07e5 100644 --- a/lib/puppet/parser/functions/pw_hash.rb +++ b/lib/puppet/parser/functions/pw_hash.rb @@ -1,11 +1,9 @@ - # Please note: This function is an implementation of a Ruby class and as such may not be entirely UTF8 compatible. To ensure compatibility please use this function with Ruby 2.4.0 or greater - https://bugs.ruby-lang.org/issues/10085. - -Puppet::Parser::Functions::newfunction( +Puppet::Parser::Functions.newfunction( :pw_hash, - :type => :rvalue, - :arity => 3, - :doc => "Hashes a password using the crypt function. Provides a hash + type: :rvalue, + arity: 3, + doc: "Hashes a password using the crypt function. Provides a hash usable on most POSIX systems. The first argument to this function is the password to hash. If it is @@ -25,42 +23,40 @@ Note: this uses the Puppet Master's implementation of crypt(3). If your environment contains several different operating systems, ensure that they - are compatible before using this function.") do |args| - raise ArgumentError, "pw_hash(): wrong number of arguments (#{args.size} for 3)" if args.size != 3 - args.map! do |arg| - if (defined? Puppet::Pops::Types::PSensitiveType::Sensitive) && (arg.is_a? Puppet::Pops::Types::PSensitiveType::Sensitive) - arg.unwrap - else - arg - end - end - raise ArgumentError, "pw_hash(): first argument must be a string" unless args[0].is_a? String or args[0].nil? - raise ArgumentError, "pw_hash(): second argument must be a string" unless args[1].is_a? String - hashes = { 'md5' => '1', - 'sha-256' => '5', - 'sha-512' => '6' } - hash_type = hashes[args[1].downcase] - raise ArgumentError, "pw_hash(): #{args[1]} is not a valid hash type" if hash_type.nil? - raise ArgumentError, "pw_hash(): third argument must be a string" unless args[2].is_a? String - raise ArgumentError, "pw_hash(): third argument must not be empty" if args[2].empty? - raise ArgumentError, "pw_hash(): characters in salt must be in the set [a-zA-Z0-9./]" unless args[2].match(/\A[a-zA-Z0-9.\/]+\z/) - - password = args[0] - return nil if password.nil? or password.empty? - - salt = "$#{hash_type}$#{args[2]}" - - # handle weak implementations of String#crypt - if 'test'.crypt('$1$1') != '$1$1$Bp8CU9Oujr9SSEw53WV6G.' - # JRuby < 1.7.17 - if RUBY_PLATFORM == 'java' - # puppetserver bundles Apache Commons Codec - org.apache.commons.codec.digest.Crypt.crypt(password.to_java_bytes, salt) - else - # MS Windows and other systems that don't support enhanced salts - raise Puppet::ParseError, 'system does not support enhanced salts' - end + are compatible before using this function.", +) do |args| + raise ArgumentError, "pw_hash(): wrong number of arguments (#{args.size} for 3)" if args.size != 3 + args.map! do |arg| + if (defined? Puppet::Pops::Types::PSensitiveType::Sensitive) && (arg.is_a? Puppet::Pops::Types::PSensitiveType::Sensitive) + arg.unwrap else - password.crypt(salt) + arg end + end + raise ArgumentError, 'pw_hash(): first argument must be a string' unless args[0].is_a?(String) || args[0].nil? + raise ArgumentError, 'pw_hash(): second argument must be a string' unless args[1].is_a? String + hashes = { 'md5' => '1', + 'sha-256' => '5', + 'sha-512' => '6' } + hash_type = hashes[args[1].downcase] + raise ArgumentError, "pw_hash(): #{args[1]} is not a valid hash type" if hash_type.nil? + raise ArgumentError, 'pw_hash(): third argument must be a string' unless args[2].is_a? String + raise ArgumentError, 'pw_hash(): third argument must not be empty' if args[2].empty? + raise ArgumentError, 'pw_hash(): characters in salt must be in the set [a-zA-Z0-9./]' unless args[2] =~ %r{\A[a-zA-Z0-9./]+\z} + + password = args[0] + return nil if password.nil? || password.empty? + + salt = "$#{hash_type}$#{args[2]}" + + # handle weak implementations of String#crypt + if 'test'.crypt('$1$1') != '$1$1$Bp8CU9Oujr9SSEw53WV6G.' + # JRuby < 1.7.17 + # MS Windows and other systems that don't support enhanced salts + raise Puppet::ParseError, 'system does not support enhanced salts' unless RUBY_PLATFORM == 'java' + # puppetserver bundles Apache Commons Codec + org.apache.commons.codec.digest.Crypt.crypt(password.to_java_bytes, salt) + else + password.crypt(salt) + end end diff --git a/lib/puppet/parser/functions/range.rb b/lib/puppet/parser/functions/range.rb index 72c373a9c..ecc8592e5 100644 --- a/lib/puppet/parser/functions/range.rb +++ b/lib/puppet/parser/functions/range.rb @@ -1,43 +1,41 @@ # # range.rb # - # TODO(Krzysztof Wilczynski): We probably need to approach numeric values differently ... - module Puppet::Parser::Functions - newfunction(:range, :type => :rvalue, :doc => <<-EOS -When given range in the form of (start, stop) it will extrapolate a range as -an array. + newfunction(:range, type: :rvalue, doc: <<-EOS + When given range in the form of (start, stop) it will extrapolate a range as + an array. -*Examples:* + *Examples:* - range("0", "9") + range("0", "9") -Will return: [0,1,2,3,4,5,6,7,8,9] + Will return: [0,1,2,3,4,5,6,7,8,9] - range("00", "09") + range("00", "09") -Will return: [0,1,2,3,4,5,6,7,8,9] (Zero padded strings are converted to -integers automatically) + Will return: [0,1,2,3,4,5,6,7,8,9] (Zero padded strings are converted to + integers automatically) - range("a", "c") + range("a", "c") -Will return: ["a","b","c"] + Will return: ["a","b","c"] - range("host01", "host10") -Will return: ["host01", "host02", ..., "host09", "host10"] -NB Be explicit in including trailing zeros. Otherwise the underlying ruby function will fail. + range("host01", "host10") + Will return: ["host01", "host02", ..., "host09", "host10"] + NB Be explicit in including trailing zeros. Otherwise the underlying ruby function will fail. -Passing a third argument will cause the generated range to step by that -interval, e.g. + Passing a third argument will cause the generated range to step by that + interval, e.g. - range("0", "9", "2") + range("0", "9", "2") -Will return: [0,2,4,6,8] + Will return: [0,2,4,6,8] EOS - ) do |arguments| + ) do |arguments| - raise(Puppet::ParseError, 'range(): Wrong number of arguments given (0 for 1)') if arguments.size == 0 + raise(Puppet::ParseError, 'range(): Wrong number of arguments given (0 for 1)') if arguments.empty? if arguments.size > 1 start = arguments[0] @@ -49,13 +47,14 @@ module Puppet::Parser::Functions else # arguments.size == 1 value = arguments[0] - if m = value.match(/^(\w+)(\.\.\.?|\-)(\w+)$/) + m = value.match(%r{^(\w+)(\.\.\.?|\-)(\w+)$}) + if m start = m[1] stop = m[3] type = m[2] step = 1 - elsif value.match(/^.+$/) + elsif value =~ %r{^.+$} raise(Puppet::ParseError, "range(): Unable to compute range from the value: #{value}") else raise(Puppet::ParseError, "range(): Unknown range format: #{value}") @@ -63,7 +62,7 @@ module Puppet::Parser::Functions end # If we were given an integer, ensure we work with one - if start.to_s.match(/^\d+$/) + if start.to_s =~ %r{^\d+$} start = start.to_i stop = stop.to_i else @@ -72,9 +71,9 @@ module Puppet::Parser::Functions end range = case type - when /^(\.\.|\-)$/ then (start .. stop) - when '...' then (start ... stop) # Exclusive of last element - end + when %r{^(..|-)$} then (start..stop) + when '...' then (start...stop) # Exclusive of last element + end result = range.step(step).to_a diff --git a/lib/puppet/parser/functions/regexpescape.rb b/lib/puppet/parser/functions/regexpescape.rb index 2cfa3bb92..57e2ad42b 100644 --- a/lib/puppet/parser/functions/regexpescape.rb +++ b/lib/puppet/parser/functions/regexpescape.rb @@ -2,7 +2,7 @@ # regexpescape.rb # module Puppet::Parser::Functions - newfunction(:regexpescape, :type => :rvalue, :doc => <<-EOS + newfunction(:regexpescape, type: :rvalue, doc: <<-EOS Regexp escape a string or array of strings. Requires either a single string or an array as an input. EOS @@ -17,7 +17,7 @@ module Puppet::Parser::Functions result = if value.is_a?(Array) # Numbers in Puppet are often string-encoded which is troublesome ... - value.collect { |i| i.is_a?(String) ? Regexp.escape(i) : i } + value.map { |i| i.is_a?(String) ? Regexp.escape(i) : i } else Regexp.escape(value) end diff --git a/lib/puppet/parser/functions/reject.rb b/lib/puppet/parser/functions/reject.rb index 1953ffcf1..61b91d2d3 100644 --- a/lib/puppet/parser/functions/reject.rb +++ b/lib/puppet/parser/functions/reject.rb @@ -1,24 +1,23 @@ # # reject.rb # - module Puppet::Parser::Functions - newfunction(:reject, :type => :rvalue, :doc => <<-EOS) do |args| -This function searches through an array and rejects all elements that match -the provided regular expression. + newfunction(:reject, type: :rvalue, doc: <<-EOS) do |args| + This function searches through an array and rejects all elements that match + the provided regular expression. -*Examples:* + *Examples:* - reject(['aaa','bbb','ccc','aaaddd'], 'aaa') + reject(['aaa','bbb','ccc','aaaddd'], 'aaa') -Would return: + Would return: - ['bbb','ccc'] + ['bbb','ccc'] EOS - if (args.size != 2) + if args.size != 2 raise Puppet::ParseError, - "reject(): Wrong number of arguments given #{args.size} for 2" + "reject(): Wrong number of arguments given #{args.size} for 2" end ary = args[0] diff --git a/lib/puppet/parser/functions/reverse.rb b/lib/puppet/parser/functions/reverse.rb index aca98cea3..32e27bbe0 100644 --- a/lib/puppet/parser/functions/reverse.rb +++ b/lib/puppet/parser/functions/reverse.rb @@ -1,14 +1,13 @@ # # reverse.rb # - module Puppet::Parser::Functions - newfunction(:reverse, :type => :rvalue, :doc => <<-EOS -Reverses the order of a string or array. + newfunction(:reverse, type: :rvalue, doc: <<-EOS + Reverses the order of a string or array. EOS - ) do |arguments| + ) do |arguments| - raise(Puppet::ParseError, "reverse(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size < 1 + raise(Puppet::ParseError, "reverse(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? value = arguments[0] diff --git a/lib/puppet/parser/functions/round.rb b/lib/puppet/parser/functions/round.rb index 489c3014d..2be5c60d0 100644 --- a/lib/puppet/parser/functions/round.rb +++ b/lib/puppet/parser/functions/round.rb @@ -1,23 +1,22 @@ # # round.rb # - module Puppet::Parser::Functions - newfunction(:round, :type => :rvalue, :doc => <<-EOS - Rounds a number to the nearest integer + newfunction(:round, type: :rvalue, doc: <<-EOS + Rounds a number to the nearest integer - *Examples:* + *Examples:* - round(2.9) + round(2.9) - returns: 3 + returns: 3 - round(2.4) + round(2.4) - returns: 2 + returns: 2 EOS - ) do |args| + ) do |args| raise Puppet::ParseError, "round(): Wrong number of arguments given #{args.size} for 1" if args.size != 1 raise Puppet::ParseError, "round(): Expected a Numeric, got #{args[0].class}" unless args[0].is_a? Numeric diff --git a/lib/puppet/parser/functions/rstrip.rb b/lib/puppet/parser/functions/rstrip.rb index e24abd553..0624beed6 100644 --- a/lib/puppet/parser/functions/rstrip.rb +++ b/lib/puppet/parser/functions/rstrip.rb @@ -1,14 +1,13 @@ # # rstrip.rb # - module Puppet::Parser::Functions - newfunction(:rstrip, :type => :rvalue, :doc => <<-EOS -Strips leading spaces to the right of the string. + newfunction(:rstrip, type: :rvalue, doc: <<-EOS + Strips leading spaces to the right of the string. EOS - ) do |arguments| + ) do |arguments| - raise(Puppet::ParseError, "rstrip(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size < 1 + raise(Puppet::ParseError, "rstrip(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? value = arguments[0] @@ -16,11 +15,11 @@ module Puppet::Parser::Functions raise(Puppet::ParseError, 'rstrip(): Requires either array or string to work with') end - if value.is_a?(Array) - result = value.collect { |i| i.is_a?(String) ? i.rstrip : i } - else - result = value.rstrip - end + result = if value.is_a?(Array) + value.map { |i| i.is_a?(String) ? i.rstrip : i } + else + value.rstrip + end return result end diff --git a/lib/puppet/parser/functions/seeded_rand.rb b/lib/puppet/parser/functions/seeded_rand.rb index 44e27b8dc..579295857 100644 --- a/lib/puppet/parser/functions/seeded_rand.rb +++ b/lib/puppet/parser/functions/seeded_rand.rb @@ -1,22 +1,24 @@ -Puppet::Parser::Functions::newfunction( +# +# seeded_rand.rb +# +Puppet::Parser::Functions.newfunction( :seeded_rand, - :arity => 2, - :type => :rvalue, - :doc => <<-EOS -Usage: `seeded_rand(MAX, SEED)`. MAX must be a positive integer; SEED is any string. - -Generates a random whole number greater than or equal to 0 and less -than MAX, using the value of SEED for repeatable randomness. If SEED -starts with "$fqdn:", this is behaves the same as `fqdn_rand`. + arity: 2, + type: :rvalue, + doc: <<-EOS + Usage: `seeded_rand(MAX, SEED)`. MAX must be a positive integer; SEED is any string. + Generates a random whole number greater than or equal to 0 and less + than MAX, using the value of SEED for repeatable randomness. If SEED + starts with "$fqdn:", this is behaves the same as `fqdn_rand`. EOS ) do |args| require 'digest/md5' - raise(ArgumentError, "seeded_rand(): first argument must be a positive integer") unless function_is_integer([args[0]]) and args[0].to_i > 0 - raise(ArgumentError, "seeded_rand(): second argument must be a string") unless args[1].is_a? String + raise(ArgumentError, 'seeded_rand(): first argument must be a positive integer') unless function_is_integer([args[0]]) && args[0].to_i > 0 + raise(ArgumentError, 'seeded_rand(): second argument must be a string') unless args[1].is_a? String max = args[0].to_i seed = Digest::MD5.hexdigest(args[1]).hex - Puppet::Util.deterministic_rand(seed,max) + Puppet::Util.deterministic_rand(seed, max) end diff --git a/lib/puppet/parser/functions/shell_escape.rb b/lib/puppet/parser/functions/shell_escape.rb index 7306b7cf9..91803996a 100644 --- a/lib/puppet/parser/functions/shell_escape.rb +++ b/lib/puppet/parser/functions/shell_escape.rb @@ -1,19 +1,17 @@ +require 'shellwords' # # shell_escape.rb # - -require 'shellwords' - module Puppet::Parser::Functions - newfunction(:shell_escape, :type => :rvalue, :doc => <<-EOS -Escapes a string so that it can be safely used in a Bourne shell command line. + newfunction(:shell_escape, type: :rvalue, doc: <<-EOS + Escapes a string so that it can be safely used in a Bourne shell command line. -Note that the resulting string should be used unquoted and is not intended for use in double quotes nor in single -quotes. + Note that the resulting string should be used unquoted and is not intended for use in double quotes nor in single + quotes. -This function behaves the same as ruby's Shellwords.shellescape() function. + This function behaves the same as ruby's Shellwords.shellescape() function. EOS - ) do |arguments| + ) do |arguments| raise(Puppet::ParseError, "shell_escape(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size != 1 diff --git a/lib/puppet/parser/functions/shell_join.rb b/lib/puppet/parser/functions/shell_join.rb index 682ed8d58..dce92cc62 100644 --- a/lib/puppet/parser/functions/shell_join.rb +++ b/lib/puppet/parser/functions/shell_join.rb @@ -1,23 +1,22 @@ + +require 'shellwords' # # shell_join.rb # - -require 'shellwords' - module Puppet::Parser::Functions - newfunction(:shell_join, :type => :rvalue, :doc => <<-EOS -Builds a command line string from the given array of strings. Each array item is escaped for Bourne shell. All items are -then joined together, with a single space in between. + newfunction(:shell_join, type: :rvalue, doc: <<-EOS + Builds a command line string from the given array of strings. Each array item is escaped for Bourne shell. All items are + then joined together, with a single space in between. -This function behaves the same as ruby's Shellwords.shelljoin() function + This function behaves the same as ruby's Shellwords.shelljoin() function EOS - ) do |arguments| + ) do |arguments| raise(Puppet::ParseError, "shell_join(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size != 1 array = arguments[0] - raise Puppet::ParseError, ("First argument is not an Array: #{array.inspect}") unless array.is_a?(Array) + raise Puppet::ParseError, "First argument is not an Array: #{array.inspect}" unless array.is_a?(Array) # explicit conversion to string is required for ruby 1.9 array = array.map { |item| item.to_s } diff --git a/lib/puppet/parser/functions/shell_split.rb b/lib/puppet/parser/functions/shell_split.rb index 09e6e78ce..e9a3c738e 100644 --- a/lib/puppet/parser/functions/shell_split.rb +++ b/lib/puppet/parser/functions/shell_split.rb @@ -1,16 +1,14 @@ +require 'shellwords' # # shell_split.rb # - -require 'shellwords' - module Puppet::Parser::Functions - newfunction(:shell_split, :type => :rvalue, :doc => <<-EOS -Splits a string into an array of tokens in the same way the Bourne shell does. + newfunction(:shell_split, type: :rvalue, doc: <<-EOS + Splits a string into an array of tokens in the same way the Bourne shell does. -This function behaves the same as ruby's Shellwords.shellsplit() function + This function behaves the same as ruby's Shellwords.shellsplit() function EOS - ) do |arguments| + ) do |arguments| raise(Puppet::ParseError, "shell_split(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size != 1 diff --git a/lib/puppet/parser/functions/shuffle.rb b/lib/puppet/parser/functions/shuffle.rb index 942cbceab..1f280dab7 100644 --- a/lib/puppet/parser/functions/shuffle.rb +++ b/lib/puppet/parser/functions/shuffle.rb @@ -1,14 +1,13 @@ # # shuffle.rb # - module Puppet::Parser::Functions - newfunction(:shuffle, :type => :rvalue, :doc => <<-EOS -Randomizes the order of a string or array elements. - EOS - ) do |arguments| + newfunction(:shuffle, type: :rvalue, doc: <<-EOS + Randomizes the order of a string or array elements. + EOS + ) do |arguments| - raise(Puppet::ParseError, "shuffle(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size < 1 + raise(Puppet::ParseError, "shuffle(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? value = arguments[0] diff --git a/lib/puppet/parser/functions/size.rb b/lib/puppet/parser/functions/size.rb index b503aa09e..933ee27c5 100644 --- a/lib/puppet/parser/functions/size.rb +++ b/lib/puppet/parser/functions/size.rb @@ -1,14 +1,13 @@ # # size.rb # - module Puppet::Parser::Functions - newfunction(:size, :type => :rvalue, :doc => <<-EOS -Returns the number of elements in a string, an array or a hash - EOS - ) do |arguments| + newfunction(:size, type: :rvalue, doc: <<-EOS + Returns the number of elements in a string, an array or a hash + EOS + ) do |arguments| - raise(Puppet::ParseError, "size(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size < 1 + raise(Puppet::ParseError, "size(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? item = arguments[0] @@ -28,7 +27,6 @@ module Puppet::Parser::Functions Float(item) raise(Puppet::ParseError, 'size(): Requires either string, array or hash to work with') - rescue ArgumentError result = item.size end diff --git a/lib/puppet/parser/functions/sort.rb b/lib/puppet/parser/functions/sort.rb index d7792f5e0..50d856b07 100644 --- a/lib/puppet/parser/functions/sort.rb +++ b/lib/puppet/parser/functions/sort.rb @@ -2,25 +2,23 @@ # sort.rb # Please note: This function is an implementation of a Ruby class and as such may not be entirely UTF8 compatible. To ensure compatibility please use this function with Ruby 2.4.0 or greater - https://bugs.ruby-lang.org/issues/10085. # - module Puppet::Parser::Functions - newfunction(:sort, :type => :rvalue, :doc => <<-EOS -Sorts strings and arrays lexically. - EOS - ) do |arguments| + newfunction(:sort, type: :rvalue, doc: <<-EOS + Sorts strings and arrays lexically. + EOS + ) do |arguments| - if (arguments.size != 1) then + if arguments.size != 1 raise(Puppet::ParseError, "sort(): Wrong number of arguments given #{arguments.size} for 1") end value = arguments[0] - if value.is_a?(Array) then + if value.is_a?(Array) value.sort - elsif value.is_a?(String) then - value.split("").sort.join("") + elsif value.is_a?(String) + value.split('').sort.join('') end - end end diff --git a/lib/puppet/parser/functions/squeeze.rb b/lib/puppet/parser/functions/squeeze.rb index f5757d1e8..2ce118db9 100644 --- a/lib/puppet/parser/functions/squeeze.rb +++ b/lib/puppet/parser/functions/squeeze.rb @@ -1,34 +1,30 @@ # # squeeze.rb # - module Puppet::Parser::Functions - newfunction(:squeeze, :type => :rvalue, :doc => <<-EOS -Returns a new string where runs of the same character that occur in this set are replaced by a single character. - EOS - ) do |arguments| + newfunction(:squeeze, type: :rvalue, doc: <<-EOS + Returns a new string where runs of the same character that occur in this set are replaced by a single character. + EOS + ) do |arguments| - if ((arguments.size != 2) and (arguments.size != 1)) then + if (arguments.size != 2) && (arguments.size != 1) raise(Puppet::ParseError, "squeeze(): Wrong number of arguments given #{arguments.size} for 2 or 1") end item = arguments[0] squeezeval = arguments[1] - if item.is_a?(Array) then - if squeezeval then - item.collect { |i| i.squeeze(squeezeval) } + if item.is_a?(Array) + if squeezeval + item.map { |i| i.squeeze(squeezeval) } else - item.collect { |i| i.squeeze } + item.map { |i| i.squeeze } end + elsif squeezeval + item.squeeze(squeezeval) else - if squeezeval then - item.squeeze(squeezeval) - else - item.squeeze - end + item.squeeze end - end end diff --git a/lib/puppet/parser/functions/str2bool.rb b/lib/puppet/parser/functions/str2bool.rb index 38ad1ce07..06d4c8d1d 100644 --- a/lib/puppet/parser/functions/str2bool.rb +++ b/lib/puppet/parser/functions/str2bool.rb @@ -1,21 +1,20 @@ # # str2bool.rb # - module Puppet::Parser::Functions - newfunction(:str2bool, :type => :rvalue, :doc => <<-EOS -This converts a string to a boolean. This attempt to convert strings that -contain things like: Y,y, 1, T,t, TRUE,true to 'true' and strings that contain things -like: 0, F,f, N,n, false, FALSE, no to 'false'. - EOS - ) do |arguments| + newfunction(:str2bool, type: :rvalue, doc: <<-EOS + This converts a string to a boolean. This attempt to convert strings that + contain things like: Y,y, 1, T,t, TRUE,true to 'true' and strings that contain things + like: 0, F,f, N,n, false, FALSE, no to 'false'. + EOS + ) do |arguments| - raise(Puppet::ParseError, "str2bool(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size < 1 + raise(Puppet::ParseError, "str2bool(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? string = arguments[0] # If string is already Boolean, return it - if !!string == string + if !!string == string # rubocop:disable Style/DoubleNegation : No viable alternative return string end @@ -25,17 +24,17 @@ module Puppet::Parser::Functions # We consider all the yes, no, y, n and so on too ... result = case string - # - # This is how undef looks like in Puppet ... - # We yield false in this case. - # - when /^$/, '' then false # Empty string will be false ... - when /^(1|t|y|true|yes)$/i then true - when /^(0|f|n|false|no)$/i then false - when /^(undef|undefined)$/ then false # This is not likely to happen ... - else - raise(Puppet::ParseError, 'str2bool(): Unknown type of boolean given') - end + # + # This is how undef looks like in Puppet ... + # We yield false in this case. + # + when %r{^$}, '' then false # Empty string will be false ... + when %r{^(1|t|y|true|yes)$}i then true + when %r{^(0|f|n|false|no)$}i then false + when %r{^(undef|undefined)$} then false # This is not likely to happen ... + else + raise(Puppet::ParseError, 'str2bool(): Unknown type of boolean given') + end return result end diff --git a/lib/puppet/parser/functions/str2saltedsha512.rb b/lib/puppet/parser/functions/str2saltedsha512.rb index 0410c62c1..d83f11822 100644 --- a/lib/puppet/parser/functions/str2saltedsha512.rb +++ b/lib/puppet/parser/functions/str2saltedsha512.rb @@ -2,15 +2,14 @@ # str2saltedsha512.rb # Please note: This function is an implementation of a Ruby class and as such may not be entirely UTF8 compatible. To ensure compatibility please use this function with Ruby 2.4.0 or greater - https://bugs.ruby-lang.org/issues/10085. # - module Puppet::Parser::Functions - newfunction(:str2saltedsha512, :type => :rvalue, :doc => <<-EOS -This converts a string to a salted-SHA512 password hash (which is used for -OS X versions >= 10.7). Given any simple string, you will get a hex version -of a salted-SHA512 password hash that can be inserted into your Puppet -manifests as a valid password attribute. + newfunction(:str2saltedsha512, type: :rvalue, doc: <<-EOS + This converts a string to a salted-SHA512 password hash (which is used for + OS X versions >= 10.7). Given any simple string, you will get a hex version + of a salted-SHA512 password hash that can be inserted into your Puppet + manifests as a valid password attribute. EOS - ) do |arguments| + ) do |arguments| require 'digest/sha2' raise(Puppet::ParseError, "str2saltedsha512(): Wrong number of arguments passed (#{arguments.size} but we require 1)") if arguments.size != 1 @@ -22,7 +21,7 @@ module Puppet::Parser::Functions end seedint = rand(2**31 - 1) - seedstring = Array(seedint).pack("L") + seedstring = Array(seedint).pack('L') saltedpass = Digest::SHA512.digest(seedstring + password) (seedstring + saltedpass).unpack('H*')[0] end diff --git a/lib/puppet/parser/functions/strftime.rb b/lib/puppet/parser/functions/strftime.rb index deae329bf..8429a9527 100644 --- a/lib/puppet/parser/functions/strftime.rb +++ b/lib/puppet/parser/functions/strftime.rb @@ -2,77 +2,76 @@ # strftime.rb # Please note: This function is an implementation of a Ruby class and as such may not be entirely UTF8 compatible. To ensure compatibility please use this function with Ruby 2.4.0 or greater - https://bugs.ruby-lang.org/issues/10085. # - module Puppet::Parser::Functions - newfunction(:strftime, :type => :rvalue, :doc => <<-EOS -This function returns formatted time. - -*Examples:* - -To return the time since epoch: - - strftime("%s") - -To return the date: - - strftime("%Y-%m-%d") - -*Format meaning:* - - %a - The abbreviated weekday name (``Sun'') - %A - The full weekday name (``Sunday'') - %b - The abbreviated month name (``Jan'') - %B - The full month name (``January'') - %c - The preferred local date and time representation - %C - Century (20 in 2009) - %d - Day of the month (01..31) - %D - Date (%m/%d/%y) - %e - Day of the month, blank-padded ( 1..31) - %F - Equivalent to %Y-%m-%d (the ISO 8601 date format) - %h - Equivalent to %b - %H - Hour of the day, 24-hour clock (00..23) - %I - Hour of the day, 12-hour clock (01..12) - %j - Day of the year (001..366) - %k - hour, 24-hour clock, blank-padded ( 0..23) - %l - hour, 12-hour clock, blank-padded ( 0..12) - %L - Millisecond of the second (000..999) - %m - Month of the year (01..12) - %M - Minute of the hour (00..59) - %n - Newline (\n) - %N - Fractional seconds digits, default is 9 digits (nanosecond) - %3N millisecond (3 digits) - %6N microsecond (6 digits) - %9N nanosecond (9 digits) - %p - Meridian indicator (``AM'' or ``PM'') - %P - Meridian indicator (``am'' or ``pm'') - %r - time, 12-hour (same as %I:%M:%S %p) - %R - time, 24-hour (%H:%M) - %s - Number of seconds since 1970-01-01 00:00:00 UTC. - %S - Second of the minute (00..60) - %t - Tab character (\t) - %T - time, 24-hour (%H:%M:%S) - %u - Day of the week as a decimal, Monday being 1. (1..7) - %U - Week number of the current year, - starting with the first Sunday as the first - day of the first week (00..53) - %v - VMS date (%e-%b-%Y) - %V - Week number of year according to ISO 8601 (01..53) - %W - Week number of the current year, - starting with the first Monday as the first - day of the first week (00..53) - %w - Day of the week (Sunday is 0, 0..6) - %x - Preferred representation for the date alone, no time - %X - Preferred representation for the time alone, no date - %y - Year without a century (00..99) - %Y - Year with century - %z - Time zone as hour offset from UTC (e.g. +0900) - %Z - Time zone name - %% - Literal ``%'' character + newfunction(:strftime, type: :rvalue, doc: <<-EOS + This function returns formatted time. + + *Examples:* + + To return the time since epoch: + + strftime("%s") + + To return the date: + + strftime("%Y-%m-%d") + + *Format meaning:* + + %a - The abbreviated weekday name (``Sun'') + %A - The full weekday name (``Sunday'') + %b - The abbreviated month name (``Jan'') + %B - The full month name (``January'') + %c - The preferred local date and time representation + %C - Century (20 in 2009) + %d - Day of the month (01..31) + %D - Date (%m/%d/%y) + %e - Day of the month, blank-padded ( 1..31) + %F - Equivalent to %Y-%m-%d (the ISO 8601 date format) + %h - Equivalent to %b + %H - Hour of the day, 24-hour clock (00..23) + %I - Hour of the day, 12-hour clock (01..12) + %j - Day of the year (001..366) + %k - hour, 24-hour clock, blank-padded ( 0..23) + %l - hour, 12-hour clock, blank-padded ( 0..12) + %L - Millisecond of the second (000..999) + %m - Month of the year (01..12) + %M - Minute of the hour (00..59) + %n - Newline (\n) + %N - Fractional seconds digits, default is 9 digits (nanosecond) + %3N millisecond (3 digits) + %6N microsecond (6 digits) + %9N nanosecond (9 digits) + %p - Meridian indicator (``AM'' or ``PM'') + %P - Meridian indicator (``am'' or ``pm'') + %r - time, 12-hour (same as %I:%M:%S %p) + %R - time, 24-hour (%H:%M) + %s - Number of seconds since 1970-01-01 00:00:00 UTC. + %S - Second of the minute (00..60) + %t - Tab character (\t) + %T - time, 24-hour (%H:%M:%S) + %u - Day of the week as a decimal, Monday being 1. (1..7) + %U - Week number of the current year, + starting with the first Sunday as the first + day of the first week (00..53) + %v - VMS date (%e-%b-%Y) + %V - Week number of year according to ISO 8601 (01..53) + %W - Week number of the current year, + starting with the first Monday as the first + day of the first week (00..53) + %w - Day of the week (Sunday is 0, 0..6) + %x - Preferred representation for the date alone, no time + %X - Preferred representation for the time alone, no date + %y - Year without a century (00..99) + %Y - Year with century + %z - Time zone as hour offset from UTC (e.g. +0900) + %Z - Time zone name + %% - Literal ``%'' character EOS - ) do |arguments| + ) do |arguments| # Technically we support two arguments but only first is mandatory ... - raise(Puppet::ParseError, "strftime(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size < 1 + raise(Puppet::ParseError, "strftime(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? format = arguments[0] @@ -84,7 +83,7 @@ module Puppet::Parser::Functions time = Time.new # There is probably a better way to handle Time Zone ... - if time_zone and not time_zone.empty? + if time_zone && !time_zone.empty? original_zone = ENV['TZ'] local_time = time.clone diff --git a/lib/puppet/parser/functions/strip.rb b/lib/puppet/parser/functions/strip.rb index 9e8366f3e..59ee166f3 100644 --- a/lib/puppet/parser/functions/strip.rb +++ b/lib/puppet/parser/functions/strip.rb @@ -1,21 +1,20 @@ # # strip.rb # - module Puppet::Parser::Functions - newfunction(:strip, :type => :rvalue, :doc => <<-EOS -This function removes leading and trailing whitespace from a string or from -every string inside an array. + newfunction(:strip, type: :rvalue, doc: <<-EOS + This function removes leading and trailing whitespace from a string or from + every string inside an array. -*Examples:* + *Examples:* - strip(" aaa ") + strip(" aaa ") -Would result in: "aaa" + Would result in: "aaa" EOS - ) do |arguments| + ) do |arguments| - raise(Puppet::ParseError, "strip(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size < 1 + raise(Puppet::ParseError, "strip(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? value = arguments[0] @@ -23,11 +22,11 @@ module Puppet::Parser::Functions raise(Puppet::ParseError, 'strip(): Requires either array or string to work with') end - if value.is_a?(Array) - result = value.collect { |i| i.is_a?(String) ? i.strip : i } - else - result = value.strip - end + result = if value.is_a?(Array) + value.map { |i| i.is_a?(String) ? i.strip : i } + else + value.strip + end return result end diff --git a/lib/puppet/parser/functions/suffix.rb b/lib/puppet/parser/functions/suffix.rb index 7c5057dcb..3dc86afce 100644 --- a/lib/puppet/parser/functions/suffix.rb +++ b/lib/puppet/parser/functions/suffix.rb @@ -1,26 +1,25 @@ # # suffix.rb # - module Puppet::Parser::Functions - newfunction(:suffix, :type => :rvalue, :doc => <<-EOS -This function applies a suffix to all elements in an array, or to the keys -in a hash. + newfunction(:suffix, type: :rvalue, doc: <<-EOS + This function applies a suffix to all elements in an array, or to the keys + in a hash. -*Examples:* + *Examples:* - suffix(['a','b','c'], 'p') + suffix(['a','b','c'], 'p') -Will return: ['ap','bp','cp'] + Will return: ['ap','bp','cp'] EOS - ) do |arguments| + ) do |arguments| # Technically we support two arguments but only first is mandatory ... - raise(Puppet::ParseError, "suffix(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size < 1 + raise(Puppet::ParseError, "suffix(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? enumerable = arguments[0] - unless enumerable.is_a?(Array) or enumerable.is_a?(Hash) + unless enumerable.is_a?(Array) || enumerable.is_a?(Hash) raise Puppet::ParseError, "suffix(): expected first argument to be an Array or a Hash, got #{enumerable.inspect}" end @@ -32,18 +31,18 @@ module Puppet::Parser::Functions end end - if enumerable.is_a?(Array) - # Turn everything into string same as join would do ... - result = enumerable.collect do |i| - i = i.to_s - suffix ? i + suffix : i - end - else - result = Hash[enumerable.map do |k,v| - k = k.to_s - [ suffix ? k + suffix : k, v ] - end] - end + result = if enumerable.is_a?(Array) + # Turn everything into string same as join would do ... + enumerable.map do |i| + i = i.to_s + suffix ? i + suffix : i + end + else + Hash[enumerable.map do |k, v| + k = k.to_s + [suffix ? k + suffix : k, v] + end] + end return result end diff --git a/lib/puppet/parser/functions/swapcase.rb b/lib/puppet/parser/functions/swapcase.rb index f3276fb5f..4da9ec0c1 100644 --- a/lib/puppet/parser/functions/swapcase.rb +++ b/lib/puppet/parser/functions/swapcase.rb @@ -2,20 +2,19 @@ # swapcase.rb # Please note: This function is an implementation of a Ruby class and as such may not be entirely UTF8 compatible. To ensure compatibility please use this function with Ruby 2.4.0 or greater - https://bugs.ruby-lang.org/issues/10085. # - module Puppet::Parser::Functions - newfunction(:swapcase, :type => :rvalue, :doc => <<-EOS -This function will swap the existing case of a string. + newfunction(:swapcase, type: :rvalue, doc: <<-EOS + This function will swap the existing case of a string. -*Examples:* + *Examples:* - swapcase("aBcD") + swapcase("aBcD") -Would result in: "AbCd" + Would result in: "AbCd" EOS - ) do |arguments| + ) do |arguments| - raise(Puppet::ParseError, "swapcase(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size < 1 + raise(Puppet::ParseError, "swapcase(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? value = arguments[0] @@ -23,12 +22,12 @@ module Puppet::Parser::Functions raise(Puppet::ParseError, 'swapcase(): Requires either array or string to work with') end - if value.is_a?(Array) - # Numbers in Puppet are often string-encoded which is troublesome ... - result = value.collect { |i| i.is_a?(String) ? i.swapcase : i } - else - result = value.swapcase - end + result = if value.is_a?(Array) + # Numbers in Puppet are often string-encoded which is troublesome ... + value.map { |i| i.is_a?(String) ? i.swapcase : i } + else + value.swapcase + end return result end diff --git a/lib/puppet/parser/functions/time.rb b/lib/puppet/parser/functions/time.rb index d7780c83d..cf7e29c04 100644 --- a/lib/puppet/parser/functions/time.rb +++ b/lib/puppet/parser/functions/time.rb @@ -1,30 +1,29 @@ # # time.rb # - module Puppet::Parser::Functions - newfunction(:time, :type => :rvalue, :doc => <<-EOS -This function will return the current time since epoch as an integer. + newfunction(:time, type: :rvalue, doc: <<-EOS + This function will return the current time since epoch as an integer. -*Examples:* + *Examples:* - time() + time() -Will return something like: 1311972653 + Will return something like: 1311972653 EOS - ) do |arguments| + ) do |arguments| # The Time Zone argument is optional ... time_zone = arguments[0] if arguments[0] - if (arguments.size != 0) and (arguments.size != 1) then + if !arguments.empty? && (arguments.size != 1) raise(Puppet::ParseError, "time(): Wrong number of arguments given #{arguments.size} for 0 or 1") end time = Time.new # There is probably a better way to handle Time Zone ... - if time_zone and not time_zone.empty? + if time_zone && !time_zone.empty? original_zone = ENV['TZ'] local_time = time.clone diff --git a/lib/puppet/parser/functions/to_bytes.rb b/lib/puppet/parser/functions/to_bytes.rb index bf72503f2..be735504c 100644 --- a/lib/puppet/parser/functions/to_bytes.rb +++ b/lib/puppet/parser/functions/to_bytes.rb @@ -1,11 +1,14 @@ +# +# to_bytes.rb +# module Puppet::Parser::Functions - newfunction(:to_bytes, :type => :rvalue, :doc => <<-EOS + newfunction(:to_bytes, type: :rvalue, doc: <<-EOS Converts the argument into bytes, for example 4 kB becomes 4096. Takes a single string value as an argument. These conversions reflect a layperson's understanding of 1 MB = 1024 KB, when in fact 1 MB = 1000 KB, and 1 MiB = 1024 KiB. EOS - ) do |arguments| + ) do |arguments| raise(Puppet::ParseError, "to_bytes(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size != 1 @@ -13,17 +16,17 @@ module Puppet::Parser::Functions return arg if arg.is_a? Numeric - value,prefix = */([0-9.e+-]*)\s*([^bB]?)/.match(arg)[1,2] + value, prefix = *%r{([0-9.e+-]*)\s*([^bB]?)}.match(arg)[1, 2] value = value.to_f case prefix when '' then return value.to_i - when 'k' then return (value*(1<<10)).to_i - when 'M' then return (value*(1<<20)).to_i - when 'G' then return (value*(1<<30)).to_i - when 'T' then return (value*(1<<40)).to_i - when 'P' then return (value*(1<<50)).to_i - when 'E' then return (value*(1<<60)).to_i + when 'k' then return (value * (1 << 10)).to_i + when 'M' then return (value * (1 << 20)).to_i + when 'G' then return (value * (1 << 30)).to_i + when 'T' then return (value * (1 << 40)).to_i + when 'P' then return (value * (1 << 50)).to_i + when 'E' then return (value * (1 << 60)).to_i else raise Puppet::ParseError, "to_bytes(): Unknown prefix #{prefix}" end end diff --git a/lib/puppet/parser/functions/try_get_value.rb b/lib/puppet/parser/functions/try_get_value.rb index fc19a230a..989d57650 100644 --- a/lib/puppet/parser/functions/try_get_value.rb +++ b/lib/puppet/parser/functions/try_get_value.rb @@ -1,43 +1,46 @@ +# +# try_get_value.rb +# module Puppet::Parser::Functions newfunction( - :try_get_value, - :type => :rvalue, - :arity => -2, - :doc => <<-eos -DEPRECATED: this function is deprecated, please use dig() instead. - -Looks up into a complex structure of arrays and hashes and returns a value -or the default value if nothing was found. - -Key can contain slashes to describe path components. The function will go down -the structure and try to extract the required value. - -$data = { - 'a' => { - 'b' => [ - 'b1', - 'b2', - 'b3', - ] - } -} - -$value = try_get_value($data, 'a/b/2', 'not_found', '/') -=> $value = 'b3' - -a -> first hash key -b -> second hash key -2 -> array index starting with 0 - -not_found -> (optional) will be returned if there is no value or the path did not match. Defaults to nil. -/ -> (optional) path delimiter. Defaults to '/'. - -In addition to the required "key" argument, "try_get_value" accepts default -argument. It will be returned if no value was found or a path component is -missing. And the fourth argument can set a variable path separator. - eos + :try_get_value, + type: :rvalue, + arity: -2, + doc: <<-eos + DEPRECATED: this function is deprecated, please use dig() instead. + + Looks up into a complex structure of arrays and hashes and returns a value + or the default value if nothing was found. + + Key can contain slashes to describe path components. The function will go down + the structure and try to extract the required value. + + $data = { + 'a' => { + 'b' => [ + 'b1', + 'b2', + 'b3', + ] + } + } + + $value = try_get_value($data, 'a/b/2', 'not_found', '/') + => $value = 'b3' + + a -> first hash key + b -> second hash key + 2 -> array index starting with 0 + + not_found -> (optional) will be returned if there is no value or the path did not match. Defaults to nil. + / -> (optional) path delimiter. Defaults to '/'. + + In addition to the required "key" argument, "try_get_value" accepts default + argument. It will be returned if no value was found or a path component is + missing. And the fourth argument can set a variable path separator. + eos ) do |args| - warning("try_get_value() DEPRECATED: this function is deprecated, please use dig() instead.") + warning('try_get_value() DEPRECATED: this function is deprecated, please use dig() instead.') data = args[0] path = args[1] || '' default = args[2] @@ -47,7 +50,7 @@ module Puppet::Parser::Functions end separator = args[3] || '/' - path = path.split(separator).map{ |key| key =~ /^\d+$/ ? key.to_i : key } + path = path.split(separator).map { |key| (key =~ %r{^\d+$}) ? key.to_i : key } function_dig([data, path, default]) end end diff --git a/lib/puppet/parser/functions/type.rb b/lib/puppet/parser/functions/type.rb index 016529b03..bb197a07c 100644 --- a/lib/puppet/parser/functions/type.rb +++ b/lib/puppet/parser/functions/type.rb @@ -1,15 +1,14 @@ # # type.rb # - module Puppet::Parser::Functions - newfunction(:type, :type => :rvalue, :doc => <<-EOS - DEPRECATED: This function will cease to function on Puppet 4; please use type3x() before upgrading to puppet 4 for backwards-compatibility, or migrate to the new parser's typing system. - EOS - ) do |args| + newfunction(:type, type: :rvalue, doc: <<-EOS + DEPRECATED: This function will cease to function on Puppet 4; please use type3x() before upgrading to puppet 4 for backwards-compatibility, or migrate to the new parser's typing system. + EOS + ) do |args| - warning("type() DEPRECATED: This function will cease to function on Puppet 4; please use type3x() before upgrading to puppet 4 for backwards-compatibility, or migrate to the new parser's typing system.") - if ! Puppet::Parser::Functions.autoloader.loaded?(:type3x) + warning("type() DEPRECATED: This function will cease to function on Puppet 4; please use type3x() before upgrading to puppet 4 for backwards-compatibility, or migrate to the new parser's typing system.") # rubocop:disable Metrics/LineLength : Cannot reduce line length + unless Puppet::Parser::Functions.autoloader.loaded?(:type3x) Puppet::Parser::Functions.autoloader.load(:type3x) end function_type3x(args + [false]) diff --git a/lib/puppet/parser/functions/type3x.rb b/lib/puppet/parser/functions/type3x.rb index b17380e70..ae794ded5 100644 --- a/lib/puppet/parser/functions/type3x.rb +++ b/lib/puppet/parser/functions/type3x.rb @@ -1,28 +1,27 @@ # # type3x.rb # - module Puppet::Parser::Functions - newfunction(:type3x, :type => :rvalue, :doc => <<-EOS -DEPRECATED: This function will be removed when puppet 3 support is dropped; please migrate to the new parser's typing system. + newfunction(:type3x, type: :rvalue, doc: <<-EOS + DEPRECATED: This function will be removed when puppet 3 support is dropped; please migrate to the new parser's typing system. -Returns the type when passed a value. Type can be one of: + Returns the type when passed a value. Type can be one of: -* string -* array -* hash -* float -* integer -* boolean - EOS - ) do |args| - raise(Puppet::ParseError, "type3x(): Wrong number of arguments given (#{args.size} for 1)") if args.size < 1 + * string + * array + * hash + * float + * integer + * boolean + EOS + ) do |args| + raise(Puppet::ParseError, "type3x(): Wrong number of arguments given (#{args.size} for 1)") if args.empty? value = args[0] klass = value.class - if not [TrueClass, FalseClass, Array, Bignum, Fixnum, Float, Hash, String].include?(klass) + unless [TrueClass, FalseClass, Array, Integer, Integer, Float, Hash, String].include?(klass) raise(Puppet::ParseError, 'type3x(): Unknown type') end @@ -30,16 +29,16 @@ module Puppet::Parser::Functions # We note that Integer is the parent to Bignum and Fixnum ... result = case klass - when /^(?:Big|Fix)num$/ then 'integer' - when /^(?:True|False)Class$/ then 'boolean' - else klass - end - - if result == "String" then - if value == value.to_i.to_s then - result = "Integer" - elsif value == value.to_f.to_s then - result = "Float" + when %r{^(?:Big|Fix)num$} then 'integer' + when %r{^(?:True|False)Class$} then 'boolean' + else klass + end + + if result == 'String' + if value == value.to_i.to_s + result = 'Integer' + elsif value == value.to_f.to_s + result = 'Float' end end diff --git a/lib/puppet/parser/functions/union.rb b/lib/puppet/parser/functions/union.rb index abe2dc88a..2543408e2 100644 --- a/lib/puppet/parser/functions/union.rb +++ b/lib/puppet/parser/functions/union.rb @@ -1,18 +1,17 @@ # # union.rb # - module Puppet::Parser::Functions - newfunction(:union, :type => :rvalue, :doc => <<-EOS -This function returns a union of two or more arrays. + newfunction(:union, type: :rvalue, doc: <<-EOS + This function returns a union of two or more arrays. -*Examples:* + *Examples:* - union(["a","b","c"],["b","c","d"]) + union(["a","b","c"],["b","c","d"]) -Would return: ["a","b","c","d"] + Would return: ["a","b","c","d"] EOS - ) do |arguments| + ) do |arguments| # Check that 2 or more arguments have been given ... raise(Puppet::ParseError, "union(): Wrong number of arguments given (#{arguments.size} for < 2)") if arguments.size < 2 diff --git a/lib/puppet/parser/functions/unique.rb b/lib/puppet/parser/functions/unique.rb index 1e2a895b5..b7c627f48 100644 --- a/lib/puppet/parser/functions/unique.rb +++ b/lib/puppet/parser/functions/unique.rb @@ -1,34 +1,33 @@ # # unique.rb # - module Puppet::Parser::Functions - newfunction(:unique, :type => :rvalue, :doc => <<-EOS -This function will remove duplicates from strings and arrays. + newfunction(:unique, type: :rvalue, doc: <<-EOS + This function will remove duplicates from strings and arrays. -*Examples:* + *Examples:* - unique("aabbcc") + unique("aabbcc") -Will return: + Will return: - abc + abc -You can also use this with arrays: + You can also use this with arrays: - unique(["a","a","b","b","c","c"]) + unique(["a","a","b","b","c","c"]) -This returns: + This returns: - ["a","b","c"] + ["a","b","c"] EOS - ) do |arguments| + ) do |arguments| if Puppet::Util::Package.versioncmp(Puppet.version, '5.0.0') >= 0 function_deprecation([:unique, 'This method is deprecated, please use the core puppet unique function. There is further documentation for the function in the release notes of Puppet 5.0.']) end - raise(Puppet::ParseError, "unique(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size < 1 + raise(Puppet::ParseError, "unique(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? value = arguments[0] diff --git a/lib/puppet/parser/functions/unix2dos.rb b/lib/puppet/parser/functions/unix2dos.rb index 0bd9cd1f1..719c6d936 100644 --- a/lib/puppet/parser/functions/unix2dos.rb +++ b/lib/puppet/parser/functions/unix2dos.rb @@ -1,15 +1,15 @@ # Custom Puppet function to convert unix to dos format module Puppet::Parser::Functions - newfunction(:unix2dos, :type => :rvalue, :arity => 1, :doc => <<-EOS + newfunction(:unix2dos, type: :rvalue, arity: 1, doc: <<-EOS Returns the DOS version of the given string. Takes a single string argument. EOS - ) do |arguments| + ) do |arguments| unless arguments[0].is_a?(String) raise(Puppet::ParseError, 'unix2dos(): Requires string as argument') end - arguments[0].gsub(/\r*\n/, "\r\n") + arguments[0].gsub(%r{\r*\n}, "\r\n") end end diff --git a/lib/puppet/parser/functions/upcase.rb b/lib/puppet/parser/functions/upcase.rb index e847e5170..033b5731d 100644 --- a/lib/puppet/parser/functions/upcase.rb +++ b/lib/puppet/parser/functions/upcase.rb @@ -2,20 +2,19 @@ # upcase.rb # Please note: This function is an implementation of a Ruby class and as such may not be entirely UTF8 compatible. To ensure compatibility please use this function with Ruby 2.4.0 or greater - https://bugs.ruby-lang.org/issues/10085. # - module Puppet::Parser::Functions - newfunction(:upcase, :type => :rvalue, :doc => <<-EOS -Converts a string or an array of strings to uppercase. + newfunction(:upcase, type: :rvalue, doc: <<-EOS + Converts a string or an array of strings to uppercase. -*Examples:* + *Examples:* - upcase("abcd") + upcase("abcd") -Will return: + Will return: - ABCD + ABCD EOS - ) do |arguments| + ) do |arguments| raise(Puppet::ParseError, "upcase(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size != 1 @@ -27,7 +26,7 @@ module Puppet::Parser::Functions if value.is_a?(Array) # Numbers in Puppet are often string-encoded which is troublesome ... - result = value.collect { |i| function_upcase([i]) } + result = value.map { |i| function_upcase([i]) } elsif value.is_a?(Hash) result = {} value.each_pair do |k, v| diff --git a/lib/puppet/parser/functions/uriescape.rb b/lib/puppet/parser/functions/uriescape.rb index 4c5c40036..726f7f99a 100644 --- a/lib/puppet/parser/functions/uriescape.rb +++ b/lib/puppet/parser/functions/uriescape.rb @@ -1,17 +1,16 @@ +require 'uri' # # uriescape.rb # Please note: This function is an implementation of a Ruby class and as such may not be entirely UTF8 compatible. To ensure compatibility please use this function with Ruby 2.4.0 or greater - https://bugs.ruby-lang.org/issues/10085. # -require 'uri' - module Puppet::Parser::Functions - newfunction(:uriescape, :type => :rvalue, :doc => <<-EOS + newfunction(:uriescape, type: :rvalue, doc: <<-EOS Urlencodes a string or array of strings. Requires either a single string or an array as an input. EOS - ) do |arguments| + ) do |arguments| - raise(Puppet::ParseError, "uriescape(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size < 1 + raise(Puppet::ParseError, "uriescape(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? value = arguments[0] @@ -19,12 +18,12 @@ module Puppet::Parser::Functions raise(Puppet::ParseError, 'uriescape(): Requires either array or string to work with') end - if value.is_a?(Array) - # Numbers in Puppet are often string-encoded which is troublesome ... - result = value.collect { |i| i.is_a?(String) ? URI.escape(i) : i } - else - result = URI.escape(value) - end + result = if value.is_a?(Array) + # Numbers in Puppet are often string-encoded which is troublesome ... + value.map { |i| i.is_a?(String) ? URI.escape(i) : i } + else + URI.escape(value) + end return result end diff --git a/lib/puppet/parser/functions/validate_absolute_path.rb b/lib/puppet/parser/functions/validate_absolute_path.rb index c73f3dfed..212bbacd0 100644 --- a/lib/puppet/parser/functions/validate_absolute_path.rb +++ b/lib/puppet/parser/functions/validate_absolute_path.rb @@ -1,5 +1,8 @@ +# +# validate_absolute_path.rb +# module Puppet::Parser::Functions - newfunction(:validate_absolute_path, :doc => <<-'ENDHEREDOC') do |args| + newfunction(:validate_absolute_path, doc: <<-'ENDHEREDOC') do |args| Validate the string represents an absolute path in the filesystem. This function works for windows and unix style paths. @@ -26,13 +29,10 @@ module Puppet::Parser::Functions ENDHEREDOC - # The deprecation function was being called twice, as validate_absolute_path calls is_absolute_path. I have removed it from here so it only calls deprecation once within is_absolute_path. - # function_deprecation([:validate_absolute_path, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Absolute_path. There is further documentation for validate_legacy function in the README.']) - require 'puppet/util' - unless args.length > 0 then - raise Puppet::ParseError, ("validate_absolute_path(): wrong number of arguments (#{args.length}; must be > 0)") + if args.empty? + raise Puppet::ParseError, "validate_absolute_path(): wrong number of arguments (#{args.length}; must be > 0)" end args.each do |arg| @@ -40,13 +40,13 @@ module Puppet::Parser::Functions candidates = arg # if arg is just a string with a path to test, convert it to an array # to avoid test code duplication - unless arg.is_a?(Array) then - candidates = Array.new(1,arg) + unless arg.is_a?(Array) + candidates = Array.new(1, arg) end # iterate over all paths within the candidates array candidates.each do |path| unless function_is_absolute_path([path]) - raise Puppet::ParseError, ("#{path.inspect} is not an absolute path.") + raise Puppet::ParseError, "#{path.inspect} is not an absolute path." end end end diff --git a/lib/puppet/parser/functions/validate_array.rb b/lib/puppet/parser/functions/validate_array.rb index 3bf398350..9ae58a6ea 100644 --- a/lib/puppet/parser/functions/validate_array.rb +++ b/lib/puppet/parser/functions/validate_array.rb @@ -1,6 +1,8 @@ +# +# validate_array.rb +# module Puppet::Parser::Functions - - newfunction(:validate_array, :doc => <<-'ENDHEREDOC') do |args| + newfunction(:validate_array, doc: <<-'ENDHEREDOC') do |args| Validate that all passed values are array data structures. Abort catalog compilation if any value fails this check. @@ -18,18 +20,17 @@ module Puppet::Parser::Functions ENDHEREDOC - function_deprecation([:validate_array, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Array. There is further documentation for validate_legacy function in the README.']) + function_deprecation([:validate_array, 'This method is deprecated, please use the stdlib validate_legacy function, + with Stdlib::Compat::Array. There is further documentation for validate_legacy function in the README.']) - unless args.length > 0 then - raise Puppet::ParseError, ("validate_array(): wrong number of arguments (#{args.length}; must be > 0)") + if args.empty? + raise Puppet::ParseError, "validate_array(): wrong number of arguments (#{args.length}; must be > 0)" end args.each do |arg| unless arg.is_a?(Array) - raise Puppet::ParseError, ("#{arg.inspect} is not an Array. It looks to be a #{arg.class}") + raise Puppet::ParseError, "#{arg.inspect} is not an Array. It looks to be a #{arg.class}" end end - end - end diff --git a/lib/puppet/parser/functions/validate_augeas.rb b/lib/puppet/parser/functions/validate_augeas.rb index 2196c3e0e..5be54e8f1 100644 --- a/lib/puppet/parser/functions/validate_augeas.rb +++ b/lib/puppet/parser/functions/validate_augeas.rb @@ -1,7 +1,10 @@ require 'tempfile' +# +# validate_augaes.rb +# module Puppet::Parser::Functions - newfunction(:validate_augeas, :doc => <<-'ENDHEREDOC') do |args| + newfunction(:validate_augeas, doc: <<-'ENDHEREDOC') do |args| Perform validation of a string using an Augeas lens The first argument of this function should be a string to test, and the second argument should be the name of the Augeas lens to use. @@ -31,22 +34,22 @@ module Puppet::Parser::Functions ENDHEREDOC unless Puppet.features.augeas? - raise Puppet::ParseError, ("validate_augeas(): this function requires the augeas feature. See http://docs.puppetlabs.com/guides/augeas.html#pre-requisites for how to activate it.") + raise Puppet::ParseError, 'validate_augeas(): this function requires the augeas feature. See http://docs.puppetlabs.com/guides/augeas.html#pre-requisites for how to activate it.' end - if (args.length < 2) or (args.length > 4) then - raise Puppet::ParseError, ("validate_augeas(): wrong number of arguments (#{args.length}; must be 2, 3, or 4)") + if (args.length < 2) || (args.length > 4) + raise Puppet::ParseError, "validate_augeas(): wrong number of arguments (#{args.length}; must be 2, 3, or 4)" end msg = args[3] || "validate_augeas(): Failed to validate content against #{args[1].inspect}" require 'augeas' - aug = Augeas::open(nil, nil, Augeas::NO_MODL_AUTOLOAD) + aug = Augeas.open(nil, nil, Augeas::NO_MODL_AUTOLOAD) begin content = args[0] # Test content in a temporary file - tmpfile = Tempfile.new("validate_augeas") + tmpfile = Tempfile.new('validate_augeas') begin tmpfile.write(content) ensure @@ -56,16 +59,16 @@ module Puppet::Parser::Functions # Check for syntax lens = args[1] aug.transform( - :lens => lens, - :name => 'Validate_augeas', - :incl => tmpfile.path + lens: lens, + name: 'Validate_augeas', + incl: tmpfile.path, ) aug.load! unless aug.match("/augeas/files#{tmpfile.path}//error").empty? error = aug.get("/augeas/files#{tmpfile.path}//error/message") msg += " with error: #{error}" - raise Puppet::ParseError, (msg) + raise Puppet::ParseError, msg end # Launch unit tests @@ -73,7 +76,7 @@ module Puppet::Parser::Functions aug.defvar('file', "/files#{tmpfile.path}") tests.each do |t| msg += " testing path #{t}" - raise Puppet::ParseError, (msg) unless aug.match(t).empty? + raise Puppet::ParseError, msg unless aug.match(t).empty? end ensure aug.close diff --git a/lib/puppet/parser/functions/validate_bool.rb b/lib/puppet/parser/functions/validate_bool.rb index 49075b833..97852c6ca 100644 --- a/lib/puppet/parser/functions/validate_bool.rb +++ b/lib/puppet/parser/functions/validate_bool.rb @@ -1,6 +1,8 @@ +# +# validate_bool.rb +# module Puppet::Parser::Functions - - newfunction(:validate_bool, :doc => <<-'ENDHEREDOC') do |args| + newfunction(:validate_bool, doc: <<-'ENDHEREDOC') do |args| Validate that all passed values are either true or false. Abort catalog compilation if any value fails this check. @@ -19,19 +21,14 @@ module Puppet::Parser::Functions ENDHEREDOC - # The deprecation function was being called twice, as validate_bool calls is_bool. I have removed it from here so it only calls deprecation once within is_bool. - # function_deprecation([:validate_bool, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Bool. There is further documentation for validate_legacy function in the README.']) - - unless args.length > 0 then - raise Puppet::ParseError, ("validate_bool(): wrong number of arguments (#{args.length}; must be > 0)") + if args.empty? + raise Puppet::ParseError, "validate_bool(): wrong number of arguments (#{args.length}; must be > 0)" end args.each do |arg| unless function_is_bool([arg]) - raise Puppet::ParseError, ("#{arg.inspect} is not a boolean. It looks to be a #{arg.class}") + raise Puppet::ParseError, "#{arg.inspect} is not a boolean. It looks to be a #{arg.class}" end end - end - end diff --git a/lib/puppet/parser/functions/validate_cmd.rb b/lib/puppet/parser/functions/validate_cmd.rb index 685162b0c..49eec5a96 100644 --- a/lib/puppet/parser/functions/validate_cmd.rb +++ b/lib/puppet/parser/functions/validate_cmd.rb @@ -1,8 +1,11 @@ require 'puppet/util/execution' require 'tempfile' +# +# validate_cmd.rb +# module Puppet::Parser::Functions - newfunction(:validate_cmd, :doc => <<-'ENDHEREDOC') do |args| + newfunction(:validate_cmd, doc: <<-'ENDHEREDOC') do |args| Perform validation of a string with an external command. The first argument of this function should be a string to test, and the second argument should be a path to a test command @@ -24,8 +27,8 @@ module Puppet::Parser::Functions validate_cmd($haproxycontent, '/usr/sbin/haproxy -f % -c', 'Haproxy failed to validate config content') ENDHEREDOC - if (args.length < 2) or (args.length > 3) then - raise Puppet::ParseError, ("validate_cmd(): wrong number of arguments (#{args.length}; must be 2 or 3)") + if (args.length < 2) || (args.length > 3) + raise Puppet::ParseError, "validate_cmd(): wrong number of arguments (#{args.length}; must be 2 or 3)" end msg = args[2] || "validate_cmd(): failed to validate content with command #{args[1].inspect}" @@ -34,16 +37,16 @@ module Puppet::Parser::Functions checkscript = args[1] # Test content in a temporary file - tmpfile = Tempfile.new("validate_cmd") + tmpfile = Tempfile.new('validate_cmd') begin tmpfile.write(content) tmpfile.close - if checkscript =~ /\s%(\s|$)/ - check_with_correct_location = checkscript.gsub(/%/,tmpfile.path) - else - check_with_correct_location = "#{checkscript} #{tmpfile.path}" - end + check_with_correct_location = if checkscript =~ %r{\s%(\s|$)} + checkscript.gsub(%r{%}, tmpfile.path) + else + "#{checkscript} #{tmpfile.path}" + end if Puppet::Util::Execution.respond_to?('execute') Puppet::Util::Execution.execute(check_with_correct_location) diff --git a/lib/puppet/parser/functions/validate_domain_name.rb b/lib/puppet/parser/functions/validate_domain_name.rb index c3fad78ab..dd6b8e86a 100644 --- a/lib/puppet/parser/functions/validate_domain_name.rb +++ b/lib/puppet/parser/functions/validate_domain_name.rb @@ -1,5 +1,8 @@ +# +# validate_domain_name.rb +# module Puppet::Parser::Functions - newfunction(:validate_domain_name, :doc => <<-ENDHEREDOC + newfunction(:validate_domain_name, doc: <<-ENDHEREDOC Validate that all values passed are syntactically correct domain names. Fail compilation if any value fails this check. @@ -18,7 +21,7 @@ module Puppet::Parser::Functions validate_domain_name('www.example.2com') ENDHEREDOC - ) do |args| + ) do |args| rescuable_exceptions = [ArgumentError] diff --git a/lib/puppet/parser/functions/validate_email_address.rb b/lib/puppet/parser/functions/validate_email_address.rb index ddd0d25f1..f9765adf0 100644 --- a/lib/puppet/parser/functions/validate_email_address.rb +++ b/lib/puppet/parser/functions/validate_email_address.rb @@ -1,5 +1,8 @@ +# +# validate_email_address.rb +# module Puppet::Parser::Functions - newfunction(:validate_email_address, :doc => <<-ENDHEREDOC + newfunction(:validate_email_address, doc: <<-ENDHEREDOC Validate that all values passed are valid email addresses. Fail compilation if any value fails this check. The following values will pass: diff --git a/lib/puppet/parser/functions/validate_hash.rb b/lib/puppet/parser/functions/validate_hash.rb index fcdc7e1d8..3ecaad121 100644 --- a/lib/puppet/parser/functions/validate_hash.rb +++ b/lib/puppet/parser/functions/validate_hash.rb @@ -1,6 +1,8 @@ +# +# validate_hash.rb +# module Puppet::Parser::Functions - - newfunction(:validate_hash, :doc => <<-'ENDHEREDOC') do |args| + newfunction(:validate_hash, doc: <<-'ENDHEREDOC') do |args| Validate that all passed values are hash data structures. Abort catalog compilation if any value fails this check. @@ -18,18 +20,17 @@ module Puppet::Parser::Functions ENDHEREDOC - function_deprecation([:validate_hash, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Hash. There is further documentation for validate_legacy function in the README.']) + function_deprecation([:validate_hash, 'This method is deprecated, please use the stdlib validate_legacy function, + with Stdlib::Compat::Hash. There is further documentation for validate_legacy function in the README.']) - unless args.length > 0 then - raise Puppet::ParseError, ("validate_hash(): wrong number of arguments (#{args.length}; must be > 0)") + if args.empty? + raise Puppet::ParseError, "validate_hash(): wrong number of arguments (#{args.length}; must be > 0)" end args.each do |arg| unless arg.is_a?(Hash) - raise Puppet::ParseError, ("#{arg.inspect} is not a Hash. It looks to be a #{arg.class}") + raise Puppet::ParseError, "#{arg.inspect} is not a Hash. It looks to be a #{arg.class}" end end - end - end diff --git a/lib/puppet/parser/functions/validate_integer.rb b/lib/puppet/parser/functions/validate_integer.rb index 2ae02931b..d0d23ede3 100644 --- a/lib/puppet/parser/functions/validate_integer.rb +++ b/lib/puppet/parser/functions/validate_integer.rb @@ -1,6 +1,8 @@ +# +# validate_interger.rb +# module Puppet::Parser::Functions - - newfunction(:validate_integer, :doc => <<-'ENDHEREDOC') do |args| + newfunction(:validate_integer, doc: <<-'ENDHEREDOC') do |args| Validate that the first argument is an integer (or an array of integers). Abort catalog compilation if any of the checks fail. The second argument is optional and passes a maximum. (All elements of) the first argument has to be less or equal to this max. @@ -53,10 +55,11 @@ module Puppet::Parser::Functions ENDHEREDOC - function_deprecation([:validate_integer, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Integer. There is further documentation for validate_legacy function in the README.']) + function_deprecation([:validate_integer, 'This method is deprecated, please use the stdlib validate_legacy function, + with Stdlib::Compat::Integer. There is further documentation for validate_legacy function in the README.']) # tell the user we need at least one, and optionally up to two other parameters - raise Puppet::ParseError, "validate_integer(): Wrong number of arguments; must be 1, 2 or 3, got #{args.length}" unless args.length > 0 and args.length < 4 + raise Puppet::ParseError, "validate_integer(): Wrong number of arguments; must be 1, 2 or 3, got #{args.length}" unless !args.empty? && args.length < 4 input, max, min = *args @@ -64,7 +67,7 @@ module Puppet::Parser::Functions if args.length > 1 max = max.to_s # allow max to be empty (or undefined) if we have a minimum set - if args.length > 2 and max == '' + if args.length > 2 && max == '' max = nil else begin @@ -89,18 +92,18 @@ module Puppet::Parser::Functions end # ensure that min < max - if min and max and min > max + if min && max && min > max raise Puppet::ParseError, "validate_integer(): Expected second argument to be larger than third argument, got #{max} < #{min}" end # create lamba validator function - validator = lambda do |num| + validator = ->(num) do # check input < max - if max and num > max + if max && num > max raise Puppet::ParseError, "validate_integer(): Expected #{input.inspect} to be smaller or equal to #{max}, got #{input.inspect}." end # check input > min (this will only be checked if no exception has been raised before) - if min and num < min + if min && num < min raise Puppet::ParseError, "validate_integer(): Expected #{input.inspect} to be greater or equal to #{min}, got #{input.inspect}." end end diff --git a/lib/puppet/parser/functions/validate_ip_address.rb b/lib/puppet/parser/functions/validate_ip_address.rb index 5d80cfbe6..2657da2f6 100644 --- a/lib/puppet/parser/functions/validate_ip_address.rb +++ b/lib/puppet/parser/functions/validate_ip_address.rb @@ -1,6 +1,8 @@ +# +# validate_ip_address.rb +# module Puppet::Parser::Functions - - newfunction(:validate_ip_address, :doc => <<-ENDHEREDOC + newfunction(:validate_ip_address, doc: <<-ENDHEREDOC Validate that all values passed are valid IP addresses, regardless they are IPv4 or IPv6 Fail compilation if any value fails this check. @@ -18,19 +20,20 @@ module Puppet::Parser::Functions $some_array = [ 1, true, false, "garbage string", "3ffe:505:2" ] validate_ip_address($some_array) ENDHEREDOC - ) do |args| + ) do |args| - require "ipaddr" - rescuable_exceptions = [ ArgumentError ] + require 'ipaddr' + rescuable_exceptions = [ArgumentError] - function_deprecation([:validate_ip_address, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Ip_address. There is further documentation for validate_legacy function in the README.']) + function_deprecation([:validate_ip_address, 'This method is deprecated, please use the stdlib validate_legacy function, + with Stdlib::Compat::Ip_address. There is further documentation for validate_legacy function in the README.']) if defined?(IPAddr::InvalidAddressError) rescuable_exceptions << IPAddr::InvalidAddressError end - unless args.length > 0 then - raise Puppet::ParseError, ("validate_ip_address(): wrong number of arguments (#{args.length}; must be > 0)") + if args.empty? + raise Puppet::ParseError, "validate_ip_address(): wrong number of arguments (#{args.length}; must be > 0)" end args.each do |arg| @@ -39,14 +42,12 @@ module Puppet::Parser::Functions end begin - unless IPAddr.new(arg).ipv4? or IPAddr.new(arg).ipv6? + unless IPAddr.new(arg).ipv4? || IPAddr.new(arg).ipv6? raise Puppet::ParseError, "#{arg.inspect} is not a valid IP address." end rescue *rescuable_exceptions raise Puppet::ParseError, "#{arg.inspect} is not a valid IP address." end end - end - end diff --git a/lib/puppet/parser/functions/validate_ipv4_address.rb b/lib/puppet/parser/functions/validate_ipv4_address.rb index 0660abdf5..e8651b51f 100644 --- a/lib/puppet/parser/functions/validate_ipv4_address.rb +++ b/lib/puppet/parser/functions/validate_ipv4_address.rb @@ -1,6 +1,8 @@ +# +# validate_ipv4_address.rb +# module Puppet::Parser::Functions - - newfunction(:validate_ipv4_address, :doc => <<-ENDHEREDOC + newfunction(:validate_ipv4_address, doc: <<-ENDHEREDOC Validate that all values passed are valid IPv4 addresses. Fail compilation if any value fails this check. @@ -16,19 +18,20 @@ module Puppet::Parser::Functions validate_ipv4_address($some_array) ENDHEREDOC - ) do |args| + ) do |args| - function_deprecation([:validate_ipv4_address, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Ipv4. There is further documentation for validate_legacy function in the README.']) + function_deprecation([:validate_ipv4_address, 'This method is deprecated, please use the stdlib validate_legacy function, + with Stdlib::Compat::Ipv4. There is further documentation for validate_legacy function in the README.']) - require "ipaddr" - rescuable_exceptions = [ ArgumentError ] + require 'ipaddr' + rescuable_exceptions = [ArgumentError] if defined?(IPAddr::InvalidAddressError) rescuable_exceptions << IPAddr::InvalidAddressError end - unless args.length > 0 then - raise Puppet::ParseError, ("validate_ipv4_address(): wrong number of arguments (#{args.length}; must be > 0)") + if args.empty? + raise Puppet::ParseError, "validate_ipv4_address(): wrong number of arguments (#{args.length}; must be > 0)" end args.each do |arg| @@ -44,7 +47,5 @@ module Puppet::Parser::Functions raise Puppet::ParseError, "#{arg.inspect} is not a valid IPv4 address." end end - end - end diff --git a/lib/puppet/parser/functions/validate_ipv6_address.rb b/lib/puppet/parser/functions/validate_ipv6_address.rb index f5dd9e500..8a0c3d342 100644 --- a/lib/puppet/parser/functions/validate_ipv6_address.rb +++ b/lib/puppet/parser/functions/validate_ipv6_address.rb @@ -1,6 +1,8 @@ +# +# validate_ipv7_address.rb +# module Puppet::Parser::Functions - - newfunction(:validate_ipv6_address, :doc => <<-ENDHEREDOC + newfunction(:validate_ipv6_address, doc: <<-ENDHEREDOC Validate that all values passed are valid IPv6 addresses. Fail compilation if any value fails this check. @@ -17,19 +19,20 @@ module Puppet::Parser::Functions validate_ipv6_address($some_array) ENDHEREDOC - ) do |args| + ) do |args| - function_deprecation([:validate_ipv6_address, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Ipv6. There is further documentation for validate_legacy function in the README.']) + function_deprecation([:validate_ipv6_address, 'This method is deprecated, please use the stdlib validate_legacy function, + with Stdlib::Compat::Ipv6. There is further documentation for validate_legacy function in the README.']) - require "ipaddr" - rescuable_exceptions = [ ArgumentError ] + require 'ipaddr' + rescuable_exceptions = [ArgumentError] if defined?(IPAddr::InvalidAddressError) rescuable_exceptions << IPAddr::InvalidAddressError end - unless args.length > 0 then - raise Puppet::ParseError, ("validate_ipv6_address(): wrong number of arguments (#{args.length}; must be > 0)") + if args.empty? + raise Puppet::ParseError, "validate_ipv6_address(): wrong number of arguments (#{args.length}; must be > 0)" end args.each do |arg| @@ -45,7 +48,5 @@ module Puppet::Parser::Functions raise Puppet::ParseError, "#{arg.inspect} is not a valid IPv6 address." end end - end - end diff --git a/lib/puppet/parser/functions/validate_numeric.rb b/lib/puppet/parser/functions/validate_numeric.rb index 4205b30d8..a87083f33 100644 --- a/lib/puppet/parser/functions/validate_numeric.rb +++ b/lib/puppet/parser/functions/validate_numeric.rb @@ -1,6 +1,8 @@ +# +# validate_numeric.rb +# module Puppet::Parser::Functions - - newfunction(:validate_numeric, :doc => <<-'ENDHEREDOC') do |args| + newfunction(:validate_numeric, doc: <<-'ENDHEREDOC') do |args| Validate that the first argument is a numeric value (or an array of numeric values). Abort catalog compilation if any of the checks fail. The second argument is optional and passes a maximum. (All elements of) the first argument has to be less or equal to this max. @@ -15,10 +17,11 @@ module Puppet::Parser::Functions ENDHEREDOC - function_deprecation([:validate_numeric, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Numeric. There is further documentation for validate_legacy function in the README.']) + function_deprecation([:validate_numeric, 'This method is deprecated, please use the stdlib validate_legacy function, + with Stdlib::Compat::Numeric. There is further documentation for validate_legacy function in the README.']) # tell the user we need at least one, and optionally up to two other parameters - raise Puppet::ParseError, "validate_numeric(): Wrong number of arguments; must be 1, 2 or 3, got #{args.length}" unless args.length > 0 and args.length < 4 + raise Puppet::ParseError, "validate_numeric(): Wrong number of arguments; must be 1, 2 or 3, got #{args.length}" unless !args.empty? && args.length < 4 input, max, min = *args @@ -26,7 +29,7 @@ module Puppet::Parser::Functions if args.length > 1 max = max.to_s # allow max to be empty (or undefined) if we have a minimum set - if args.length > 2 and max == '' + if args.length > 2 && max == '' max = nil else begin @@ -51,18 +54,18 @@ module Puppet::Parser::Functions end # ensure that min < max - if min and max and min > max + if min && max && min > max raise Puppet::ParseError, "validate_numeric(): Expected second argument to be larger than third argument, got #{max} < #{min}" end # create lamba validator function - validator = lambda do |num| + validator = ->(num) do # check input < max - if max and num > max + if max && num > max raise Puppet::ParseError, "validate_numeric(): Expected #{input.inspect} to be smaller or equal to #{max}, got #{input.inspect}." end # check input > min (this will only be checked if no exception has been raised before) - if min and num < min + if min && num < min raise Puppet::ParseError, "validate_numeric(): Expected #{input.inspect} to be greater or equal to #{min}, got #{input.inspect}." end end diff --git a/lib/puppet/parser/functions/validate_re.rb b/lib/puppet/parser/functions/validate_re.rb index 0ac83ddca..d3578aa24 100644 --- a/lib/puppet/parser/functions/validate_re.rb +++ b/lib/puppet/parser/functions/validate_re.rb @@ -1,5 +1,8 @@ +# +# validate.rb +# module Puppet::Parser::Functions - newfunction(:validate_re, :doc => <<-'ENDHEREDOC') do |args| + newfunction(:validate_re, doc: <<-'ENDHEREDOC') do |args| Perform simple validation of a string against one or more regular expressions. The first argument of this function should be a string to test, and the second argument should be a stringified regular expression @@ -30,9 +33,10 @@ module Puppet::Parser::Functions ENDHEREDOC - function_deprecation([:validate_re, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::Re. There is further documentation for validate_legacy function in the README.']) + function_deprecation([:validate_re, 'This method is deprecated, please use the stdlib validate_legacy function, + with Stdlib::Compat::Re. There is further documentation for validate_legacy function in the README.']) - if (args.length < 2) or (args.length > 3) then + if (args.length < 2) || (args.length > 3) raise Puppet::ParseError, "validate_re(): wrong number of arguments (#{args.length}; must be 2 or 3)" end @@ -45,6 +49,5 @@ module Puppet::Parser::Functions raise Puppet::ParseError, msg unless [args[1]].flatten.any? do |re_str| args[0] =~ Regexp.compile(re_str) end - end end diff --git a/lib/puppet/parser/functions/validate_slength.rb b/lib/puppet/parser/functions/validate_slength.rb index 383855c71..df5bab30b 100644 --- a/lib/puppet/parser/functions/validate_slength.rb +++ b/lib/puppet/parser/functions/validate_slength.rb @@ -1,6 +1,8 @@ +# +# validate_slength.rb +# module Puppet::Parser::Functions - - newfunction(:validate_slength, :doc => <<-'ENDHEREDOC') do |args| + newfunction(:validate_slength, doc: <<-'ENDHEREDOC') do |args| Validate that the first argument is a string (or an array of strings), and less/equal to than the length of the second argument. An optional third parameter can be given the minimum length. It fails if the first @@ -21,9 +23,10 @@ module Puppet::Parser::Functions ENDHEREDOC - function_deprecation([:validate_slength, 'This method is deprecated, please use the stdlib validate_legacy function, with String[]. There is further documentation for validate_legacy function in the README.']) + function_deprecation([:validate_slength, 'This method is deprecated, please use the stdlib validate_legacy function, + with String[]. There is further documentation for validate_legacy function in the README.']) - raise Puppet::ParseError, "validate_slength(): Wrong number of arguments (#{args.length}; must be 2 or 3)" unless args.length == 2 or args.length == 3 + raise Puppet::ParseError, "validate_slength(): Wrong number of arguments (#{args.length}; must be 2 or 3)" unless args.length == 2 || args.length == 3 input, max_length, min_length = *args @@ -38,17 +41,17 @@ module Puppet::Parser::Functions begin min_length = Integer(min_length) raise ArgumentError if min_length < 0 - rescue ArgumentError, TypeError + rescue ArgumentError, TypeError raise Puppet::ParseError, "validate_slength(): Expected third argument to be unset or a positive Numeric, got #{min_length}:#{min_length.class}" end else min_length = 0 end - raise Puppet::ParseError, "validate_slength(): Expected second argument to be equal to or larger than third argument" unless max_length >= min_length + raise Puppet::ParseError, 'validate_slength(): Expected second argument to be equal to or larger than third argument' unless max_length >= min_length - validator = lambda do |str| - unless str.length <= max_length and str.length >= min_length + validator = ->(str) do + unless str.length <= max_length && str.length >= min_length raise Puppet::ParseError, "validate_slength(): Expected length of #{input.inspect} to be between #{min_length} and #{max_length}, was #{input.length}" end end @@ -58,11 +61,8 @@ module Puppet::Parser::Functions validator.call(input) when Array input.each_with_index do |arg, pos| - if arg.is_a? String - validator.call(arg) - else - raise Puppet::ParseError, "validate_slength(): Expected element at array position #{pos} to be a String, got #{arg.class}" - end + raise Puppet::ParseError, "validate_slength(): Expected element at array position #{pos} to be a String, got #{arg.class}" unless arg.is_a? String + validator.call(arg) end else raise Puppet::ParseError, "validate_slength(): Expected first argument to be a String or Array, got #{input.class}" diff --git a/lib/puppet/parser/functions/validate_string.rb b/lib/puppet/parser/functions/validate_string.rb index 6675d86d6..bef21423b 100644 --- a/lib/puppet/parser/functions/validate_string.rb +++ b/lib/puppet/parser/functions/validate_string.rb @@ -1,6 +1,8 @@ +# +# validate_String.rb +# module Puppet::Parser::Functions - - newfunction(:validate_string, :doc => <<-'ENDHEREDOC') do |args| + newfunction(:validate_string, doc: <<-'ENDHEREDOC') do |args| Validate that all passed values are string data structures. Abort catalog compilation if any value fails this check. @@ -23,19 +25,18 @@ module Puppet::Parser::Functions ENDHEREDOC - function_deprecation([:validate_string, 'This method is deprecated, please use the stdlib validate_legacy function, with Stdlib::Compat::String. There is further documentation for validate_legacy function in the README.']) + function_deprecation([:validate_string, 'This method is deprecated, please use the stdlib validate_legacy function, + with Stdlib::Compat::String. There is further documentation for validate_legacy function in the README.']) - unless args.length > 0 then - raise Puppet::ParseError, ("validate_string(): wrong number of arguments (#{args.length}; must be > 0)") + if args.empty? + raise Puppet::ParseError, "validate_string(): wrong number of arguments (#{args.length}; must be > 0)" end args.each do |arg| # when called through the v4 API shim, undef gets translated to nil unless arg.is_a?(String) || arg.nil? - raise Puppet::ParseError, ("#{arg.inspect} is not a string. It looks to be a #{arg.class}") + raise Puppet::ParseError, "#{arg.inspect} is not a string. It looks to be a #{arg.class}" end end - end - end diff --git a/lib/puppet/parser/functions/validate_x509_rsa_key_pair.rb b/lib/puppet/parser/functions/validate_x509_rsa_key_pair.rb index fc9f23ff1..557e3a623 100644 --- a/lib/puppet/parser/functions/validate_x509_rsa_key_pair.rb +++ b/lib/puppet/parser/functions/validate_x509_rsa_key_pair.rb @@ -1,6 +1,8 @@ +# +# validate_x509_rsa_key_pair.rb +# module Puppet::Parser::Functions - - newfunction(:validate_x509_rsa_key_pair, :doc => <<-ENDHEREDOC + newfunction(:validate_x509_rsa_key_pair, doc: <<-ENDHEREDOC Validates a PEM-formatted X.509 certificate and RSA private key using OpenSSL. Verifies that the certficate's signature was created from the supplied key. @@ -10,15 +12,15 @@ module Puppet::Parser::Functions validate_x509_rsa_key_pair($cert, $key) ENDHEREDOC - ) do |args| + ) do |args| require 'openssl' NUM_ARGS = 2 unless defined? NUM_ARGS - unless args.length == NUM_ARGS then + unless args.length == NUM_ARGS raise Puppet::ParseError, - ("validate_x509_rsa_key_pair(): wrong number of arguments (#{args.length}; must be #{NUM_ARGS})") + "validate_x509_rsa_key_pair(): wrong number of arguments (#{args.length}; must be #{NUM_ARGS})" end args.each do |arg| @@ -40,8 +42,7 @@ module Puppet::Parser::Functions end unless cert.verify(key) - raise Puppet::ParseError, "Certificate signature does not match supplied key" + raise Puppet::ParseError, 'Certificate signature does not match supplied key' end end - end diff --git a/lib/puppet/parser/functions/values.rb b/lib/puppet/parser/functions/values.rb index 0ca236c3d..01c448b5c 100644 --- a/lib/puppet/parser/functions/values.rb +++ b/lib/puppet/parser/functions/values.rb @@ -1,27 +1,26 @@ # # values.rb # - module Puppet::Parser::Functions - newfunction(:values, :type => :rvalue, :doc => <<-EOS -When given a hash this function will return the values of that hash. + newfunction(:values, type: :rvalue, doc: <<-EOS + When given a hash this function will return the values of that hash. -*Examples:* + *Examples:* - $hash = { - 'a' => 1, - 'b' => 2, - 'c' => 3, - } - values($hash) + $hash = { + 'a' => 1, + 'b' => 2, + 'c' => 3, + } + values($hash) -This example would return: + This example would return: - [1,2,3] + [1,2,3] EOS - ) do |arguments| + ) do |arguments| - raise(Puppet::ParseError, "values(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size < 1 + raise(Puppet::ParseError, "values(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? hash = arguments[0] diff --git a/lib/puppet/parser/functions/values_at.rb b/lib/puppet/parser/functions/values_at.rb index 04a3d1ac4..dd9a040d6 100644 --- a/lib/puppet/parser/functions/values_at.rb +++ b/lib/puppet/parser/functions/values_at.rb @@ -1,33 +1,32 @@ # # values_at.rb # - module Puppet::Parser::Functions - newfunction(:values_at, :type => :rvalue, :doc => <<-EOS -Finds value inside an array based on location. + newfunction(:values_at, type: :rvalue, doc: <<-EOS + Finds value inside an array based on location. -The first argument is the array you want to analyze, and the second element can -be a combination of: + The first argument is the array you want to analyze, and the second element can + be a combination of: -* A single numeric index -* A range in the form of 'start-stop' (eg. 4-9) -* An array combining the above + * A single numeric index + * A range in the form of 'start-stop' (eg. 4-9) + * An array combining the above -*Examples*: + *Examples*: - values_at(['a','b','c'], 2) + values_at(['a','b','c'], 2) -Would return ['c']. + Would return ['c']. - values_at(['a','b','c'], ["0-1"]) + values_at(['a','b','c'], ["0-1"]) -Would return ['a','b']. + Would return ['a','b']. - values_at(['a','b','c','d','e'], [0, "2-3"]) + values_at(['a','b','c','d','e'], [0, "2-3"]) -Would return ['a','c','d']. + Would return ['a','c','d']. EOS - ) do |arguments| + ) do |arguments| raise(Puppet::ParseError, "values_at(): Wrong number of arguments given (#{arguments.size} for 2)") if arguments.size < 2 @@ -37,38 +36,35 @@ module Puppet::Parser::Functions raise(Puppet::ParseError, 'values_at(): Requires array to work with') end - indices = [arguments.shift].flatten() # Get them all ... Pokemon ... + indices = [arguments.shift].flatten # Get them all ... Pokemon ... - if not indices or indices.empty? + if !indices || indices.empty? raise(Puppet::ParseError, 'values_at(): You must provide at least one positive index to collect') end - result = [] indices_list = [] indices.each do |i| i = i.to_s - if m = i.match(/^(\d+)(\.\.\.?|\-)(\d+)$/) + m = i.match(%r{^(\d+)(\.\.\.?|\-)(\d+)$}) + if m start = m[1].to_i stop = m[3].to_i type = m[2] - if start > stop - raise(Puppet::ParseError, 'values_at(): Stop index in given indices range is smaller than the start index') - elsif stop > array.size - 1 # First element is at index 0 is it not? - raise(Puppet::ParseError, 'values_at(): Stop index in given indices range exceeds array size') - end + raise(Puppet::ParseError, 'values_at(): Stop index in given indices range is smaller than the start index') if start > stop + raise(Puppet::ParseError, 'values_at(): Stop index in given indices range exceeds array size') if stop > array.size - 1 # First element is at index 0 is it not? range = case type - when /^(\.\.|\-)$/ then (start .. stop) - when /^(\.\.\.)$/ then (start ... stop) # Exclusive of last element ... - end + when %r{^(\.\.|\-)$} then (start..stop) + when %r{^(\.\.\.)$} then (start...stop) # Exclusive of last element ... + end - range.each { |i| indices_list << i.to_i } + range.each { |i| indices_list << i.to_i } # rubocop:disable Lint/ShadowingOuterLocalVariable : Value is meant to be shadowed else # Only positive numbers allowed in this case ... - if not i.match(/^\d+$/) + unless i =~ %r{^\d+$} raise(Puppet::ParseError, 'values_at(): Unknown format of given index') end @@ -84,7 +80,7 @@ module Puppet::Parser::Functions end # We remove nil values as they make no sense in Puppet DSL ... - result = indices_list.collect { |i| array[i] }.compact + result = indices_list.map { |i| array[i] }.compact return result end diff --git a/lib/puppet/parser/functions/zip.rb b/lib/puppet/parser/functions/zip.rb index 13e24b6c9..d183b3c15 100644 --- a/lib/puppet/parser/functions/zip.rb +++ b/lib/puppet/parser/functions/zip.rb @@ -1,20 +1,19 @@ # # zip.rb # - module Puppet::Parser::Functions - newfunction(:zip, :type => :rvalue, :doc => <<-EOS -Takes one element from first array and merges corresponding elements from second array. This generates a sequence of n-element arrays, where n is one more than the count of arguments. + newfunction(:zip, type: :rvalue, doc: <<-EOS + Takes one element from first array and merges corresponding elements from second array. This generates a sequence of n-element arrays, where n is one more than the count of arguments. -*Example:* + *Example:* - zip(['1','2','3'],['4','5','6']) + zip(['1','2','3'],['4','5','6']) -Would result in: + Would result in: - ["1", "4"], ["2", "5"], ["3", "6"] + ["1", "4"], ["2", "5"], ["3", "6"] EOS - ) do |arguments| + ) do |arguments| # Technically we support three arguments but only first is mandatory ... raise(Puppet::ParseError, "zip(): Wrong number of arguments given (#{arguments.size} for 2)") if arguments.size < 2 @@ -22,7 +21,7 @@ module Puppet::Parser::Functions a = arguments[0] b = arguments[1] - unless a.is_a?(Array) and b.is_a?(Array) + unless a.is_a?(Array) && b.is_a?(Array) raise(Puppet::ParseError, 'zip(): Requires array to work with') end diff --git a/lib/puppet/provider/file_line/ruby.rb b/lib/puppet/provider/file_line/ruby.rb index 2d188e050..6e95b9e97 100644 --- a/lib/puppet/provider/file_line/ruby.rb +++ b/lib/puppet/provider/file_line/ruby.rb @@ -8,68 +8,54 @@ def exists? lines_count += 1 end end - if resource[:match] == nil - found = lines_count > 0 - else - match_count = count_matches(new_match_regex) - if resource[:ensure] == :present - if match_count == 0 - if lines_count == 0 - if resource[:append_on_no_match].to_s == 'false' - found = true # lies, but gets the job done - else - found = false - end - else - found = true - end - else - if resource[:replace_all_matches_not_matching_line].to_s == 'true' - found = false # maybe lies, but knows there's still work to do - else - if lines_count == 0 - if resource[:replace].to_s == 'false' - found = true + return found = lines_count > 0 if resource[:match].nil? + + match_count = count_matches(new_match_regex) + found = if resource[:ensure] == :present + if match_count.zero? + if lines_count.zero? && resource[:append_on_no_match].to_s == 'false' + true # lies, but gets the job done + elsif lines_count.zero? && resource[:append_on_no_match].to_s != 'false' + false + else + true + end + elsif resource[:replace_all_matches_not_matching_line].to_s == 'true' + false # maybe lies, but knows there's still work to do + elsif lines_count.zero? + if resource[:replace].to_s == 'false' + true + else + false + end else - found = false + true + end + elsif match_count.zero? + if lines_count.zero? + false + else + true + end + elsif lines_count.zero? + if resource[:match_for_absence].to_s == 'true' + true # found matches, not lines + else + false end else - found = true - end - end - end - else - if match_count == 0 - if lines_count == 0 - found = false - else - found = true - end - else - if lines_count == 0 - if resource[:match_for_absence].to_s == 'true' - found = true # found matches, not lines - else - found = false + true end - else - found = true - end - end - end - end - found end def create - unless resource[:replace].to_s != 'true' && count_matches(new_match_regex) > 0 - if resource[:match] - handle_create_with_match - elsif resource[:after] - handle_create_with_after - else - handle_append_line - end + return if resource[:replace].to_s != 'true' && count_matches(new_match_regex) > 0 + if resource[:match] + handle_create_with_match + elsif resource[:after] + handle_create_with_after + else + handle_append_line end end @@ -89,12 +75,11 @@ def lines # file; for now assuming that this type is only used on # small-ish config files that can fit into memory without # too much trouble. - begin - @lines ||= File.readlines(resource[:path], :encoding => resource[:encoding]) - rescue TypeError => e - # Ruby 1.8 doesn't support open_args - @lines ||= File.readlines(resource[:path]) - end + + @lines ||= File.readlines(resource[:path], encoding: resource[:encoding]) + rescue TypeError => _e + # Ruby 1.8 doesn't support open_args + @lines ||= File.readlines(resource[:path]) end def new_after_regex @@ -106,36 +91,35 @@ def new_match_regex end def count_matches(regex) - lines.select do |line| + lines.select { |line| if resource[:replace_all_matches_not_matching_line].to_s == 'true' line.match(regex) unless line.chomp == resource[:line] else line.match(regex) end - end.size + }.size end - def handle_create_with_match() + def handle_create_with_match after_regex = new_after_regex match_regex = new_match_regex match_count = count_matches(new_match_regex) if match_count > 1 && resource[:multiple].to_s != 'true' - raise Puppet::Error, "More than one line in file '#{resource[:path]}' matches pattern '#{resource[:match]}'" + raise Puppet::Error, "More than one line in file '#{resource[:path]}' matches pattern '#{resource[:match]}'" end File.open(resource[:path], 'w') do |fh| lines.each do |line| fh.puts(match_regex.match(line) ? resource[:line] : line) - if match_count == 0 && after_regex - if after_regex.match(line) - fh.puts(resource[:line]) - match_count += 1 # Increment match_count to indicate that the new line has been inserted. - end + next unless match_count.zero? && after_regex + if after_regex.match(line) + fh.puts(resource[:line]) + match_count += 1 # Increment match_count to indicate that the new line has been inserted. end end - if (match_count == 0) + if match_count.zero? fh.puts(resource[:line]) end end @@ -149,7 +133,7 @@ def handle_create_with_after raise Puppet::Error, "#{after_count} lines match pattern '#{resource[:after]}' in file '#{resource[:path]}'. One or no line must match the pattern." end - File.open(resource[:path],'w') do |fh| + File.open(resource[:path], 'w') do |fh| lines.each do |line| fh.puts(line) if after_regex.match(line) @@ -157,7 +141,7 @@ def handle_create_with_after end end - if (after_count == 0) + if after_count.zero? fh.puts(resource[:line]) end end @@ -167,25 +151,25 @@ def handle_destroy_with_match match_regex = new_match_regex match_count = count_matches(match_regex) if match_count > 1 && resource[:multiple].to_s != 'true' - raise Puppet::Error, "More than one line in file '#{resource[:path]}' matches pattern '#{resource[:match]}'" + raise Puppet::Error, "More than one line in file '#{resource[:path]}' matches pattern '#{resource[:match]}'" end local_lines = lines - File.open(resource[:path],'w') do |fh| - fh.write(local_lines.reject{ |line| match_regex.match(line) }.join('')) + File.open(resource[:path], 'w') do |fh| + fh.write(local_lines.reject { |line| match_regex.match(line) }.join('')) end end def handle_destroy_line local_lines = lines - File.open(resource[:path],'w') do |fh| - fh.write(local_lines.reject{ |line| line.chomp == resource[:line] }.join('')) + File.open(resource[:path], 'w') do |fh| + fh.write(local_lines.reject { |line| line.chomp == resource[:line] }.join('')) end end def handle_append_line local_lines = lines - File.open(resource[:path],'w') do |fh| + File.open(resource[:path], 'w') do |fh| local_lines.each do |line| fh.puts(line) end diff --git a/lib/puppet/type/anchor.rb b/lib/puppet/type/anchor.rb index fe1e5aa19..843334ba9 100644 --- a/lib/puppet/type/anchor.rb +++ b/lib/puppet/type/anchor.rb @@ -35,7 +35,7 @@ class { 'mcollective': } -> class { 'ntp': } ENDOFDESC newparam :name do - desc "The name of the anchor resource." + desc 'The name of the anchor resource.' end def refresh diff --git a/lib/puppet/type/file_line.rb b/lib/puppet/type/file_line.rb index 5076b06ba..377f4d556 100644 --- a/lib/puppet/type/file_line.rb +++ b/lib/puppet/type/file_line.rb @@ -1,5 +1,4 @@ Puppet::Type.newtype(:file_line) do - desc <<-EOT Ensures that a given line is contained within a file. The implementation matches the full line, including whitespace at the beginning and end. If @@ -93,34 +92,34 @@ 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(:match) do - desc 'An optional ruby regular expression to run against existing lines in the file.' + - ' If a match is found, we replace that line rather than adding a new line.' + - ' A regex comparison is performed against the line value and if it does not' + + desc 'An optional ruby regular expression to run against existing lines in the file.' \ + ' If a match is found, we replace that line rather than adding a new line.' \ + ' A regex comparison is performed against the line value and if it does not' \ ' match an exception will be raised.' end newparam(:match_for_absence) do - desc 'An optional value to determine if match should be applied when ensure => absent.' + - ' If set to true and match is set, the line that matches match will be deleted.' + - ' If set to false (the default), match is ignored when ensure => absent.' + + desc 'An optional value to determine if match should be applied when ensure => absent.' \ + ' If set to true and match is set, the line that matches match will be deleted.' \ + ' If set to false (the default), match is ignored when ensure => absent.' \ ' When `ensure => present`, match_for_absence is ignored.' newvalues(true, false) defaultto false end newparam(:multiple) do - desc 'An optional value to determine if match can change multiple lines.' + + desc 'An optional value to determine if match can change multiple lines.' \ ' If set to false, an exception will be raised if more than one line matches' newvalues(true, false) end newparam(:after) do - desc 'An optional value used to specify the line after which we will add any new lines. (Existing lines are added in place)' + + desc 'An optional value used to specify the line after which we will add any new lines. (Existing lines are added in place)' \ ' This is also takes a regex.' end @@ -175,19 +174,19 @@ def retrieve end validate do - if self[:replace_all_matches_not_matching_line].to_s == 'true' and self[:multiple].to_s == 'false' - raise(Puppet::Error, "multiple must be true when replace_all_matches_not_matching_line is true") + if self[:replace_all_matches_not_matching_line].to_s == 'true' && self[:multiple].to_s == 'false' + raise(Puppet::Error, 'multiple must be true when replace_all_matches_not_matching_line is true') end - if self[:replace_all_matches_not_matching_line].to_s == 'true' and self[:replace].to_s == 'false' - raise(Puppet::Error, "replace must be true when replace_all_matches_not_matching_line is true") + if self[:replace_all_matches_not_matching_line].to_s == 'true' && self[:replace].to_s == 'false' + raise(Puppet::Error, 'replace must be true when replace_all_matches_not_matching_line is true') end unless self[:line] - unless (self[:ensure].to_s == 'absent') and (self[:match_for_absence].to_s == 'true') and self[:match] - raise(Puppet::Error, "line is a required attribute") + unless (self[:ensure].to_s == 'absent') && (self[:match_for_absence].to_s == 'true') && self[:match] + raise(Puppet::Error, 'line is a required attribute') end end unless self[:path] - raise(Puppet::Error, "path is a required attribute") + raise(Puppet::Error, 'path is a required attribute') end end end diff --git a/spec/acceptance/abs_spec.rb b/spec/acceptance/abs_spec.rb index 5af436f2a..a7df2cbd1 100755 --- a/spec/acceptance/abs_spec.rb +++ b/spec/acceptance/abs_spec.rb @@ -3,27 +3,25 @@ describe 'abs function' do describe 'success' do - it 'should accept a string' do - pp = <<-EOS + pp1 = <<-EOS $input = '-34.56' $output = abs($input) notify { "$output": } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: 34.56/) + EOS + it 'accepts a string' do + apply_manifest(pp1, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: 34.56}) end end - it 'should accept a float' do - pp = <<-EOS - $input = -34.56 + pp2 = <<-EOS + $input = -35.46 $output = abs($input) notify { "$output": } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: 34.56/) + EOS + it 'accepts a float' do + apply_manifest(pp2, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: 35.46}) end end end diff --git a/spec/acceptance/anchor_spec.rb b/spec/acceptance/anchor_spec.rb index 24a90647c..d558dde61 100755 --- a/spec/acceptance/anchor_spec.rb +++ b/spec/acceptance/anchor_spec.rb @@ -2,8 +2,7 @@ describe 'anchor type' do describe 'success' do - it 'should effect proper chaining of resources' do - pp = <<-EOS + pp = <<-EOS class anchored { anchor { 'anchored::begin': } ~> anchor { 'anchored::end': } @@ -16,10 +15,10 @@ class anchorrefresh { } include anchorrefresh - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Anchor\[final\]: Triggered 'refresh'/) + EOS + it 'effects proper chaining of resources' do + apply_manifest(pp, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Anchor\[final\]: Triggered 'refresh'}) end end end diff --git a/spec/acceptance/any2array_spec.rb b/spec/acceptance/any2array_spec.rb index 8a13911ea..a7d18fad1 100755 --- a/spec/acceptance/any2array_spec.rb +++ b/spec/acceptance/any2array_spec.rb @@ -3,34 +3,31 @@ describe 'any2array function' do describe 'success' do - it 'should create an empty array' do - pp = <<-EOS + pp1 = <<-EOS $input = '' $output = any2array($input) validate_array($output) notify { "Output: ${output}": } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: Output: /) + EOS + it 'creates an empty array' do + apply_manifest(pp1, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: Output: }) end end - it 'should leave arrays modified' do - pp = <<-EOS - $input = ['test', 'array'] + pp2 = <<-EOS + $input = ['array', 'test'] $output = any2array($input) validate_array($output) notify { "Output: ${output}": } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: Output: (\[|)test(,\s|)array(\]|)/) + EOS + it 'leaves arrays modified' do + apply_manifest(pp2, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: Output: (\[|)array(,\s|)test(\]|)}) end end - it 'should turn a hash into an array' do - pp = <<-EOS + pp3 = <<-EOS $input = {'test' => 'array'} $output = any2array($input) @@ -39,10 +36,10 @@ validate_string($output[0]) validate_string($output[1]) notify { "Output: ${output}": } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: Output: (\[|)test(,\s|)array(\]|)/) + EOS + it 'turns a hash into an array' do + apply_manifest(pp3, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: Output: (\[|)test(,\s|)array(\]|)}) end end end diff --git a/spec/acceptance/base64_spec.rb b/spec/acceptance/base64_spec.rb index e9096a7e6..537165512 100755 --- a/spec/acceptance/base64_spec.rb +++ b/spec/acceptance/base64_spec.rb @@ -3,15 +3,14 @@ describe 'base64 function' do describe 'success' do - it 'should encode then decode a string' do - pp = <<-EOS + pp = <<-EOS $encodestring = base64('encode', 'thestring') $decodestring = base64('decode', $encodestring) notify { $decodestring: } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/thestring/) + EOS + it 'encodes then decode a string' do + apply_manifest(pp, catch_failures: true) do |r| + expect(r.stdout).to match(%r{thestring}) end end end diff --git a/spec/acceptance/bool2num_spec.rb b/spec/acceptance/bool2num_spec.rb index c69acc653..0665b166b 100755 --- a/spec/acceptance/bool2num_spec.rb +++ b/spec/acceptance/bool2num_spec.rb @@ -3,30 +3,28 @@ describe 'bool2num function' do describe 'success' do - ['false', 'f', '0', 'n', 'no'].each do |bool| - it "should convert a given boolean, #{bool}, to 0" do - pp = <<-EOS + %w[false f 0 n no].each do |bool| + pp1 = <<-EOS $input = "#{bool}" $output = bool2num($input) notify { "$output": } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: 0/) + EOS + it "should convert a given boolean, #{bool}, to 0" do + apply_manifest(pp1, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: 0}) end end end - ['true', 't', '1', 'y', 'yes'].each do |bool| - it "should convert a given boolean, #{bool}, to 1" do - pp = <<-EOS + %w[true t 1 y yes].each do |bool| + pp2 = <<-EOS $input = "#{bool}" $output = bool2num($input) notify { "$output": } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: 1/) + EOS + it "should convert a given boolean, #{bool}, to 1" do + apply_manifest(pp2, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: 1}) end end end diff --git a/spec/acceptance/build_csv.rb b/spec/acceptance/build_csv.rb index 62ecbf13a..e8929d49d 100755 --- a/spec/acceptance/build_csv.rb +++ b/spec/acceptance/build_csv.rb @@ -2,82 +2,89 @@ # vim: set sw=2 sts=2 et tw=80 : require 'rspec' -#XXX Super ugly hack to keep from starting beaker nodes +# XXX Super ugly hack to keep from starting beaker nodes module Kernel # make an alias of the original require - alias_method :original_require, :require + alias original_require require # rewrite require - def require name + def require(name) original_require name if name != 'spec_helper_acceptance' end end -UNSUPPORTED_PLATFORMS = [] -def fact(*args) [] end -#XXX End hax +UNSUPPORTED_PLATFORMS = [].freeze +def fact(*_args) + [] +end +# XXX End hax # Get a list of functions for test coverage -function_list = Dir[File.join(File.dirname(__FILE__),"..","..","lib","puppet","parser","functions","*.rb")].collect do |function_rb| - File.basename(function_rb,".rb") +function_list = Dir[File.join(File.dirname(__FILE__), '..', '..', 'lib', 'puppet', 'parser', 'functions', '*.rb')].map do |function_rb| + File.basename(function_rb, '.rb') end ## Configure rspec to parse tests options = RSpec::Core::ConfigurationOptions.new(['spec/acceptance']) -configuration = RSpec::configuration -world = RSpec::world +configuration = RSpec.configuration +world = RSpec.world options.parse_options options.configure(configuration) configuration.load_spec_files ## Collect up tests and example groups into a hash def get_tests(children) - children.inject({}) do |memo,c| - memo[c.description] = Hash.new - memo[c.description]["groups"] = get_tests(c.children) unless c.children.empty? - memo[c.description]["tests"] = c.examples.collect { |e| - e.description unless e.pending? - }.compact unless c.examples.empty? - memo[c.description]["pending_tests"] = c.examples.collect { |e| + children.each_with_object({}) do |c, memo| + memo[c.description] = {} + memo[c.description]['groups'] = get_tests(c.children) unless c.children.empty? + unless c.examples.empty? + memo[c.description]['tests'] = c.examples.map { |e| + e.description unless e.pending? + }.compact + end + next if c.examples.empty? + memo[c.description]['pending_tests'] = c.examples.map { |e| e.description if e.pending? - }.compact unless c.examples.empty? - memo + }.compact end end -def count_test_types_in(type,group) +def count_test_types_in(type, group) return 0 if group.nil? - group.inject(0) do |m,(k,v)| + group.reduce(0) do |m, (k, v)| m += v.length if k == type m += count_tests_in(v) if v.is_a?(Hash) m end end + def count_tests_in(group) - count_test_types_in('tests',group) + count_test_types_in('tests', group) end + def count_pending_tests_in(group) - count_test_types_in('pending_tests',group) + count_test_types_in('pending_tests', group) end # Convert tests hash to csv format -def to_csv(function_list,tests) - function_list.collect do |function_name| - if v = tests["#{function_name} function"] - positive_tests = count_tests_in(v["groups"]["success"]) - negative_tests = count_tests_in(v["groups"]["failure"]) +def to_csv(function_list, tests) + function_list.map { |function_name| + v = tests["#{function_name} function"] + if v + positive_tests = count_tests_in(v['groups']['success']) + negative_tests = count_tests_in(v['groups']['failure']) pending_tests = - count_pending_tests_in(v["groups"]["failure"]) + - count_pending_tests_in(v["groups"]["failure"]) + count_pending_tests_in(v['groups']['failure']) + + count_pending_tests_in(v['groups']['failure']) else positive_tests = 0 negative_tests = 0 pending_tests = 0 end - sprintf("%-25s, %-9d, %-9d, %-9d", function_name,positive_tests,negative_tests,pending_tests) - end.compact + '%-25s, %-9d, %-9d, %-9d' % [function_name, positive_tests, negative_tests, pending_tests] + }.compact end tests = get_tests(world.example_groups) -csv = to_csv(function_list,tests) -percentage_tested = "#{tests.count*100/function_list.count}%" -printf("%-25s, %-9s, %-9s, %-9s\n","#{percentage_tested} have tests.","Positive","Negative","Pending") +csv = to_csv(function_list, tests) +percentage_tested = "#{tests.count * 100 / function_list.count}%" +printf("%-25s, %-9s, %-9s, %-9s\n", "#{percentage_tested} have tests.", 'Positive', 'Negative', 'Pending') puts csv diff --git a/spec/acceptance/capitalize_spec.rb b/spec/acceptance/capitalize_spec.rb index 03d01a8b9..11d40b70e 100755 --- a/spec/acceptance/capitalize_spec.rb +++ b/spec/acceptance/capitalize_spec.rb @@ -3,30 +3,28 @@ describe 'capitalize function' do describe 'success' do - it 'should capitalize the first letter of a string' do - pp = <<-EOS - $input = 'this is a string' - $output = capitalize($input) - notify { $output: } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: This is a string/) + pp1 = <<-EOS + $input = 'this is a string' + $output = capitalize($input) + notify { $output: } + EOS + it 'capitalizes the first letter of a string' do + apply_manifest(pp1, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: This is a string}) end end - it 'should capitalize the first letter of an array of strings' do - pp = <<-EOS + pp2 = <<-EOS $input = ['this', 'is', 'a', 'string'] $output = capitalize($input) notify { $output: } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: This/) - expect(r.stdout).to match(/Notice: Is/) - expect(r.stdout).to match(/Notice: A/) - expect(r.stdout).to match(/Notice: String/) + EOS + regex_array = [%r{Notice: This}, %r{Notice: Is}, %r{Notice: A}, %r{Notice: String}] + it 'capitalizes the first letter of an array of strings' do + apply_manifest(pp2, catch_failures: true) do |r| + regex_array.each do |i| + expect(r.stdout).to match(i) + end end end end diff --git a/spec/acceptance/ceiling_spec.rb b/spec/acceptance/ceiling_spec.rb index 895e4a09f..34ef04b35 100755 --- a/spec/acceptance/ceiling_spec.rb +++ b/spec/acceptance/ceiling_spec.rb @@ -3,32 +3,31 @@ describe 'ceiling function' do describe 'success' do - it 'ceilings floats' do - pp = <<-EOS + pp1 = <<-EOS $a = 12.8 $b = 13 $o = ceiling($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'ceilings floats' do + apply_manifest(pp1, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end - it 'ceilings integers' do - pp = <<-EOS + + pp2 = <<-EOS $a = 7 $b = 7 $o = ceiling($a) if $o == $b { - notify { 'output correct': } + notify { 'output is correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'ceilings integers' do + apply_manifest(pp2, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output is correct}) end end end diff --git a/spec/acceptance/chomp_spec.rb b/spec/acceptance/chomp_spec.rb index 56e0876da..bdfd47e54 100755 --- a/spec/acceptance/chomp_spec.rb +++ b/spec/acceptance/chomp_spec.rb @@ -3,8 +3,7 @@ describe 'chomp function' do describe 'success' do - it 'should eat the newline' do - pp = <<-EOS + pp = <<-EOS $input = "test\n" if size($input) != 5 { fail("Size of ${input} is not 5.") @@ -13,9 +12,9 @@ if size($output) != 4 { fail("Size of ${input} is not 4.") } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'eats the newline' do + apply_manifest(pp, catch_failures: true) end end end diff --git a/spec/acceptance/chop_spec.rb b/spec/acceptance/chop_spec.rb index 09938064f..a75315e5d 100755 --- a/spec/acceptance/chop_spec.rb +++ b/spec/acceptance/chop_spec.rb @@ -3,8 +3,7 @@ describe 'chop function' do describe 'success' do - it 'should eat the last character' do - pp = <<-EOS + pp1 = <<-EOS $input = "test" if size($input) != 4 { fail("Size of ${input} is not 4.") @@ -13,13 +12,12 @@ if size($output) != 3 { fail("Size of ${input} is not 3.") } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'eats the last character' do + apply_manifest(pp1, catch_failures: true) end - it 'should eat the last two characters of \r\n' do - pp = <<-'EOS' + pp2 = <<-'EOS' $input = "test\r\n" if size($input) != 6 { fail("Size of ${input} is not 6.") @@ -28,18 +26,17 @@ if size($output) != 4 { fail("Size of ${input} is not 4.") } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'eats the last two characters of \r\n' do + apply_manifest(pp2, catch_failures: true) end - it 'should not fail on empty strings' do - pp = <<-EOS + pp3 = <<-EOS $input = "" $output = chop($input) - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'does not fail on empty strings' do + apply_manifest(pp3, catch_failures: true) end end end diff --git a/spec/acceptance/clamp_spec.rb b/spec/acceptance/clamp_spec.rb index e8ccb967e..1f5038b7d 100755 --- a/spec/acceptance/clamp_spec.rb +++ b/spec/acceptance/clamp_spec.rb @@ -3,8 +3,7 @@ describe 'clamp function' do describe 'success' do - it 'clamps list of values' do - pp = <<-EOS + pp1 = <<-EOS $x = 17 $y = 225 $z = 155 @@ -12,24 +11,24 @@ if $o == $z { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'clamps list of values' do + apply_manifest(pp1, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end - it 'clamps array of values' do - pp = <<-EOS + + pp2 = <<-EOS $a = [7, 19, 66] $b = 19 $o = clamp($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'clamps array of values' do + apply_manifest(pp2, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end end diff --git a/spec/acceptance/concat_spec.rb b/spec/acceptance/concat_spec.rb index 8d184d1e9..a65f77890 100755 --- a/spec/acceptance/concat_spec.rb +++ b/spec/acceptance/concat_spec.rb @@ -3,41 +3,40 @@ describe 'concat function' do describe 'success' do - it 'should concat one array to another' do - pp = <<-EOS + pp1 = <<-EOS $output = concat(['1','2','3'],['4','5','6']) validate_array($output) if size($output) != 6 { fail("${output} should have 6 elements.") } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'concats one array to another' do + apply_manifest(pp1, catch_failures: true) end - it 'should concat arrays and primitives to array' do - pp = <<-EOS + + pp2 = <<-EOS $output = concat(['1','2','3'],'4','5','6',['7','8','9']) validate_array($output) if size($output) != 9 { fail("${output} should have 9 elements.") } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'concats arrays and primitives to array' do + apply_manifest(pp2, catch_failures: true) end - it 'should concat multiple arrays to one' do - pp = <<-EOS + + pp3 = <<-EOS $output = concat(['1','2','3'],['4','5','6'],['7','8','9']) validate_array($output) if size($output) != 9 { fail("${output} should have 9 elements.") } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'concats multiple arrays to one' do + apply_manifest(pp3, catch_failures: true) end - it 'should concat hash arguments' do - pp = <<-EOS + + pp4 = <<-EOS $output = concat([{"a" => "b"}], {"c" => "d", "e" => "f"}) validate_array($output) if size($output) != 2 { @@ -46,9 +45,9 @@ if $output[1] != {"c" => "d", "e" => "f"} { fail("${output} does not have the expected hash for the second element.") } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'concats hash arguments' do + apply_manifest(pp4, catch_failures: true) end end end diff --git a/spec/acceptance/count_spec.rb b/spec/acceptance/count_spec.rb index 18c039d12..280546291 100755 --- a/spec/acceptance/count_spec.rb +++ b/spec/acceptance/count_spec.rb @@ -3,27 +3,25 @@ describe 'count function' do describe 'success' do - it 'should count elements in an array' do - pp = <<-EOS + pp1 = <<-EOS $input = [1,2,3,4] $output = count($input) notify { "$output": } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: 4/) + EOS + it 'counts elements in an array' do + apply_manifest(pp1, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: 4}) end end - it 'should count elements in an array that match a second argument' do - pp = <<-EOS + pp2 = <<-EOS $input = [1,1,1,2] $output = count($input, 1) notify { "$output": } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: 3/) + EOS + it 'counts elements in an array that match a second argument' do + apply_manifest(pp2, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: 3}) end end end diff --git a/spec/acceptance/deep_merge_spec.rb b/spec/acceptance/deep_merge_spec.rb index 8222f24bc..93edc3b2f 100755 --- a/spec/acceptance/deep_merge_spec.rb +++ b/spec/acceptance/deep_merge_spec.rb @@ -3,8 +3,7 @@ describe 'deep_merge function' do describe 'success' do - it 'should deep merge two hashes' do - pp = <<-EOS + pp = <<-EOS $hash1 = {'one' => 1, 'two' => 2, 'three' => { 'four' => 4 } } $hash2 = {'two' => 'dos', 'three' => { 'five' => 5 } } $merged_hash = deep_merge($hash1, $hash2) @@ -12,9 +11,9 @@ if $merged_hash != { 'one' => 1, 'two' => 'dos', 'three' => { 'four' => 4, 'five' => 5 } } { fail("Hash was incorrectly merged.") } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'deeps merge two hashes' do + apply_manifest(pp, catch_failures: true) end end end diff --git a/spec/acceptance/defined_with_params_spec.rb b/spec/acceptance/defined_with_params_spec.rb index a332bd638..809c48576 100755 --- a/spec/acceptance/defined_with_params_spec.rb +++ b/spec/acceptance/defined_with_params_spec.rb @@ -3,8 +3,7 @@ describe 'defined_with_params function' do describe 'success' do - it 'should successfully notify' do - pp = <<-EOS + pp = <<-EOS user { 'dan': ensure => present, } @@ -12,10 +11,10 @@ if defined_with_params(User[dan], {'ensure' => 'present' }) { notify { 'User defined with ensure=>present': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: User defined with ensure=>present/) + EOS + it 'successfullies notify' do + apply_manifest(pp, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: User defined with ensure=>present}) end end end diff --git a/spec/acceptance/delete_at_spec.rb b/spec/acceptance/delete_at_spec.rb index d4f852a8a..dbd39b48a 100755 --- a/spec/acceptance/delete_at_spec.rb +++ b/spec/acceptance/delete_at_spec.rb @@ -3,16 +3,15 @@ describe 'delete_at function' do describe 'success' do - it 'should delete elements of the array' do - pp = <<-EOS + pp = <<-EOS $output = delete_at(['a','b','c','b'], 1) if $output == ['a','c','b'] { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'deletes elements of the array' do + apply_manifest(pp, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end end diff --git a/spec/acceptance/delete_spec.rb b/spec/acceptance/delete_spec.rb index f85b09385..da9f1cf68 100755 --- a/spec/acceptance/delete_spec.rb +++ b/spec/acceptance/delete_spec.rb @@ -2,17 +2,16 @@ require 'spec_helper_acceptance' describe 'delete function' do - describe 'success' do - it 'should delete elements of the array' do - pp = <<-EOS + pp = <<-EOS $output = delete(['a','b','c','b'], 'b') if $output == ['a','c'] { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + describe 'success' do + it 'deletes elements of the array' do + apply_manifest(pp, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end end diff --git a/spec/acceptance/delete_undef_values_spec.rb b/spec/acceptance/delete_undef_values_spec.rb index af45a9262..d07fdede8 100755 --- a/spec/acceptance/delete_undef_values_spec.rb +++ b/spec/acceptance/delete_undef_values_spec.rb @@ -3,16 +3,15 @@ describe 'delete_undef_values function' do describe 'success' do - it 'should delete elements of the array' do - pp = <<-EOS + pp = <<-EOS $output = delete_undef_values({a=>'A', b=>'', c=>undef, d => false}) if $output == { a => 'A', b => '', d => false } { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'deletes elements of the array' do + apply_manifest(pp, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end end diff --git a/spec/acceptance/delete_values_spec.rb b/spec/acceptance/delete_values_spec.rb index 04b6920f2..23279bfa1 100755 --- a/spec/acceptance/delete_values_spec.rb +++ b/spec/acceptance/delete_values_spec.rb @@ -3,18 +3,17 @@ describe 'delete_values function' do describe 'success' do - it 'should delete elements of the hash' do - pp = <<-EOS + pp = <<-EOS $a = { 'a' => 'A', 'b' => 'B', 'B' => 'C', 'd' => 'B' } $b = { 'a' => 'A', 'B' => 'C' } $o = delete_values($a, 'B') if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'deletes elements of the hash' do + apply_manifest(pp, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end end diff --git a/spec/acceptance/deprecation_spec.rb b/spec/acceptance/deprecation_spec.rb index 7a0b34c46..3c53b68c2 100644 --- a/spec/acceptance/deprecation_spec.rb +++ b/spec/acceptance/deprecation_spec.rb @@ -1,13 +1,12 @@ -#! /usr/bin/env ruby -S rspec +#! /usr/bin/env ruby -S rspec # rubocop:disable Lint/ScriptPermission : Rubocop Mistake??? require 'spec_helper_acceptance' describe 'deprecation function' do - - if fact('operatingsystem') == 'windows' - test_file = 'C:/deprecation' - else - test_file = "/tmp/deprecation" - end + test_file = if fact('operatingsystem') == 'windows' + 'C:/deprecation' + else + '/tmp/deprecation' + end # It seems that Windows needs everything to be on one line when using puppet apply -e, otherwise the manifests would be in an easier format add_file_manifest = "\"deprecation('key', 'message') file { '#{test_file}': ensure => present, content => 'test', }\"" @@ -17,86 +16,78 @@ apply_manifest(remove_file_manifest) end - context 'with --strict=error', if: get_puppet_version =~ /^4/ do - before :all do - @result = on(default, puppet('apply', '--strict=error', '-e', add_file_manifest), acceptable_exit_codes: (0...256)) - end + context 'with --strict=error', if: return_puppet_version =~ %r{^4} do + let(:result) { on(default, puppet('apply', '--strict=error', '-e', add_file_manifest), acceptable_exit_codes: (0...256)) } after :all do apply_manifest(remove_file_manifest) end - it "should return an error" do - expect(@result.exit_code).to eq(1) + it 'returns an error' do + expect(result.exit_code).to eq(1) end - it "should show the error message" do - expect(@result.stderr).to match(/deprecation. key. message/) + it 'shows the error message' do + expect(result.stderr).to match(%r{deprecation. key. message}) end - describe file("#{test_file}") do + describe file(test_file.to_s) do it { is_expected.not_to be_file } end end - context 'with --strict=warning', if: get_puppet_version =~ /^4/ do - before :all do - @result = on(default, puppet('apply', '--strict=warning', '-e', add_file_manifest), acceptable_exit_codes: (0...256)) - end + context 'with --strict=warning', if: return_puppet_version =~ %r{^4} do + let(:result) { on(default, puppet('apply', '--strict=warning', '-e', add_file_manifest), acceptable_exit_codes: (0...256)) } after :all do apply_manifest(remove_file_manifest) end - it "should not return an error" do - expect(@result.exit_code).to eq(0) + it 'does not return an error' do + expect(result.exit_code).to eq(0) end - it "should show the error message" do - expect(@result.stderr).to match(/Warning: message/) + it 'shows the error message' do + expect(result.stderr).to match(%r{Warning: message}) end - describe file("#{test_file}") do + describe file(test_file.to_s) do it { is_expected.to be_file } end end - context 'with --strict=off', if: get_puppet_version =~ /^4/ do - before :all do - @result = on(default, puppet('apply', '--strict=off', '-e', add_file_manifest), acceptable_exit_codes: (0...256)) - end + context 'with --strict=off', if: return_puppet_version =~ %r{^4} do + let(:result) { on(default, puppet('apply', '--strict=off', '-e', add_file_manifest), acceptable_exit_codes: (0...256)) } after :all do apply_manifest(remove_file_manifest) end - it "should not return an error" do - expect(@result.exit_code).to eq(0) + it 'does not return an error' do + expect(result.exit_code).to eq(0) end - it "should not show the error message" do - expect(@result.stderr).not_to match(/Warning: message/) + it 'does not show the error message' do + expect(result.stderr).not_to match(%r{Warning: message}) end - describe file("#{test_file}") do + describe file(test_file.to_s) do it { is_expected.to be_file } end end - context 'puppet 3 test', if: get_puppet_version =~ /^3/ do - before :all do - @result = on(default, puppet('apply', '--parser=future', '-e', add_file_manifest), acceptable_exit_codes: (0...256)) - end + context 'puppet 3 test', if: return_puppet_version =~ %r{^3} do + let(:result) { on(default, puppet('apply', '--parser=future', '-e', add_file_manifest), acceptable_exit_codes: (0...256)) } + after :all do apply_manifest(remove_file_manifest) end - it "should return a deprecation error" do - expect(@result.stderr).to match(/Warning: message/) + it 'returns a deprecation error' do + expect(result.stderr).to match(%r{Warning: message}) end - it "should pass without error" do - expect(@result.exit_code).to eq(0) + it 'passes without error' do + expect(result.exit_code).to eq(0) end end - end diff --git a/spec/acceptance/difference_spec.rb b/spec/acceptance/difference_spec.rb index 68f6bbebc..b0c131cf4 100755 --- a/spec/acceptance/difference_spec.rb +++ b/spec/acceptance/difference_spec.rb @@ -3,8 +3,7 @@ describe 'difference function' do describe 'success' do - it 'returns non-duplicates in the first array' do - pp = <<-EOS + pp = <<-EOS $a = ['a','b','c'] $b = ['b','c','d'] $c = ['a'] @@ -12,10 +11,10 @@ if $o == $c { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'returns non-duplicates in the first array' do + apply_manifest(pp, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end end diff --git a/spec/acceptance/dirname_spec.rb b/spec/acceptance/dirname_spec.rb index db83f0f7d..0cd26a24e 100755 --- a/spec/acceptance/dirname_spec.rb +++ b/spec/acceptance/dirname_spec.rb @@ -4,34 +4,32 @@ describe 'dirname function' do describe 'success' do context 'absolute path' do - it 'returns the dirname' do - pp = <<-EOS + pp1 = <<-EOS $a = '/path/to/a/file.txt' $b = '/path/to/a' $o = dirname($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'returns the dirname' do + apply_manifest(pp1, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end end context 'relative path' do - it 'returns the dirname' do - pp = <<-EOS + pp2 = <<-EOS $a = 'path/to/a/file.txt' $b = 'path/to/a' $o = dirname($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'returns the dirname' do + apply_manifest(pp2, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end end diff --git a/spec/acceptance/downcase_spec.rb b/spec/acceptance/downcase_spec.rb index 300bcfae3..297c7845c 100755 --- a/spec/acceptance/downcase_spec.rb +++ b/spec/acceptance/downcase_spec.rb @@ -3,32 +3,31 @@ describe 'downcase function' do describe 'success' do - it 'returns the downcase' do - pp = <<-EOS + pp1 = <<-EOS $a = 'AOEU' $b = 'aoeu' $o = downcase($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'returns the downcase' do + apply_manifest(pp1, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end - it 'doesn\'t affect lowercase words' do - pp = <<-EOS + + pp2 = <<-EOS $a = 'aoeu aoeu' $b = 'aoeu aoeu' $o = downcase($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'doesn\'t affect lowercase words' do + apply_manifest(pp2, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end end diff --git a/spec/acceptance/empty_spec.rb b/spec/acceptance/empty_spec.rb index 97b733348..902f8db43 100755 --- a/spec/acceptance/empty_spec.rb +++ b/spec/acceptance/empty_spec.rb @@ -3,46 +3,45 @@ describe 'empty function' do describe 'success' do - it 'recognizes empty strings' do - pp = <<-EOS + pp1 = <<-EOS $a = '' $b = true $o = empty($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'recognizes empty strings' do + apply_manifest(pp1, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end - it 'recognizes non-empty strings' do - pp = <<-EOS + + pp2 = <<-EOS $a = 'aoeu' $b = false $o = empty($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'recognizes non-empty strings' do + apply_manifest(pp2, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end - it 'handles numerical values' do - pp = <<-EOS + + pp3 = <<-EOS $a = 7 $b = false $o = empty($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'handles numerical values' do + apply_manifest(pp3, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end end diff --git a/spec/acceptance/ensure_resource_spec.rb b/spec/acceptance/ensure_resource_spec.rb index 93f25ddc0..cc751ba48 100755 --- a/spec/acceptance/ensure_resource_spec.rb +++ b/spec/acceptance/ensure_resource_spec.rb @@ -3,23 +3,23 @@ describe 'ensure_resource function' do describe 'success' do - it 'ensures a resource already declared' do - apply_manifest('') - pp = <<-EOS + pp1 = <<-EOS notify { "test": loglevel => 'err' } ensure_resource('notify', 'test', { 'loglevel' => 'err' }) - EOS + EOS + it 'ensures a resource already declared' do + apply_manifest('') - apply_manifest(pp, :expect_changes => true) + apply_manifest(pp1, expect_changes: true) end + pp2 = <<-EOS + ensure_resource('notify', 'test', { 'loglevel' => 'err' }) + EOS it 'ensures a undeclared resource' do apply_manifest('') - pp = <<-EOS - ensure_resource('notify', 'test', { 'loglevel' => 'err' }) - EOS - apply_manifest(pp, :expect_changes => true) + apply_manifest(pp2, expect_changes: true) end it 'takes defaults arguments' end diff --git a/spec/acceptance/flatten_spec.rb b/spec/acceptance/flatten_spec.rb index 289eec95e..95637902b 100755 --- a/spec/acceptance/flatten_spec.rb +++ b/spec/acceptance/flatten_spec.rb @@ -3,32 +3,31 @@ describe 'flatten function' do describe 'success' do - it 'flattens arrays' do - pp = <<-EOS + pp1 = <<-EOS $a = ["a","b",["c",["d","e"],"f","g"]] $b = ["a","b","c","d","e","f","g"] $o = flatten($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'flattens arrays' do + apply_manifest(pp1, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end - it 'does not affect flat arrays' do - pp = <<-EOS + + pp2 = <<-EOS $a = ["a","b","c","d","e","f","g"] $b = ["a","b","c","d","e","f","g"] $o = flatten($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'does not affect flat arrays' do + apply_manifest(pp2, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end end diff --git a/spec/acceptance/floor_spec.rb b/spec/acceptance/floor_spec.rb index 8259d2a17..628045dec 100755 --- a/spec/acceptance/floor_spec.rb +++ b/spec/acceptance/floor_spec.rb @@ -3,32 +3,31 @@ describe 'floor function' do describe 'success' do - it 'floors floats' do - pp = <<-EOS + pp1 = <<-EOS $a = 12.8 $b = 12 $o = floor($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'floors floats' do + apply_manifest(pp1, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end - it 'floors integers' do - pp = <<-EOS + + pp2 = <<-EOS $a = 7 $b = 7 $o = floor($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'floors integers' do + apply_manifest(pp2, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end end diff --git a/spec/acceptance/fqdn_rand_string_spec.rb b/spec/acceptance/fqdn_rand_string_spec.rb index af1b2a975..7f265a07b 100644 --- a/spec/acceptance/fqdn_rand_string_spec.rb +++ b/spec/acceptance/fqdn_rand_string_spec.rb @@ -1,60 +1,59 @@ -#! /usr/bin/env ruby -S rspec +#! /usr/bin/env ruby -S rspec # rubocop:disable Lint/ScriptPermission : Rubocop Mistake??? require 'spec_helper_acceptance' describe 'fqdn_rand_string function' do describe 'success' do - include_context "with faked facts" + include_context 'with faked facts' context "when the FQDN is 'fakehost.localdomain'" do before :each do - fake_fact("fqdn", "fakehost.localdomain") + fake_fact('fqdn', 'fakehost.localdomain') end - it 'generates random alphanumeric strings' do - pp = <<-eos + pp1 = <<-eos $l = 10 $o = fqdn_rand_string($l) notice(inline_template('fqdn_rand_string is <%= @o.inspect %>')) - eos - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/fqdn_rand_string is "(7oDp0KOr1b|9Acvnhkt4J)"/) + eos + it 'generates random alphanumeric strings' do + apply_manifest(pp1, catch_failures: true) do |r| + expect(r.stdout).to match(%r{fqdn_rand_string is "(7oDp0KOr1b|9Acvnhkt4J)"}) end end - it 'generates random alphanumeric strings with custom charsets' do - pp = <<-eos + + pp2 = <<-eos $l = 10 $c = '0123456789' $o = fqdn_rand_string($l, $c) notice(inline_template('fqdn_rand_string is <%= @o.inspect %>')) - eos - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/fqdn_rand_string is "(7203048515|2383756694)"/) + eos + it 'generates random alphanumeric strings with custom charsets' do + apply_manifest(pp2, catch_failures: true) do |r| + expect(r.stdout).to match(%r{fqdn_rand_string is "(7203048515|2383756694)"}) end end - it 'generates random alphanumeric strings with custom seeds' do - pp = <<-eos + + pp3 = <<-eos $l = 10 $s = 'seed' $o = fqdn_rand_string($l, undef, $s) notice(inline_template('fqdn_rand_string is <%= @o.inspect %>')) - eos - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/fqdn_rand_string is "(3HS4mbuI3E|1jJtAMs94d)"/) + eos + it 'generates random alphanumeric strings with custom seeds' do + apply_manifest(pp3, catch_failures: true) do |r| + expect(r.stdout).to match(%r{fqdn_rand_string is "(3HS4mbuI3E|1jJtAMs94d)"}) end end - it 'generates random alphanumeric strings with custom charsets and seeds' do - pp = <<-eos + + pp4 = <<-eos $l = 10 $c = '0123456789' $s = 'seed' $o = fqdn_rand_string($l, $c, $s) notice(inline_template('fqdn_rand_string is <%= @o.inspect %>')) - eos - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/fqdn_rand_string is "(3104058232|7100592312)"/) + eos + it 'generates random alphanumeric strings with custom charsets and seeds' do + apply_manifest(pp4, catch_failures: true) do |r| + expect(r.stdout).to match(%r{fqdn_rand_string is "(3104058232|7100592312)"}) end end end diff --git a/spec/acceptance/fqdn_rotate_spec.rb b/spec/acceptance/fqdn_rotate_spec.rb index 66e94a99c..ec1b43f44 100755 --- a/spec/acceptance/fqdn_rotate_spec.rb +++ b/spec/acceptance/fqdn_rotate_spec.rb @@ -3,56 +3,55 @@ describe 'fqdn_rotate function' do describe 'success' do - include_context "with faked facts" + include_context 'with faked facts' context "when the FQDN is 'fakehost.localdomain'" do before :each do - fake_fact("fqdn", "fakehost.localdomain") + fake_fact('fqdn', 'fakehost.localdomain') end - it 'rotates arrays' do - pp = <<-EOS + pp1 = <<-EOS $a = ['a','b','c','d'] $o = fqdn_rotate($a) notice(inline_template('fqdn_rotate is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/fqdn_rotate is \["d", "a", "b", "c"\]/) + EOS + it 'rotates arrays' do + apply_manifest(pp1, catch_failures: true) do |r| + expect(r.stdout).to match(%r{fqdn_rotate is \["d", "a", "b", "c"\]}) end end - it 'rotates arrays with custom seeds' do - pp = <<-EOS + + pp2 = <<-EOS $a = ['a','b','c','d'] $s = 'seed' $o = fqdn_rotate($a, $s) notice(inline_template('fqdn_rotate is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/fqdn_rotate is \["c", "d", "a", "b"\]/) + EOS + it 'rotates arrays with custom seeds' do + apply_manifest(pp2, catch_failures: true) do |r| + expect(r.stdout).to match(%r{fqdn_rotate is \["c", "d", "a", "b"\]}) end end - it 'rotates strings' do - pp = <<-EOS + + pp3 = <<-EOS $a = 'abcd' $o = fqdn_rotate($a) notice(inline_template('fqdn_rotate is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/fqdn_rotate is "dabc"/) + EOS + it 'rotates strings' do + apply_manifest(pp3, catch_failures: true) do |r| + expect(r.stdout).to match(%r{fqdn_rotate is "dabc"}) end end - it 'rotates strings with custom seeds' do - pp = <<-EOS + + pp4 = <<-EOS $a = 'abcd' $s = 'seed' $o = fqdn_rotate($a, $s) notice(inline_template('fqdn_rotate is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/fqdn_rotate is "cdab"/) + EOS + it 'rotates strings with custom seeds' do + apply_manifest(pp4, catch_failures: true) do |r| + expect(r.stdout).to match(%r{fqdn_rotate is "cdab"}) end end end diff --git a/spec/acceptance/get_module_path_spec.rb b/spec/acceptance/get_module_path_spec.rb index 3d10251a4..9fb685929 100755 --- a/spec/acceptance/get_module_path_spec.rb +++ b/spec/acceptance/get_module_path_spec.rb @@ -3,8 +3,7 @@ describe 'get_module_path function' do describe 'success' do - it 'get_module_paths dne' do - pp = <<-EOS + pp = <<-EOS $a = $::is_pe ? { 'true' => '/etc/puppetlabs/puppet/modules/dne', 'false' => '/etc/puppet/modules/dne', @@ -15,9 +14,9 @@ } else { notify { "failed; module path is '$o'": } } - EOS - - apply_manifest(pp, :expect_failures => true) + EOS + it 'get_module_paths dne' do + apply_manifest(pp, expect_failures: true) end end describe 'failure' do diff --git a/spec/acceptance/getparam_spec.rb b/spec/acceptance/getparam_spec.rb index bd1215419..b03eed0e1 100755 --- a/spec/acceptance/getparam_spec.rb +++ b/spec/acceptance/getparam_spec.rb @@ -3,17 +3,16 @@ describe 'getparam function' do describe 'success' do - it 'getparam a notify' do - pp = <<-EOS + pp = <<-EOS notify { 'rspec': message => 'custom rspec message', } $o = getparam(Notify['rspec'], 'message') notice(inline_template('getparam is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/getparam is "custom rspec message"/) + EOS + it 'getparam a notify' do + apply_manifest(pp, catch_failures: true) do |r| + expect(r.stdout).to match(%r{getparam is "custom rspec message"}) end end end diff --git a/spec/acceptance/getvar_spec.rb b/spec/acceptance/getvar_spec.rb index 605cdce0a..22a24dae6 100755 --- a/spec/acceptance/getvar_spec.rb +++ b/spec/acceptance/getvar_spec.rb @@ -3,8 +3,7 @@ describe 'getvar function' do describe 'success' do - it 'getvars from classes' do - pp = <<-EOS + pp = <<-EOS class a::data { $foo = 'aoeu' } include a::data $b = 'aoeu' @@ -12,10 +11,10 @@ class a::data { $foo = 'aoeu' } if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'getvars from classes' do + apply_manifest(pp, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end end diff --git a/spec/acceptance/grep_spec.rb b/spec/acceptance/grep_spec.rb index 7c35ee432..a1a1f412b 100755 --- a/spec/acceptance/grep_spec.rb +++ b/spec/acceptance/grep_spec.rb @@ -3,8 +3,7 @@ describe 'grep function' do describe 'success' do - it 'greps arrays' do - pp = <<-EOS + pp = <<-EOS $a = ['aaabbb','bbbccc','dddeee'] $b = 'bbb' $c = ['aaabbb','bbbccc'] @@ -12,10 +11,10 @@ if $o == $c { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'greps arrays' do + apply_manifest(pp, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end end diff --git a/spec/acceptance/has_interface_with_spec.rb b/spec/acceptance/has_interface_with_spec.rb index fd33af5c5..58be6117b 100755 --- a/spec/acceptance/has_interface_with_spec.rb +++ b/spec/acceptance/has_interface_with_spec.rb @@ -1,32 +1,31 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'has_interface_with function', :unless => ((fact('osfamily') == 'windows') or (fact('osfamily') == 'AIX')) do +describe 'has_interface_with function', unless: ((fact('osfamily') == 'windows') || (fact('osfamily') == 'AIX')) do describe 'success' do - it 'has_interface_with existing ipaddress' do - pp = <<-EOS + pp1 = <<-EOS $a = $::ipaddress $o = has_interface_with('ipaddress', $a) notice(inline_template('has_interface_with is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/has_interface_with is true/) + EOS + it 'has_interface_with existing ipaddress' do + apply_manifest(pp1, catch_failures: true) do |r| + expect(r.stdout).to match(%r{has_interface_with is true}) end end - it 'has_interface_with absent ipaddress' do - pp = <<-EOS + + pp2 = <<-EOS $a = '128.0.0.1' $o = has_interface_with('ipaddress', $a) notice(inline_template('has_interface_with is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/has_interface_with is false/) + EOS + it 'has_interface_with absent ipaddress' do + apply_manifest(pp2, catch_failures: true) do |r| + expect(r.stdout).to match(%r{has_interface_with is false}) end end - it 'has_interface_with existing interface' do - pp = <<-EOS + + pp3 = <<-EOS if $osfamily == 'Solaris' or $osfamily == 'Darwin' { $a = 'lo0' }elsif $osfamily == 'windows' { @@ -40,10 +39,10 @@ } $o = has_interface_with($a) notice(inline_template('has_interface_with is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/has_interface_with is true/) + EOS + it 'has_interface_with existing interface' do + apply_manifest(pp3, catch_failures: true) do |r| + expect(r.stdout).to match(%r{has_interface_with is true}) end end end diff --git a/spec/acceptance/has_ip_address_spec.rb b/spec/acceptance/has_ip_address_spec.rb index 878d921b4..7f4c89afa 100755 --- a/spec/acceptance/has_ip_address_spec.rb +++ b/spec/acceptance/has_ip_address_spec.rb @@ -1,28 +1,27 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'has_ip_address function', :unless => ((fact('osfamily') == 'windows') or (fact('osfamily') == 'AIX')) do +describe 'has_ip_address function', unless: ((fact('osfamily') == 'windows') || (fact('osfamily') == 'AIX')) do describe 'success' do - it 'has_ip_address existing ipaddress' do - pp = <<-EOS + pp1 = <<-EOS $a = '127.0.0.1' $o = has_ip_address($a) notice(inline_template('has_ip_address is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/has_ip_address is true/) + EOS + it 'has_ip_address existing ipaddress' do + apply_manifest(pp1, catch_failures: true) do |r| + expect(r.stdout).to match(%r{has_ip_address is true}) end end - it 'has_ip_address absent ipaddress' do - pp = <<-EOS + + pp2 = <<-EOS $a = '128.0.0.1' $o = has_ip_address($a) notice(inline_template('has_ip_address is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/has_ip_address is false/) + EOS + it 'has_ip_address absent ipaddress' do + apply_manifest(pp2, catch_failures: true) do |r| + expect(r.stdout).to match(%r{has_ip_address is false}) end end end diff --git a/spec/acceptance/has_ip_network_spec.rb b/spec/acceptance/has_ip_network_spec.rb index f7a7d3533..b2f81c3c5 100755 --- a/spec/acceptance/has_ip_network_spec.rb +++ b/spec/acceptance/has_ip_network_spec.rb @@ -1,28 +1,27 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'has_ip_network function', :unless => ((fact('osfamily') == 'windows') or (fact('osfamily') == 'AIX')) do +describe 'has_ip_network function', unless: ((fact('osfamily') == 'windows') || (fact('osfamily') == 'AIX')) do describe 'success' do - it 'has_ip_network existing ipaddress' do - pp = <<-EOS + pp1 = <<-EOS $a = '127.0.0.0' $o = has_ip_network($a) notice(inline_template('has_ip_network is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/has_ip_network is true/) + EOS + it 'has_ip_network existing ipaddress' do + apply_manifest(pp1, catch_failures: true) do |r| + expect(r.stdout).to match(%r{has_ip_network is true}) end end - it 'has_ip_network absent ipaddress' do - pp = <<-EOS + + pp2 = <<-EOS $a = '128.0.0.0' $o = has_ip_network($a) notice(inline_template('has_ip_network is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/has_ip_network is false/) + EOS + it 'has_ip_network absent ipaddress' do + apply_manifest(pp2, catch_failures: true) do |r| + expect(r.stdout).to match(%r{has_ip_network is false}) end end end diff --git a/spec/acceptance/has_key_spec.rb b/spec/acceptance/has_key_spec.rb index 661c12250..3d024b403 100755 --- a/spec/acceptance/has_key_spec.rb +++ b/spec/acceptance/has_key_spec.rb @@ -3,8 +3,7 @@ describe 'has_key function' do describe 'success' do - it 'has_keys in hashes' do - pp = <<-EOS + pp1 = <<-EOS $a = { 'aaa' => 'bbb','bbb' => 'ccc','ddd' => 'eee' } $b = 'bbb' $c = true @@ -12,14 +11,14 @@ if $o == $c { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'has_keys in hashes' do + apply_manifest(pp1, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end - it 'has_keys not in hashes' do - pp = <<-EOS + + pp2 = <<-EOS $a = { 'aaa' => 'bbb','bbb' => 'ccc','ddd' => 'eee' } $b = 'ccc' $c = false @@ -27,10 +26,10 @@ if $o == $c { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'has_keys not in hashes' do + apply_manifest(pp2, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end end diff --git a/spec/acceptance/hash_spec.rb b/spec/acceptance/hash_spec.rb index 85da50bab..0ed90886d 100755 --- a/spec/acceptance/hash_spec.rb +++ b/spec/acceptance/hash_spec.rb @@ -3,18 +3,17 @@ describe 'hash function' do describe 'success' do - it 'hashs arrays' do - pp = <<-EOS + pp = <<-EOS $a = ['aaa','bbb','bbb','ccc','ddd','eee'] $b = { 'aaa' => 'bbb', 'bbb' => 'ccc', 'ddd' => 'eee' } $o = hash($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'hashs arrays' do + apply_manifest(pp, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end it 'handles odd-length arrays' diff --git a/spec/acceptance/intersection_spec.rb b/spec/acceptance/intersection_spec.rb index 02d4e7da2..a9dea7ff6 100755 --- a/spec/acceptance/intersection_spec.rb +++ b/spec/acceptance/intersection_spec.rb @@ -3,8 +3,7 @@ describe 'intersection function' do describe 'success' do - it 'intersections arrays' do - pp = <<-EOS + pp = <<-EOS $a = ['aaa','bbb','ccc'] $b = ['bbb','ccc','ddd','eee'] $c = ['bbb','ccc'] @@ -12,10 +11,10 @@ if $o == $c { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'intersections arrays' do + apply_manifest(pp, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end it 'intersections empty arrays' diff --git a/spec/acceptance/is_a_spec.rb b/spec/acceptance/is_a_spec.rb index fb0019a36..62570be0c 100644 --- a/spec/acceptance/is_a_spec.rb +++ b/spec/acceptance/is_a_spec.rb @@ -1,29 +1,27 @@ -#! /usr/bin/env ruby -S rspec +#! /usr/bin/env ruby -S rspec # rubocop:disable Lint/ScriptPermission : Rubocop Mistake??? require 'spec_helper_acceptance' -if get_puppet_version =~ /^4/ +if return_puppet_version =~ %r{^4} describe 'is_a function' do - it 'should match a string' do - pp = <<-EOS + pp1 = <<-EOS if 'hello world'.is_a(String) { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'matches a string' do + apply_manifest(pp1, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end - it 'should not match a integer as string' do - pp = <<-EOS + pp2 = <<-EOS if 5.is_a(String) { notify { 'output wrong': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).not_to match(/Notice: output wrong/) + EOS + it 'does not match a integer as string' do + apply_manifest(pp2, catch_failures: true) do |r| + expect(r.stdout).not_to match(%r{Notice: output wrong}) end end end diff --git a/spec/acceptance/is_array_spec.rb b/spec/acceptance/is_array_spec.rb index 1a834175b..b06b76dc0 100755 --- a/spec/acceptance/is_array_spec.rb +++ b/spec/acceptance/is_array_spec.rb @@ -3,60 +3,59 @@ describe 'is_array function' do describe 'success' do - it 'is_arrays arrays' do - pp = <<-EOS + pp1 = <<-EOS $a = ['aaa','bbb','ccc'] $b = true $o = is_array($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'is_arrays arrays' do + apply_manifest(pp1, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end - it 'is_arrays empty arrays' do - pp = <<-EOS + + pp2 = <<-EOS $a = [] $b = true $o = is_array($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'is_arrays empty arrays' do + apply_manifest(pp2, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end - it 'is_arrays strings' do - pp = <<-EOS + + pp3 = <<-EOS $a = "aoeu" $b = false $o = is_array($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'is_arrays strings' do + apply_manifest(pp3, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end - it 'is_arrays hashes' do - pp = <<-EOS + + pp4 = <<-EOS $a = {'aaa'=>'bbb'} $b = false $o = is_array($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'is_arrays hashes' do + apply_manifest(pp4, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end end diff --git a/spec/acceptance/is_bool_spec.rb b/spec/acceptance/is_bool_spec.rb index 823cb4673..fa962d335 100755 --- a/spec/acceptance/is_bool_spec.rb +++ b/spec/acceptance/is_bool_spec.rb @@ -3,74 +3,73 @@ describe 'is_bool function' do describe 'success' do - it 'is_bools arrays' do - pp = <<-EOS + pp1 = <<-EOS $a = ['aaa','bbb','ccc'] $b = false $o = is_bool($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'is_bools arrays' do + apply_manifest(pp1, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end - it 'is_bools true' do - pp = <<-EOS + + pp2 = <<-EOS $a = true $b = true $o = is_bool($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'is_bools true' do + apply_manifest(pp2, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end - it 'is_bools false' do - pp = <<-EOS + + pp3 = <<-EOS $a = false $b = true $o = is_bool($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'is_bools false' do + apply_manifest(pp3, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end - it 'is_bools strings' do - pp = <<-EOS + + pp4 = <<-EOS $a = "true" $b = false $o = is_bool($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'is_bools strings' do + apply_manifest(pp4, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end - it 'is_bools hashes' do - pp = <<-EOS + + pp5 = <<-EOS $a = {'aaa'=>'bbb'} $b = false $o = is_bool($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'is_bools hashes' do + apply_manifest(pp5, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end end diff --git a/spec/acceptance/is_domain_name_spec.rb b/spec/acceptance/is_domain_name_spec.rb index 884b0bcb1..aa69a5a95 100755 --- a/spec/acceptance/is_domain_name_spec.rb +++ b/spec/acceptance/is_domain_name_spec.rb @@ -3,76 +3,75 @@ describe 'is_domain_name function' do describe 'success' do - it 'is_domain_names arrays' do - pp = <<-EOS + pp1 = <<-EOS $a = ['aaa.com','bbb','ccc'] $o = is_domain_name($a) notice(inline_template('is_domain_name is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/is_domain_name is false/) + EOS + it 'is_domain_names arrays' do + apply_manifest(pp1, catch_failures: true) do |r| + expect(r.stdout).to match(%r{is_domain_name is false}) end end - it 'is_domain_names true' do - pp = <<-EOS + + pp2 = <<-EOS $a = true $o = is_domain_name($a) notice(inline_template('is_domain_name is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/is_domain_name is false/) + EOS + it 'is_domain_names true' do + apply_manifest(pp2, catch_failures: true) do |r| + expect(r.stdout).to match(%r{is_domain_name is false}) end end - it 'is_domain_names false' do - pp = <<-EOS + + pp3 = <<-EOS $a = false $o = is_domain_name($a) notice(inline_template('is_domain_name is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/is_domain_name is false/) + EOS + it 'is_domain_names false' do + apply_manifest(pp3, catch_failures: true) do |r| + expect(r.stdout).to match(%r{is_domain_name is false}) end end - it 'is_domain_names strings with hyphens' do - pp = <<-EOS + + pp4 = <<-EOS $a = "3foo-bar.2bar-fuzz.com" $b = true $o = is_domain_name($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'is_domain_names strings with hyphens' do + apply_manifest(pp4, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end - it 'is_domain_names strings beginning with hyphens' do - pp = <<-EOS + + pp5 = <<-EOS $a = "-bar.2bar-fuzz.com" $b = false $o = is_domain_name($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'is_domain_names strings beginning with hyphens' do + apply_manifest(pp5, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end - it 'is_domain_names hashes' do - pp = <<-EOS + + pp6 = <<-EOS $a = {'aaa'=>'www.com'} $o = is_domain_name($a) notice(inline_template('is_domain_name is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/is_domain_name is false/) + EOS + it 'is_domain_names hashes' do + apply_manifest(pp6, catch_failures: true) do |r| + expect(r.stdout).to match(%r{is_domain_name is false}) end end end diff --git a/spec/acceptance/is_float_spec.rb b/spec/acceptance/is_float_spec.rb index 0b38d9423..1447dda4c 100755 --- a/spec/acceptance/is_float_spec.rb +++ b/spec/acceptance/is_float_spec.rb @@ -3,79 +3,78 @@ describe 'is_float function' do describe 'success' do - it 'is_floats arrays' do - pp = <<-EOS + pp1 = <<-EOS $a = ['aaa.com','bbb','ccc'] $o = is_float($a) notice(inline_template('is_float is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/is_float is false/) + EOS + it 'is_floats arrays' do + apply_manifest(pp1, catch_failures: true) do |r| + expect(r.stdout).to match(%r{is_float is false}) end end - it 'is_floats true' do - pp = <<-EOS + + pp2 = <<-EOS $a = true $o = is_float($a) notice(inline_template('is_float is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/is_float is false/) + EOS + it 'is_floats true' do + apply_manifest(pp2, catch_failures: true) do |r| + expect(r.stdout).to match(%r{is_float is false}) end end - it 'is_floats strings' do - pp = <<-EOS + + pp3 = <<-EOS $a = "3.5" $b = true $o = is_float($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'is_floats strings' do + apply_manifest(pp3, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end - it 'is_floats floats' do - pp = <<-EOS + + pp4 = <<-EOS $a = 3.5 $b = true $o = is_float($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'is_floats floats' do + apply_manifest(pp4, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end - it 'is_floats integers' do - pp = <<-EOS + + pp5 = <<-EOS $a = 3 $b = false $o = is_float($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'is_floats integers' do + apply_manifest(pp5, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end - it 'is_floats hashes' do - pp = <<-EOS + + pp6 = <<-EOS $a = {'aaa'=>'www.com'} $o = is_float($a) notice(inline_template('is_float is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/is_float is false/) + EOS + it 'is_floats hashes' do + apply_manifest(pp6, catch_failures: true) do |r| + expect(r.stdout).to match(%r{is_float is false}) end end end diff --git a/spec/acceptance/is_function_available_spec.rb b/spec/acceptance/is_function_available_spec.rb index f8191ee7a..a8827af35 100755 --- a/spec/acceptance/is_function_available_spec.rb +++ b/spec/acceptance/is_function_available_spec.rb @@ -3,51 +3,50 @@ describe 'is_function_available function' do describe 'success' do - it 'is_function_availables arrays' do - pp = <<-EOS + pp1 = <<-EOS $a = ['fail','include','require'] $o = is_function_available($a) notice(inline_template('is_function_available is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/is_function_available is false/) + EOS + it 'is_function_availables arrays' do + apply_manifest(pp1, catch_failures: true) do |r| + expect(r.stdout).to match(%r{is_function_available is false}) end end - it 'is_function_availables true' do - pp = <<-EOS + + pp2 = <<-EOS $a = true $o = is_function_available($a) notice(inline_template('is_function_available is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/is_function_available is false/) + EOS + it 'is_function_availables true' do + apply_manifest(pp2, catch_failures: true) do |r| + expect(r.stdout).to match(%r{is_function_available is false}) end end - it 'is_function_availables strings' do - pp = <<-EOS + + pp3 = <<-EOS $a = "fail" $b = true $o = is_function_available($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'is_function_availables strings' do + apply_manifest(pp3, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end - it 'is_function_availables function_availables' do - pp = <<-EOS + + pp4 = <<-EOS $a = "is_function_available" $o = is_function_available($a) notice(inline_template('is_function_available is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/is_function_available is true/) + EOS + it 'is_function_availables function_availables' do + apply_manifest(pp4, catch_failures: true) do |r| + expect(r.stdout).to match(%r{is_function_available is true}) end end end diff --git a/spec/acceptance/is_hash_spec.rb b/spec/acceptance/is_hash_spec.rb index 64f016c66..8cb9bec4e 100755 --- a/spec/acceptance/is_hash_spec.rb +++ b/spec/acceptance/is_hash_spec.rb @@ -3,57 +3,56 @@ describe 'is_hash function' do describe 'success' do - it 'is_hashs arrays' do - pp = <<-EOS + pp1 = <<-EOS $a = ['aaa','bbb','ccc'] $o = is_hash($a) notice(inline_template('is_hash is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/is_hash is false/) + EOS + it 'is_hashs arrays' do + apply_manifest(pp1, catch_failures: true) do |r| + expect(r.stdout).to match(%r{is_hash is false}) end end - it 'is_hashs empty hashs' do - pp = <<-EOS + + pp2 = <<-EOS $a = {} $b = true $o = is_hash($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'is_hashs empty hashs' do + apply_manifest(pp2, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end - it 'is_hashs strings' do - pp = <<-EOS + + pp3 = <<-EOS $a = "aoeu" $b = false $o = is_hash($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'is_hashs strings' do + apply_manifest(pp3, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end - it 'is_hashs hashes' do - pp = <<-EOS + + pp4 = <<-EOS $a = {'aaa'=>'bbb'} $b = true $o = is_hash($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'is_hashs hashes' do + apply_manifest(pp4, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end end diff --git a/spec/acceptance/is_integer_spec.rb b/spec/acceptance/is_integer_spec.rb index 7333687c5..693879235 100755 --- a/spec/acceptance/is_integer_spec.rb +++ b/spec/acceptance/is_integer_spec.rb @@ -3,88 +3,87 @@ describe 'is_integer function' do describe 'success' do - it 'is_integers arrays' do - pp = <<-EOS + pp1 = <<-EOS $a = ['aaa.com','bbb','ccc'] $b = false $o = is_integer($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'is_integers arrays' do + apply_manifest(pp1, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end - it 'is_integers true' do - pp = <<-EOS + + pp2 = <<-EOS $a = true $b = false $o = is_integer($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'is_integers true' do + apply_manifest(pp2, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end - it 'is_integers strings' do - pp = <<-EOS + + pp3 = <<-EOS $a = "3" $b = true $o = is_integer($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'is_integers strings' do + apply_manifest(pp3, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end - it 'is_integers floats' do - pp = <<-EOS + + pp4 = <<-EOS $a = 3.5 $b = false $o = is_integer($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'is_integers floats' do + apply_manifest(pp4, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end - it 'is_integers integers' do - pp = <<-EOS + + pp5 = <<-EOS $a = 3 $b = true $o = is_integer($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'is_integers integers' do + apply_manifest(pp5, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end - it 'is_integers hashes' do - pp = <<-EOS + + pp6 = <<-EOS $a = {'aaa'=>'www.com'} $b = false $o = is_integer($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'is_integers hashes' do + apply_manifest(pp6, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end end diff --git a/spec/acceptance/is_ip_address_spec.rb b/spec/acceptance/is_ip_address_spec.rb index 2c62c778d..c77fc0ef5 100755 --- a/spec/acceptance/is_ip_address_spec.rb +++ b/spec/acceptance/is_ip_address_spec.rb @@ -3,74 +3,73 @@ describe 'is_ip_address function' do describe 'success' do - it 'is_ip_addresss ipv4' do - pp = <<-EOS + pp1 = <<-EOS $a = '1.2.3.4' $b = true $o = is_ip_address($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'is_ip_addresss ipv4' do + apply_manifest(pp1, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end - it 'is_ip_addresss ipv6' do - pp = <<-EOS + + pp2 = <<-EOS $a = "fe80:0000:cd12:d123:e2f8:47ff:fe09:dd74" $b = true $o = is_ip_address($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'is_ip_addresss ipv6' do + apply_manifest(pp2, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end - it 'is_ip_addresss ipv6 compressed' do - pp = <<-EOS + + pp3 = <<-EOS $a = "fe00::1" $b = true $o = is_ip_address($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'is_ip_addresss ipv6 compressed' do + apply_manifest(pp3, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end - it 'is_ip_addresss strings' do - pp = <<-EOS + + pp4 = <<-EOS $a = "aoeu" $b = false $o = is_ip_address($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'is_ip_addresss strings' do + apply_manifest(pp4, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end - it 'is_ip_addresss ipv4 out of range' do - pp = <<-EOS + + pp5 = <<-EOS $a = '1.2.3.400' $b = false $o = is_ip_address($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'is_ip_addresss ipv4 out of range' do + apply_manifest(pp5, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end end diff --git a/spec/acceptance/is_ipv4_address_spec.rb b/spec/acceptance/is_ipv4_address_spec.rb index abe26d80f..fab7b0148 100755 --- a/spec/acceptance/is_ipv4_address_spec.rb +++ b/spec/acceptance/is_ipv4_address_spec.rb @@ -3,46 +3,45 @@ describe 'is_ipv4_address function' do describe 'success' do - it 'is_ipv4_addresss' do - pp = <<-EOS + pp1 = <<-EOS $a = '1.2.3.4' $b = true $o = is_ipv4_address($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'is_ipv4_addresss' do + apply_manifest(pp1, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end - it 'is_ipv4_addresss strings' do - pp = <<-EOS + + pp2 = <<-EOS $a = "aoeu" $b = false $o = is_ipv4_address($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'is_ipv4_addresss strings' do + apply_manifest(pp2, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end - it 'is_ipv4_addresss ipv4 out of range' do - pp = <<-EOS + + pp3 = <<-EOS $a = '1.2.3.400' $b = false $o = is_ipv4_address($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'is_ipv4_addresss ipv4 out of range' do + apply_manifest(pp3, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end end diff --git a/spec/acceptance/is_ipv6_address_spec.rb b/spec/acceptance/is_ipv6_address_spec.rb index 73a3fa411..90e1524a5 100755 --- a/spec/acceptance/is_ipv6_address_spec.rb +++ b/spec/acceptance/is_ipv6_address_spec.rb @@ -3,60 +3,59 @@ describe 'is_ipv6_address function' do describe 'success' do - it 'is_ipv6_addresss' do - pp = <<-EOS + pp1 = <<-EOS $a = "fe80:0000:cd12:d123:e2f8:47ff:fe09:dd74" $b = true $o = is_ipv6_address($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'is_ipv6_addresss' do + apply_manifest(pp1, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end - it 'is_ipv6_addresss ipv6 compressed' do - pp = <<-EOS + + pp2 = <<-EOS $a = "fe00::1" $b = true $o = is_ipv6_address($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'is_ipv6_addresss ipv6 compressed' do + apply_manifest(pp2, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end - it 'is_ipv6_addresss strings' do - pp = <<-EOS + + pp3 = <<-EOS $a = "aoeu" $b = false $o = is_ipv6_address($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'is_ipv6_addresss strings' do + apply_manifest(pp3, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end - it 'is_ipv6_addresss ip out of range' do - pp = <<-EOS + + pp4 = <<-EOS $a = 'fe80:0000:cd12:d123:e2f8:47ff:fe09:gggg' $b = false $o = is_ipv6_address($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'is_ipv6_addresss ip out of range' do + apply_manifest(pp4, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end end diff --git a/spec/acceptance/is_mac_address_spec.rb b/spec/acceptance/is_mac_address_spec.rb index 617bef668..f6fc251fc 100755 --- a/spec/acceptance/is_mac_address_spec.rb +++ b/spec/acceptance/is_mac_address_spec.rb @@ -3,32 +3,31 @@ describe 'is_mac_address function' do describe 'success' do - it 'is_mac_addresss a mac' do - pp = <<-EOS + pp1 = <<-EOS $a = '00:a0:1f:12:7f:a0' $b = true $o = is_mac_address($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'is_mac_addresss a mac' do + apply_manifest(pp1, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end - it 'is_mac_addresss a mac out of range' do - pp = <<-EOS + + pp2 = <<-EOS $a = '00:a0:1f:12:7f:g0' $b = false $o = is_mac_address($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'is_mac_addresss a mac out of range' do + apply_manifest(pp2, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end end diff --git a/spec/acceptance/is_numeric_spec.rb b/spec/acceptance/is_numeric_spec.rb index 7e6538446..1157dfb80 100755 --- a/spec/acceptance/is_numeric_spec.rb +++ b/spec/acceptance/is_numeric_spec.rb @@ -3,88 +3,87 @@ describe 'is_numeric function' do describe 'success' do - it 'is_numerics arrays' do - pp = <<-EOS + pp1 = <<-EOS $a = ['aaa.com','bbb','ccc'] $b = false $o = is_numeric($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'is_numerics arrays' do + apply_manifest(pp1, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end - it 'is_numerics true' do - pp = <<-EOS + + pp2 = <<-EOS $a = true $b = false $o = is_numeric($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'is_numerics true' do + apply_manifest(pp2, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end - it 'is_numerics strings' do - pp = <<-EOS + + pp3 = <<-EOS $a = "3" $b = true $o = is_numeric($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'is_numerics strings' do + apply_manifest(pp3, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end - it 'is_numerics floats' do - pp = <<-EOS + + pp4 = <<-EOS $a = 3.5 $b = true $o = is_numeric($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'is_numerics floats' do + apply_manifest(pp4, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end - it 'is_numerics integers' do - pp = <<-EOS + + pp5 = <<-EOS $a = 3 $b = true $o = is_numeric($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'is_numerics integers' do + apply_manifest(pp5, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end - it 'is_numerics hashes' do - pp = <<-EOS + + pp6 = <<-EOS $a = {'aaa'=>'www.com'} $b = false $o = is_numeric($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'is_numerics hashes' do + apply_manifest(pp6, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end end diff --git a/spec/acceptance/is_string_spec.rb b/spec/acceptance/is_string_spec.rb index bee5e0149..7d5d10bcc 100755 --- a/spec/acceptance/is_string_spec.rb +++ b/spec/acceptance/is_string_spec.rb @@ -3,107 +3,106 @@ describe 'is_string function' do describe 'success' do - it 'is_strings arrays' do - pp = <<-EOS + pp1 = <<-EOS $a = ['aaa.com','bbb','ccc'] $b = false $o = is_string($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'is_strings arrays' do + apply_manifest(pp1, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end - it 'is_strings true' do - pp = <<-EOS + + pp2 = <<-EOS $a = true $b = false $o = is_string($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'is_strings true' do + apply_manifest(pp2, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end - it 'is_strings strings' do - pp = <<-EOS + + pp3 = <<-EOS $a = "aoeu" $o = is_string($a) notice(inline_template('is_string is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/is_string is true/) + EOS + it 'is_strings strings' do + apply_manifest(pp3, catch_failures: true) do |r| + expect(r.stdout).to match(%r{is_string is true}) end end - it 'is_strings number strings' do - pp = <<-EOS + + pp4 = <<-EOS $a = "3" $o = is_string($a) notice(inline_template('is_string is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/is_string is false/) + EOS + it 'is_strings number strings' do + apply_manifest(pp4, catch_failures: true) do |r| + expect(r.stdout).to match(%r{is_string is false}) end end - it 'is_strings floats' do - pp = <<-EOS + + pp5 = <<-EOS $a = 3.5 $b = false $o = is_string($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'is_strings floats' do + apply_manifest(pp5, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end - it 'is_strings integers' do - pp = <<-EOS + + pp6 = <<-EOS $a = 3 $b = false $o = is_string($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'is_strings integers' do + apply_manifest(pp6, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end - it 'is_strings hashes' do - pp = <<-EOS + + pp7 = <<-EOS $a = {'aaa'=>'www.com'} $b = false $o = is_string($a) if $o == $b { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'is_strings hashes' do + apply_manifest(pp7, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end - it 'is_strings undef' do - pp = <<-EOS + + pp8 = <<-EOS $a = undef $o = is_string($a) notice(inline_template('is_string is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/is_string is true/) + EOS + it 'is_strings undef' do + apply_manifest(pp8, catch_failures: true) do |r| + expect(r.stdout).to match(%r{is_string is true}) end end end diff --git a/spec/acceptance/join_keys_to_values_spec.rb b/spec/acceptance/join_keys_to_values_spec.rb index ae6947e9b..8b30f208a 100755 --- a/spec/acceptance/join_keys_to_values_spec.rb +++ b/spec/acceptance/join_keys_to_values_spec.rb @@ -3,16 +3,15 @@ describe 'join_keys_to_values function' do describe 'success' do - it 'join_keys_to_valuess hashes' do - pp = <<-EOS + pp = <<-EOS $a = {'aaa'=>'bbb','ccc'=>'ddd'} $b = ':' $o = join_keys_to_values($a,$b) notice(inline_template('join_keys_to_values is <%= @o.sort.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/join_keys_to_values is \["aaa:bbb", "ccc:ddd"\]/) + EOS + it 'join_keys_to_valuess hashes' do + apply_manifest(pp, catch_failures: true) do |r| + expect(r.stdout).to match(%r{join_keys_to_values is \["aaa:bbb", "ccc:ddd"\]}) end end it 'handles non hashes' diff --git a/spec/acceptance/join_spec.rb b/spec/acceptance/join_spec.rb index 75b88d818..95b367552 100755 --- a/spec/acceptance/join_spec.rb +++ b/spec/acceptance/join_spec.rb @@ -3,8 +3,7 @@ describe 'join function' do describe 'success' do - it 'joins arrays' do - pp = <<-EOS + pp = <<-EOS $a = ['aaa','bbb','ccc'] $b = ':' $c = 'aaa:bbb:ccc' @@ -12,10 +11,10 @@ if $o == $c { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'joins arrays' do + apply_manifest(pp, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end it 'handles non arrays' diff --git a/spec/acceptance/keys_spec.rb b/spec/acceptance/keys_spec.rb index 65bfe2871..06b01f8bc 100755 --- a/spec/acceptance/keys_spec.rb +++ b/spec/acceptance/keys_spec.rb @@ -3,15 +3,14 @@ describe 'keys function' do describe 'success' do - it 'keyss hashes' do - pp = <<-EOS + pp = <<-EOS $a = {'aaa'=>'bbb','ccc'=>'ddd'} $o = keys($a) notice(inline_template('keys is <%= @o.sort.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/keys is \["aaa", "ccc"\]/) + EOS + it 'keyss hashes' do + apply_manifest(pp, catch_failures: true) do |r| + expect(r.stdout).to match(%r{keys is \["aaa", "ccc"\]}) end end it 'handles non hashes' diff --git a/spec/acceptance/loadjson_spec.rb b/spec/acceptance/loadjson_spec.rb index ebd5307e2..8665730a0 100644 --- a/spec/acceptance/loadjson_spec.rb +++ b/spec/acceptance/loadjson_spec.rb @@ -1,48 +1,45 @@ -#! /usr/bin/env ruby -S rspec +#! /usr/bin/env ruby -S rspec # rubocop:disable Lint/ScriptPermission : Rubocop Error require 'spec_helper_acceptance' tmpdir = default.tmpdir('stdlib') describe 'loadjson function' do describe 'success' do - it 'loadjsons array of values' do - shell("echo '{\"aaa\":1,\"bbb\":2,\"ccc\":3,\"ddd\":4}' > #{tmpdir}/testjson.json") - pp = <<-EOS - $o = loadjson('#{tmpdir}/testjson.json') + shell("echo '{\"aaa\":1,\"bbb\":2,\"ccc\":3,\"ddd\":4}' > #{tmpdir}/test1json.json") + pp1 = <<-EOS + $o = loadjson('#{tmpdir}/test1json.json') notice(inline_template('loadjson[aaa] is <%= @o["aaa"].inspect %>')) notice(inline_template('loadjson[bbb] is <%= @o["bbb"].inspect %>')) notice(inline_template('loadjson[ccc] is <%= @o["ccc"].inspect %>')) notice(inline_template('loadjson[ddd] is <%= @o["ddd"].inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/loadjson\[aaa\] is 1/) - expect(r.stdout).to match(/loadjson\[bbb\] is 2/) - expect(r.stdout).to match(/loadjson\[ccc\] is 3/) - expect(r.stdout).to match(/loadjson\[ddd\] is 4/) + EOS + regex_array = [%r{loadjson\[aaa\] is 1}, %r{loadjson\[bbb\] is 2}, %r{loadjson\[ccc\] is 3}, %r{loadjson\[ddd\] is 4}] + it 'loadjsons array of values' do + apply_manifest(pp1, catch_failures: true) do |r| + regex_array.each do |i| + expect(r.stdout).to match(i) + end end end - it 'returns the default value if there is no file to load' do - pp = <<-EOS + pp2 = <<-EOS $o = loadjson('#{tmpdir}/no-file.json', {'default' => 'value'}) notice(inline_template('loadjson[default] is <%= @o["default"].inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/loadjson\[default\] is "value"/) + EOS + it 'returns the default value if there is no file to load' do + apply_manifest(pp2, catch_failures: true) do |r| + expect(r.stdout).to match(%r{loadjson\[default\] is "value"}) end end - it 'returns the default value if the file was parsed with an error' do - shell("echo '!' > #{tmpdir}/testjson.json") - pp = <<-EOS - $o = loadjson('#{tmpdir}/testjson.json', {'default' => 'value'}) + shell("echo '!' > #{tmpdir}/test2json.json") + pp3 = <<-EOS + $o = loadjson('#{tmpdir}/test2json.json', {'default' => 'value'}) notice(inline_template('loadjson[default] is <%= @o["default"].inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/loadjson\[default\] is "value"/) + EOS + it 'returns the default value if the file was parsed with an error' do + apply_manifest(pp3, catch_failures: true) do |r| + expect(r.stdout).to match(%r{loadjson\[default\] is "value"}) end end end diff --git a/spec/acceptance/loadyaml_spec.rb b/spec/acceptance/loadyaml_spec.rb index 57fb8cbbb..721d42892 100644 --- a/spec/acceptance/loadyaml_spec.rb +++ b/spec/acceptance/loadyaml_spec.rb @@ -1,52 +1,49 @@ -#! /usr/bin/env ruby -S rspec +#! /usr/bin/env ruby -S rspec # rubocop:disable Lint/ScriptPermission : Rubocop Error require 'spec_helper_acceptance' tmpdir = default.tmpdir('stdlib') describe 'loadyaml function' do describe 'success' do - it 'loadyamls array of values' do - shell("echo '--- + shell("echo '--- aaa: 1 bbb: 2 ccc: 3 - ddd: 4' > #{tmpdir}/testyaml.yaml") - pp = <<-EOS - $o = loadyaml('#{tmpdir}/testyaml.yaml') + ddd: 4' > #{tmpdir}/test1yaml.yaml") + pp1 = <<-EOS + $o = loadyaml('#{tmpdir}/test1yaml.yaml') notice(inline_template('loadyaml[aaa] is <%= @o["aaa"].inspect %>')) notice(inline_template('loadyaml[bbb] is <%= @o["bbb"].inspect %>')) notice(inline_template('loadyaml[ccc] is <%= @o["ccc"].inspect %>')) notice(inline_template('loadyaml[ddd] is <%= @o["ddd"].inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/loadyaml\[aaa\] is 1/) - expect(r.stdout).to match(/loadyaml\[bbb\] is 2/) - expect(r.stdout).to match(/loadyaml\[ccc\] is 3/) - expect(r.stdout).to match(/loadyaml\[ddd\] is 4/) + EOS + regex_array = [%r{loadyaml\[aaa\] is 1}, %r{loadyaml\[bbb\] is 2}, %r{loadyaml\[ccc\] is 3}, %r{loadyaml\[ddd\] is 4}] + it 'loadyamls array of values' do + apply_manifest(pp1, catch_failures: true) do |r| + regex_array.each do |i| + expect(r.stdout).to match(i) + end end end - it 'returns the default value if there is no file to load' do - pp = <<-EOS + pp2 = <<-EOS $o = loadyaml('#{tmpdir}/no-file.yaml', {'default' => 'value'}) notice(inline_template('loadyaml[default] is <%= @o["default"].inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/loadyaml\[default\] is "value"/) + EOS + it 'returns the default value if there is no file to load' do + apply_manifest(pp2, catch_failures: true) do |r| + expect(r.stdout).to match(%r{loadyaml\[default\] is "value"}) end end - it 'returns the default value if the file was parsed with an error' do - shell("echo '!' > #{tmpdir}/testyaml.yaml") - pp = <<-EOS - $o = loadyaml('#{tmpdir}/testyaml.yaml', {'default' => 'value'}) + shell("echo '!' > #{tmpdir}/test2yaml.yaml") + pp3 = <<-EOS + $o = loadyaml('#{tmpdir}/test2yaml.yaml', {'default' => 'value'}) notice(inline_template('loadyaml[default] is <%= @o["default"].inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/loadyaml\[default\] is "value"/) + EOS + it 'returns the default value if the file was parsed with an error' do + apply_manifest(pp3, catch_failures: true) do |r| + expect(r.stdout).to match(%r{loadyaml\[default\] is "value"}) end end end diff --git a/spec/acceptance/lstrip_spec.rb b/spec/acceptance/lstrip_spec.rb index eba5d0d06..c0739abfe 100755 --- a/spec/acceptance/lstrip_spec.rb +++ b/spec/acceptance/lstrip_spec.rb @@ -3,27 +3,26 @@ describe 'lstrip function' do describe 'success' do - it 'lstrips arrays' do - pp = <<-EOS + pp1 = <<-EOS $a = [" the "," public "," art","galleries "] # Anagram: Large picture halls, I bet $o = lstrip($a) notice(inline_template('lstrip is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/lstrip is \["the ", "public ", "art", "galleries "\]/) + EOS + it 'lstrips arrays' do + apply_manifest(pp1, catch_failures: true) do |r| + expect(r.stdout).to match(%r{lstrip is \["the ", "public ", "art", "galleries "\]}) end end - it 'lstrips strings' do - pp = <<-EOS + + pp2 = <<-EOS $a = " blowzy night-frumps vex'd jack q " $o = lstrip($a) notice(inline_template('lstrip is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/lstrip is "blowzy night-frumps vex'd jack q "/) + EOS + it 'lstrips strings' do + apply_manifest(pp2, catch_failures: true) do |r| + expect(r.stdout).to match(%r{lstrip is "blowzy night-frumps vex'd jack q "}) end end end diff --git a/spec/acceptance/max_spec.rb b/spec/acceptance/max_spec.rb index 3caa8131b..2b903866b 100755 --- a/spec/acceptance/max_spec.rb +++ b/spec/acceptance/max_spec.rb @@ -3,14 +3,13 @@ describe 'max function' do describe 'success' do - it 'maxs arrays' do - pp = <<-EOS + pp = <<-EOS $o = max("the","public","art","galleries") notice(inline_template('max is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/max is "the"/) + EOS + it 'maxs arrays' do + apply_manifest(pp, catch_failures: true) do |r| + expect(r.stdout).to match(%r{max is "the"}) end end end diff --git a/spec/acceptance/member_spec.rb b/spec/acceptance/member_spec.rb index 2bcadd395..96232a762 100755 --- a/spec/acceptance/member_spec.rb +++ b/spec/acceptance/member_spec.rb @@ -3,15 +3,14 @@ describe 'member function' do shared_examples 'item found' do - it 'should output correctly' do - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + it 'outputs correctly' do + apply_manifest(pp, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end end describe 'success' do - it 'members arrays' do - pp = <<-EOS + pp1 = <<-EOS $a = ['aaa','bbb','ccc'] $b = 'ccc' $c = true @@ -19,30 +18,33 @@ if $o == $c { notify { 'output correct': } } - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/Notice: output correct/) + EOS + it 'members arrays' do + apply_manifest(pp1, catch_failures: true) do |r| + expect(r.stdout).to match(%r{Notice: output correct}) end end + describe 'members array of integers' do - it_should_behave_like 'item found' do - let(:pp) { <<-EOS - if member( [1,2,3,4], 4 ){ - notify { 'output correct': } - } - EOS - } + it_behaves_like 'item found' do + let(:pp) do # rubocop:disable RSpec/LetBeforeExamples : 'let' required to be inside example for it to work + <<-EOS + if member( [1,2,3,4], 4 ){ + notify { 'output correct': } + } + EOS + end end end describe 'members of mixed array' do - it_should_behave_like 'item found' do - let(:pp) { <<-EOS - if member( ['a','4',3], 'a' ){ - notify { 'output correct': } -} - EOS - } + it_behaves_like 'item found' do + let(:pp) do # rubocop:disable RSpec/LetBeforeExamples : 'let' required to be inside example for it to work + <<-EOS + if member( ['a','4',3], 'a' ){ + notify { 'output correct': } + } + EOS + end end end it 'members arrays without members' diff --git a/spec/acceptance/merge_spec.rb b/spec/acceptance/merge_spec.rb index 814db4e13..5ce305503 100755 --- a/spec/acceptance/merge_spec.rb +++ b/spec/acceptance/merge_spec.rb @@ -3,20 +3,20 @@ describe 'merge function' do describe 'success' do - it 'should merge two hashes' do - pp = <<-EOS + pp = <<-EOS $a = {'one' => 1, 'two' => 2, 'three' => { 'four' => 4 } } $b = {'two' => 'dos', 'three' => { 'five' => 5 } } $o = merge($a, $b) notice(inline_template('merge[one] is <%= @o["one"].inspect %>')) notice(inline_template('merge[two] is <%= @o["two"].inspect %>')) notice(inline_template('merge[three] is <%= @o["three"].inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/merge\[one\] is ("1"|1)/) - expect(r.stdout).to match(/merge\[two\] is "dos"/) - expect(r.stdout).to match(/merge\[three\] is {"five"=>("5"|5)}/) + EOS + regex_array = [%r{merge\[one\] is ("1"|1)}, %r{merge\[two\] is "dos"}, %r{merge\[three\] is {"five"=>("5"|5)}}] + it 'merges two hashes' do + apply_manifest(pp, catch_failures: true) do |r| + regex_array.each do |i| + expect(r.stdout).to match(i) + end end end end diff --git a/spec/acceptance/min_spec.rb b/spec/acceptance/min_spec.rb index 7b18facdf..fd12e2a7a 100755 --- a/spec/acceptance/min_spec.rb +++ b/spec/acceptance/min_spec.rb @@ -3,14 +3,13 @@ describe 'min function' do describe 'success' do - it 'mins arrays' do - pp = <<-EOS + pp = <<-EOS $o = min("the","public","art","galleries") notice(inline_template('min is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/min is "art"/) + EOS + it 'mins arrays' do + apply_manifest(pp, catch_failures: true) do |r| + expect(r.stdout).to match(%r{min is "art"}) end end end diff --git a/spec/acceptance/num2bool_spec.rb b/spec/acceptance/num2bool_spec.rb index 00d0ddc09..41cad9031 100755 --- a/spec/acceptance/num2bool_spec.rb +++ b/spec/acceptance/num2bool_spec.rb @@ -3,8 +3,7 @@ describe 'num2bool function' do describe 'success' do - it 'bools positive numbers and numeric strings as true' do - pp = <<-EOS + pp1 = <<-EOS $a = 1 $b = "1" $c = "50" @@ -14,16 +13,17 @@ notice(inline_template('a is <%= @ao.inspect %>')) notice(inline_template('b is <%= @bo.inspect %>')) notice(inline_template('c is <%= @co.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/a is true/) - expect(r.stdout).to match(/b is true/) - expect(r.stdout).to match(/c is true/) + EOS + regex_array_true = [%r{a is true}, %r{b is true}, %r{c is true}] + it 'bools positive numbers and numeric strings as true' do + apply_manifest(pp1, catch_failures: true) do |r| + regex_array_true.each do |i| + expect(r.stdout).to match(i) + end end end - it 'bools negative numbers as false' do - pp = <<-EOS + + pp2 = <<-EOS $a = 0 $b = -0.1 $c = ["-50","1"] @@ -33,44 +33,45 @@ notice(inline_template('a is <%= @ao.inspect %>')) notice(inline_template('b is <%= @bo.inspect %>')) notice(inline_template('c is <%= @co.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/a is false/) - expect(r.stdout).to match(/b is false/) - expect(r.stdout).to match(/c is false/) + EOS + regex_array_false = [%r{a is false}, %r{b is false}, %r{c is false}] + it 'bools negative numbers as false' do + apply_manifest(pp2, catch_failures: true) do |r| + regex_array_false.each do |i| + expect(r.stdout).to match(i) + end end end end + describe 'failure' do - it 'fails on words' do - pp = <<-EOS + pp3 = <<-EOS $a = "a" $ao = num2bool($a) notice(inline_template('a is <%= @ao.inspect %>')) - EOS - expect(apply_manifest(pp, :expect_failures => true).stderr).to match(/not look like a number/) + EOS + it 'fails on words' do + expect(apply_manifest(pp3, expect_failures: true).stderr).to match(%r{not look like a number}) end - it 'fails on numberwords' do - pp = <<-EOS + pp4 = <<-EOS $b = "1b" $bo = num2bool($b) notice(inline_template('b is <%= @bo.inspect %>')) - EOS - expect(apply_manifest(pp, :expect_failures => true).stderr).to match(/not look like a number/) - + EOS + it 'fails on numberwords' do + expect(apply_manifest(pp4, expect_failures: true).stderr).to match(%r{not look like a number}) end - it 'fails on non-numeric/strings' do - pending "The function will call .to_s.to_i on anything not a Numeric or - String, and results in 0. Is this intended?" - pp = <<-EOS + pp5 = <<-EOS # rubocop:disable Lint/UselessAssignment $c = {"c" => "-50"} $co = num2bool($c) notice(inline_template('c is <%= @co.inspect %>')) - EOS - expect(apply_manifest(ppc :expect_failures => true).stderr).to match(/Unable to parse/) + EOS + it 'fails on non-numeric/strings' do + pending "The function will call .to_s.to_i on anything not a Numeric or + String, and results in 0. Is this intended?" + expect(apply_manifest(pp5(expect_failures: true)).stderr).to match(%r{Unable to parse}) end end end diff --git a/spec/acceptance/parsejson_spec.rb b/spec/acceptance/parsejson_spec.rb index 52133e436..1dcfd5514 100755 --- a/spec/acceptance/parsejson_spec.rb +++ b/spec/acceptance/parsejson_spec.rb @@ -3,52 +3,48 @@ describe 'parsejson function' do describe 'success' do - it 'parses valid json' do - pp = <<-EOS + pp1 = <<-EOS $a = '{"hunter": "washere", "tests": "passing"}' $ao = parsejson($a) $tests = $ao['tests'] notice(inline_template('tests are <%= @tests.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/tests are "passing"/) + EOS + it 'parses valid json' do + apply_manifest(pp1, catch_failures: true) do |r| + expect(r.stdout).to match(%r{tests are "passing"}) end end end describe 'failure' do - it 'raises error on incorrect json' do - pp = <<-EOS + pp2 = <<-EOS $a = '{"hunter": "washere", "tests": "passing",}' $ao = parsejson($a, 'tests are using the default value') notice(inline_template('a is <%= @ao.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/tests are using the default value/) + EOS + it 'raises error on incorrect json - default value is used' do + apply_manifest(pp2, catch_failures: true) do |r| + expect(r.stdout).to match(%r{tests are using the default value}) end end - it 'raises error on incorrect json' do - pp = <<-EOS + pp3 = <<-EOS $a = '{"hunter": "washere", "tests": "passing",}' $ao = parsejson($a) notice(inline_template('a is <%= @ao.inspect %>')) - EOS - - apply_manifest(pp, :expect_failures => true) do |r| - expect(r.stderr).to match(/expected next name/) + EOS + it 'raises error on incorrect json' do + apply_manifest(pp3, expect_failures: true) do |r| + expect(r.stderr).to match(%r{expected next name}) end end - it 'raises error on incorrect number of arguments' do - pp = <<-EOS + pp4 = <<-EOS $o = parsejson() - EOS - - apply_manifest(pp, :expect_failures => true) do |r| - expect(r.stderr).to match(/wrong number of arguments/i) + EOS + it 'raises error on incorrect number of arguments' do + apply_manifest(pp4, expect_failures: true) do |r| + expect(r.stderr).to match(%r{wrong number of arguments}i) end end end diff --git a/spec/acceptance/parseyaml_spec.rb b/spec/acceptance/parseyaml_spec.rb index acbda46ee..985c45629 100755 --- a/spec/acceptance/parseyaml_spec.rb +++ b/spec/acceptance/parseyaml_spec.rb @@ -3,55 +3,50 @@ describe 'parseyaml function' do describe 'success' do - it 'parses valid yaml' do - pp = <<-EOS + pp1 = <<-EOS $a = "---\nhunter: washere\ntests: passing\n" $o = parseyaml($a) $tests = $o['tests'] notice(inline_template('tests are <%= @tests.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/tests are "passing"/) + EOS + it 'parses valid yaml' do + apply_manifest(pp1, catch_failures: true) do |r| + expect(r.stdout).to match(%r{tests are "passing"}) end end end describe 'failure' do - it 'returns the default value on incorrect yaml' do - pp = <<-EOS + pp2 = <<-EOS $a = "---\nhunter: washere\ntests: passing\n:" $o = parseyaml($a, {'tests' => 'using the default value'}) $tests = $o['tests'] notice(inline_template('tests are <%= @tests.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/tests are "using the default value"/) + EOS + it 'returns the default value on incorrect yaml' do + apply_manifest(pp2, catch_failures: true) do |r| + expect(r.stdout).to match(%r{tests are "using the default value"}) end end - it 'raises error on incorrect yaml' do - pp = <<-EOS + pp3 = <<-EOS $a = "---\nhunter: washere\ntests: passing\n:" $o = parseyaml($a) $tests = $o['tests'] notice(inline_template('tests are <%= @tests.inspect %>')) - EOS - - apply_manifest(pp, :expect_failures => true) do |r| - expect(r.stderr).to match(/(syntax error|did not find expected key)/) + EOS + it 'raises error on incorrect yaml' do + apply_manifest(pp3, expect_failures: true) do |r| + expect(r.stderr).to match(%r{(syntax error|did not find expected key)}) end end - - it 'raises error on incorrect number of arguments' do - pp = <<-EOS + pp4 = <<-EOS $o = parseyaml() - EOS - - apply_manifest(pp, :expect_failures => true) do |r| - expect(r.stderr).to match(/wrong number of arguments/i) + EOS + it 'raises error on incorrect number of arguments' do + apply_manifest(pp4, expect_failures: true) do |r| + expect(r.stderr).to match(%r{wrong number of arguments}i) end end end diff --git a/spec/acceptance/pick_default_spec.rb b/spec/acceptance/pick_default_spec.rb index e7e25ab5c..473768942 100755 --- a/spec/acceptance/pick_default_spec.rb +++ b/spec/acceptance/pick_default_spec.rb @@ -3,51 +3,49 @@ describe 'pick_default function' do describe 'success' do - it 'pick_defaults a default value' do - pp = <<-EOS + pp1 = <<-EOS $a = undef $o = pick_default($a, 'default') notice(inline_template('picked is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/picked is "default"/) + EOS + it 'pick_defaults a default value' do + apply_manifest(pp1, catch_failures: true) do |r| + expect(r.stdout).to match(%r{picked is "default"}) end end - it 'pick_defaults with no value' do - pp = <<-EOS + + pp2 = <<-EOS $a = undef $b = undef $o = pick_default($a,$b) notice(inline_template('picked is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/picked is ""/) + EOS + it 'pick_defaults with no value' do + apply_manifest(pp2, catch_failures: true) do |r| + expect(r.stdout).to match(%r{picked is ""}) end end - it 'pick_defaults the first set value' do - pp = <<-EOS + + pp3 = <<-EOS $a = "something" $b = "long" $o = pick_default($a, $b, 'default') notice(inline_template('picked is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/picked is "something"/) + EOS + it 'pick_defaults the first set value' do + apply_manifest(pp3, catch_failures: true) do |r| + expect(r.stdout).to match(%r{picked is "something"}) end end end describe 'failure' do - it 'raises error with no values' do - pp = <<-EOS + pp4 = <<-EOS $o = pick_default() notice(inline_template('picked is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :expect_failures => true) do |r| - expect(r.stderr).to match(/Must receive at least one argument/) + EOS + it 'raises error with no values' do + apply_manifest(pp4, expect_failures: true) do |r| + expect(r.stderr).to match(%r{Must receive at least one argument}) end end end diff --git a/spec/acceptance/pick_spec.rb b/spec/acceptance/pick_spec.rb index c70b2d91e..8ab9e00b7 100755 --- a/spec/acceptance/pick_spec.rb +++ b/spec/acceptance/pick_spec.rb @@ -3,41 +3,40 @@ describe 'pick function' do describe 'success' do - it 'picks a default value' do - pp = <<-EOS + pp1 = <<-EOS $a = undef $o = pick($a, 'default') notice(inline_template('picked is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/picked is "default"/) + EOS + it 'picks a default value' do + apply_manifest(pp1, catch_failures: true) do |r| + expect(r.stdout).to match(%r{picked is "default"}) end end - it 'picks the first set value' do - pp = <<-EOS + + pp2 = <<-EOS $a = "something" $b = "long" $o = pick($a, $b, 'default') notice(inline_template('picked is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/picked is "something"/) + EOS + it 'picks the first set value' do + apply_manifest(pp2, catch_failures: true) do |r| + expect(r.stdout).to match(%r{picked is "something"}) end end end + describe 'failure' do - it 'raises error with all undef values' do - pp = <<-EOS + pp3 = <<-EOS $a = undef $b = undef $o = pick($a, $b) notice(inline_template('picked is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :expect_failures => true) do |r| - expect(r.stderr).to match(/must receive at least one non empty value/) + EOS + it 'raises error with all undef values' do + apply_manifest(pp3, expect_failures: true) do |r| + expect(r.stderr).to match(%r{must receive at least one non empty value}) end end end diff --git a/spec/acceptance/prefix_spec.rb b/spec/acceptance/prefix_spec.rb index 58c691d11..d5efe25bc 100755 --- a/spec/acceptance/prefix_spec.rb +++ b/spec/acceptance/prefix_spec.rb @@ -3,34 +3,33 @@ describe 'prefix function' do describe 'success' do - it 'prefixes array of values' do - pp = <<-EOS + pp1 = <<-EOS $o = prefix(['a','b','c'],'p') notice(inline_template('prefix is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/prefix is \["pa", "pb", "pc"\]/) + EOS + it 'prefixes array of values' do + apply_manifest(pp1, catch_failures: true) do |r| + expect(r.stdout).to match(%r{prefix is \["pa", "pb", "pc"\]}) end end - it 'prefixs with empty array' do - pp = <<-EOS + + pp2 = <<-EOS $o = prefix([],'p') notice(inline_template('prefix is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/prefix is \[\]/) + EOS + it 'prefixs with empty array' do + apply_manifest(pp2, catch_failures: true) do |r| + expect(r.stdout).to match(%r{prefix is \[\]}) end end - it 'prefixs array of values with undef' do - pp = <<-EOS + + pp3 = <<-EOS $o = prefix(['a','b','c'], undef) notice(inline_template('prefix is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/prefix is \["a", "b", "c"\]/) + EOS + it 'prefixs array of values with undef' do + apply_manifest(pp3, catch_failures: true) do |r| + expect(r.stdout).to match(%r{prefix is \["a", "b", "c"\]}) end end end diff --git a/spec/acceptance/pw_hash_spec.rb b/spec/acceptance/pw_hash_spec.rb index 829d08777..6e0a9cf90 100644 --- a/spec/acceptance/pw_hash_spec.rb +++ b/spec/acceptance/pw_hash_spec.rb @@ -1,28 +1,26 @@ -#! /usr/bin/env ruby -S rspec +#! /usr/bin/env ruby -S rspec # rubocop:disable Lint/ScriptPermission require 'spec_helper_acceptance' # Windows and OS X do not have useful implementations of crypt(3) -describe 'pw_hash function', :unless => (['windows', 'Darwin', 'SLES']).include?(fact('operatingsystem')) do +describe 'pw_hash function', unless: %w[windows Darwin SLES].include?(fact('operatingsystem')) do describe 'success' do - it 'hashes passwords' do - pp = <<-EOS + pp1 = <<-EOS $o = pw_hash('password', 'sha-512', 'salt') notice(inline_template('pw_hash is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/pw_hash is "\$6\$salt\$IxDD3jeSOb5eB1CX5LBsqZFVkJdido3OUILO5Ifz5iwMuTS4XMS130MTSuDDl3aCI6WouIL9AjRbLCelDCy\.g\."/) + EOS + it 'hashes passwords' do + apply_manifest(pp1, catch_failures: true) do |r| + expect(r.stdout).to match(%r{pw_hash is "\$6\$salt\$IxDD3jeSOb5eB1CX5LBsqZFVkJdido3OUILO5Ifz5iwMuTS4XMS130MTSuDDl3aCI6WouIL9AjRbLCelDCy\.g\."}) end end - it 'returns nil if no password is provided' do - pp = <<-EOS + pp2 = <<-EOS $o = pw_hash('', 'sha-512', 'salt') notice(inline_template('pw_hash is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/pw_hash is nil/) + EOS + it 'returns nil if no password is provided' do + apply_manifest(pp2, catch_failures: true) do |r| + expect(r.stdout).to match(%r{pw_hash is nil}) end end end diff --git a/spec/acceptance/range_spec.rb b/spec/acceptance/range_spec.rb index f57f8840d..6bc9aeed2 100755 --- a/spec/acceptance/range_spec.rb +++ b/spec/acceptance/range_spec.rb @@ -3,24 +3,23 @@ describe 'range function' do describe 'success' do - it 'ranges letters' do - pp = <<-EOS + pp1 = <<-EOS $o = range('a','d') notice(inline_template('range is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/range is \["a", "b", "c", "d"\]/) + EOS + it 'ranges letters' do + apply_manifest(pp1, catch_failures: true) do |r| + expect(r.stdout).to match(%r{range is \["a", "b", "c", "d"\]}) end end - it 'ranges letters with a step' do - pp = <<-EOS + + pp2 = <<-EOS $o = range('a','d', '2') notice(inline_template('range is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/range is \["a", "c"\]/) + EOS + it 'ranges letters with a step' do + apply_manifest(pp2, catch_failures: true) do |r| + expect(r.stdout).to match(%r{range is \["a", "c"\]}) end end it 'ranges letters with a negative step' diff --git a/spec/acceptance/reject_spec.rb b/spec/acceptance/reject_spec.rb index ce4342d61..a9983e114 100755 --- a/spec/acceptance/reject_spec.rb +++ b/spec/acceptance/reject_spec.rb @@ -3,34 +3,33 @@ describe 'reject function' do describe 'success' do - it 'rejects array of values' do - pp = <<-EOS + pp1 = <<-EOS $o = reject(['aaa','bbb','ccc','aaaddd'], 'aaa') notice(inline_template('reject is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/reject is \["bbb", "ccc"\]/) + EOS + it 'rejects array of values' do + apply_manifest(pp1, catch_failures: true) do |r| + expect(r.stdout).to match(%r{reject is \["bbb", "ccc"\]}) end end - it 'rejects with empty array' do - pp = <<-EOS + + pp2 = <<-EOS $o = reject([],'aaa') notice(inline_template('reject is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/reject is \[\]/) + EOS + it 'rejects with empty array' do + apply_manifest(pp2, catch_failures: true) do |r| + expect(r.stdout).to match(%r{reject is \[\]}) end end - it 'rejects array of values with undef' do - pp = <<-EOS + + pp3 = <<-EOS $o = reject(['aaa','bbb','ccc','aaaddd'], undef) notice(inline_template('reject is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/reject is \[\]/) + EOS + it 'rejects array of values with undef' do + apply_manifest(pp3, catch_failures: true) do |r| + expect(r.stdout).to match(%r{reject is \[\]}) end end end diff --git a/spec/acceptance/reverse_spec.rb b/spec/acceptance/reverse_spec.rb index 3b5dfade7..f8759cc8c 100755 --- a/spec/acceptance/reverse_spec.rb +++ b/spec/acceptance/reverse_spec.rb @@ -3,16 +3,15 @@ describe 'reverse function' do describe 'success' do - it 'reverses strings' do - pp = <<-EOS + pp1 = <<-EOS $a = "the public art galleries" # Anagram: Large picture halls, I bet $o = reverse($a) notice(inline_template('reverse is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/reverse is "seirellag tra cilbup eht"/) + EOS + it 'reverses strings' do + apply_manifest(pp1, catch_failures: true) do |r| + expect(r.stdout).to match(%r{reverse is "seirellag tra cilbup eht"}) end end end diff --git a/spec/acceptance/rstrip_spec.rb b/spec/acceptance/rstrip_spec.rb index 150dac15b..0616aa701 100755 --- a/spec/acceptance/rstrip_spec.rb +++ b/spec/acceptance/rstrip_spec.rb @@ -3,27 +3,26 @@ describe 'rstrip function' do describe 'success' do - it 'rstrips arrays' do - pp = <<-EOS + pp1 = <<-EOS $a = [" the "," public "," art","galleries "] # Anagram: Large picture halls, I bet $o = rstrip($a) notice(inline_template('rstrip is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/rstrip is \[" the", " public", " art", "galleries"\]/) + EOS + it 'rstrips arrays' do + apply_manifest(pp1, catch_failures: true) do |r| + expect(r.stdout).to match(%r{rstrip is \[" the", " public", " art", "galleries"\]}) end end - it 'rstrips strings' do - pp = <<-EOS + + pp2 = <<-EOS $a = " blowzy night-frumps vex'd jack q " $o = rstrip($a) notice(inline_template('rstrip is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/rstrip is " blowzy night-frumps vex'd jack q"/) + EOS + it 'rstrips strings' do + apply_manifest(pp2, catch_failures: true) do |r| + expect(r.stdout).to match(%r{rstrip is " blowzy night-frumps vex'd jack q"}) end end end diff --git a/spec/acceptance/shuffle_spec.rb b/spec/acceptance/shuffle_spec.rb index 0738383c7..99a74776e 100755 --- a/spec/acceptance/shuffle_spec.rb +++ b/spec/acceptance/shuffle_spec.rb @@ -3,27 +3,26 @@ describe 'shuffle function' do describe 'success' do - it 'shuffles arrays' do - pp = <<-EOS + pp1 = <<-EOS $a = ["1", "2", "3", "4", "5", "6", "7", "8", "the","public","art","galleries"] # Anagram: Large picture halls, I bet $o = shuffle($a) notice(inline_template('shuffle is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to_not match(/shuffle is \["1", "2", "3", "4", "5", "6", "7", "8", "the", "public", "art", "galleries"\]/) + EOS + it 'shuffles arrays' do + apply_manifest(pp1, catch_failures: true) do |r| + expect(r.stdout).not_to match(%r{shuffle is \["1", "2", "3", "4", "5", "6", "7", "8", "the", "public", "art", "galleries"\]}) end end - it 'shuffles strings' do - pp = <<-EOS + + pp2 = <<-EOS $a = "blowzy night-frumps vex'd jack q" $o = shuffle($a) notice(inline_template('shuffle is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to_not match(/shuffle is "blowzy night-frumps vex'd jack q"/) + EOS + it 'shuffles strings' do + apply_manifest(pp2, catch_failures: true) do |r| + expect(r.stdout).not_to match(%r{shuffle is "blowzy night-frumps vex'd jack q"}) end end end diff --git a/spec/acceptance/size_spec.rb b/spec/acceptance/size_spec.rb index 6390c20df..dc8f2bd6c 100755 --- a/spec/acceptance/size_spec.rb +++ b/spec/acceptance/size_spec.rb @@ -3,48 +3,47 @@ describe 'size function' do describe 'success' do - it 'single string size' do - pp = <<-EOS + pp1 = <<-EOS $a = 'discombobulate' $o = size($a) notice(inline_template('size is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/size is 14/) + EOS + it 'single string size' do + apply_manifest(pp1, catch_failures: true) do |r| + expect(r.stdout).to match(%r{size is 14}) end end - it 'with empty string' do - pp = <<-EOS + + pp2 = <<-EOS $a = '' $o = size($a) notice(inline_template('size is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/size is 0/) + EOS + it 'with empty string' do + apply_manifest(pp2, catch_failures: true) do |r| + expect(r.stdout).to match(%r{size is 0}) end end - it 'with undef' do - pp = <<-EOS + + pp3 = <<-EOS $a = undef $o = size($a) notice(inline_template('size is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/size is 0/) + EOS + it 'with undef' do + apply_manifest(pp3, catch_failures: true) do |r| + expect(r.stdout).to match(%r{size is 0}) end end - it 'strings in array' do - pp = <<-EOS + + pp4 = <<-EOS $a = ['discombobulate', 'moo'] $o = size($a) notice(inline_template('size is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/size is 2/) + EOS + it 'strings in array' do + apply_manifest(pp4, catch_failures: true) do |r| + expect(r.stdout).to match(%r{size is 2}) end end end diff --git a/spec/acceptance/sort_spec.rb b/spec/acceptance/sort_spec.rb index e7ff7f709..a9fb5b541 100755 --- a/spec/acceptance/sort_spec.rb +++ b/spec/acceptance/sort_spec.rb @@ -3,27 +3,26 @@ describe 'sort function' do describe 'success' do - it 'sorts arrays' do - pp = <<-EOS + pp1 = <<-EOS $a = ["the","public","art","galleries"] # Anagram: Large picture halls, I bet $o = sort($a) notice(inline_template('sort is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/sort is \["art", "galleries", "public", "the"\]/) + EOS + it 'sorts arrays' do + apply_manifest(pp1, catch_failures: true) do |r| + expect(r.stdout).to match(%r{sort is \["art", "galleries", "public", "the"\]}) end end - it 'sorts strings' do - pp = <<-EOS + + pp2 = <<-EOS $a = "blowzy night-frumps vex'd jack q" $o = sort($a) notice(inline_template('sort is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/sort is " '-abcdefghijklmnopqrstuvwxyz"/) + EOS + it 'sorts strings' do + apply_manifest(pp2, catch_failures: true) do |r| + expect(r.stdout).to match(%r{sort is " '-abcdefghijklmnopqrstuvwxyz"}) end end end diff --git a/spec/acceptance/squeeze_spec.rb b/spec/acceptance/squeeze_spec.rb index 33246916d..97d0917a4 100755 --- a/spec/acceptance/squeeze_spec.rb +++ b/spec/acceptance/squeeze_spec.rb @@ -3,40 +3,38 @@ describe 'squeeze function' do describe 'success' do - it 'squeezes arrays' do - pp = <<-EOS + pp1 = <<-EOS # Real words! $a = ["wallless", "laparohysterosalpingooophorectomy", "brrr", "goddessship"] $o = squeeze($a) notice(inline_template('squeeze is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/squeeze is \["wales", "laparohysterosalpingophorectomy", "br", "godeship"\]/) + EOS + it 'squeezes arrays' do + apply_manifest(pp1, catch_failures: true) do |r| + expect(r.stdout).to match(%r{squeeze is \["wales", "laparohysterosalpingophorectomy", "br", "godeship"\]}) end end + it 'squeezez arrays with an argument' - it 'squeezes strings' do - pp = <<-EOS + pp2 = <<-EOS $a = "wallless laparohysterosalpingooophorectomy brrr goddessship" $o = squeeze($a) notice(inline_template('squeeze is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/squeeze is "wales laparohysterosalpingophorectomy br godeship"/) + EOS + it 'squeezes strings' do + apply_manifest(pp2, catch_failures: true) do |r| + expect(r.stdout).to match(%r{squeeze is "wales laparohysterosalpingophorectomy br godeship"}) end end - it 'squeezes strings with an argument' do - pp = <<-EOS + pp3 = <<-EOS $a = "countessship duchessship governessship hostessship" $o = squeeze($a, 's') notice(inline_template('squeeze is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/squeeze is "counteship ducheship governeship hosteship"/) + EOS + it 'squeezes strings with an argument' do + apply_manifest(pp3, catch_failures: true) do |r| + expect(r.stdout).to match(%r{squeeze is "counteship ducheship governeship hosteship"}) end end end diff --git a/spec/acceptance/str2bool_spec.rb b/spec/acceptance/str2bool_spec.rb index 9a8c06ce8..06558b360 100755 --- a/spec/acceptance/str2bool_spec.rb +++ b/spec/acceptance/str2bool_spec.rb @@ -3,14 +3,13 @@ describe 'str2bool function' do describe 'success' do - it 'works with "y"' do - pp = <<-EOS + pp = <<-EOS $o = str2bool('y') notice(inline_template('str2bool is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/str2bool is true/) + EOS + it 'works with "y"' do + apply_manifest(pp, catch_failures: true) do |r| + expect(r.stdout).to match(%r{str2bool is true}) end end it 'works with "Y"' diff --git a/spec/acceptance/str2saltedsha512_spec.rb b/spec/acceptance/str2saltedsha512_spec.rb index 5f03924b6..6bff4eb93 100755 --- a/spec/acceptance/str2saltedsha512_spec.rb +++ b/spec/acceptance/str2saltedsha512_spec.rb @@ -3,14 +3,13 @@ describe 'str2saltedsha512 function' do describe 'success' do - it 'works with "y"' do - pp = <<-EOS + pp = <<-EOS $o = str2saltedsha512('password') notice(inline_template('str2saltedsha512 is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/str2saltedsha512 is "[a-f0-9]{136}"/) + EOS + it 'works with "y"' do + apply_manifest(pp, catch_failures: true) do |r| + expect(r.stdout).to match(%r{str2saltedsha512 is "[a-f0-9]{136}"}) end end end diff --git a/spec/acceptance/strftime_spec.rb b/spec/acceptance/strftime_spec.rb index 38521b006..d2973f0af 100755 --- a/spec/acceptance/strftime_spec.rb +++ b/spec/acceptance/strftime_spec.rb @@ -3,14 +3,13 @@ describe 'strftime function' do describe 'success' do - it 'gives the Century' do - pp = <<-EOS + pp = <<-EOS $o = strftime('%C') notice(inline_template('strftime is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/strftime is "20"/) + EOS + it 'gives the Century' do + apply_manifest(pp, catch_failures: true) do |r| + expect(r.stdout).to match(%r{strftime is "20"}) end end it 'takes a timezone argument' diff --git a/spec/acceptance/strip_spec.rb b/spec/acceptance/strip_spec.rb index 05cd39596..cd6599c59 100755 --- a/spec/acceptance/strip_spec.rb +++ b/spec/acceptance/strip_spec.rb @@ -3,27 +3,26 @@ describe 'strip function' do describe 'success' do - it 'strips arrays' do - pp = <<-EOS + pp1 = <<-EOS $a = [" the "," public "," art","galleries "] # Anagram: Large picture halls, I bet $o = strip($a) notice(inline_template('strip is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/strip is \["the", "public", "art", "galleries"\]/) + EOS + it 'strips arrays' do + apply_manifest(pp1, catch_failures: true) do |r| + expect(r.stdout).to match(%r{strip is \["the", "public", "art", "galleries"\]}) end end - it 'strips strings' do - pp = <<-EOS + + pp2 = <<-EOS $a = " blowzy night-frumps vex'd jack q " $o = strip($a) notice(inline_template('strip is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/strip is "blowzy night-frumps vex'd jack q"/) + EOS + it 'strips strings' do + apply_manifest(pp2, catch_failures: true) do |r| + expect(r.stdout).to match(%r{strip is "blowzy night-frumps vex'd jack q"}) end end end diff --git a/spec/acceptance/suffix_spec.rb b/spec/acceptance/suffix_spec.rb index 60a62649f..d1cabf11f 100755 --- a/spec/acceptance/suffix_spec.rb +++ b/spec/acceptance/suffix_spec.rb @@ -3,34 +3,33 @@ describe 'suffix function' do describe 'success' do - it 'suffixes array of values' do - pp = <<-EOS + pp1 = <<-EOS $o = suffix(['a','b','c'],'p') notice(inline_template('suffix is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/suffix is \["ap", "bp", "cp"\]/) + EOS + it 'suffixes array of values' do + apply_manifest(pp1, catch_failures: true) do |r| + expect(r.stdout).to match(%r{suffix is \["ap", "bp", "cp"\]}) end end - it 'suffixs with empty array' do - pp = <<-EOS + + pp2 = <<-EOS $o = suffix([],'p') notice(inline_template('suffix is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/suffix is \[\]/) + EOS + it 'suffixs with empty array' do + apply_manifest(pp2, catch_failures: true) do |r| + expect(r.stdout).to match(%r{suffix is \[\]}) end end - it 'suffixs array of values with undef' do - pp = <<-EOS + + pp3 = <<-EOS $o = suffix(['a','b','c'], undef) notice(inline_template('suffix is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/suffix is \["a", "b", "c"\]/) + EOS + it 'suffixs array of values with undef' do + apply_manifest(pp3, catch_failures: true) do |r| + expect(r.stdout).to match(%r{suffix is \["a", "b", "c"\]}) end end end diff --git a/spec/acceptance/swapcase_spec.rb b/spec/acceptance/swapcase_spec.rb index 9f94c0ded..c23235ef0 100755 --- a/spec/acceptance/swapcase_spec.rb +++ b/spec/acceptance/swapcase_spec.rb @@ -3,14 +3,13 @@ describe 'swapcase function' do describe 'success' do - it 'works with strings' do - pp = <<-EOS + pp = <<-EOS $o = swapcase('aBcD') notice(inline_template('swapcase is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/swapcase is "AbCd"/) + EOS + it 'works with strings' do + apply_manifest(pp, catch_failures: true) do |r| + expect(r.stdout).to match(%r{swapcase is "AbCd"}) end end it 'works with arrays' diff --git a/spec/acceptance/time_spec.rb b/spec/acceptance/time_spec.rb index dae11666b..390b5f849 100755 --- a/spec/acceptance/time_spec.rb +++ b/spec/acceptance/time_spec.rb @@ -3,29 +3,26 @@ describe 'time function' do describe 'success' do - it 'gives the time' do - pp = <<-EOS + pp1 = <<-EOS $o = time() notice(inline_template('time is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - m = r.stdout.match(/time is (\d+)\D/) - + EOS + it 'gives the time' do + apply_manifest(pp1, catch_failures: true) do |r| + m = r.stdout.match(%r{time is (\d+)\D}) # When I wrote this test - expect(Integer(m[1])).to be > 1398894170 + expect(Integer(m[1])).to be > 1_398_894_170 end end - it 'takes a timezone argument' do - pp = <<-EOS + + pp2 = <<-EOS $o = time('UTC') notice(inline_template('time is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - m = r.stdout.match(/time is (\d+)\D/) - - expect(Integer(m[1])).to be > 1398894170 + EOS + it 'takes a timezone argument' do + apply_manifest(pp2, catch_failures: true) do |r| + m = r.stdout.match(%r{time is (\d+)\D}) + expect(Integer(m[1])).to be > 1_398_894_170 end end end diff --git a/spec/acceptance/to_bytes_spec.rb b/spec/acceptance/to_bytes_spec.rb index b1015a393..9fb898fdd 100755 --- a/spec/acceptance/to_bytes_spec.rb +++ b/spec/acceptance/to_bytes_spec.rb @@ -3,15 +3,14 @@ describe 'to_bytes function' do describe 'success' do - it 'converts kB to B' do - pp = <<-EOS + pp = <<-EOS $o = to_bytes('4 kB') notice(inline_template('to_bytes is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - m = r.stdout.match(/to_bytes is (\d+)\D/) - expect(m[1]).to eq("4096") + EOS + it 'converts kB to B' do + apply_manifest(pp, catch_failures: true) do |r| + m = r.stdout.match(%r{to_bytes is (\d+)\D}) + expect(m[1]).to eq('4096') end end it 'works without the B in unit' diff --git a/spec/acceptance/try_get_value_spec.rb b/spec/acceptance/try_get_value_spec.rb index 716241c04..5bf461c4d 100755 --- a/spec/acceptance/try_get_value_spec.rb +++ b/spec/acceptance/try_get_value_spec.rb @@ -3,44 +3,42 @@ describe 'try_get_value function' do describe 'success' do - it 'gets a value' do - pp = <<-EOS + pp1 = <<-EOS $data = { 'a' => { 'b' => 'passing'} } $tests = try_get_value($data, 'a/b') notice(inline_template('tests are <%= @tests.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/tests are "passing"/) + EOS + it 'gets a value' do + apply_manifest(pp1, catch_failures: true) do |r| + expect(r.stdout).to match(%r{tests are "passing"}) end end end + describe 'failure' do - it 'uses a default value' do - pp = <<-EOS + pp2 = <<-EOS $data = { 'a' => { 'b' => 'passing'} } $tests = try_get_value($data, 'c/d', 'using the default value') notice(inline_template('tests are <%= @tests.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/using the default value/) + EOS + it 'uses a default value' do + apply_manifest(pp2, catch_failures: true) do |r| + expect(r.stdout).to match(%r{using the default value}) end end - it 'raises error on incorrect number of arguments' do - pp = <<-EOS + pp = <<-EOS $o = try_get_value() - EOS - - apply_manifest(pp, :expect_failures => true) do |r| - expect(r.stderr).to match(/wrong number of arguments/i) + EOS + it 'raises error on incorrect number of arguments' do + apply_manifest(pp, expect_failures: true) do |r| + expect(r.stderr).to match(%r{wrong number of arguments}i) end end end diff --git a/spec/acceptance/type_spec.rb b/spec/acceptance/type_spec.rb index 5cc947028..57ed16d57 100755 --- a/spec/acceptance/type_spec.rb +++ b/spec/acceptance/type_spec.rb @@ -3,27 +3,26 @@ describe 'type function' do describe 'success' do - it 'types arrays' do - pp = <<-EOS + pp1 = <<-EOS $a = ["the","public","art","galleries"] # Anagram: Large picture halls, I bet $o = type($a) notice(inline_template('type is <%= @o.to_s %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/type is Tuple\[String.*, String.*, String.*, String.*\]/) + EOS + it 'types arrays' do + apply_manifest(pp1, catch_failures: true) do |r| + expect(r.stdout).to match(%r{type is Tuple\[String.*, String.*, String.*, String.*\]}) end end - it 'types strings' do - pp = <<-EOS + + pp2 = <<-EOS $a = "blowzy night-frumps vex'd jack q" $o = type($a) notice(inline_template('type is <%= @o.to_s %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/type is String/) + EOS + it 'types strings' do + apply_manifest(pp2, catch_failures: true) do |r| + expect(r.stdout).to match(%r{type is String}) end end it 'types hashes' diff --git a/spec/acceptance/union_spec.rb b/spec/acceptance/union_spec.rb index 7229bf572..dd0793b4e 100755 --- a/spec/acceptance/union_spec.rb +++ b/spec/acceptance/union_spec.rb @@ -3,18 +3,17 @@ describe 'union function' do describe 'success' do - it 'unions arrays' do - pp = <<-EOS + pp = <<-EOS $a = ["the","public"] $b = ["art"] $c = ["galleries"] # Anagram: Large picture halls, I bet $o = union($a,$b,$c) notice(inline_template('union is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/union is \["the", "public", "art", "galleries"\]/) + EOS + it 'unions arrays' do + apply_manifest(pp, catch_failures: true) do |r| + expect(r.stdout).to match(%r{union is \["the", "public", "art", "galleries"\]}) end end end diff --git a/spec/acceptance/unique_spec.rb b/spec/acceptance/unique_spec.rb index 7fb5eca61..14369dfcd 100755 --- a/spec/acceptance/unique_spec.rb +++ b/spec/acceptance/unique_spec.rb @@ -3,26 +3,25 @@ describe 'unique function' do describe 'success' do - it 'uniques arrays' do - pp = <<-EOS + pp1 = <<-EOS $a = ["wallless", "wallless", "brrr", "goddessship"] $o = unique($a) notice(inline_template('unique is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/unique is \["wallless", "brrr", "goddessship"\]/) + EOS + it 'uniques arrays' do + apply_manifest(pp1, catch_failures: true) do |r| + expect(r.stdout).to match(%r{unique is \["wallless", "brrr", "goddessship"\]}) end end - it 'uniques strings' do - pp = <<-EOS + + pp2 = <<-EOS $a = "wallless laparohysterosalpingooophorectomy brrr goddessship" $o = unique($a) notice(inline_template('unique is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/unique is "wales prohytingcmbd"/) + EOS + it 'uniques strings' do + apply_manifest(pp2, catch_failures: true) do |r| + expect(r.stdout).to match(%r{unique is "wales prohytingcmbd"}) end end end diff --git a/spec/acceptance/upcase_spec.rb b/spec/acceptance/upcase_spec.rb index 178230927..522ff0d4a 100755 --- a/spec/acceptance/upcase_spec.rb +++ b/spec/acceptance/upcase_spec.rb @@ -3,26 +3,25 @@ describe 'upcase function' do describe 'success' do - it 'upcases arrays' do - pp = <<-EOS + pp1 = <<-EOS $a = ["wallless", "laparohysterosalpingooophorectomy", "brrr", "goddessship"] $o = upcase($a) notice(inline_template('upcase is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/upcase is \["WALLLESS", "LAPAROHYSTEROSALPINGOOOPHORECTOMY", "BRRR", "GODDESSSHIP"\]/) + EOS + it 'upcases arrays' do + apply_manifest(pp1, catch_failures: true) do |r| + expect(r.stdout).to match(%r{upcase is \["WALLLESS", "LAPAROHYSTEROSALPINGOOOPHORECTOMY", "BRRR", "GODDESSSHIP"\]}) end end - it 'upcases strings' do - pp = <<-EOS + + pp2 = <<-EOS $a = "wallless laparohysterosalpingooophorectomy brrr goddessship" $o = upcase($a) notice(inline_template('upcase is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/upcase is "WALLLESS LAPAROHYSTEROSALPINGOOOPHORECTOMY BRRR GODDESSSHIP"/) + EOS + it 'upcases strings' do + apply_manifest(pp2, catch_failures: true) do |r| + expect(r.stdout).to match(%r{upcase is "WALLLESS LAPAROHYSTEROSALPINGOOOPHORECTOMY BRRR GODDESSSHIP"}) end end end diff --git a/spec/acceptance/uriescape_spec.rb b/spec/acceptance/uriescape_spec.rb index e1234259c..0f3d13acb 100755 --- a/spec/acceptance/uriescape_spec.rb +++ b/spec/acceptance/uriescape_spec.rb @@ -3,15 +3,14 @@ describe 'uriescape function' do describe 'success' do - it 'uriescape strings' do - pp = <<-EOS + pp = <<-EOS $a = ":/?#[]@!$&'()*+,;= \\\"{}" $o = uriescape($a) notice(inline_template('uriescape is <%= @o.inspect %>')) - EOS - - apply_manifest(pp, :catch_failures => true) do |r| - expect(r.stdout).to match(/uriescape is ":\/\?%23\[\]@!\$&'\(\)\*\+,;=%20%22%7B%7D"/) + EOS + it 'uriescape strings' do + apply_manifest(pp, catch_failures: true) do |r| + expect(r.stdout).to match(%r{uriescape is ":\/\?%23\[\]@!\$&'\(\)\*\+,;=%20%22%7B%7D"}) end end it 'does nothing if a string is already safe' diff --git a/spec/acceptance/validate_absolute_path_spec.rb b/spec/acceptance/validate_absolute_path_spec.rb index 880850d66..cba8a64d7 100755 --- a/spec/acceptance/validate_absolute_path_spec.rb +++ b/spec/acceptance/validate_absolute_path_spec.rb @@ -3,7 +3,7 @@ describe 'validate_absolute_path function' do describe 'success' do - %w{ + %w[ C:/ C:\\\\ C:\\\\WINDOWS\\\\System32 @@ -13,14 +13,13 @@ /var/tmp /var/lib/puppet /var/opt/../lib/puppet - }.each do |path| - it "validates a single argument #{path}" do - pp = <<-EOS + ].each do |path| + pp = <<-EOS $one = '#{path}' validate_absolute_path($one) - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it "validates a single argument #{path}" do + apply_manifest(pp, catch_failures: true) end end end diff --git a/spec/acceptance/validate_array_spec.rb b/spec/acceptance/validate_array_spec.rb index a76321dc9..b91dc8e10 100755 --- a/spec/acceptance/validate_array_spec.rb +++ b/spec/acceptance/validate_array_spec.rb @@ -3,31 +3,30 @@ describe 'validate_array function' do describe 'success' do - it 'validates a single argument' do - pp = <<-EOS + pp1 = <<-EOS $one = ['a', 'b'] validate_array($one) - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'validates a single argument' do + apply_manifest(pp1, catch_failures: true) end - it 'validates an multiple arguments' do - pp = <<-EOS + + pp2 = <<-EOS $one = ['a', 'b'] $two = [['c'], 'd'] validate_array($one,$two) - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'validates an multiple arguments' do + apply_manifest(pp2, catch_failures: true) end [ %{validate_array({'a' => 'hash' })}, %{validate_array('string')}, %{validate_array(false)}, - %{validate_array(undef)} + %{validate_array(undef)}, ].each do |pp| it "rejects #{pp.inspect}" do - expect(apply_manifest(pp, :expect_failures => true).stderr).to match(/is not an Array\. It looks to be a/) + expect(apply_manifest(pp, expect_failures: true).stderr).to match(%r{is not an Array\. It looks to be a}) end end end diff --git a/spec/acceptance/validate_augeas_spec.rb b/spec/acceptance/validate_augeas_spec.rb index be213d3e7..d08a1ca4d 100755 --- a/spec/acceptance/validate_augeas_spec.rb +++ b/spec/acceptance/validate_augeas_spec.rb @@ -1,7 +1,7 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper_acceptance' -describe 'validate_augeas function', :unless => (fact('osfamily') == 'windows') do +describe 'validate_augeas function', unless: (fact('osfamily') == 'windows') do describe 'prep' do it 'installs augeas for tests' end @@ -9,47 +9,46 @@ context 'valid inputs with no 3rd argument' do { 'root:x:0:0:root:/root:/bin/bash\n' => 'Passwd.lns', - 'proc /proc proc nodev,noexec,nosuid 0 0\n' => 'Fstab.lns' - }.each do |line,lens| - it "validates a single argument for #{lens}" do - pp = <<-EOS + 'proc /proc proc nodev,noexec,nosuid 0 0\n' => 'Fstab.lns', + }.each do |line, lens| + pp1 = <<-EOS $line = "#{line}" $lens = "#{lens}" validate_augeas($line, $lens) - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it "validates a single argument for #{lens}" do + apply_manifest(pp1, catch_failures: true) end end end + context 'valid inputs with 3rd and 4th arguments' do - it "validates a restricted value" do - line = 'root:x:0:0:root:/root:/bin/barsh\n' - lens = 'Passwd.lns' - restriction = '$file/*[shell="/bin/barsh"]' - pp = <<-EOS + line = 'root:x:0:0:root:/root:/bin/barsh\n' + lens = 'Passwd.lns' + restriction = '$file/*[shell="/bin/barsh"]' + pp2 = <<-EOS $line = "#{line}" $lens = "#{lens}" $restriction = ['#{restriction}'] validate_augeas($line, $lens, $restriction, "my custom failure message") - EOS - - expect(apply_manifest(pp, :expect_failures => true).stderr).to match(/my custom failure message/) + EOS + it 'validates a restricted value' do + expect(apply_manifest(pp2, expect_failures: true).stderr).to match(%r{my custom failure message}) end end + context 'invalid inputs' do { 'root:x:0:0:root' => 'Passwd.lns', - '127.0.1.1' => 'Hosts.lns' - }.each do |line,lens| - it "validates a single argument for #{lens}" do - pp = <<-EOS + '127.0.1.1' => 'Hosts.lns', + }.each do |line, lens| + pp3 = <<-EOS $line = "#{line}" $lens = "#{lens}" validate_augeas($line, $lens) - EOS - - apply_manifest(pp, :expect_failures => true) + EOS + it "validates a single argument for #{lens}" do + apply_manifest(pp3, expect_failures: true) end end end diff --git a/spec/acceptance/validate_bool_spec.rb b/spec/acceptance/validate_bool_spec.rb index 993f9ef30..1c25b681a 100755 --- a/spec/acceptance/validate_bool_spec.rb +++ b/spec/acceptance/validate_bool_spec.rb @@ -3,31 +3,30 @@ describe 'validate_bool function' do describe 'success' do - it 'validates a single argument' do - pp = <<-EOS + pp1 = <<-EOS $one = true validate_bool($one) - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'validates a single argument' do + apply_manifest(pp1, catch_failures: true) end - it 'validates an multiple arguments' do - pp = <<-EOS + + pp2 = <<-EOS $one = true $two = false validate_bool($one,$two) - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'validates an multiple arguments' do + apply_manifest(pp2, catch_failures: true) end [ %{validate_bool('true')}, %{validate_bool('false')}, %{validate_bool([true])}, - %{validate_bool(undef)} - ].each do |pp| - it "rejects #{pp.inspect}" do - expect(apply_manifest(pp, :expect_failures => true).stderr).to match(/is not a boolean\. It looks to be a/) + %{validate_bool(undef)}, + ].each do |pp3| + it "rejects #{pp3.inspect}" do + expect(apply_manifest(pp3, expect_failures: true).stderr).to match(%r{is not a boolean\. It looks to be a}) end end end diff --git a/spec/acceptance/validate_cmd_spec.rb b/spec/acceptance/validate_cmd_spec.rb index 5fc7b943d..5f1da6b97 100755 --- a/spec/acceptance/validate_cmd_spec.rb +++ b/spec/acceptance/validate_cmd_spec.rb @@ -3,8 +3,7 @@ describe 'validate_cmd function' do describe 'success' do - it 'validates a true command' do - pp = <<-EOS + pp1 = <<-EOS $one = 'foo' if $::osfamily == 'windows' { $two = 'echo' #shell built-in @@ -12,12 +11,12 @@ $two = '/bin/echo' } validate_cmd($one,$two) - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'validates a true command' do + apply_manifest(pp1, catch_failures: true) end - it 'validates a fail command' do - pp = <<-EOS + + pp2 = <<-EOS $one = 'foo' if $::osfamily == 'windows' { $two = 'C:/aoeu' @@ -25,12 +24,12 @@ $two = '/bin/aoeu' } validate_cmd($one,$two) - EOS - - apply_manifest(pp, :expect_failures => true) + EOS + it 'validates a fail command' do + apply_manifest(pp2, expect_failures: true) end - it 'validates a fail command with a custom error message' do - pp = <<-EOS + + pp3 = <<-EOS $one = 'foo' if $::osfamily == 'windows' { $two = 'C:/aoeu' @@ -38,10 +37,10 @@ $two = '/bin/aoeu' } validate_cmd($one,$two,"aoeu is dvorak") - EOS - - apply_manifest(pp, :expect_failures => true) do |output| - expect(output.stderr).to match(/aoeu is dvorak/) + EOS + it 'validates a fail command with a custom error message' do + apply_manifest(pp3, expect_failures: true) do |output| + expect(output.stderr).to match(%r{aoeu is dvorak}) end end end diff --git a/spec/acceptance/validate_hash_spec.rb b/spec/acceptance/validate_hash_spec.rb index fc0f079ba..a81f69df0 100755 --- a/spec/acceptance/validate_hash_spec.rb +++ b/spec/acceptance/validate_hash_spec.rb @@ -3,31 +3,31 @@ describe 'validate_hash function' do describe 'success' do - it 'validates a single argument' do - pp = <<-EOS + pp1 = <<-EOS $one = { 'a' => 1 } validate_hash($one) - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'validates a single argument' do + apply_manifest(pp1, catch_failures: true) end - it 'validates an multiple arguments' do - pp = <<-EOS + + pp2 = <<-EOS $one = { 'a' => 1 } $two = { 'b' => 2 } validate_hash($one,$two) - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'validates an multiple arguments' do + apply_manifest(pp2, catch_failures: true) end + [ %{validate_hash('{ "not" => "hash" }')}, %{validate_hash('string')}, %{validate_hash(["array"])}, - %{validate_hash(undef)} - ].each do |pp| - it "rejects #{pp.inspect}" do - expect(apply_manifest(pp, :expect_failures => true).stderr).to match(//) + %{validate_hash(undef)}, + ].each do |pp3| + it "rejects #{pp3.inspect}" do + expect(apply_manifest(pp3, expect_failures: true).stderr).to match(%r{}) end end end diff --git a/spec/acceptance/validate_ipv4_address_spec.rb b/spec/acceptance/validate_ipv4_address_spec.rb index 67d313967..a26db2a50 100755 --- a/spec/acceptance/validate_ipv4_address_spec.rb +++ b/spec/acceptance/validate_ipv4_address_spec.rb @@ -3,22 +3,21 @@ describe 'validate_ipv4_address function' do describe 'success' do - it 'validates a single argument' do - pp = <<-EOS + pp1 = <<-EOS $one = '1.2.3.4' validate_ipv4_address($one) - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'validates a single argument' do + apply_manifest(pp1, catch_failures: true) end - it 'validates an multiple arguments' do - pp = <<-EOS + + pp2 = <<-EOS $one = '1.2.3.4' $two = '5.6.7.8' validate_ipv4_address($one,$two) - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'validates an multiple arguments' do + apply_manifest(pp2, catch_failures: true) end end describe 'failure' do diff --git a/spec/acceptance/validate_ipv6_address_spec.rb b/spec/acceptance/validate_ipv6_address_spec.rb index eaa845d53..201e35606 100755 --- a/spec/acceptance/validate_ipv6_address_spec.rb +++ b/spec/acceptance/validate_ipv6_address_spec.rb @@ -3,22 +3,21 @@ describe 'validate_ipv6_address function' do describe 'success' do - it 'validates a single argument' do - pp = <<-EOS + pp1 = <<-EOS $one = '3ffe:0505:0002::' validate_ipv6_address($one) - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'validates a single argument' do + apply_manifest(pp1, catch_failures: true) end - it 'validates an multiple arguments' do - pp = <<-EOS + + pp2 = <<-EOS $one = '3ffe:0505:0002::' $two = '3ffe:0505:0001::' validate_ipv6_address($one,$two) - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'validates an multiple arguments' do + apply_manifest(pp2, catch_failures: true) end end describe 'failure' do diff --git a/spec/acceptance/validate_re_spec.rb b/spec/acceptance/validate_re_spec.rb index eefb28607..b3ae129b8 100755 --- a/spec/acceptance/validate_re_spec.rb +++ b/spec/acceptance/validate_re_spec.rb @@ -3,43 +3,43 @@ describe 'validate_re function' do describe 'success' do - it 'validates a string' do - pp = <<-EOS + pp1 = <<-EOS $one = 'one' $two = '^one$' validate_re($one,$two) - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'validates a string' do + apply_manifest(pp1, catch_failures: true) end - it 'validates an array' do - pp = <<-EOS + + pp2 = <<-EOS $one = 'one' $two = ['^one$', '^two'] validate_re($one,$two) - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'validates an array' do + apply_manifest(pp2, catch_failures: true) end - it 'validates a failed array' do - pp = <<-EOS + + pp3 = <<-EOS $one = 'one' $two = ['^two$', '^three'] validate_re($one,$two) - EOS - - apply_manifest(pp, :expect_failures => true) + EOS + it 'validates a failed array' do + apply_manifest(pp3, expect_failures: true) end - it 'validates a failed array with a custom error message' do - pp = <<-EOS + + pp4 = <<-EOS $one = '3.4.3' $two = '^2.7' validate_re($one,$two,"The $puppetversion fact does not match 2.7") - EOS - - expect(apply_manifest(pp, :expect_failures => true).stderr).to match(/does not match/) + EOS + it 'validates a failed array with a custom error message' do + expect(apply_manifest(pp4, expect_failures: true).stderr).to match(%r{does not match}) end end + describe 'failure' do it 'handles improper number of arguments' it 'handles improper argument types' diff --git a/spec/acceptance/validate_slength_spec.rb b/spec/acceptance/validate_slength_spec.rb index c29fd2323..a661a21fa 100755 --- a/spec/acceptance/validate_slength_spec.rb +++ b/spec/acceptance/validate_slength_spec.rb @@ -3,61 +3,60 @@ describe 'validate_slength function' do describe 'success' do - it 'validates a single string max' do - pp = <<-EOS + pp1 = <<-EOS $one = 'discombobulate' $two = 17 validate_slength($one,$two) - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'validates a single string max' do + apply_manifest(pp1, catch_failures: true) end - it 'validates multiple string maxes' do - pp = <<-EOS + + pp2 = <<-EOS $one = ['discombobulate', 'moo'] $two = 17 validate_slength($one,$two) - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'validates multiple string maxes' do + apply_manifest(pp2, catch_failures: true) end - it 'validates min/max of strings in array' do - pp = <<-EOS + + pp3 = <<-EOS $one = ['discombobulate', 'moo'] $two = 17 $three = 3 validate_slength($one,$two,$three) - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'validates min/max of strings in array' do + apply_manifest(pp3, catch_failures: true) end - it 'validates a single string max of incorrect length' do - pp = <<-EOS + + pp4 = <<-EOS $one = 'discombobulate' $two = 1 validate_slength($one,$two) - EOS - - apply_manifest(pp, :expect_failures => true) + EOS + it 'validates a single string max of incorrect length' do + apply_manifest(pp4, expect_failures: true) end - it 'validates multiple string maxes of incorrect length' do - pp = <<-EOS + + pp5 = <<-EOS $one = ['discombobulate', 'moo'] $two = 3 validate_slength($one,$two) - EOS - - apply_manifest(pp, :expect_failures => true) + EOS + it 'validates multiple string maxes of incorrect length' do + apply_manifest(pp5, expect_failures: true) end - it 'validates multiple strings min/maxes of incorrect length' do - pp = <<-EOS + + pp6 = <<-EOS $one = ['discombobulate', 'moo'] $two = 17 $three = 10 validate_slength($one,$two,$three) - EOS - - apply_manifest(pp, :expect_failures => true) + EOS + it 'validates multiple strings min/maxes of incorrect length' do + apply_manifest(pp6, expect_failures: true) end end describe 'failure' do diff --git a/spec/acceptance/validate_string_spec.rb b/spec/acceptance/validate_string_spec.rb index f04608de9..3d4629ca0 100755 --- a/spec/acceptance/validate_string_spec.rb +++ b/spec/acceptance/validate_string_spec.rb @@ -3,37 +3,37 @@ describe 'validate_string function' do describe 'success' do - it 'validates a single argument' do - pp = <<-EOS + pp1 = <<-EOS $one = 'string' validate_string($one) - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'validates a single argument' do + apply_manifest(pp1, catch_failures: true) end - it 'validates an multiple arguments' do - pp = <<-EOS + + pp2 = <<-EOS $one = 'string' $two = 'also string' validate_string($one,$two) - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'validates an multiple arguments' do + apply_manifest(pp2, catch_failures: true) end - it 'validates undef' do - pp = <<-EOS - validate_string(undef) - EOS - apply_manifest(pp, :catch_failures => true) + pp3 = <<-EOS + validate_string(undef) + EOS + it 'validates undef' do + apply_manifest(pp3, catch_failures: true) end - it 'validates a non-string' do - { - %{validate_string({ 'a' => 'hash' })} => "Hash", - %{validate_string(['array'])} => "Array", - %{validate_string(false)} => "FalseClass", - }.each do |pp,type| - expect(apply_manifest(pp, :expect_failures => true).stderr).to match(/a #{type}/) + + { + %{validate_string({ 'a' => 'hash' })} => 'Hash', + %{validate_string(['array'])} => 'Array', + %{validate_string(false)} => 'FalseClass', + }.each do |pp4, type| + it "validates a non-string: #{pp4.inspect}" do + expect(apply_manifest(pp4, expect_failures: true).stderr).to match(%r{a #{type}}) end end end diff --git a/spec/acceptance/values_at_spec.rb b/spec/acceptance/values_at_spec.rb index eb0bf4f28..fa443c35e 100755 --- a/spec/acceptance/values_at_spec.rb +++ b/spec/acceptance/values_at_spec.rb @@ -3,67 +3,66 @@ describe 'values_at function' do describe 'success' do - it 'returns a specific value' do - pp = <<-EOS + pp1 = <<-EOS $one = ['a','b','c','d','e'] $two = 1 $output = values_at($one,$two) notice(inline_template('<%= @output.inspect %>')) - EOS - - expect(apply_manifest(pp, :catch_failures => true).stdout).to match(/\["b"\]/) + EOS + it 'returns a specific value' do + expect(apply_manifest(pp1, catch_failures: true).stdout).to match(%r{\["b"\]}) end - it 'returns a specific negative index value' do - pending("negative numbers don't work") - pp = <<-EOS + + pp2 = <<-EOS $one = ['a','b','c','d','e'] $two = -1 $output = values_at($one,$two) notice(inline_template('<%= @output.inspect %>')) - EOS - - expect(apply_manifest(pp, :catch_failures => true).stdout).to match(/\["e"\]/) + EOS + it 'returns a specific negative index value' do + pending("negative numbers don't work") + expect(apply_manifest(pp2, catch_failures: true).stdout).to match(%r{\["e"\]}) end - it 'returns a range of values' do - pp = <<-EOS + + pp3 = <<-EOS $one = ['a','b','c','d','e'] $two = "1-3" $output = values_at($one,$two) notice(inline_template('<%= @output.inspect %>')) - EOS - - expect(apply_manifest(pp, :catch_failures => true).stdout).to match(/\["b", "c", "d"\]/) + EOS + it 'returns a range of values' do + expect(apply_manifest(pp3, catch_failures: true).stdout).to match(%r{\["b", "c", "d"\]}) end - it 'returns a negative specific value and range of values' do - pp = <<-EOS + + pp4 = <<-EOS $one = ['a','b','c','d','e'] $two = ["1-3",0] $output = values_at($one,$two) notice(inline_template('<%= @output.inspect %>')) - EOS - - expect(apply_manifest(pp, :catch_failures => true).stdout).to match(/\["b", "c", "d", "a"\]/) + EOS + it 'returns a negative specific value and range of values' do + expect(apply_manifest(pp4, catch_failures: true).stdout).to match(%r{\["b", "c", "d", "a"\]}) end end + describe 'failure' do - it 'handles improper number of arguments' do - pp = <<-EOS + pp5 = <<-EOS $one = ['a','b','c','d','e'] $output = values_at($one) notice(inline_template('<%= @output.inspect %>')) - EOS - - expect(apply_manifest(pp, :expect_failures => true).stderr).to match(/Wrong number of arguments/) + EOS + it 'handles improper number of arguments' do + expect(apply_manifest(pp5, expect_failures: true).stderr).to match(%r{Wrong number of arguments}) end - it 'handles non-indicies arguments' do - pp = <<-EOS + + pp6 = <<-EOS $one = ['a','b','c','d','e'] $two = [] $output = values_at($one,$two) notice(inline_template('<%= @output.inspect %>')) - EOS - - expect(apply_manifest(pp, :expect_failures => true).stderr).to match(/at least one positive index/) + EOS + it 'handles non-indicies arguments' do + expect(apply_manifest(pp6, expect_failures: true).stderr).to match(%r{at least one positive index}) end it 'detects index ranges smaller than the start range' diff --git a/spec/acceptance/values_spec.rb b/spec/acceptance/values_spec.rb index cef1c9d66..47c4ecfda 100755 --- a/spec/acceptance/values_spec.rb +++ b/spec/acceptance/values_spec.rb @@ -3,8 +3,7 @@ describe 'values function' do describe 'success' do - it 'returns an array of values' do - pp = <<-EOS + pp1 = <<-EOS $arg = { 'a' => 1, 'b' => 2, @@ -12,19 +11,20 @@ } $output = values($arg) notice(inline_template('<%= @output.sort.inspect %>')) - EOS - expect(apply_manifest(pp, :catch_failures => true).stdout).to match(/\[1, 2, 3\]/) + EOS + it 'returns an array of values' do + expect(apply_manifest(pp1, catch_failures: true).stdout).to match(%r{\[1, 2, 3\]}) end end + describe 'failure' do - it 'handles non-hash arguments' do - pp = <<-EOS + pp2 = <<-EOS $arg = "foo" $output = values($arg) notice(inline_template('<%= @output.inspect %>')) - EOS - - expect(apply_manifest(pp, :expect_failures => true).stderr).to match(/Requires hash/) + EOS + it 'handles non-hash arguments' do + expect(apply_manifest(pp2, expect_failures: true).stderr).to match(%r{Requires hash}) end end end diff --git a/spec/acceptance/zip_spec.rb b/spec/acceptance/zip_spec.rb index ae2289633..a48b0a8e5 100755 --- a/spec/acceptance/zip_spec.rb +++ b/spec/acceptance/zip_spec.rb @@ -3,65 +3,70 @@ describe 'zip function' do describe 'success' do - it 'zips two arrays of numbers together' do - pp = <<-EOS + pp1 = <<-EOS $one = [1,2,3,4] $two = [5,6,7,8] $output = zip($one,$two) notice(inline_template('<%= @output.inspect %>')) - EOS - expect(apply_manifest(pp, :catch_failures => true).stdout).to match(/\[\[1, 5\], \[2, 6\], \[3, 7\], \[4, 8\]\]/) + EOS + it 'zips two arrays of numbers together' do + expect(apply_manifest(pp1, catch_failures: true).stdout).to match(%r{\[\[1, 5\], \[2, 6\], \[3, 7\], \[4, 8\]\]}) end - it 'zips two arrays of numbers & bools together' do - pp = <<-EOS + + pp2 = <<-EOS $one = [1,2,"three",4] $two = [true,true,false,false] $output = zip($one,$two) notice(inline_template('<%= @output.inspect %>')) - EOS - expect(apply_manifest(pp, :catch_failures => true).stdout).to match(/\[\[1, true\], \[2, true\], \["three", false\], \[4, false\]\]/) + EOS + it 'zips two arrays of numbers & bools together' do + expect(apply_manifest(pp2, catch_failures: true).stdout).to match(%r{\[\[1, true\], \[2, true\], \["three", false\], \[4, false\]\]}) end - it 'zips two arrays of numbers together and flattens them' do - # XXX This only tests the argument `true`, even though the following are valid: - # 1 t y true yes - # 0 f n false no - # undef undefined - pp = <<-EOS + + # XXX This only tests the argument `true`, even though the following are valid: + # 1 t y true yes + # 0 f n false no + # undef undefined + pp3 = <<-EOS $one = [1,2,3,4] $two = [5,6,7,8] $output = zip($one,$two,true) notice(inline_template('<%= @output.inspect %>')) - EOS - expect(apply_manifest(pp, :catch_failures => true).stdout).to match(/\[1, 5, 2, 6, 3, 7, 4, 8\]/) + EOS + it 'zips two arrays of numbers together and flattens them' do + expect(apply_manifest(pp3, catch_failures: true).stdout).to match(%r{\[1, 5, 2, 6, 3, 7, 4, 8\]}) end - it 'handles unmatched length' do - # XXX Is this expected behavior? - pp = <<-EOS + + # XXX Is this expected behavior? + pp4 = <<-EOS $one = [1,2] $two = [5,6,7,8] $output = zip($one,$two) notice(inline_template('<%= @output.inspect %>')) - EOS - expect(apply_manifest(pp, :catch_failures => true).stdout).to match(/\[\[1, 5\], \[2, 6\]\]/) + EOS + it 'handles unmatched length' do + expect(apply_manifest(pp4, catch_failures: true).stdout).to match(%r{\[\[1, 5\], \[2, 6\]\]}) end end + describe 'failure' do - it 'handles improper number of arguments' do - pp = <<-EOS + pp5 = <<-EOS $one = [1,2] $output = zip($one) notice(inline_template('<%= @output.inspect %>')) - EOS - expect(apply_manifest(pp, :expect_failures => true).stderr).to match(/Wrong number of arguments/) + EOS + it 'handles improper number of arguments' do + expect(apply_manifest(pp5, expect_failures: true).stderr).to match(%r{Wrong number of arguments}) end - it 'handles improper argument types' do - pp = <<-EOS + + pp6 = <<-EOS $one = "a string" $two = [5,6,7,8] $output = zip($one,$two) notice(inline_template('<%= @output.inspect %>')) - EOS - expect(apply_manifest(pp, :expect_failures => true).stderr).to match(/Requires array/) + EOS + it 'handles improper argument types' do + expect(apply_manifest(pp6, expect_failures: true).stderr).to match(%r{Requires array}) end end end diff --git a/spec/aliases/absolute_path_spec.rb b/spec/aliases/absolute_path_spec.rb index 308a3aaeb..3a7141ebc 100644 --- a/spec/aliases/absolute_path_spec.rb +++ b/spec/aliases/absolute_path_spec.rb @@ -3,7 +3,7 @@ if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'test::absolute_path', type: :class do describe 'valid paths handling' do - %w{ + %w[ C:/ C:\\ C:\\WINDOWS\\System32 @@ -18,9 +18,10 @@ /var/opt//lib/puppet /var/ůťƒ8 /var/ネット - }.each do |value| + ].each do |value| describe value.inspect do - let(:params) {{ value: value }} + let(:params) { { value: value } } + it { is_expected.to compile } end end @@ -30,21 +31,22 @@ context 'garbage inputs' do [ nil, - [ nil ], - [ nil, nil ], + [nil], + [nil, nil], { 'foo' => 'bar' }, - { }, + {}, '', ].each do |value| describe value.inspect do - let(:params) {{ value: value }} - it { is_expected.to compile.and_raise_error(/parameter 'value' expects a match for Stdlib::Compat::Absolute_path/) } + let(:params) { { value: value } } + + it { is_expected.to compile.and_raise_error(%r{parameter 'value' expects a match for Stdlib::Compat::Absolute_path}) } end end end context 'relative paths' do - %w{ + %w[ relative1 . .. @@ -55,10 +57,11 @@ relative\\windows \var\ůťƒ8 \var\ネット - }.each do |value| + ].each do |value| describe value.inspect do - let(:params) {{ value: value }} - it { is_expected.to compile.and_raise_error(/parameter 'value' expects a match for Stdlib::Compat::Absolute_path/) } + let(:params) { { value: value } } + + it { is_expected.to compile.and_raise_error(%r{parameter 'value' expects a match for Stdlib::Compat::Absolute_path}) } end end end diff --git a/spec/aliases/array_spec.rb b/spec/aliases/array_spec.rb index 89cc2af04..6ff6a75cc 100644 --- a/spec/aliases/array_spec.rb +++ b/spec/aliases/array_spec.rb @@ -11,7 +11,8 @@ [[]], ].each do |value| describe value.inspect do - let(:params) {{ value: value }} + let(:params) { { value: value } } + it { is_expected.to compile } end end @@ -25,8 +26,9 @@ {}, ].each do |value| describe value.inspect do - let(:params) {{ value: value }} - it { is_expected.to compile.and_raise_error(/parameter 'value' expects a Stdlib::Compat::Array/) } + let(:params) { { value: value } } + + it { is_expected.to compile.and_raise_error(%r{parameter 'value' expects a Stdlib::Compat::Array}) } end end end diff --git a/spec/aliases/bool_spec.rb b/spec/aliases/bool_spec.rb index b84ab51da..db9498941 100644 --- a/spec/aliases/bool_spec.rb +++ b/spec/aliases/bool_spec.rb @@ -8,7 +8,8 @@ false, ].each do |value| describe value.inspect do - let(:params) {{ value: value }} + let(:params) { { value: value } } + it { is_expected.to compile } end end @@ -23,8 +24,9 @@ 'false', ].each do |value| describe value.inspect do - let(:params) {{ value: value }} - it { is_expected.to compile.and_raise_error(/parameter 'value' expects a Stdlib::Compat::Bool/) } + let(:params) { { value: value } } + + it { is_expected.to compile.and_raise_error(%r{parameter 'value' expects a Stdlib::Compat::Bool}) } end end end diff --git a/spec/aliases/filemode_spec.rb b/spec/aliases/filemode_spec.rb index 4db13a20e..92ce58a7e 100644 --- a/spec/aliases/filemode_spec.rb +++ b/spec/aliases/filemode_spec.rb @@ -3,16 +3,17 @@ if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'test::filemode', type: :class do describe 'valid modes' do - %w{ + %w[ 0644 1644 2644 4644 0123 0777 - }.each do |value| + ].each do |value| describe value.inspect do - let(:params) {{ value: value }} + let(:params) { { value: value } } + it { is_expected.to compile } end end @@ -22,12 +23,12 @@ context 'garbage inputs' do [ nil, - [ nil ], - [ nil, nil ], + [nil], + [nil, nil], { 'foo' => 'bar' }, - { }, + {}, '', - "ネット", + 'ネット', '644', '7777', '1', @@ -38,8 +39,9 @@ '0649', ].each do |value| describe value.inspect do - let(:params) {{ value: value }} - it { is_expected.to compile.and_raise_error(/parameter 'value' expects a match for Stdlib::Filemode/) } + let(:params) { { value: value } } + + it { is_expected.to compile.and_raise_error(%r{parameter 'value' expects a match for Stdlib::Filemode}) } end end end diff --git a/spec/aliases/float_spec.rb b/spec/aliases/float_spec.rb index 84e19341b..6310f15a4 100644 --- a/spec/aliases/float_spec.rb +++ b/spec/aliases/float_spec.rb @@ -10,17 +10,19 @@ '-342.2315e-12', ].each do |value| describe value.inspect do - let(:params) {{ value: value }} + let(:params) { { value: value } } + it { is_expected.to compile } end end end describe 'rejects other values' do - [ true, 'true', false, 'false', 'iAmAString', '1test', '1 test', 'test 1', 'test 1 test', {}, { 'key' => 'value' }, { 1=> 2 }, '', :undef , 'x', 3, '3', -3, '-3'].each do |value| + [true, 'true', false, 'false', 'iAmAString', '1test', '1 test', 'test 1', 'test 1 test', {}, { 'key' => 'value' }, { 1 => 2 }, '', :undef, 'x', 3, '3', -3, '-3'].each do |value| describe value.inspect do - let(:params) {{ value: value }} - it { is_expected.to compile.and_raise_error(/parameter 'value' expects.*Float.*Pattern/) } + let(:params) { { value: value } } + + it { is_expected.to compile.and_raise_error(%r{parameter 'value' expects.*Float.*Pattern}) } end end end diff --git a/spec/aliases/hash_spec.rb b/spec/aliases/hash_spec.rb index 6e5060db7..702abd5e7 100644 --- a/spec/aliases/hash_spec.rb +++ b/spec/aliases/hash_spec.rb @@ -5,12 +5,13 @@ describe 'accepts hashes' do [ {}, - {'one' => "two"}, - {'wan' => 3}, - {'001' => "helly"}, + { 'one' => 'two' }, + { 'wan' => 3 }, + { '001' => 'helly' }, ].each do |value| describe value.inspect do - let(:params) {{ value: value }} + let(:params) { { value: value } } + it { is_expected.to compile } end end @@ -23,8 +24,9 @@ [], ].each do |value| describe value.inspect do - let(:params) {{ value: value }} - it { is_expected.to compile.and_raise_error(/parameter 'value' expects a Stdlib::Compat::Hash/) } + let(:params) { { value: value } } + + it { is_expected.to compile.and_raise_error(%r{parameter 'value' expects a Stdlib::Compat::Hash}) } end end end diff --git a/spec/aliases/httpsurl_spec.rb b/spec/aliases/httpsurl_spec.rb index 3e51118ca..ca7883388 100644 --- a/spec/aliases/httpsurl_spec.rb +++ b/spec/aliases/httpsurl_spec.rb @@ -3,15 +3,16 @@ if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'test::httpsurl', type: :class do describe 'valid handling' do - %w{ + %w[ https://hello.com https://notcreative.org https://notexciting.co.uk https://graphemica.com/❤ https://graphemica.com/緩 - }.each do |value| + ].each do |value| describe value.inspect do - let(:params) {{ value: value }} + let(:params) { { value: value } } + it { is_expected.to compile } end end @@ -21,24 +22,24 @@ context 'garbage inputs' do [ nil, - [ nil ], - [ nil, nil ], + [nil], + [nil, nil], { 'foo' => 'bar' }, - { }, + {}, '', - "httds://notquiteright.org", - "hptts:/nah", - "https;//notrightbutclose.org", - "http://graphemica.com/❤", - "http://graphemica.com/緩" + 'httds://notquiteright.org', + 'hptts:/nah', + 'https;//notrightbutclose.org', + 'http://graphemica.com/❤', + 'http://graphemica.com/緩', ].each do |value| describe value.inspect do - let(:params) {{ value: value }} - it { is_expected.to compile.and_raise_error(/parameter 'value' expects a match for Stdlib::HTTPSUrl/) } + let(:params) { { value: value } } + + it { is_expected.to compile.and_raise_error(%r{parameter 'value' expects a match for Stdlib::HTTPSUrl}) } end end end - end end end diff --git a/spec/aliases/httpurl_spec.rb b/spec/aliases/httpurl_spec.rb index fd49a47ce..a535278e6 100644 --- a/spec/aliases/httpurl_spec.rb +++ b/spec/aliases/httpurl_spec.rb @@ -3,7 +3,7 @@ if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'test::httpurl', type: :class do describe 'valid handling' do - %w{ + %w[ https://hello.com https://notcreative.org https://canstillaccepthttps.co.uk @@ -12,9 +12,10 @@ http:// http://graphemica.com/❤ http://graphemica.com/緩 - }.each do |value| + ].each do |value| describe value.inspect do - let(:params) {{ value: value }} + let(:params) { { value: value } } + it { is_expected.to compile } end end @@ -24,24 +25,24 @@ context 'garbage inputs' do [ nil, - [ nil ], - [ nil, nil ], + [nil], + [nil, nil], { 'foo' => 'bar' }, - { }, + {}, '', - "httds://notquiteright.org", - "hptts:/nah", - "https;//notrightbutclose.org", - "hts://graphemica.com/❤", - "https:graphemica.com/緩" + 'httds://notquiteright.org', + 'hptts:/nah', + 'https;//notrightbutclose.org', + 'hts://graphemica.com/❤', + 'https:graphemica.com/緩', ].each do |value| describe value.inspect do - let(:params) {{ value: value }} - it { is_expected.to compile.and_raise_error(/parameter 'value' expects a match for Stdlib::HTTPUrl/) } + let(:params) { { value: value } } + + it { is_expected.to compile.and_raise_error(%r{parameter 'value' expects a match for Stdlib::HTTPUrl}) } end end end - end end end diff --git a/spec/aliases/integer_spec.rb b/spec/aliases/integer_spec.rb index 9cf03571e..0aafc02d8 100644 --- a/spec/aliases/integer_spec.rb +++ b/spec/aliases/integer_spec.rb @@ -12,20 +12,23 @@ "foo\n123", ].each do |value| describe value.inspect do - let(:params) {{ value: value }} + let(:params) { { value: value } } + it { is_expected.to compile } end end end describe 'rejects other values' do - [ "foo\nbar", true, 'true', false, 'false', 'iAmAString', '1test', '1 test', 'test 1', 'test 1 test', {}, { 'key' => 'value' }, { 1=> 2 }, '', :undef , 'x', 3.7, '3.7',-3.7, '-342.2315e-12' ].each do |value| + ["foo\nbar", true, 'true', false, 'false', 'iAmAString', '1test', '1 test', 'test 1', 'test 1 test', + {}, { 'key' => 'value' }, { 1 => 2 }, '', :undef, 'x', 3.7, '3.7', -3.7, '-342.2315e-12'].each do |value| describe value.inspect do - let(:params) {{ value: value }} + let(:params) { { value: value } } + if Puppet::Util::Package.versioncmp(Puppet.version, '5.0.0') >= 0 - it { is_expected.to compile.and_raise_error(/parameter 'value' expects a Stdlib::Compat::Integer = Variant\[Integer, Pattern\[.*\], Array\[.*\]\] value/) } + it { is_expected.to compile.and_raise_error(%r{parameter 'value' expects a Stdlib::Compat::Integer = Variant\[Integer, Pattern\[.*\], Array\[.*\]\] value}) } else - it { is_expected.to compile.and_raise_error(/parameter 'value' expects a value of type Integer, Pattern(\[.*\]+)?, or Array/) } + it { is_expected.to compile.and_raise_error(%r{parameter 'value' expects a value of type Integer, Pattern(\[.*\]+)?, or Array}) } end end end diff --git a/spec/aliases/ip_address.rb b/spec/aliases/ip_address.rb index 67a555ca5..b3ab9d32c 100644 --- a/spec/aliases/ip_address.rb +++ b/spec/aliases/ip_address.rb @@ -9,10 +9,11 @@ '0.0.0.0', '192.88.99.0', '2001:0db8:85a3:0000:0000:8a2e:0370:7334', - 'fa76:8765:34ac:0823:ab76:eee9:0987:1111' + 'fa76:8765:34ac:0823:ab76:eee9:0987:1111', ].each do |value| describe value.inspect do - let(:params) {{ value: value }} + let(:params) { { value: value } } + it { is_expected.to compile } end end @@ -22,11 +23,12 @@ 'nope', '77', '4.4.4', - '2001:0db8:85a3:000000:0000:8a2e:0370:7334' + '2001:0db8:85a3:000000:0000:8a2e:0370:7334', ].each do |value| describe value.inspect do - let(:params) {{ value: value }} - it { is_expected.to compile.and_raise_error(/parameter 'value' expects a match for/) } + let(:params) { { value: value } } + + it { is_expected.to compile.and_raise_error(%r{parameter 'value' expects a match for}) } end end end diff --git a/spec/aliases/ipv4_spec.rb b/spec/aliases/ipv4_spec.rb index 6a503ad7a..244826ad9 100644 --- a/spec/aliases/ipv4_spec.rb +++ b/spec/aliases/ipv4_spec.rb @@ -5,7 +5,8 @@ describe 'accepts ipv4 addresses' do SharedData::IPV4_PATTERNS.each do |value| describe value.inspect do - let(:params) {{ value: value }} + let(:params) { { value: value } } + it { is_expected.to compile } end end @@ -13,8 +14,9 @@ describe 'rejects other values' do SharedData::IPV4_NEGATIVE_PATTERNS.each do |value| describe value.inspect do - let(:params) {{ value: value }} - it { is_expected.to compile.and_raise_error(/parameter 'value' expects a match for Stdlib::Compat::Ipv4/) } + let(:params) { { value: value } } + + it { is_expected.to compile.and_raise_error(%r{parameter 'value' expects a match for Stdlib::Compat::Ipv4}) } end end end diff --git a/spec/aliases/ipv6_spec.rb b/spec/aliases/ipv6_spec.rb index ae90f4228..0b35a029e 100644 --- a/spec/aliases/ipv6_spec.rb +++ b/spec/aliases/ipv6_spec.rb @@ -15,7 +15,8 @@ '2001::', ].each do |value| describe value.inspect do - let(:params) {{ value: value }} + let(:params) { { value: value } } + it { is_expected.to compile } end end @@ -31,8 +32,9 @@ '::ffff:12345678901234567890.1.26', ].each do |value| describe value.inspect do - let(:params) {{ value: value }} - it { is_expected.to compile.and_raise_error(/parameter 'value' expects a match for Stdlib::Compat::Ipv6/) } + let(:params) { { value: value } } + + it { is_expected.to compile.and_raise_error(%r{parameter 'value' expects a match for Stdlib::Compat::Ipv6}) } end end end diff --git a/spec/aliases/numeric_spec.rb b/spec/aliases/numeric_spec.rb index 09c28ec3f..c4de7ae2a 100644 --- a/spec/aliases/numeric_spec.rb +++ b/spec/aliases/numeric_spec.rb @@ -14,17 +14,19 @@ '-342.2315e-12', ].each do |value| describe value.inspect do - let(:params) {{ value: value }} + let(:params) { { value: value } } + it { is_expected.to compile } end end end describe 'rejects other values' do - [ true, 'true', false, 'false', 'iAmAString', '1test', '1 test', 'test 1', 'test 1 test', {}, { 'key' => 'value' }, { 1=> 2 }, '', :undef , 'x' ].each do |value| + [true, 'true', false, 'false', 'iAmAString', '1test', '1 test', 'test 1', 'test 1 test', {}, { 'key' => 'value' }, { 1 => 2 }, '', :undef, 'x'].each do |value| describe value.inspect do - let(:params) {{ value: value }} - it { is_expected.to compile.and_raise_error(/parameter 'value' expects.*Numeric.*Pattern.*Array/) } + let(:params) { { value: value } } + + it { is_expected.to compile.and_raise_error(%r{parameter 'value' expects.*Numeric.*Pattern.*Array}) } end end end diff --git a/spec/aliases/string_spec.rb b/spec/aliases/string_spec.rb index 4fc8ce6d4..9a40923de 100644 --- a/spec/aliases/string_spec.rb +++ b/spec/aliases/string_spec.rb @@ -9,7 +9,8 @@ nil, ].each do |value| describe value.inspect do - let(:params) {{ value: value }} + let(:params) { { value: value } } + it { is_expected.to compile } end end @@ -23,8 +24,9 @@ true, ].each do |value| describe value.inspect do - let(:params) {{ value: value }} - it { is_expected.to compile.and_raise_error(/parameter 'value' expects a (?:value of type Undef or )?.*String/) } + let(:params) { { value: value } } + + it { is_expected.to compile.and_raise_error(%r{parameter 'value' expects a (?:value of type Undef or )?.*String}) } end end end diff --git a/spec/aliases/unixpath_spec.rb b/spec/aliases/unixpath_spec.rb index 6aecfe71e..d99408693 100644 --- a/spec/aliases/unixpath_spec.rb +++ b/spec/aliases/unixpath_spec.rb @@ -3,7 +3,7 @@ if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'test::unixpath', type: :class do describe 'valid handling' do - %w{ + %w[ /usr2/username/bin:/usr/local/bin:/usr/bin:. /var/tmp /Users/helencampbell/workspace/puppetlabs-stdlib @@ -11,9 +11,10 @@ /var/ネット /var//tmp /var/../tmp - }.each do |value| + ].each do |value| describe value.inspect do - let(:params) {{ value: value }} + let(:params) { { value: value } } + it { is_expected.to compile } end end @@ -23,25 +24,25 @@ context 'garbage inputs' do [ nil, - [ nil ], - [ nil, nil ], + [nil], + [nil, nil], { 'foo' => 'bar' }, - { }, + {}, '', - "C:/whatever", - "\\var\\tmp", - "\\Users/hc/wksp/stdlib", - "*/Users//nope", + 'C:/whatever', + '\\var\\tmp', + '\\Users/hc/wksp/stdlib', + '*/Users//nope', "var\ůťƒ8", - "var\ネット" + "var\ネット", ].each do |value| describe value.inspect do - let(:params) {{ value: value }} - it { is_expected.to compile.and_raise_error(/parameter 'value' expects a match for Stdlib::Unixpath/) } + let(:params) { { value: value } } + + it { is_expected.to compile.and_raise_error(%r{parameter 'value' expects a match for Stdlib::Unixpath}) } end end end - end end end diff --git a/spec/aliases/windowspath_spec.rb b/spec/aliases/windowspath_spec.rb index c20e373d7..bec7b3bc6 100644 --- a/spec/aliases/windowspath_spec.rb +++ b/spec/aliases/windowspath_spec.rb @@ -3,7 +3,7 @@ if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'test::windowspath', type: :class do describe 'valid handling' do - %w{ + %w[ C:\\ C:\\WINDOWS\\System32 C:/windows/system32 @@ -12,9 +12,10 @@ \\\\host\\windows X:/var/ůťƒ8 X:/var/ネット - }.each do |value| + ].each do |value| describe value.inspect do - let(:params) {{ value: value }} + let(:params) { { value: value } } + it { is_expected.to compile } end end @@ -24,21 +25,22 @@ context 'garbage inputs' do [ nil, - [ nil ], - [ nil, nil ], + [nil], + [nil, nil], { 'foo' => 'bar' }, - { }, + {}, '', - "httds://notquiteright.org", - "/usr2/username/bin:/usr/local/bin:/usr/bin:.", - "C;//notright/here", - "C:noslashes", - "C:ネット", - "C:ůťƒ8" + 'httds://notquiteright.org', + '/usr2/username/bin:/usr/local/bin:/usr/bin:.', + 'C;//notright/here', + 'C:noslashes', + 'C:ネット', + 'C:ůťƒ8', ].each do |value| describe value.inspect do - let(:params) {{ value: value }} - it { is_expected.to compile.and_raise_error(/parameter 'value' expects a match for Stdlib::Windowspath/) } + let(:params) { { value: value } } + + it { is_expected.to compile.and_raise_error(%r{parameter 'value' expects a match for Stdlib::Windowspath}) } end end end diff --git a/spec/functions/abs_spec.rb b/spec/functions/abs_spec.rb index 7d2257b02..41c2650ae 100755 --- a/spec/functions/abs_spec.rb +++ b/spec/functions/abs_spec.rb @@ -3,28 +3,43 @@ describe 'abs' do it { is_expected.not_to eq(nil) } - describe 'signature validation in puppet3', :unless => RSpec.configuration.puppet_future do - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + describe 'signature validation in puppet3', unless: RSpec.configuration.puppet_future do + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { - pending("Current implementation ignores parameters after the first.") - is_expected.to run.with_params(1, 2).and_raise_error(Puppet::ParseError, /wrong number of arguments/i) + pending('Current implementation ignores parameters after the first.') + is_expected.to run.with_params(1, 2).and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } end - describe 'signature validation in puppet4', :if => RSpec.configuration.puppet_future do - it { pending "the puppet 4 implementation"; is_expected.to run.with_params().and_raise_error(ArgumentError) } - it { pending "the puppet 4 implementation"; is_expected.to run.with_params(1, 2).and_raise_error(ArgumentError) } - it { pending "the puppet 4 implementation"; is_expected.to run.with_params([]).and_raise_error(ArgumentError) } - it { pending "the puppet 4 implementation"; is_expected.to run.with_params({}).and_raise_error(ArgumentError) } - it { pending "the puppet 4 implementation"; is_expected.to run.with_params(true).and_raise_error(ArgumentError) } + describe 'signature validation in puppet4', if: RSpec.configuration.puppet_future do + it { + pending 'the puppet 4 implementation' + is_expected.to run.with_params.and_raise_error(ArgumentError) + } + it { + pending 'the puppet 4 implementation' + is_expected.to run.with_params(1, 2).and_raise_error(ArgumentError) + } + it { + pending 'the puppet 4 implementation' + is_expected.to run.with_params([]).and_raise_error(ArgumentError) + } + it { + pending 'the puppet 4 implementation' + is_expected.to run.with_params({}).and_raise_error(ArgumentError) + } + it { + pending 'the puppet 4 implementation' + is_expected.to run.with_params(true).and_raise_error(ArgumentError) + } end it { is_expected.to run.with_params(-34).and_return(34) } - it { is_expected.to run.with_params("-34").and_return(34) } + it { is_expected.to run.with_params('-34').and_return(34) } it { is_expected.to run.with_params(34).and_return(34) } - it { is_expected.to run.with_params("34").and_return(34) } + it { is_expected.to run.with_params('34').and_return(34) } it { is_expected.to run.with_params(-34.5).and_return(34.5) } - it { is_expected.to run.with_params("-34.5").and_return(34.5) } + it { is_expected.to run.with_params('-34.5').and_return(34.5) } it { is_expected.to run.with_params(34.5).and_return(34.5) } - it { is_expected.to run.with_params("34.5").and_return(34.5) } + it { is_expected.to run.with_params('34.5').and_return(34.5) } end diff --git a/spec/functions/any2array_spec.rb b/spec/functions/any2array_spec.rb index 631657f34..345adc225 100755 --- a/spec/functions/any2array_spec.rb +++ b/spec/functions/any2array_spec.rb @@ -1,17 +1,16 @@ require 'spec_helper' -describe "any2array" do +describe 'any2array' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_return([]) } + it { is_expected.to run.with_params.and_return([]) } it { is_expected.to run.with_params(true).and_return([true]) } it { is_expected.to run.with_params('one').and_return(['one']) } - it { is_expected.to run.with_params('one', 'two').and_return(['one', 'two']) } + it { is_expected.to run.with_params('one', 'two').and_return(%w[one two]) } it { is_expected.to run.with_params([]).and_return([]) } it { is_expected.to run.with_params(['one']).and_return(['one']) } - it { is_expected.to run.with_params(['one', 'two']).and_return(['one', 'two']) } + it { is_expected.to run.with_params(%w[one two]).and_return(%w[one two]) } it { is_expected.to run.with_params({}).and_return([]) } - it { is_expected.to run.with_params({ 'key' => 'value' }).and_return(['key', 'value']) } - it { is_expected.to run.with_params({ 'key' => 'value' }).and_return(['key', 'value']) } + it { is_expected.to run.with_params('key' => 'value').and_return(%w[key value]) } it { is_expected.to run.with_params('‰').and_return(['‰']) } it { is_expected.to run.with_params('竹').and_return(['竹']) } diff --git a/spec/functions/any2bool_spec.rb b/spec/functions/any2bool_spec.rb index 9d351cea3..e4d0482ab 100755 --- a/spec/functions/any2bool_spec.rb +++ b/spec/functions/any2bool_spec.rb @@ -2,7 +2,7 @@ describe 'any2bool' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params(true).and_return(true) } it { is_expected.to run.with_params(false).and_return(false) } @@ -10,33 +10,32 @@ it { is_expected.to run.with_params('1.5').and_return(true) } describe 'when testing stringy values that mean "true"' do - [ 'TRUE','1', 't', 'y', 'true', 'yes'].each do |value| + %w[TRUE 1 t y true yes].each do |value| it { is_expected.to run.with_params(value).and_return(true) } end end describe 'when testing stringy values that mean "false"' do - [ 'FALSE','', '0', 'f', 'n', 'false', 'no', 'undef', 'undefined', nil, :undef ].each do |value| + ['FALSE', '', '0', 'f', 'n', 'false', 'no', 'undef', 'undefined', nil, :undef].each do |value| it { is_expected.to run.with_params(value).and_return(false) } end end describe 'when testing numeric values that mean "true"' do - [ 1,'1',1.5, '1.5'].each do |value| + [1, '1', 1.5, '1.5'].each do |value| it { is_expected.to run.with_params(value).and_return(true) } end end describe 'when testing numeric that mean "false"' do - [ -1, '-1', -1.5, '-1.5', '0', 0 ].each do |value| + [-1, '-1', -1.5, '-1.5', '0', 0].each do |value| it { is_expected.to run.with_params(value).and_return(false) } end end describe 'everything else returns true' do - [ [], {}, ['1'], [1], {:one => 1} ].each do |value| + [[], {}, ['1'], [1], { one: 1 }].each do |value| it { is_expected.to run.with_params(value).and_return(true) } end end - end diff --git a/spec/functions/assert_private_spec.rb b/spec/functions/assert_private_spec.rb index 355e0dd3a..09abc77be 100755 --- a/spec/functions/assert_private_spec.rb +++ b/spec/functions/assert_private_spec.rb @@ -2,40 +2,40 @@ describe 'assert_private' do context 'when called from inside module' do - it "should not fail" do + it 'does not fail' do scope.expects(:lookupvar).with('module_name').returns('foo') scope.expects(:lookupvar).with('caller_module_name').returns('foo') - is_expected.to run.with_params() + is_expected.to run.with_params end end - context "when called from private class" do + context 'when called from private class' do before :each do scope.expects(:lookupvar).with('module_name').returns('foo') scope.expects(:lookupvar).with('caller_module_name').returns('bar') end - it "should fail with a class error message" do + it 'fails with a class error message' do scope.source.expects(:name).returns('foo::baz') scope.source.expects(:type).returns('hostclass') - is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /Class foo::baz is private/) + is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{Class foo::baz is private}) end - context "with an explicit failure message" do - it { is_expected.to run.with_params('failure message!').and_raise_error(Puppet::ParseError, /failure message!/) } + context 'with an explicit failure message' do + it { is_expected.to run.with_params('failure message!').and_raise_error(Puppet::ParseError, %r{failure message!}) } end end - context "when called from private definition" do - it "should fail with a class error message" do + context 'when called from private definition' do + it 'fails with a class error message' do scope.expects(:lookupvar).with('module_name').returns('foo') scope.expects(:lookupvar).with('caller_module_name').returns('bar') scope.source.expects(:name).returns('foo::baz') scope.source.expects(:type).returns('definition') - is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /Definition foo::baz is private/) + is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{Definition foo::baz is private}) end end end diff --git a/spec/functions/base64_spec.rb b/spec/functions/base64_spec.rb index 842a37a98..dafab360c 100755 --- a/spec/functions/base64_spec.rb +++ b/spec/functions/base64_spec.rb @@ -2,36 +2,59 @@ describe 'base64' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError) } - it { is_expected.to run.with_params("one").and_raise_error(Puppet::ParseError) } - it { is_expected.to run.with_params("one", "two").and_raise_error(Puppet::ParseError, /first argument must be one of/) } - it { is_expected.to run.with_params("encode", ["two"]).and_raise_error(Puppet::ParseError, /second argument must be a string/) } - it { is_expected.to run.with_params("encode", 2).and_raise_error(Puppet::ParseError, /second argument must be a string/) } - it { is_expected.to run.with_params("encode", "thestring", "three").and_raise_error(Puppet::ParseError, /third argument must be one of/) } - it { is_expected.to run.with_params("decode", "dGhlc3RyaW5n\n", "strict").and_raise_error(ArgumentError) } - - it { is_expected.to run.with_params("encode", "thestring").and_return("dGhlc3RyaW5n\n") } - it { is_expected.to run.with_params("decode", "dGhlc3RyaW5n").and_return("thestring") } - it { is_expected.to run.with_params("decode", "dGhlc3RyaW5n\n").and_return("thestring") } - - it { is_expected.to run.with_params("encode", "thestring", "default").and_return("dGhlc3RyaW5n\n") } - it { is_expected.to run.with_params("decode", "dGhlc3RyaW5n", "default").and_return("thestring") } - it { is_expected.to run.with_params("decode", "dGhlc3RyaW5n\n", "default").and_return("thestring") } - - it { is_expected.to run.with_params("encode", "thestring", "strict").and_return("dGhlc3RyaW5n") } - it { is_expected.to run.with_params("decode", "dGhlc3RyaW5n", "strict").and_return("thestring") } - - it { is_expected.to run.with_params("encode", "a very long string that will cause the base64 encoder to produce output with multiple lines").and_return("YSB2ZXJ5IGxvbmcgc3RyaW5nIHRoYXQgd2lsbCBjYXVzZSB0aGUgYmFzZTY0\nIGVuY29kZXIgdG8gcHJvZHVjZSBvdXRwdXQgd2l0aCBtdWx0aXBsZSBsaW5l\ncw==\n") } - it { is_expected.to run.with_params("decode", "YSB2ZXJ5IGxvbmcgc3RyaW5nIHRoYXQgd2lsbCBjYXVzZSB0aGUgYmFzZTY0\nIGVuY29kZXIgdG8gcHJvZHVjZSBvdXRwdXQgd2l0aCBtdWx0aXBsZSBsaW5l\ncw==\n").and_return("a very long string that will cause the base64 encoder to produce output with multiple lines") } - it { is_expected.to run.with_params("decode", "YSB2ZXJ5IGxvbmcgc3RyaW5nIHRoYXQgd2lsbCBjYXVzZSB0aGUgYmFzZTY0IGVuY29kZXIgdG8gcHJvZHVjZSBvdXRwdXQgd2l0aCBtdWx0aXBsZSBsaW5lcw==").and_return("a very long string that will cause the base64 encoder to produce output with multiple lines") } - - it { is_expected.to run.with_params("encode", "a very long string that will cause the base64 encoder to produce output with multiple lines", "strict").and_return("YSB2ZXJ5IGxvbmcgc3RyaW5nIHRoYXQgd2lsbCBjYXVzZSB0aGUgYmFzZTY0IGVuY29kZXIgdG8gcHJvZHVjZSBvdXRwdXQgd2l0aCBtdWx0aXBsZSBsaW5lcw==") } - it { is_expected.to run.with_params("decode", "YSB2ZXJ5IGxvbmcgc3RyaW5nIHRoYXQgd2lsbCBjYXVzZSB0aGUgYmFzZTY0IGVuY29kZXIgdG8gcHJvZHVjZSBvdXRwdXQgd2l0aCBtdWx0aXBsZSBsaW5lcw==").and_return("a very long string that will cause the base64 encoder to produce output with multiple lines") } - it { is_expected.to run.with_params("decode", "YSB2ZXJ5IGxvbmcgc3RyaW5nIHRoYXQgd2lsbCBjYXVzZSB0aGUgYmFzZTY0IGVuY29kZXIgdG8gcHJvZHVjZSBvdXRwdXQgd2l0aCBtdWx0aXBsZSBsaW5lcw==", "strict").and_return("a very long string that will cause the base64 encoder to produce output with multiple lines") } - - it { is_expected.to run.with_params("encode", "https://www.google.com.tw/?gws_rd=ssl#q=hello+world", "urlsafe").and_return("aHR0cHM6Ly93d3cuZ29vZ2xlLmNvbS50dy8_Z3dzX3JkPXNzbCNxPWhlbGxvK3dvcmxk") } - it { is_expected.to run.with_params("decode", "aHR0cHM6Ly93d3cuZ29vZ2xlLmNvbS50dy8_Z3dzX3JkPXNzbCNxPWhlbGxvK3dvcmxk", "urlsafe").and_return("https://www.google.com.tw/?gws_rd=ssl#q=hello+world") } - - it { is_expected.to run.with_params("encode", "https://github.com/puppetlabs/puppetlabs-stdlib/pulls?utf8=%E2%9C%93&q=is%3Apr+is%3Aopen+Add", "urlsafe").and_return("aHR0cHM6Ly9naXRodWIuY29tL3B1cHBldGxhYnMvcHVwcGV0bGFicy1zdGRsaWIvcHVsbHM_dXRmOD0lRTIlOUMlOTMmcT1pcyUzQXByK2lzJTNBb3BlbitBZGQ=") } - it { is_expected.to run.with_params("decode", "aHR0cHM6Ly9naXRodWIuY29tL3B1cHBldGxhYnMvcHVwcGV0bGFicy1zdGRsaWIvcHVsbHM_dXRmOD0lRTIlOUMlOTMmcT1pcyUzQXByK2lzJTNBb3BlbitBZGQ=", "urlsafe").and_return("https://github.com/puppetlabs/puppetlabs-stdlib/pulls?utf8=%E2%9C%93&q=is%3Apr+is%3Aopen+Add") } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError) } + it { is_expected.to run.with_params('one').and_raise_error(Puppet::ParseError) } + it { is_expected.to run.with_params('one', 'two').and_raise_error(Puppet::ParseError, %r{first argument must be one of}) } + it { is_expected.to run.with_params('encode', ['two']).and_raise_error(Puppet::ParseError, %r{second argument must be a string}) } + it { is_expected.to run.with_params('encode', 2).and_raise_error(Puppet::ParseError, %r{second argument must be a string}) } + it { is_expected.to run.with_params('encode', 'thestring', 'three').and_raise_error(Puppet::ParseError, %r{third argument must be one of}) } + it { is_expected.to run.with_params('decode', "dGhlc3RyaW5n\n", 'strict').and_raise_error(ArgumentError) } + + it { is_expected.to run.with_params('encode', 'thestring').and_return("dGhlc3RyaW5n\n") } + it { is_expected.to run.with_params('decode', 'dGhlc3RyaW5n').and_return('thestring') } + it { is_expected.to run.with_params('decode', "dGhlc3RyaW5n\n").and_return('thestring') } + + it { is_expected.to run.with_params('encode', 'thestring', 'default').and_return("dGhlc3RyaW5n\n") } + it { is_expected.to run.with_params('decode', 'dGhlc3RyaW5n', 'default').and_return('thestring') } + it { is_expected.to run.with_params('decode', "dGhlc3RyaW5n\n", 'default').and_return('thestring') } + + it { is_expected.to run.with_params('encode', 'thestring', 'strict').and_return('dGhlc3RyaW5n') } + it { is_expected.to run.with_params('decode', 'dGhlc3RyaW5n', 'strict').and_return('thestring') } + + it { + is_expected.to run.with_params('encode', 'a very long string that will cause the base64 encoder to produce output with multiple lines') + .and_return("YSB2ZXJ5IGxvbmcgc3RyaW5nIHRoYXQgd2lsbCBjYXVzZSB0aGUgYmFzZTY0\nIGVuY29kZXIgdG8gcHJvZHVjZSBvdXRwdXQgd2l0aCBtdWx0aXBsZSBsaW5l\ncw==\n") + } + it { + is_expected.to run.with_params('decode', "YSB2ZXJ5IGxvbmcgc3RyaW5nIHRoYXQgd2lsbCBjYXVzZSB0aGUgYmFzZTY0\nIGVuY29kZXIgdG8gcHJvZHVjZSBvdXRwdXQgd2l0aCBtdWx0aXBsZSBsaW5l\ncw==\n") + .and_return('a very long string that will cause the base64 encoder to produce output with multiple lines') + } + it { + is_expected.to run.with_params('decode', 'YSB2ZXJ5IGxvbmcgc3RyaW5nIHRoYXQgd2lsbCBjYXVzZSB0aGUgYmFzZTY0IGVuY29kZXIgdG8gcHJvZHVjZSBvdXRwdXQgd2l0aCBtdWx0aXBsZSBsaW5lcw==') + .and_return('a very long string that will cause the base64 encoder to produce output with multiple lines') + } + it { + is_expected.to run.with_params('encode', 'a very long string that will cause the base64 encoder to produce output with multiple lines', 'strict') + .and_return('YSB2ZXJ5IGxvbmcgc3RyaW5nIHRoYXQgd2lsbCBjYXVzZSB0aGUgYmFzZTY0IGVuY29kZXIgdG8gcHJvZHVjZSBvdXRwdXQgd2l0aCBtdWx0aXBsZSBsaW5lcw==') + } + it { + is_expected.to run.with_params('decode', 'YSB2ZXJ5IGxvbmcgc3RyaW5nIHRoYXQgd2lsbCBjYXVzZSB0aGUgYmFzZTY0IGVuY29kZXIgdG8gcHJvZHVjZSBvdXRwdXQgd2l0aCBtdWx0aXBsZSBsaW5lcw==', 'strict') + .and_return('a very long string that will cause the base64 encoder to produce output with multiple lines') + } + it { + is_expected.to run.with_params('encode', 'https://www.google.com.tw/?gws_rd=ssl#q=hello+world', 'urlsafe') + .and_return('aHR0cHM6Ly93d3cuZ29vZ2xlLmNvbS50dy8_Z3dzX3JkPXNzbCNxPWhlbGxvK3dvcmxk') + } + it { + is_expected.to run.with_params('decode', 'aHR0cHM6Ly93d3cuZ29vZ2xlLmNvbS50dy8_Z3dzX3JkPXNzbCNxPWhlbGxvK3dvcmxk', 'urlsafe') + .and_return('https://www.google.com.tw/?gws_rd=ssl#q=hello+world') + } + it { + is_expected.to run.with_params('encode', 'https://github.com/puppetlabs/puppetlabs-stdlib/pulls?utf8=%E2%9C%93&q=is%3Apr+is%3Aopen+Add', 'urlsafe') + .and_return('aHR0cHM6Ly9naXRodWIuY29tL3B1cHBldGxhYnMvcHVwcGV0bGFicy1zdGRsaWIvcHVsbHM_dXRmOD0lRTIlOUMlOTMmcT1pcyUzQXByK2lzJTNBb3BlbitBZGQ=') + } + it { + is_expected.to run.with_params('decode', 'aHR0cHM6Ly9naXRodWIuY29tL3B1cHBldGxhYnMvcHVwcGV0bGFicy1zdGRsaWIvcHVsbHM_dXRmOD0lRTIlOUMlOTMmcT1pcyUzQXByK2lzJTNBb3BlbitBZGQ=', 'urlsafe') + .and_return('https://github.com/puppetlabs/puppetlabs-stdlib/pulls?utf8=%E2%9C%93&q=is%3Apr+is%3Aopen+Add') + } end diff --git a/spec/functions/basename_spec.rb b/spec/functions/basename_spec.rb index 3e02b01ba..d751d92ec 100755 --- a/spec/functions/basename_spec.rb +++ b/spec/functions/basename_spec.rb @@ -2,7 +2,7 @@ describe 'basename' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params('one', 'two', 'three').and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params([]).and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params('/path/to/a/file.ext', []).and_raise_error(Puppet::ParseError) } diff --git a/spec/functions/bool2num_spec.rb b/spec/functions/bool2num_spec.rb index e5068594b..3ba5e2cf7 100755 --- a/spec/functions/bool2num_spec.rb +++ b/spec/functions/bool2num_spec.rb @@ -2,13 +2,13 @@ describe 'bool2num' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError) } - [ true, 'true', AlsoString.new('true') ].each do |truthy| + [true, 'true', AlsoString.new('true')].each do |truthy| it { is_expected.to run.with_params(truthy).and_return(1) } end - [ false, 'false', AlsoString.new('false') ].each do |falsey| + [false, 'false', AlsoString.new('false')].each do |falsey| it { is_expected.to run.with_params(falsey).and_return(0) } end end diff --git a/spec/functions/bool2str_spec.rb b/spec/functions/bool2str_spec.rb index 23a754ba4..8d8f9b5bc 100755 --- a/spec/functions/bool2str_spec.rb +++ b/spec/functions/bool2str_spec.rb @@ -2,16 +2,15 @@ describe 'bool2str' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError) } - [ 'true', 'false', nil, :undef, ''].each do |invalid| + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError) } + ['true', 'false', nil, :undef, ''].each do |invalid| it { is_expected.to run.with_params(invalid).and_raise_error(Puppet::ParseError) } end it { is_expected.to run.with_params(true, 'yes', 'no', 'maybe').and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params(true, 'maybe').and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params(true, 0, 1).and_raise_error(Puppet::ParseError) } - it { is_expected.to run.with_params(true).and_return("true") } - it { is_expected.to run.with_params(false).and_return("false") } - it { is_expected.to run.with_params(true, 'yes', 'no').and_return("yes") } - it { is_expected.to run.with_params(false, 'yes', 'no').and_return("no") } - + it { is_expected.to run.with_params(true).and_return('true') } + it { is_expected.to run.with_params(false).and_return('false') } + it { is_expected.to run.with_params(true, 'yes', 'no').and_return('yes') } + it { is_expected.to run.with_params(false, 'yes', 'no').and_return('no') } end diff --git a/spec/functions/camelcase_spec.rb b/spec/functions/camelcase_spec.rb index c78aa62ff..892e1da9c 100755 --- a/spec/functions/camelcase_spec.rb +++ b/spec/functions/camelcase_spec.rb @@ -2,16 +2,16 @@ describe 'camelcase' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params(100).and_raise_error(Puppet::ParseError) } - it { is_expected.to run.with_params("abc").and_return("Abc") } - it { is_expected.to run.with_params("aa_bb_cc").and_return("AaBbCc") } - it { is_expected.to run.with_params("_aa__bb__cc_").and_return("AaBbCc") } - it { is_expected.to run.with_params("100").and_return("100") } - it { is_expected.to run.with_params("1_00").and_return("100") } - it { is_expected.to run.with_params("_").and_return("") } - it { is_expected.to run.with_params("").and_return("") } + it { is_expected.to run.with_params('abc').and_return('Abc') } + it { is_expected.to run.with_params('aa_bb_cc').and_return('AaBbCc') } + it { is_expected.to run.with_params('_aa__bb__cc_').and_return('AaBbCc') } + it { is_expected.to run.with_params('100').and_return('100') } + it { is_expected.to run.with_params('1_00').and_return('100') } + it { is_expected.to run.with_params('_').and_return('') } + it { is_expected.to run.with_params('').and_return('') } it { is_expected.to run.with_params([]).and_return([]) } - it { is_expected.to run.with_params(["abc", "aa_bb_cc"]).and_return(["Abc", "AaBbCc"]) } - it { is_expected.to run.with_params(["abc", 1, "aa_bb_cc"]).and_return(["Abc", 1, "AaBbCc"]) } + it { is_expected.to run.with_params(%w[abc aa_bb_cc]).and_return(%w[Abc AaBbCc]) } + it { is_expected.to run.with_params(['abc', 1, 'aa_bb_cc']).and_return(['Abc', 1, 'AaBbCc']) } end diff --git a/spec/functions/capitalize_spec.rb b/spec/functions/capitalize_spec.rb index 7ce2e1630..15c2acf0f 100755 --- a/spec/functions/capitalize_spec.rb +++ b/spec/functions/capitalize_spec.rb @@ -2,14 +2,14 @@ describe 'capitalize' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params(100).and_raise_error(Puppet::ParseError) } - it { is_expected.to run.with_params("one").and_return("One") } - it { is_expected.to run.with_params("one two").and_return("One two") } - it { is_expected.to run.with_params("ONE TWO").and_return("One two") } + it { is_expected.to run.with_params('one').and_return('One') } + it { is_expected.to run.with_params('one two').and_return('One two') } + it { is_expected.to run.with_params('ONE TWO').and_return('One two') } - it { is_expected.to run.with_params(AlsoString.new("one")).and_return("One") } + it { is_expected.to run.with_params(AlsoString.new('one')).and_return('One') } it { is_expected.to run.with_params([]).and_return([]) } - it { is_expected.to run.with_params(["one", "two"]).and_return(["One", "Two"]) } - it { is_expected.to run.with_params(["one", 1, "two"]).and_return(["One", 1, "Two"]) } + it { is_expected.to run.with_params(%w[one two]).and_return(%w[One Two]) } + it { is_expected.to run.with_params(['one', 1, 'two']).and_return(['One', 1, 'Two']) } end diff --git a/spec/functions/ceiling_spec.rb b/spec/functions/ceiling_spec.rb index 567426fd3..068272084 100755 --- a/spec/functions/ceiling_spec.rb +++ b/spec/functions/ceiling_spec.rb @@ -2,12 +2,11 @@ describe 'ceiling' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError) } - it { is_expected.to run.with_params("foo").and_raise_error(Puppet::ParseError) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError) } + it { is_expected.to run.with_params('foo').and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params([]).and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params(34).and_return(34) } it { is_expected.to run.with_params(-34).and_return(-34) } it { is_expected.to run.with_params(33.1).and_return(34) } it { is_expected.to run.with_params(-33.1).and_return(-33) } end - diff --git a/spec/functions/chomp_spec.rb b/spec/functions/chomp_spec.rb index 56bd9b1e1..c511ab79e 100755 --- a/spec/functions/chomp_spec.rb +++ b/spec/functions/chomp_spec.rb @@ -2,21 +2,21 @@ describe 'chomp' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError) } it { - pending("Current implementation ignores parameters after the first.") - is_expected.to run.with_params("a", "b").and_raise_error(Puppet::ParseError) + pending('Current implementation ignores parameters after the first.') + is_expected.to run.with_params('a', 'b').and_raise_error(Puppet::ParseError) } - it { is_expected.to run.with_params("one").and_return("one") } - it { is_expected.to run.with_params("one\n").and_return("one") } + it { is_expected.to run.with_params('one').and_return('one') } + it { is_expected.to run.with_params("one\n").and_return('one') } it { is_expected.to run.with_params("one\n\n").and_return("one\n") } - it { is_expected.to run.with_params(["one\n", "two", "three\n"]).and_return(["one", "two", "three"]) } + it { is_expected.to run.with_params(%W[one\n two three\n]).and_return(%w[one two three]) } - it { is_expected.to run.with_params(AlsoString.new("one")).and_return("one") } - it { is_expected.to run.with_params(AlsoString.new("one\n")).and_return("one") } + it { is_expected.to run.with_params(AlsoString.new('one')).and_return('one') } + it { is_expected.to run.with_params(AlsoString.new("one\n")).and_return('one') } it { is_expected.to run.with_params(AlsoString.new("one\n\n")).and_return("one\n") } - it { is_expected.to run.with_params([AlsoString.new("one\n"), AlsoString.new("two"), "three\n"]).and_return(["one", "two", "three"]) } + it { is_expected.to run.with_params([AlsoString.new("one\n"), AlsoString.new('two'), "three\n"]).and_return(%w[one two three]) } context 'should run with UTF8 and double byte characters' do it { is_expected.to run.with_params("ůťƒ8\n\n").and_return("ůťƒ8\n") } diff --git a/spec/functions/chop_spec.rb b/spec/functions/chop_spec.rb index b70fc37eb..4150e2529 100755 --- a/spec/functions/chop_spec.rb +++ b/spec/functions/chop_spec.rb @@ -2,21 +2,21 @@ describe 'chop' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError) } it { - pending("Current implementation ignores parameters after the first.") - is_expected.to run.with_params("a", "b").and_raise_error(Puppet::ParseError) + pending('Current implementation ignores parameters after the first.') + is_expected.to run.with_params('a', 'b').and_raise_error(Puppet::ParseError) } - it { is_expected.to run.with_params("one").and_return("on") } - it { is_expected.to run.with_params("one\n").and_return("one") } + it { is_expected.to run.with_params('one').and_return('on') } + it { is_expected.to run.with_params("one\n").and_return('one') } it { is_expected.to run.with_params("one\n\n").and_return("one\n") } - it { is_expected.to run.with_params(["one\n", "two", "three\n"]).and_return(["one", "tw", "three"]) } + it { is_expected.to run.with_params(%W[one\n two three\n]).and_return(%w[one tw three]) } - it { is_expected.to run.with_params(AlsoString.new("one")).and_return("on") } - it { is_expected.to run.with_params(AlsoString.new("one\n")).and_return("one") } + it { is_expected.to run.with_params(AlsoString.new('one')).and_return('on') } + it { is_expected.to run.with_params(AlsoString.new("one\n")).and_return('one') } it { is_expected.to run.with_params(AlsoString.new("one\n\n")).and_return("one\n") } - it { is_expected.to run.with_params([AlsoString.new("one\n"), AlsoString.new("two"), "three\n"]).and_return(["one", "tw", "three"]) } + it { is_expected.to run.with_params([AlsoString.new("one\n"), AlsoString.new('two'), "three\n"]).and_return(%w[one tw three]) } context 'should run with UTF8 and double byte characters' do it { is_expected.to run.with_params("ůťƒ8\n\n").and_return("ůťƒ8\n") } diff --git a/spec/functions/clamp_spec.rb b/spec/functions/clamp_spec.rb index 3e2fe7ac3..7f0de3431 100644 --- a/spec/functions/clamp_spec.rb +++ b/spec/functions/clamp_spec.rb @@ -2,11 +2,11 @@ describe 'clamp' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(ArgumentError) } + it { is_expected.to run.with_params.and_raise_error(ArgumentError) } it { is_expected.to run.with_params([]).and_raise_error(Puppet::ParseError) } - it { is_expected.to run.with_params(12, 88, 71, 190).and_raise_error(Puppet::ParseError, /Wrong number of arguments, need three to clamp/) } - it { is_expected.to run.with_params('12string', 88, 15).and_raise_error(Puppet::ParseError, /Required explicit numeric/) } - it { is_expected.to run.with_params(1, 2, {'a' => 55}).and_raise_error(Puppet::ParseError, /The Hash type is not allowed/) } + it { is_expected.to run.with_params(12, 88, 71, 190).and_raise_error(Puppet::ParseError, %r{Wrong number of arguments, need three to clamp}) } + it { is_expected.to run.with_params('12string', 88, 15).and_raise_error(Puppet::ParseError, %r{Required explicit numeric}) } + it { is_expected.to run.with_params(1, 2, 'a' => 55).and_raise_error(Puppet::ParseError, %r{The Hash type is not allowed}) } it { is_expected.to run.with_params('24', [575, 187]).and_return(187) } it { is_expected.to run.with_params([4, 3, '99']).and_return(4) } it { is_expected.to run.with_params(16, 750, 88).and_return(88) } diff --git a/spec/functions/concat_spec.rb b/spec/functions/concat_spec.rb index 6ab1b6e1d..a43cfb6ee 100755 --- a/spec/functions/concat_spec.rb +++ b/spec/functions/concat_spec.rb @@ -2,28 +2,27 @@ describe 'concat' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params([1]).and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params(1, [2]).and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params([1], [2], [3]).and_return([1, 2, 3]) } - it { is_expected.to run.with_params(['1','2','3'],['4','5','6']).and_return(['1','2','3','4','5','6']) } - it { is_expected.to run.with_params(['1','2','3'],'4').and_return(['1','2','3','4']) } - it { is_expected.to run.with_params(['1','2','3'],[['4','5'],'6']).and_return(['1','2','3',['4','5'],'6']) } - it { is_expected.to run.with_params(['1','2'],['3','4'],['5','6']).and_return(['1','2','3','4','5','6']) } - it { is_expected.to run.with_params(['1','2'],'3','4',['5','6']).and_return(['1','2','3','4','5','6']) } + it { is_expected.to run.with_params(%w[1 2 3], %w[4 5 6]).and_return(%w[1 2 3 4 5 6]) } + it { is_expected.to run.with_params(%w[1 2 3], '4').and_return(%w[1 2 3 4]) } + it { is_expected.to run.with_params(%w[1 2 3], [%w[4 5], '6']).and_return(['1', '2', '3', %w[4 5], '6']) } + it { is_expected.to run.with_params(%w[1 2], %w[3 4], %w[5 6]).and_return(%w[1 2 3 4 5 6]) } + it { is_expected.to run.with_params(%w[1 2], '3', '4', %w[5 6]).and_return(%w[1 2 3 4 5 6]) } -context 'should run with UTF8 and double byte characters' do - it { is_expected.to run.with_params([{"a" => "b"}], {"c" => "d", "e" => "f"}).and_return([{"a" => "b"}, {"c" => "d", "e" => "f"}]) } - it { is_expected.to run.with_params(['ấ','β','©'],['đ','ể','文字列']).and_return(['ấ','β','©','đ','ể','文字列']) } -end + context 'should run with UTF8 and double byte characters' do + it { is_expected.to run.with_params([{ 'a' => 'b' }], 'c' => 'd', 'e' => 'f').and_return([{ 'a' => 'b' }, { 'c' => 'd', 'e' => 'f' }]) } + it { is_expected.to run.with_params(['ấ', 'β', '©'], %w[đ ể 文字列]).and_return(['ấ', 'β', '©', 'đ', 'ể', '文字列']) } + end - it "should leave the original array intact" do - argument1 = ['1','2','3'] - original1 = argument1.dup - argument2 = ['4','5','6'] - original2 = argument2.dup - result = subject.call([argument1,argument2]) - expect(argument1).to eq(original1) - expect(argument2).to eq(original2) + arguments = [%w[1 2 3], %w[4 5 6]] + originals = [arguments[0].dup, arguments[1].dup] + it 'leaves the original array intact' do + _result = subject.call([arguments[0], arguments[1]]) + arguments.each_with_index do |argument, index| + expect(argument).to eq(originals[index]) + end end end diff --git a/spec/functions/convert_base_spec.rb b/spec/functions/convert_base_spec.rb index 8ab228454..d1a6cef14 100644 --- a/spec/functions/convert_base_spec.rb +++ b/spec/functions/convert_base_spec.rb @@ -2,23 +2,23 @@ describe 'convert_base' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(ArgumentError) } - it { is_expected.to run.with_params("asdf").and_raise_error(ArgumentError) } - it { is_expected.to run.with_params("asdf","moo","cow").and_raise_error(ArgumentError) } - it { is_expected.to run.with_params(["1"],"2").and_raise_error(Puppet::ParseError, /argument must be either a string or an integer/) } - it { is_expected.to run.with_params("1",["2"]).and_raise_error(Puppet::ParseError, /argument must be either a string or an integer/) } - it { is_expected.to run.with_params("1",1).and_raise_error(Puppet::ParseError, /base must be at least 2 and must not be greater than 36/) } - it { is_expected.to run.with_params("1",37).and_raise_error(Puppet::ParseError, /base must be at least 2 and must not be greater than 36/) } + it { is_expected.to run.with_params.and_raise_error(ArgumentError) } + it { is_expected.to run.with_params('asdf').and_raise_error(ArgumentError) } + it { is_expected.to run.with_params('asdf', 'moo', 'cow').and_raise_error(ArgumentError) } + it { is_expected.to run.with_params(['1'], '2').and_raise_error(Puppet::ParseError, %r{argument must be either a string or an integer}) } + it { is_expected.to run.with_params('1', ['2']).and_raise_error(Puppet::ParseError, %r{argument must be either a string or an integer}) } + it { is_expected.to run.with_params('1', 1).and_raise_error(Puppet::ParseError, %r{base must be at least 2 and must not be greater than 36}) } + it { is_expected.to run.with_params('1', 37).and_raise_error(Puppet::ParseError, %r{base must be at least 2 and must not be greater than 36}) } - it "should raise a ParseError if argument 1 is a string that does not correspond to an integer in base 10" do - is_expected.to run.with_params("ten",6).and_raise_error(Puppet::ParseError, /argument must be an integer or a string corresponding to an integer in base 10/) + it 'raises a ParseError if argument 1 is a string that does not correspond to an integer in base 10' do + is_expected.to run.with_params('ten', 6).and_raise_error(Puppet::ParseError, %r{argument must be an integer or a string corresponding to an integer in base 10}) end - it "should raise a ParseError if argument 2 is a string and does not correspond to an integer in base 10" do - is_expected.to run.with_params(100,"hex").and_raise_error(Puppet::ParseError, /argument must be an integer or a string corresponding to an integer in base 10/) + it 'raises a ParseError if argument 2 is a string and does not correspond to an integer in base 10' do + is_expected.to run.with_params(100, 'hex').and_raise_error(Puppet::ParseError, %r{argument must be an integer or a string corresponding to an integer in base 10}) end - it { is_expected.to run.with_params("11",'16').and_return('b') } - it { is_expected.to run.with_params("35",'36').and_return('z') } + it { is_expected.to run.with_params('11', '16').and_return('b') } + it { is_expected.to run.with_params('35', '36').and_return('z') } it { is_expected.to run.with_params(5, 2).and_return('101') } end diff --git a/spec/functions/count_spec.rb b/spec/functions/count_spec.rb index 3854cb877..9f5d54459 100755 --- a/spec/functions/count_spec.rb +++ b/spec/functions/count_spec.rb @@ -2,22 +2,22 @@ describe 'count' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(ArgumentError) } - it { is_expected.to run.with_params("one").and_raise_error(ArgumentError) } - it { is_expected.to run.with_params("one", "two").and_return(1) } + it { is_expected.to run.with_params.and_raise_error(ArgumentError) } + it { is_expected.to run.with_params('one').and_raise_error(ArgumentError) } + it { is_expected.to run.with_params('one', 'two').and_return(1) } it { - pending("should actually be like this, and not like above") - is_expected.to run.with_params("one", "two").and_raise_error(ArgumentError) + pending('should actually be like this, and not like above') + is_expected.to run.with_params('one', 'two').and_raise_error(ArgumentError) } - it { is_expected.to run.with_params("one", "two", "three").and_raise_error(ArgumentError) } - it { is_expected.to run.with_params(["one", "two", "three"]).and_return(3) } - it { is_expected.to run.with_params(["one", "two", "two"], "two").and_return(2) } - it { is_expected.to run.with_params(["one", nil, "two"]).and_return(2) } - it { is_expected.to run.with_params(["one", "", "two"]).and_return(2) } - it { is_expected.to run.with_params(["one", :undef, "two"]).and_return(2) } + it { is_expected.to run.with_params('one', 'two', 'three').and_raise_error(ArgumentError) } + it { is_expected.to run.with_params(%w[one two three]).and_return(3) } + it { is_expected.to run.with_params(%w[one two two], 'two').and_return(2) } + it { is_expected.to run.with_params(['one', nil, 'two']).and_return(2) } + it { is_expected.to run.with_params(['one', '', 'two']).and_return(2) } + it { is_expected.to run.with_params(['one', :undef, 'two']).and_return(2) } - it { is_expected.to run.with_params(["ổņ℮", "ŧщộ", "three"]).and_return(3) } - it { is_expected.to run.with_params(["ổņ℮", "ŧщộ", "ŧщộ"], "ŧщộ").and_return(2) } - it { is_expected.to run.with_params(["ổņ℮", nil, "ŧщộ"]).and_return(2) } - it { is_expected.to run.with_params(["ổņ℮", :undef, "ŧщộ"]).and_return(2) } + it { is_expected.to run.with_params(['ổņ℮', 'ŧщộ', 'three']).and_return(3) } + it { is_expected.to run.with_params(['ổņ℮', 'ŧщộ', 'ŧщộ'], 'ŧщộ').and_return(2) } + it { is_expected.to run.with_params(['ổņ℮', nil, 'ŧщộ']).and_return(2) } + it { is_expected.to run.with_params(['ổņ℮', :undef, 'ŧщộ']).and_return(2) } end diff --git a/spec/functions/deep_merge_spec.rb b/spec/functions/deep_merge_spec.rb index 819e025f0..74d20a75c 100755 --- a/spec/functions/deep_merge_spec.rb +++ b/spec/functions/deep_merge_spec.rb @@ -1,59 +1,58 @@ require 'spec_helper' describe 'deep_merge' do - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } - it { is_expected.to run.with_params({ 'key' => 'value' }).and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } - it { is_expected.to run.with_params({}, '2').and_raise_error(Puppet::ParseError, /unexpected argument type String/) } - it { is_expected.to run.with_params({}, 2).and_raise_error(Puppet::ParseError, /unexpected argument/) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } + it { is_expected.to run.with_params('key' => 'value').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } + it { is_expected.to run.with_params({}, '2').and_raise_error(Puppet::ParseError, %r{unexpected argument type String}) } + it { is_expected.to run.with_params({}, 2).and_raise_error(Puppet::ParseError, %r{unexpected argument}) } it { is_expected.to run.with_params({}, '').and_return({}) } it { is_expected.to run.with_params({}, {}).and_return({}) } it { is_expected.to run.with_params({}, {}, {}).and_return({}) } it { is_expected.to run.with_params({}, {}, {}, {}).and_return({}) } - it { is_expected.to run.with_params({'key' => 'value'}, '').and_return({'key' => 'value'}) } - it { is_expected.to run.with_params({'key1' => 'value1'}, {'key2' => 'value2' }).and_return({'key1' => 'value1', 'key2' => 'value2'}) } + it { is_expected.to run.with_params({ 'key' => 'value' }, '').and_return('key' => 'value') } + it { is_expected.to run.with_params({ 'key1' => 'value1' }, 'key2' => 'value2').and_return('key1' => 'value1', 'key2' => 'value2') } describe 'when arguments have key collisions' do - it 'should prefer values from the last hash' do + it 'prefers values from the last hash' do is_expected.to run \ - .with_params( - {'key1' => 'value1', 'key2' => 'value2' }, - {'key2' => 'replacement_value', 'key3' => 'value3'}) \ - .and_return( - {'key1' => 'value1', 'key2' => 'replacement_value', 'key3' => 'value3'}) + .with_params({ 'key1' => 'value1', 'key2' => 'value2' }, 'key2' => 'replacement_value', 'key3' => 'value3') \ + .and_return('key1' => 'value1', 'key2' => 'replacement_value', 'key3' => 'value3') end - it { is_expected.to run \ - .with_params({'key1' => 'value1'}, {'key1' => 'value2'}, {'key1' => 'value3'}) \ - .and_return({'key1' => 'value3' }) + it { + is_expected.to run \ + .with_params({ 'key1' => 'value1' }, { 'key1' => 'value2' }, 'key1' => 'value3') \ + .and_return('key1' => 'value3') } end describe 'when arguments have subhashes' do - it { is_expected.to run \ - .with_params({'key1' => 'value1'}, {'key2' => 'value2', 'key3' => {'subkey1' => 'value4'}}) \ - .and_return( {'key1' => 'value1', 'key2' => 'value2', 'key3' => {'subkey1' => 'value4'}}) + it { + is_expected.to run \ + .with_params({ 'key1' => 'value1' }, 'key2' => 'value2', 'key3' => { 'subkey1' => 'value4' }) \ + .and_return('key1' => 'value1', 'key2' => 'value2', 'key3' => { 'subkey1' => 'value4' }) } - it { is_expected.to run \ - .with_params({'key1' => {'subkey1' => 'value1'}}, {'key1' => {'subkey2' => 'value2'}}) \ - .and_return( {'key1' => {'subkey1' => 'value1', 'subkey2' => 'value2'}}) + it { + is_expected.to run \ + .with_params({ 'key1' => { 'subkey1' => 'value1' } }, 'key1' => { 'subkey2' => 'value2' }) \ + .and_return('key1' => { 'subkey1' => 'value1', 'subkey2' => 'value2' }) } - it { is_expected.to run \ - .with_params({'key1' => {'subkey1' => {'subsubkey1' => 'value1'}}}, {'key1' => {'subkey1' => {'subsubkey1' => 'value2'}}}) \ - .and_return( {'key1' => {'subkey1' => {'subsubkey1' => 'value2'}}}) + it { + is_expected.to run \ + .with_params({ 'key1' => { 'subkey1' => { 'subsubkey1' => 'value1' } } }, 'key1' => { 'subkey1' => { 'subsubkey1' => 'value2' } }) \ + .and_return('key1' => { 'subkey1' => { 'subsubkey1' => 'value2' } }) } end - it 'should not change the original hashes' do - argument1 = { 'key1' => 'value1' } - original1 = argument1.dup - argument2 = { 'key2' => 'value2' } - original2 = argument2.dup - - subject.call([argument1, argument2]) - expect(argument1).to eq(original1) - expect(argument2).to eq(original2) + arguments = { 'key1' => 'value1' }, { 'key2' => 'value2' } + originals = [arguments[0].dup, arguments[1].dup] + it 'does not change the original hashes' do + subject.call([arguments[0], arguments[1]]) + arguments.each_with_index do |argument, index| + expect(argument).to eq(originals[index]) + end end context 'should run with UTF8 and double byte characters' do - it { is_expected.to run.with_params({'ĸέỹ1' => 'ϋǻļủë1'}, {'この文字列' => '万' }).and_return({'ĸέỹ1' => 'ϋǻļủë1', 'この文字列' => '万'}) } + it { is_expected.to run.with_params({ 'ĸέỹ1' => 'ϋǻļủë1' }, 'この文字列' => '万').and_return('ĸέỹ1' => 'ϋǻļủë1', 'この文字列' => '万') } end end diff --git a/spec/functions/defined_with_params_spec.rb b/spec/functions/defined_with_params_spec.rb index 491a03be7..5715f6f1b 100755 --- a/spec/functions/defined_with_params_spec.rb +++ b/spec/functions/defined_with_params_spec.rb @@ -2,15 +2,16 @@ describe 'defined_with_params' do describe 'when no resource is specified' do - it { is_expected.to run.with_params().and_raise_error(ArgumentError) } + it { is_expected.to run.with_params.and_raise_error(ArgumentError) } end describe 'when compared against a resource with no attributes' do let :pre_condition do 'user { "dan": }' end + it { is_expected.to run.with_params('User[dan]', {}).and_return(true) } it { is_expected.to run.with_params('User[bob]', {}).and_return(false) } - it { is_expected.to run.with_params('User[dan]', {'foo' => 'bar'}).and_return(false) } + it { is_expected.to run.with_params('User[dan]', 'foo' => 'bar').and_return(false) } context 'should run with UTF8 and double byte characters' do it { is_expected.to run.with_params('User[ĵĭмოү]', {}).and_return(false) } @@ -22,11 +23,12 @@ let :pre_condition do 'user { "dan": ensure => present, shell => "/bin/csh", managehome => false}' end + it { is_expected.to run.with_params('User[dan]', {}).and_return(true) } it { is_expected.to run.with_params('User[dan]', '').and_return(true) } - it { is_expected.to run.with_params('User[dan]', {'ensure' => 'present'}).and_return(true) } - it { is_expected.to run.with_params('User[dan]', {'ensure' => 'present', 'managehome' => false}).and_return(true) } - it { is_expected.to run.with_params('User[dan]', {'ensure' => 'absent', 'managehome' => false}).and_return(false) } + it { is_expected.to run.with_params('User[dan]', 'ensure' => 'present').and_return(true) } + it { is_expected.to run.with_params('User[dan]', 'ensure' => 'present', 'managehome' => false).and_return(true) } + it { is_expected.to run.with_params('User[dan]', 'ensure' => 'absent', 'managehome' => false).and_return(false) } end describe 'when passing undef values' do @@ -35,13 +37,14 @@ end it { is_expected.to run.with_params('File[/tmp/a]', {}).and_return(true) } - it { is_expected.to run.with_params('File[/tmp/a]', { 'ensure' => 'present', 'owner' => :undef }).and_return(true) } + it { is_expected.to run.with_params('File[/tmp/a]', 'ensure' => 'present', 'owner' => :undef).and_return(true) } end describe 'when the reference is a' do let :pre_condition do 'user { "dan": }' end + context 'reference' do it { is_expected.to run.with_params(Puppet::Resource.new('User[dan]'), {}).and_return(true) } end @@ -50,7 +53,7 @@ it 'fails' do expect { subject.call([['User[dan]'], {}]) - }.to raise_error ArgumentError, /not understood: 'Array'/ + }.to raise_error ArgumentError, %r{not understood: 'Array'} end end end @@ -60,6 +63,7 @@ let :pre_condition do 'test::deftype { "foo": }' end + it { is_expected.to run.with_params('Test::Deftype[foo]', {}).and_return(true) } it { is_expected.to run.with_params('Test::Deftype[bar]', {}).and_return(false) } it { is_expected.to run.with_params(Puppet::Resource.new('Test::Deftype[foo]'), {}).and_return(true) } diff --git a/spec/functions/delete_at_spec.rb b/spec/functions/delete_at_spec.rb index 047103924..8889fbc2a 100755 --- a/spec/functions/delete_at_spec.rb +++ b/spec/functions/delete_at_spec.rb @@ -2,12 +2,12 @@ describe 'delete_at' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params('one', 1).and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params(1, 1).and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params(['one'], 'two').and_raise_error(Puppet::ParseError) } it { - pending("Current implementation ignores parameters after the first two.") + pending('Current implementation ignores parameters after the first two.') is_expected.to run.with_params(['one'], 0, 1).and_raise_error(Puppet::ParseError) } @@ -18,13 +18,12 @@ it { is_expected.to run.with_params([0, 1, 2], 1).and_return([0, 2]) } it { is_expected.to run.with_params([0, 1, 2], -1).and_return([0, 1]) } it { is_expected.to run.with_params([0, 1, 2], -4).and_return([0, 1, 2]) } - it { is_expected.to run.with_params(["ƒờở", "βāř", "ьầż"], 1).and_return(["ƒờở", "ьầż"]) } + it { is_expected.to run.with_params(%w[ƒờở βāř ьầż], 1).and_return(%w[ƒờở ьầż]) } - - it "should leave the original array intact" do + it 'leaves the original array intact' do argument = [1, 2, 3] original = argument.dup - result = subject.call([argument,2]) + _result = subject.call([argument, 2]) expect(argument).to eq(original) end end diff --git a/spec/functions/delete_regex_spec.rb b/spec/functions/delete_regex_spec.rb index f27a9467b..1e1cc2c4b 100755 --- a/spec/functions/delete_regex_spec.rb +++ b/spec/functions/delete_regex_spec.rb @@ -2,7 +2,7 @@ describe 'delete_regex' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params([]).and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params([], 'two') } it { is_expected.to run.with_params({}, 'two') } @@ -14,13 +14,13 @@ it { is_expected.to run.with_params([], '').and_return([]) } it { is_expected.to run.with_params([], 'two').and_return([]) } it { is_expected.to run.with_params(['two'], 'two').and_return([]) } - it { is_expected.to run.with_params(['two', 'two'], 'two').and_return([]) } - it { is_expected.to run.with_params(['one', 'two', 'three'], '^t.*').and_return(['one']) } - it { is_expected.to run.with_params(['ab', 'b', 'c', 'b'], 'b').and_return(['ab', 'c']) } - it { is_expected.to run.with_params(['one', 'two', 'three'], 'four').and_return(['one', 'two', 'three']) } - it { is_expected.to run.with_params(['one', 'two', 'three'], 'e').and_return(['one', 'two', 'three']) } - it { is_expected.to run.with_params(['one', 'two', 'three'], 'two').and_return(['one', 'three']) } - it { is_expected.to run.with_params(['two', 'one', 'two', 'three', 'two'], 'two').and_return(['one', 'three']) } + it { is_expected.to run.with_params(%w[two two], 'two').and_return([]) } + it { is_expected.to run.with_params(%w[one two three], '^t.*').and_return(['one']) } + it { is_expected.to run.with_params(%w[ab b c b], 'b').and_return(%w[ab c]) } + it { is_expected.to run.with_params(%w[one two three], 'four').and_return(%w[one two three]) } + it { is_expected.to run.with_params(%w[one two three], 'e').and_return(%w[one two three]) } + it { is_expected.to run.with_params(%w[one two three], 'two').and_return(%w[one three]) } + it { is_expected.to run.with_params(%w[two one two three two], 'two').and_return(%w[one three]) } it { is_expected.to run.with_params(['abracadabra'], 'abr').and_return(['abracadabra']) } it { is_expected.to run.with_params(['abracadabra'], '^.*jimbob.*$').and_return(['abracadabra']) } end @@ -28,27 +28,29 @@ describe 'deleting from an array' do it { is_expected.to run.with_params({}, '').and_return({}) } it { is_expected.to run.with_params({}, 'key').and_return({}) } - it { is_expected.to run.with_params({'key' => 'value'}, 'key').and_return({}) } - it { is_expected.to run \ - .with_params({'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3'}, 'key2') \ - .and_return( {'key1' => 'value1', 'key3' => 'value3'}) + it { is_expected.to run.with_params({ 'key' => 'value' }, 'key').and_return({}) } + it { + is_expected.to run \ + .with_params({ 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3' }, 'key2') \ + .and_return('key1' => 'value1', 'key3' => 'value3') } - it { is_expected.to run \ - .with_params({'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3'}, ['key1', 'key2']) \ - .and_return( {'key3' => 'value3'}) + it { + is_expected.to run \ + .with_params({ 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3' }, %w[key1 key2]) \ + .and_return('key3' => 'value3') } end - it "should leave the original array intact" do - argument1 = ['one','two','three'] + it 'leaves the original array intact' do + argument1 = %w[one two three] original1 = argument1.dup - subject.call([argument1,'two']) + subject.call([argument1, 'two']) expect(argument1).to eq(original1) end - it "should leave the original hash intact" do - argument1 = {'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3'} + it 'leaves the original hash intact' do + argument1 = { 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3' } original1 = argument1.dup - subject.call([argument1,'key2']) + subject.call([argument1, 'key2']) expect(argument1).to eq(original1) end end diff --git a/spec/functions/delete_spec.rb b/spec/functions/delete_spec.rb index 4e37865ae..fa2f1b8ef 100755 --- a/spec/functions/delete_spec.rb +++ b/spec/functions/delete_spec.rb @@ -2,7 +2,7 @@ describe 'delete' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params([]).and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params([], 'two') } it { is_expected.to run.with_params([], 'two', 'three').and_raise_error(Puppet::ParseError) } @@ -12,14 +12,14 @@ it { is_expected.to run.with_params([], '').and_return([]) } it { is_expected.to run.with_params([], 'two').and_return([]) } it { is_expected.to run.with_params(['two'], 'two').and_return([]) } - it { is_expected.to run.with_params(['two', 'two'], 'two').and_return([]) } - it { is_expected.to run.with_params(['ab', 'b', 'c', 'b'], 'b').and_return(['ab', 'c']) } - it { is_expected.to run.with_params(['one', 'two', 'three'], 'four').and_return(['one', 'two', 'three']) } - it { is_expected.to run.with_params(['one', 'two', 'three'], 'e').and_return(['one', 'two', 'three']) } - it { is_expected.to run.with_params(['one', 'two', 'three'], 'two').and_return(['one', 'three']) } - it { is_expected.to run.with_params(['two', 'one', 'two', 'three', 'two'], 'two').and_return(['one', 'three']) } - it { is_expected.to run.with_params(['one', 'two', 'three', 'two'], ['one', 'two']).and_return(['three']) } - it { is_expected.to run.with_params(['ồאּẻ', 'ŧẅơ', 'ŧңŗё℮', 'ŧẅơ'], ['ồאּẻ', 'ŧẅơ']).and_return(['ŧңŗё℮']) } + it { is_expected.to run.with_params(%w[two two], 'two').and_return([]) } + it { is_expected.to run.with_params(%w[ab b c b], 'b').and_return(%w[ab c]) } + it { is_expected.to run.with_params(%w[one two three], 'four').and_return(%w[one two three]) } + it { is_expected.to run.with_params(%w[one two three], 'e').and_return(%w[one two three]) } + it { is_expected.to run.with_params(%w[one two three], 'two').and_return(%w[one three]) } + it { is_expected.to run.with_params(%w[two one two three two], 'two').and_return(%w[one three]) } + it { is_expected.to run.with_params(%w[one two three two], %w[one two]).and_return(['three']) } + it { is_expected.to run.with_params(['ồאּẻ', 'ŧẅơ', 'ŧңŗё℮', 'ŧẅơ'], %w[ồאּẻ ŧẅơ]).and_return(['ŧңŗё℮']) } end describe 'deleting from a string' do @@ -30,47 +30,50 @@ it { is_expected.to run.with_params('barbar', 'bar').and_return('') } it { is_expected.to run.with_params('barfoobar', 'bar').and_return('foo') } it { is_expected.to run.with_params('foobarbabarz', 'bar').and_return('foobaz') } - it { is_expected.to run.with_params('foobarbabarz', ['foo', 'bar']).and_return('baz') } - it { is_expected.to run.with_params('ƒōōβậяβậβậяź', ['ƒōō', 'βậя']).and_return('βậź') } + it { is_expected.to run.with_params('foobarbabarz', %w[foo bar]).and_return('baz') } + it { is_expected.to run.with_params('ƒōōβậяβậβậяź', %w[ƒōō βậя]).and_return('βậź') } - it { is_expected.to run.with_params('barfoobar', ['barbar', 'foo']).and_return('barbar') } - it { is_expected.to run.with_params('barfoobar', ['foo', 'barbar']).and_return('') } + it { is_expected.to run.with_params('barfoobar', %w[barbar foo]).and_return('barbar') } + it { is_expected.to run.with_params('barfoobar', %w[foo barbar]).and_return('') } end describe 'deleting from an array' do it { is_expected.to run.with_params({}, '').and_return({}) } it { is_expected.to run.with_params({}, 'key').and_return({}) } - it { is_expected.to run.with_params({'key' => 'value'}, 'key').and_return({}) } - it { is_expected.to run \ - .with_params({'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3'}, 'key2') \ - .and_return( {'key1' => 'value1', 'key3' => 'value3'}) + it { is_expected.to run.with_params({ 'key' => 'value' }, 'key').and_return({}) } + it { + is_expected.to run \ + .with_params({ 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3' }, 'key2') \ + .and_return('key1' => 'value1', 'key3' => 'value3') } - it { is_expected.to run \ - .with_params({'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3'}, ['key1', 'key2']) \ - .and_return( {'key3' => 'value3'}) + it { + is_expected.to run \ + .with_params({ 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3' }, %w[key1 key2]) \ + .and_return('key3' => 'value3') } - it { is_expected.to run \ - .with_params({'ĸəұ1' => 'νãŀủĕ1', 'ĸəұ2' => 'νãŀủĕ2', 'ĸəұ3' => 'νãŀủĕ3'}, ['ĸəұ1', 'ĸəұ2']) \ - .and_return( {'ĸəұ3' => 'νãŀủĕ3'}) + it { + is_expected.to run \ + .with_params({ 'ĸəұ1' => 'νãŀủĕ1', 'ĸəұ2' => 'νãŀủĕ2', 'ĸəұ3' => 'νãŀủĕ3' }, %w[ĸəұ1 ĸəұ2]) \ + .and_return('ĸəұ3' => 'νãŀủĕ3') } end - it "should leave the original array intact" do - argument1 = ['one','two','three'] + it 'leaves the original array intact' do + argument1 = %w[one two three] original1 = argument1.dup - result = subject.call([argument1,'two']) + _result = subject.call([argument1, 'two']) expect(argument1).to eq(original1) end - it "should leave the original string intact" do + it 'leaves the original string intact' do argument1 = 'onetwothree' original1 = argument1.dup - result = subject.call([argument1,'two']) + _result = subject.call([argument1, 'two']) expect(argument1).to eq(original1) end - it "should leave the original hash intact" do - argument1 = {'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3'} + it 'leaves the original hash intact' do + argument1 = { 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3' } original1 = argument1.dup - result = subject.call([argument1,'key2']) + _result = subject.call([argument1, 'key2']) expect(argument1).to eq(original1) end end diff --git a/spec/functions/delete_undef_values_spec.rb b/spec/functions/delete_undef_values_spec.rb index c20cee271..2a282f5c8 100755 --- a/spec/functions/delete_undef_values_spec.rb +++ b/spec/functions/delete_undef_values_spec.rb @@ -2,27 +2,27 @@ describe 'delete_undef_values' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params('one').and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params('one', 'two').and_raise_error(Puppet::ParseError) } describe 'when deleting from an array' do - [ :undef, '', nil ].each do |undef_value| + [:undef, '', nil].each do |undef_value| describe "when undef is represented by #{undef_value.inspect}" do - before do + before(:each) do pending("review behaviour when being passed undef as #{undef_value.inspect}") if undef_value == '' - pending("review behaviour when being passed undef as #{undef_value.inspect}") if undef_value == nil + pending("review behaviour when being passed undef as #{undef_value.inspect}") if undef_value.nil? end it { is_expected.to run.with_params([undef_value]).and_return([]) } - it { is_expected.to run.with_params(['one',undef_value,'two','three']).and_return(['one','two','three']) } - it { is_expected.to run.with_params(['ớņέ',undef_value,'ŧשּׁō','ŧħґëə']).and_return(['ớņέ','ŧשּׁō','ŧħґëə']) } + it { is_expected.to run.with_params(['one', undef_value, 'two', 'three']).and_return(%w[one two three]) } + it { is_expected.to run.with_params(['ớņέ', undef_value, 'ŧשּׁō', 'ŧħґëə']).and_return(%w[ớņέ ŧשּׁō ŧħґëə]) } end - it "should leave the original argument intact" do - argument = ['one',undef_value,'two'] + it 'leaves the original argument intact' do + argument = ['one', undef_value, 'two'] original = argument.dup - result = subject.call([argument,2]) + _result = subject.call([argument, 2]) expect(argument).to eq(original) end end @@ -31,27 +31,28 @@ end describe 'when deleting from a hash' do - [ :undef, '', nil ].each do |undef_value| + [:undef, '', nil].each do |undef_value| describe "when undef is represented by #{undef_value.inspect}" do - before do + before(:each) do pending("review behaviour when being passed undef as #{undef_value.inspect}") if undef_value == '' - pending("review behaviour when being passed undef as #{undef_value.inspect}") if undef_value == nil + pending("review behaviour when being passed undef as #{undef_value.inspect}") if undef_value.nil? end - it { is_expected.to run.with_params({'key' => undef_value}).and_return({}) } - it { is_expected.to run \ - .with_params({'key1' => 'value1', 'undef_key' => undef_value, 'key2' => 'value2'}) \ - .and_return({'key1' => 'value1', 'key2' => 'value2'}) + it { is_expected.to run.with_params('key' => undef_value).and_return({}) } + it { + is_expected.to run \ + .with_params('key1' => 'value1', 'undef_key' => undef_value, 'key2' => 'value2') \ + .and_return('key1' => 'value1', 'key2' => 'value2') } end - it "should leave the original argument intact" do + it 'leaves the original argument intact' do argument = { 'key1' => 'value1', 'key2' => undef_value } original = argument.dup - result = subject.call([argument,2]) + _result = subject.call([argument, 2]) expect(argument).to eq(original) end end - it { is_expected.to run.with_params({'key' => 'undef'}).and_return({'key' => 'undef'}) } + it { is_expected.to run.with_params('key' => 'undef').and_return('key' => 'undef') } end end diff --git a/spec/functions/delete_values_spec.rb b/spec/functions/delete_values_spec.rb index 329fa0be2..20f26489c 100755 --- a/spec/functions/delete_values_spec.rb +++ b/spec/functions/delete_values_spec.rb @@ -2,7 +2,7 @@ describe 'delete_values' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params('one').and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params('one', 'two', 'three').and_raise_error(Puppet::ParseError) } @@ -14,28 +14,32 @@ describe 'when deleting from a hash' do it { is_expected.to run.with_params({}, 'value').and_return({}) } - it { is_expected.to run \ - .with_params({'key1' => 'value1'}, 'non-existing value') \ - .and_return({'key1' => 'value1'}) + it { + is_expected.to run \ + .with_params({ 'key1' => 'value1' }, 'non-existing value') \ + .and_return('key1' => 'value1') } - it { is_expected.to run \ - .with_params({'ҝếỵ1 ' => 'νâĺūẹ1', 'ҝếỵ2' => 'value to delete'}, 'value to delete') \ - .and_return({'ҝếỵ1 ' => 'νâĺūẹ1'}) + it { + is_expected.to run \ + .with_params({ 'ҝếỵ1 ' => 'νâĺūẹ1', 'ҝếỵ2' => 'value to delete' }, 'value to delete') \ + .and_return('ҝếỵ1 ' => 'νâĺūẹ1') } - it { is_expected.to run \ - .with_params({'key1' => 'value1', 'key2' => 'νǎŀữ℮ ťớ đêłểťė'}, 'νǎŀữ℮ ťớ đêłểťė') \ - .and_return({'key1' => 'value1'}) + it { + is_expected.to run \ + .with_params({ 'key1' => 'value1', 'key2' => 'νǎŀữ℮ ťớ đêłểťė' }, 'νǎŀữ℮ ťớ đêłểťė') \ + .and_return('key1' => 'value1') } - it { is_expected.to run \ - .with_params({'key1' => 'value1', 'key2' => 'value to delete', 'key3' => 'value to delete'}, 'value to delete') \ - .and_return({'key1' => 'value1'}) + it { + is_expected.to run \ + .with_params({ 'key1' => 'value1', 'key2' => 'value to delete', 'key3' => 'value to delete' }, 'value to delete') \ + .and_return('key1' => 'value1') } end - it "should leave the original argument intact" do + it 'leaves the original argument intact' do argument = { 'key1' => 'value1', 'key2' => 'value2' } original = argument.dup - result = subject.call([argument, 'value2']) + _result = subject.call([argument, 'value2']) expect(argument).to eq(original) end end diff --git a/spec/functions/deprecation_spec.rb b/spec/functions/deprecation_spec.rb index bde4e89cc..8410867e8 100644 --- a/spec/functions/deprecation_spec.rb +++ b/spec/functions/deprecation_spec.rb @@ -2,57 +2,60 @@ if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'deprecation' do - before(:each) { + before(:each) do # this is to reset the strict variable to default Puppet.settings[:strict] = :warning - } + end it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(ArgumentError) } + it { is_expected.to run.with_params.and_raise_error(ArgumentError) } - it 'should display a single warning' do + it 'displays a single warning' do Puppet.expects(:warning).with(includes('heelo')) is_expected.to run.with_params('key', 'heelo') end - it 'should display a single warning, despite multiple calls' do + it 'displays a single warning, despite multiple calls' do Puppet.expects(:warning).with(includes('heelo')).once - is_expected.to run.with_params('key', 'heelo') - is_expected.to run.with_params('key', 'heelo') + (0..1).each do |_i| + is_expected.to run.with_params('key', 'heelo') + end end - it 'should fail twice with message, with multiple calls. when strict= :error' do + it 'fails twice with message, with multiple calls. when strict= :error' do Puppet.settings[:strict] = :error Puppet.expects(:warning).with(includes('heelo')).never - is_expected.to run.with_params('key', 'heelo').and_raise_error(RuntimeError, /deprecation. key. heelo/) - is_expected.to run.with_params('key', 'heelo').and_raise_error(RuntimeError, /deprecation. key. heelo/) + (0..1).each do |_i| + is_expected.to run.with_params('key', 'heelo').and_raise_error(RuntimeError, %r{deprecation. key. heelo}) + end end - it 'should display nothing, despite multiple calls. strict= :off' do + it 'displays nothing, despite multiple calls. strict= :off' do Puppet.settings[:strict] = :off Puppet.expects(:warning).with(includes('heelo')).never - is_expected.to run.with_params('key', 'heelo') - is_expected.to run.with_params('key', 'heelo') + (0..1).each do |_i| + is_expected.to run.with_params('key', 'heelo') + end end - after(:all) { + after(:each) do # this is to reset the strict variable to default Puppet.settings[:strict] = :warning - } + end end elsif Puppet.version.to_f < 4.0 # Puppet version < 4 will use these tests. describe 'deprecation' do - after(:all) do + after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end - before(:all) do - ENV['STDLIB_LOG_DEPRECATIONS'] = "true" + before(:each) do + ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' end it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } - it 'should display a single warning' do + it 'displays a single warning' do scope.expects(:warning).with(includes('heelo')) is_expected.to run.with_params('key', 'heelo') end diff --git a/spec/functions/difference_spec.rb b/spec/functions/difference_spec.rb index 0ae3689bd..d8c676587 100755 --- a/spec/functions/difference_spec.rb +++ b/spec/functions/difference_spec.rb @@ -2,7 +2,7 @@ describe 'difference' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params('one').and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params('one', 'two').and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params('one', 'two', 'three').and_raise_error(Puppet::ParseError) } @@ -14,10 +14,10 @@ it { is_expected.to run.with_params(['one'], ['one']).and_return([]) } it { is_expected.to run.with_params(['ớņέ'], ['']).and_return(['ớņέ']) } it { is_expected.to run.with_params(['one'], []).and_return(['one']) } - it { is_expected.to run.with_params(['one', 'two', 'three'], ['two', 'three']).and_return(['one']) } - it { is_expected.to run.with_params(['ớņέ', 'ŧשּׁō', 'ŧħґëə', 2], ['ŧשּׁō', 'ŧħґëə']).and_return(['ớņέ', 2]) } - it { is_expected.to run.with_params(['one', 'two', 'two', 'three'], ['two', 'three']).and_return(['one']) } - it { is_expected.to run.with_params(['one', 'two', 'three'], ['two', 'two', 'three']).and_return(['one']) } - it { is_expected.to run.with_params(['one', 'two', 'three'], ['two', 'three', 'four']).and_return(['one']) } - it 'should not confuse types' do is_expected.to run.with_params(['1', '2', '3'], [1, 2]).and_return(['1', '2', '3']) end + it { is_expected.to run.with_params(%w[one two three], %w[two three]).and_return(['one']) } + it { is_expected.to run.with_params(['ớņέ', 'ŧשּׁō', 'ŧħґëə', 2], %w[ŧשּׁō ŧħґëə]).and_return(['ớņέ', 2]) } + it { is_expected.to run.with_params(%w[one two two three], %w[two three]).and_return(['one']) } + it { is_expected.to run.with_params(%w[one two three], %w[two two three]).and_return(['one']) } + it { is_expected.to run.with_params(%w[one two three], %w[two three four]).and_return(['one']) } + it 'does not confuse types' do is_expected.to run.with_params(%w[1 2 3], [1, 2]).and_return(%w[1 2 3]) end end diff --git a/spec/functions/dig44_spec.rb b/spec/functions/dig44_spec.rb index a7b8a3d4c..48236b642 100644 --- a/spec/functions/dig44_spec.rb +++ b/spec/functions/dig44_spec.rb @@ -1,130 +1,127 @@ require 'spec_helper' describe 'dig44' do - let(:data) do { - 'a' => { - 'g' => '2', - 'e' => [ - 'f0', - 'f1', - { - 'x' => { - 'y' => 'z' - } - }, - 'f3', - ] - }, - 'b' => true, - 'c' => false, - 'd' => '1', - 'e' => :undef, - 'f' => nil, + 'a' => { + 'g' => '2', + 'e' => [ + 'f0', + 'f1', + { + 'x' => { + 'y' => 'z', + }, + }, + 'f3', + ], + }, + 'b' => true, + 'c' => false, + 'd' => '1', + 'e' => :undef, + 'f' => nil, } end let(:utf8_data) do { - 'ẵ' => { - 'в' => [ - '©', - 'ĝ', - 'に', - ] - } + 'ẵ' => { + 'в' => [ + '©', + 'ĝ', + 'に', + ], + }, } end context 'single values' do - it 'should exist' do + it 'exists' do is_expected.not_to be_nil end - it 'should require two arguments' do - is_expected.to run.with_params().and_raise_error(ArgumentError) + it 'requires two arguments' do + is_expected.to run.with_params.and_raise_error(ArgumentError) end - it 'should fail if the data is not a structure' do + it 'fails if the data is not a structure' do is_expected.to run.with_params('test', []).and_raise_error(Puppet::Error) end - it 'should fail if the path is not an array' do + it 'fails if the path is not an array' do is_expected.to run.with_params({}, '').and_raise_error(Puppet::Error) end - it 'should return the value if the value is string' do + it 'returns the value if the value is string' do is_expected.to run.with_params(data, ['d'], 'default').and_return('1') end - it 'should return true if the value is true' do + it 'returns true if the value is true' do is_expected.to run.with_params(data, ['b'], 'default').and_return(true) end - it 'should return false if the value is false' do + it 'returns false if the value is false' do is_expected.to run.with_params(data, ['c'], 'default').and_return(false) end - it 'should return the default if the value is nil' do + it 'returns the default if the value is nil' do is_expected.to run.with_params(data, ['f'], 'default').and_return('default') end - it 'should return the default if the value is :undef (same as nil)' do + it 'returns the default if the value is :undef (same as nil)' do is_expected.to run.with_params(data, ['e'], 'default').and_return('default') end - it 'should return the default if the path is not found' do + it 'returns the default if the path is not found' do is_expected.to run.with_params(data, ['missing'], 'default').and_return('default') end end context 'structure values' do - - it 'should be able to extract a deeply nested hash value' do - is_expected.to run.with_params(data, %w(a g), 'default').and_return('2') + it 'is able to extract a deeply nested hash value' do + is_expected.to run.with_params(data, %w[a g], 'default').and_return('2') end - it 'should return the default value if the path is too long' do - is_expected.to run.with_params(data, %w(a g c d), 'default').and_return('default') + it 'returns the default value if the path is too long' do + is_expected.to run.with_params(data, %w[a g c d], 'default').and_return('default') end - it 'should support an array index (number) in the path' do + it 'supports an array index (number) in the path' do is_expected.to run.with_params(data, ['a', 'e', 1], 'default').and_return('f1') end - it 'should support an array index (string) in the path' do - is_expected.to run.with_params(data, %w(a e 1), 'default').and_return('f1') + it 'supports an array index (string) in the path' do + is_expected.to run.with_params(data, %w[a e 1], 'default').and_return('f1') end - it 'should return the default value if an array index is not a number' do - is_expected.to run.with_params(data, %w(a b c), 'default').and_return('default') + it 'returns the default value if an array index is not a number' do + is_expected.to run.with_params(data, %w[a b c], 'default').and_return('default') end - it 'should return the default value if and index is out of array length' do - is_expected.to run.with_params(data, %w(a e 5), 'default').and_return('default') + it 'returns the default value if and index is out of array length' do + is_expected.to run.with_params(data, %w[a e 5], 'default').and_return('default') end - it 'should be able to path though both arrays and hashes' do - is_expected.to run.with_params(data, %w(a e 2 x y), 'default').and_return('z') + it 'is able to path though both arrays and hashes' do + is_expected.to run.with_params(data, %w[a e 2 x y], 'default').and_return('z') end - it 'should return "nil" if value is not found and no default value is provided' do - is_expected.to run.with_params(data, %w(a 1)).and_return(nil) + it 'returns "nil" if value is not found and no default value is provided' do + is_expected.to run.with_params(data, %w[a 1]).and_return(nil) end end context 'Internationalization (i18N) values' do - - it 'should be able to return a unicode character' do + it 'is able to return a unicode character' do is_expected.to run.with_params(utf8_data, ['ẵ', 'в', 0]).and_return('©') end - it 'should be able to return a utf8 character' do + it 'is able to return a utf8 character' do is_expected.to run.with_params(utf8_data, ['ẵ', 'в', 1]).and_return('ĝ') end - it 'should be able to return a double byte character' do + it 'is able to return a double byte character' do is_expected.to run.with_params(utf8_data, ['ẵ', 'в', 2]).and_return('に') end end diff --git a/spec/functions/dig_spec.rb b/spec/functions/dig_spec.rb index ad16fdd43..af5ec512c 100644 --- a/spec/functions/dig_spec.rb +++ b/spec/functions/dig_spec.rb @@ -1,13 +1,12 @@ require 'spec_helper' describe 'dig' do - - it "should exist" do - expect(Puppet::Parser::Functions.function("dig")).to eq("function_dig") + it 'exists' do + expect(Puppet::Parser::Functions.function('dig')).to eq('function_dig') end - it "should give a deprecation warning when called" do - scope.expects(:warning).with("dig() DEPRECATED: This function has been replaced in Puppet 4.5.0, please use dig44() for backwards compatibility or use the new version.") + it 'gives a deprecation warning when called' do + scope.expects(:warning).with('dig() DEPRECATED: This function has been replaced in Puppet 4.5.0, please use dig44() for backwards compatibility or use the new version.') scope.function_dig([{}, []]) end end diff --git a/spec/functions/dirname_spec.rb b/spec/functions/dirname_spec.rb index c494915ed..8c410cc90 100755 --- a/spec/functions/dirname_spec.rb +++ b/spec/functions/dirname_spec.rb @@ -2,7 +2,7 @@ describe 'dirname' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params('one', 'two').and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params([]).and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError) } diff --git a/spec/functions/dos2unix_spec.rb b/spec/functions/dos2unix_spec.rb index 97abae7e3..cba0bc61b 100644 --- a/spec/functions/dos2unix_spec.rb +++ b/spec/functions/dos2unix_spec.rb @@ -4,10 +4,10 @@ context 'Checking parameter validity' do it { is_expected.not_to eq(nil) } it do - is_expected.to run.with_params.and_raise_error(ArgumentError, /Wrong number of arguments/) + is_expected.to run.with_params.and_raise_error(ArgumentError, %r{Wrong number of arguments}) end it do - is_expected.to run.with_params('one', 'two').and_raise_error(ArgumentError, /Wrong number of arguments/) + is_expected.to run.with_params('one', 'two').and_raise_error(ArgumentError, %r{Wrong number of arguments}) end it do is_expected.to run.with_params([]).and_raise_error(Puppet::ParseError) @@ -24,8 +24,8 @@ sample_text = "Hello\r\nWorld\r\n" desired_output = "Hello\nWorld\n" - it 'should output unix format' do - should run.with_params(sample_text).and_return(desired_output) + it 'outputs unix format' do + is_expected.to run.with_params(sample_text).and_return(desired_output) end end @@ -36,12 +36,12 @@ sample_text_doublebyte = "こんにちは\r\n世界\r\n" desired_output_doublebyte = "こんにちは\n世界\n" - it 'should output uft8 string' do - should run.with_params(sample_text_utf8).and_return(desired_output_utf8) + it 'outputs uft8 string' do + is_expected.to run.with_params(sample_text_utf8).and_return(desired_output_utf8) end - it 'should output double byte string' do - should run.with_params(sample_text_doublebyte).and_return(desired_output_doublebyte) + it 'outputs double byte string' do + is_expected.to run.with_params(sample_text_doublebyte).and_return(desired_output_doublebyte) end end end diff --git a/spec/functions/downcase_spec.rb b/spec/functions/downcase_spec.rb index c594560a0..d49e16934 100755 --- a/spec/functions/downcase_spec.rb +++ b/spec/functions/downcase_spec.rb @@ -2,14 +2,14 @@ describe 'downcase' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params(100).and_raise_error(Puppet::ParseError) } - it { is_expected.to run.with_params("abc").and_return("abc") } - it { is_expected.to run.with_params("Abc").and_return("abc") } - it { is_expected.to run.with_params("ABC").and_return("abc") } + it { is_expected.to run.with_params('abc').and_return('abc') } + it { is_expected.to run.with_params('Abc').and_return('abc') } + it { is_expected.to run.with_params('ABC').and_return('abc') } - it { is_expected.to run.with_params(AlsoString.new("ABC")).and_return("abc") } + it { is_expected.to run.with_params(AlsoString.new('ABC')).and_return('abc') } it { is_expected.to run.with_params([]).and_return([]) } - it { is_expected.to run.with_params(["ONE", "TWO"]).and_return(["one", "two"]) } - it { is_expected.to run.with_params(["One", 1, "Two"]).and_return(["one", 1, "two"]) } + it { is_expected.to run.with_params(%w[ONE TWO]).and_return(%w[one two]) } + it { is_expected.to run.with_params(['One', 1, 'Two']).and_return(['one', 1, 'two']) } end diff --git a/spec/functions/empty_spec.rb b/spec/functions/empty_spec.rb index a3a25d6a0..dbe038b34 100755 --- a/spec/functions/empty_spec.rb +++ b/spec/functions/empty_spec.rb @@ -2,9 +2,9 @@ describe 'empty' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError) } it { - pending("Current implementation ignores parameters after the first.") + pending('Current implementation ignores parameters after the first.') is_expected.to run.with_params('one', 'two').and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params(0).and_return(false) } @@ -18,5 +18,5 @@ it { is_expected.to run.with_params(['one']).and_return(false) } it { is_expected.to run.with_params({}).and_return(true) } - it { is_expected.to run.with_params({'key' => 'value'}).and_return(false) } + it { is_expected.to run.with_params('key' => 'value').and_return(false) } end diff --git a/spec/functions/ensure_packages_spec.rb b/spec/functions/ensure_packages_spec.rb index 190e58022..0428008b0 100755 --- a/spec/functions/ensure_packages_spec.rb +++ b/spec/functions/ensure_packages_spec.rb @@ -2,35 +2,35 @@ describe 'ensure_packages' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError) } it { - pending("should not accept numbers as arguments") + pending('should not accept numbers as arguments') is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError) } it { - pending("should not accept numbers as arguments") - is_expected.to run.with_params(["packagename", 1]).and_raise_error(Puppet::ParseError) + pending('should not accept numbers as arguments') + is_expected.to run.with_params(['packagename', 1]).and_raise_error(Puppet::ParseError) } - it { is_expected.to run.with_params("packagename") } - it { is_expected.to run.with_params(["packagename1", "packagename2"]) } + it { is_expected.to run.with_params('packagename') } + it { is_expected.to run.with_params(%w[packagename1 packagename2]) } context 'given a catalog with "package { puppet: ensure => absent }"' do let(:pre_condition) { 'package { puppet: ensure => absent }' } describe 'after running ensure_package("facter")' do - before { subject.call(['facter']) } + before(:each) { subject.call(['facter']) } # this lambda is required due to strangeness within rspec-puppet's expectation handling - it { expect(lambda { catalogue }).to contain_package('puppet').with_ensure('absent') } - it { expect(lambda { catalogue }).to contain_package('facter').with_ensure('present') } + it { expect(-> { catalogue }).to contain_package('puppet').with_ensure('absent') } + it { expect(-> { catalogue }).to contain_package('facter').with_ensure('present') } end describe 'after running ensure_package("facter", { "provider" => "gem" })' do - before { subject.call(['facter', { "provider" => "gem" }]) } + before(:each) { subject.call(['facter', { 'provider' => 'gem' }]) } # this lambda is required due to strangeness within rspec-puppet's expectation handling - it { expect(lambda { catalogue }).to contain_package('puppet').with_ensure('absent').without_provider() } - it { expect(lambda { catalogue }).to contain_package('facter').with_ensure('present').with_provider("gem") } + it { expect(-> { catalogue }).to contain_package('puppet').with_ensure('absent').without_provider } + it { expect(-> { catalogue }).to contain_package('facter').with_ensure('present').with_provider('gem') } end end @@ -38,22 +38,24 @@ let(:pre_condition) { 'notify { "hi": } -> Package <| |>; $somearray = ["vim",""]; ensure_packages($somearray)' } describe 'after running ensure_package(["vim", ""])' do - it { expect { catalogue }.to raise_error(Puppet::ParseError, /Empty String provided/) } + it { expect { catalogue }.to raise_error(Puppet::ParseError, %r{Empty String provided}) } end end context 'given hash of packages' do - before { subject.call([{"foo" => { "provider" => "rpm" }, "bar" => { "provider" => "gem" }}, { "ensure" => "present"}]) } - before { subject.call([{"パッケージ" => { "ensure" => "absent"}}]) } - before { subject.call([{"ρǻ¢κầģẻ" => { "ensure" => "absent"}}]) } + before(:each) do + subject.call([{ 'foo' => { 'provider' => 'rpm' }, 'bar' => { 'provider' => 'gem' } }, { 'ensure' => 'present' }]) + subject.call([{ 'パッケージ' => { 'ensure' => 'absent' } }]) + subject.call([{ 'ρǻ¢κầģẻ' => { 'ensure' => 'absent' } }]) + end # this lambda is required due to strangeness within rspec-puppet's expectation handling - it { expect(lambda { catalogue }).to contain_package('foo').with({'provider' => 'rpm', 'ensure' => 'present'}) } - it { expect(lambda { catalogue }).to contain_package('bar').with({'provider' => 'gem', 'ensure' => 'present'}) } + it { expect(-> { catalogue }).to contain_package('foo').with('provider' => 'rpm', 'ensure' => 'present') } + it { expect(-> { catalogue }).to contain_package('bar').with('provider' => 'gem', 'ensure' => 'present') } context 'should run with UTF8 and double byte characters' do - it { expect(lambda { catalogue }).to contain_package('パッケージ').with({'ensure' => 'absent'}) } - it { expect(lambda { catalogue }).to contain_package('ρǻ¢κầģẻ').with({'ensure' => 'absent'}) } + it { expect(-> { catalogue }).to contain_package('パッケージ').with('ensure' => 'absent') } + it { expect(-> { catalogue }).to contain_package('ρǻ¢κầģẻ').with('ensure' => 'absent') } end end @@ -61,11 +63,10 @@ let(:pre_condition) { 'package { puppet: ensure => present }' } describe 'after running ensure_package("puppet", { "ensure" => "installed" })' do - before { subject.call(['puppet', { "ensure" => "installed" }]) } + before(:each) { subject.call(['puppet', { 'ensure' => 'installed' }]) } # this lambda is required due to strangeness within rspec-puppet's expectation handling - it { expect(lambda { catalogue }).to contain_package('puppet').with_ensure('present') } + it { expect(-> { catalogue }).to contain_package('puppet').with_ensure('present') } end end - end diff --git a/spec/functions/ensure_resource_spec.rb b/spec/functions/ensure_resource_spec.rb index c847bf76b..aa2e1a2d9 100755 --- a/spec/functions/ensure_resource_spec.rb +++ b/spec/functions/ensure_resource_spec.rb @@ -2,8 +2,8 @@ describe 'ensure_resource' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(ArgumentError, /Must specify a type/) } - it { is_expected.to run.with_params('type').and_raise_error(ArgumentError, /Must specify a title/) } + it { is_expected.to run.with_params.and_raise_error(ArgumentError, %r{Must specify a type}) } + it { is_expected.to run.with_params('type').and_raise_error(ArgumentError, %r{Must specify a title}) } if Puppet::Util::Package.versioncmp(Puppet.version, '4.6.0') >= 0 it { is_expected.to run.with_params('type', 'title', {}, 'extras').and_raise_error(ArgumentError) } else @@ -11,64 +11,64 @@ end it { - pending("should not accept numbers as arguments") - is_expected.to run.with_params(1,2,3).and_raise_error(Puppet::ParseError) + pending('should not accept numbers as arguments') + is_expected.to run.with_params(1, 2, 3).and_raise_error(Puppet::ParseError) } context 'given an empty catalog' do describe 'after running ensure_resource("user", "username1", {})' do - before { subject.call(['User', 'username1', {}]) } + before(:each) { subject.call(['User', 'username1', {}]) } # this lambda is required due to strangeness within rspec-puppet's expectation handling - it { expect(lambda { catalogue }).to contain_user('username1').without_ensure } + it { expect(-> { catalogue }).to contain_user('username1').without_ensure } end describe 'after running ensure_resource("user", "username1", { gid => undef })' do - before { subject.call(['User', 'username1', { 'gid' => :undef }]) } + before(:each) { subject.call(['User', 'username1', { 'gid' => :undef }]) } # this lambda is required due to strangeness within rspec-puppet's expectation handling - it { expect(lambda { catalogue }).to contain_user('username1').without_ensure } - it { expect(lambda { catalogue }).to contain_user('username1').without_gid } + it { expect(-> { catalogue }).to contain_user('username1').without_ensure } + it { expect(-> { catalogue }).to contain_user('username1').without_gid } end describe 'after running ensure_resource("user", "username1", { ensure => present, gid => undef })' do - before { subject.call(['User', 'username1', { 'ensure' => 'present', 'gid' => :undef }]) } + before(:each) { subject.call(['User', 'username1', { 'ensure' => 'present', 'gid' => :undef }]) } # this lambda is required due to strangeness within rspec-puppet's expectation handling - it { expect(lambda { catalogue }).to contain_user('username1').with_ensure('present') } - it { expect(lambda { catalogue }).to contain_user('username1').without_gid } + it { expect(-> { catalogue }).to contain_user('username1').with_ensure('present') } + it { expect(-> { catalogue }).to contain_user('username1').without_gid } end describe 'after running ensure_resource("test::deftype", "foo", {})' do - before { subject.call(['test::deftype', 'foo', {}]) } + before(:each) { subject.call(['test::deftype', 'foo', {}]) } # this lambda is required due to strangeness within rspec-puppet's expectation handling - it { expect(lambda { catalogue }).to contain_test__deftype('foo').without_ensure } + it { expect(-> { catalogue }).to contain_test__deftype('foo').without_ensure } end end context 'given a catalog with UTF8 chars' do describe 'after running ensure_resource("user", "Şắოрŀễ Ţëם", {})' do - before { subject.call(['User', 'Şắოрŀễ Ţëם', {}]) } + before(:each) { subject.call(['User', 'Şắოрŀễ Ţëם', {}]) } # this lambda is required due to strangeness within rspec-puppet's expectation handling - it { expect(lambda { catalogue }).to contain_user('Şắოрŀễ Ţëם').without_ensure } + it { expect(-> { catalogue }).to contain_user('Şắოрŀễ Ţëם').without_ensure } end describe 'after running ensure_resource("user", "Şắოрŀễ Ţëם", { gid => undef })' do - before { subject.call(['User', 'Şắოрŀễ Ţëם', { 'gid' => :undef }]) } + before(:each) { subject.call(['User', 'Şắოрŀễ Ţëם', { 'gid' => :undef }]) } # this lambda is required due to strangeness within rspec-puppet's expectation handling - it { expect(lambda { catalogue }).to contain_user('Şắოрŀễ Ţëם').without_ensure } - it { expect(lambda { catalogue }).to contain_user('Şắოрŀễ Ţëם').without_gid } + it { expect(-> { catalogue }).to contain_user('Şắოрŀễ Ţëם').without_ensure } + it { expect(-> { catalogue }).to contain_user('Şắოрŀễ Ţëם').without_gid } end describe 'after running ensure_resource("user", "Şắოрŀễ Ţëם", { ensure => present, gid => undef })' do - before { subject.call(['User', 'Şắოрŀễ Ţëם', { 'ensure' => 'present', 'gid' => :undef }]) } + before(:each) { subject.call(['User', 'Şắოрŀễ Ţëם', { 'ensure' => 'present', 'gid' => :undef }]) } # this lambda is required due to strangeness within rspec-puppet's expectation handling - it { expect(lambda { catalogue }).to contain_user('Şắოрŀễ Ţëם').with_ensure('present') } - it { expect(lambda { catalogue }).to contain_user('Şắოрŀễ Ţëם').without_gid } + it { expect(-> { catalogue }).to contain_user('Şắოрŀễ Ţëם').with_ensure('present') } + it { expect(-> { catalogue }).to contain_user('Şắოрŀễ Ţëם').without_gid } end end @@ -76,48 +76,50 @@ let(:pre_condition) { 'user { username1: ensure => present }' } describe 'after running ensure_resource("user", "username1", {})' do - before { subject.call(['User', 'username1', {}]) } + before(:each) { subject.call(['User', 'username1', {}]) } # this lambda is required due to strangeness within rspec-puppet's expectation handling - it { expect(lambda { catalogue }).to contain_user('username1').with_ensure('present') } + it { expect(-> { catalogue }).to contain_user('username1').with_ensure('present') } end describe 'after running ensure_resource("user", "username2", {})' do - before { subject.call(['User', 'username2', {}]) } + before(:each) { subject.call(['User', 'username2', {}]) } # this lambda is required due to strangeness within rspec-puppet's expectation handling - it { expect(lambda { catalogue }).to contain_user('username1').with_ensure('present') } - it { expect(lambda { catalogue }).to contain_user('username2').without_ensure } + it { expect(-> { catalogue }).to contain_user('username1').with_ensure('present') } + it { expect(-> { catalogue }).to contain_user('username2').without_ensure } end describe 'after running ensure_resource("user", "username1", { gid => undef })' do - before { subject.call(['User', 'username1', { 'gid' => :undef }]) } + before(:each) { subject.call(['User', 'username1', { 'gid' => :undef }]) } # this lambda is required due to strangeness within rspec-puppet's expectation handling - it { expect(lambda { catalogue }).to contain_user('username1').with_ensure('present') } + it { expect(-> { catalogue }).to contain_user('username1').with_ensure('present') } end describe 'after running ensure_resource("user", ["username1", "username2"], {})' do - before { subject.call(['User', ['username1', 'username2'], {}]) } + before(:each) { subject.call(['User', %w[username1 username2], {}]) } # this lambda is required due to strangeness within rspec-puppet's expectation handling - it { expect(lambda { catalogue }).to contain_user('username1').with_ensure('present') } - it { expect(lambda { catalogue }).to contain_user('username2').without_ensure } + it { expect(-> { catalogue }).to contain_user('username1').with_ensure('present') } + it { expect(-> { catalogue }).to contain_user('username2').without_ensure } end describe 'when providing already set params' do let(:params) { { 'ensure' => 'present' } } - before { subject.call(['User', ['username2', 'username3'], params]) } + + before(:each) { subject.call(['User', %w[username2 username3], params]) } # this lambda is required due to strangeness within rspec-puppet's expectation handling - it { expect(lambda { catalogue }).to contain_user('username1').with(params) } - it { expect(lambda { catalogue }).to contain_user('username2').with(params) } + it { expect(-> { catalogue }).to contain_user('username1').with(params) } + it { expect(-> { catalogue }).to contain_user('username2').with(params) } end context 'when trying to add params' do - it { is_expected.to run \ - .with_params('User', 'username1', { 'ensure' => 'present', 'shell' => true }) \ - .and_raise_error(Puppet::Resource::Catalog::DuplicateResourceError, /User\[username1\] is already declared/) + it { + is_expected.to run \ + .with_params('User', 'username1', 'ensure' => 'present', 'shell' => true) \ + .and_raise_error(Puppet::Resource::Catalog::DuplicateResourceError, %r{User\[username1\] is already declared}) } end end @@ -126,10 +128,10 @@ let(:pre_condition) { 'test::deftype { "foo": }' } describe 'after running ensure_resource("test::deftype", "foo", {})' do - before { subject.call(['test::deftype', 'foo', {}]) } + before(:each) { subject.call(['test::deftype', 'foo', {}]) } # this lambda is required due to strangeness within rspec-puppet's expectation handling - it { expect(lambda { catalogue }).to contain_test__deftype('foo').without_ensure } + it { expect(-> { catalogue }).to contain_test__deftype('foo').without_ensure } end end end diff --git a/spec/functions/ensure_resources_spec.rb b/spec/functions/ensure_resources_spec.rb index 7cca67199..5ec0b20f1 100644 --- a/spec/functions/ensure_resources_spec.rb +++ b/spec/functions/ensure_resources_spec.rb @@ -2,24 +2,24 @@ describe 'ensure_resources' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(ArgumentError, /Must specify a type/) } - it { is_expected.to run.with_params('type').and_raise_error(ArgumentError, /Must specify a title/) } + it { is_expected.to run.with_params.and_raise_error(ArgumentError, %r{Must specify a type}) } + it { is_expected.to run.with_params('type').and_raise_error(ArgumentError, %r{Must specify a title}) } describe 'given a title hash of multiple resources' do - before { subject.call(['user', {'dan' => { 'gid' => 'mygroup', 'uid' => '600' }, 'alex' => { 'gid' => 'mygroup', 'uid' => '700'}}, {'ensure' => 'present'}]) } + before(:each) { subject.call(['user', { 'dan' => { 'gid' => 'mygroup', 'uid' => '600' }, 'alex' => { 'gid' => 'mygroup', 'uid' => '700' } }, { 'ensure' => 'present' }]) } # this lambda is required due to strangeness within rspec-puppet's expectation handling - it { expect(lambda { catalogue }).to contain_user('dan').with_ensure('present') } - it { expect(lambda { catalogue }).to contain_user('alex').with_ensure('present') } - it { expect(lambda { catalogue }).to contain_user('dan').with({ 'gid' => 'mygroup', 'uid' => '600'}) } - it { expect(lambda { catalogue }).to contain_user('alex').with({ 'gid' => 'mygroup', 'uid' => '700'}) } + it { expect(-> { catalogue }).to contain_user('dan').with_ensure('present') } + it { expect(-> { catalogue }).to contain_user('alex').with_ensure('present') } + it { expect(-> { catalogue }).to contain_user('dan').with('gid' => 'mygroup', 'uid' => '600') } + it { expect(-> { catalogue }).to contain_user('alex').with('gid' => 'mygroup', 'uid' => '700') } end describe 'given a title hash of a single resource' do - before { subject.call(['user', {'dan' => { 'gid' => 'mygroup', 'uid' => '600' }}, {'ensure' => 'present'}]) } + before(:each) { subject.call(['user', { 'dan' => { 'gid' => 'mygroup', 'uid' => '600' } }, { 'ensure' => 'present' }]) } # this lambda is required due to strangeness within rspec-puppet's expectation handling - it { expect(lambda { catalogue }).to contain_user('dan').with_ensure('present') } - it { expect(lambda { catalogue }).to contain_user('dan').with({ 'gid' => 'mygroup', 'uid' => '600'}) } + it { expect(-> { catalogue }).to contain_user('dan').with_ensure('present') } + it { expect(-> { catalogue }).to contain_user('dan').with('gid' => 'mygroup', 'uid' => '600') } end end diff --git a/spec/functions/flatten_spec.rb b/spec/functions/flatten_spec.rb index b80f3c5ad..ed30e015a 100755 --- a/spec/functions/flatten_spec.rb +++ b/spec/functions/flatten_spec.rb @@ -2,14 +2,14 @@ describe 'flatten' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params([], []).and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params('one').and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params([]).and_return([]) } it { is_expected.to run.with_params(['one']).and_return(['one']) } it { is_expected.to run.with_params([['one']]).and_return(['one']) } - it { is_expected.to run.with_params(["a","b","c","d","e","f","g"]).and_return(["a","b","c","d","e","f","g"]) } - it { is_expected.to run.with_params([["a","b",["c",["d","e"],"f","g"]]]).and_return(["a","b","c","d","e","f","g"]) } - it { is_expected.to run.with_params(["ã","β",["ĉ",["đ","ẽ","ƒ","ġ"]]]).and_return(["ã","β","ĉ","đ","ẽ","ƒ","ġ"]) } + it { is_expected.to run.with_params(%w[a b c d e f g]).and_return(%w[a b c d e f g]) } + it { is_expected.to run.with_params([['a', 'b', ['c', %w[d e], 'f', 'g']]]).and_return(%w[a b c d e f g]) } + it { is_expected.to run.with_params(['ã', 'β', ['ĉ', %w[đ ẽ ƒ ġ]]]).and_return(%w[ã β ĉ đ ẽ ƒ ġ]) } end diff --git a/spec/functions/floor_spec.rb b/spec/functions/floor_spec.rb index 608c602fa..c669966ed 100755 --- a/spec/functions/floor_spec.rb +++ b/spec/functions/floor_spec.rb @@ -2,8 +2,8 @@ describe 'floor' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError) } - it { is_expected.to run.with_params("foo").and_raise_error(Puppet::ParseError) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError) } + it { is_expected.to run.with_params('foo').and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params([]).and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params(34).and_return(34) } it { is_expected.to run.with_params(-34).and_return(-34) } diff --git a/spec/functions/fqdn_rand_string_spec.rb b/spec/functions/fqdn_rand_string_spec.rb index 861a59ecb..425fe9d44 100644 --- a/spec/functions/fqdn_rand_string_spec.rb +++ b/spec/functions/fqdn_rand_string_spec.rb @@ -2,47 +2,48 @@ describe 'fqdn_rand_string' do let(:default_charset) { %r{\A[a-zA-Z0-9]{100}\z} } + it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(ArgumentError, /wrong number of arguments/i) } - it { is_expected.to run.with_params(0).and_raise_error(ArgumentError, /first argument must be a positive integer/) } - it { is_expected.to run.with_params(1.5).and_raise_error(ArgumentError, /first argument must be a positive integer/) } - it { is_expected.to run.with_params(-10).and_raise_error(ArgumentError, /first argument must be a positive integer/) } - it { is_expected.to run.with_params("-10").and_raise_error(ArgumentError, /first argument must be a positive integer/) } - it { is_expected.to run.with_params("string").and_raise_error(ArgumentError, /first argument must be a positive integer/) } - it { is_expected.to run.with_params([]).and_raise_error(ArgumentError, /first argument must be a positive integer/) } - it { is_expected.to run.with_params({}).and_raise_error(ArgumentError, /first argument must be a positive integer/) } - it { is_expected.to run.with_params(1, 1).and_raise_error(ArgumentError, /second argument must be undef or a string/) } - it { is_expected.to run.with_params(1, []).and_raise_error(ArgumentError, /second argument must be undef or a string/) } - it { is_expected.to run.with_params(1, {}).and_raise_error(ArgumentError, /second argument must be undef or a string/) } + it { is_expected.to run.with_params.and_raise_error(ArgumentError, %r{wrong number of arguments}i) } + it { is_expected.to run.with_params(0).and_raise_error(ArgumentError, %r{first argument must be a positive integer}) } + it { is_expected.to run.with_params(1.5).and_raise_error(ArgumentError, %r{first argument must be a positive integer}) } + it { is_expected.to run.with_params(-10).and_raise_error(ArgumentError, %r{first argument must be a positive integer}) } + it { is_expected.to run.with_params('-10').and_raise_error(ArgumentError, %r{first argument must be a positive integer}) } + it { is_expected.to run.with_params('string').and_raise_error(ArgumentError, %r{first argument must be a positive integer}) } + it { is_expected.to run.with_params([]).and_raise_error(ArgumentError, %r{first argument must be a positive integer}) } + it { is_expected.to run.with_params({}).and_raise_error(ArgumentError, %r{first argument must be a positive integer}) } + it { is_expected.to run.with_params(1, 1).and_raise_error(ArgumentError, %r{second argument must be undef or a string}) } + it { is_expected.to run.with_params(1, []).and_raise_error(ArgumentError, %r{second argument must be undef or a string}) } + it { is_expected.to run.with_params(1, {}).and_raise_error(ArgumentError, %r{second argument must be undef or a string}) } it { is_expected.to run.with_params(100).and_return(default_charset) } - it { is_expected.to run.with_params("100").and_return(default_charset) } + it { is_expected.to run.with_params('100').and_return(default_charset) } it { is_expected.to run.with_params(100, nil).and_return(default_charset) } it { is_expected.to run.with_params(100, '').and_return(default_charset) } - it { is_expected.to run.with_params(100, 'a').and_return(/\Aa{100}\z/) } - it { is_expected.to run.with_params(100, 'ab').and_return(/\A[ab]{100}\z/) } - it { is_expected.to run.with_params(100, 'ãβ').and_return(/\A[ãβ]{100}\z/) } + it { is_expected.to run.with_params(100, 'a').and_return(%r{\Aa{100}\z}) } + it { is_expected.to run.with_params(100, 'ab').and_return(%r{\A[ab]{100}\z}) } + it { is_expected.to run.with_params(100, 'ãβ').and_return(%r{\A[ãβ]{100}\z}) } it "provides the same 'random' value on subsequent calls for the same host" do expect(fqdn_rand_string(10)).to eql(fqdn_rand_string(10)) end - it "considers the same host and same extra arguments to have the same random sequence" do - first_random = fqdn_rand_string(10, :extra_identifier => [1, "same", "host"]) - second_random = fqdn_rand_string(10, :extra_identifier => [1, "same", "host"]) + it 'considers the same host and same extra arguments to have the same random sequence' do + first_random = fqdn_rand_string(10, extra_identifier: [1, 'same', 'host']) + second_random = fqdn_rand_string(10, extra_identifier: [1, 'same', 'host']) expect(first_random).to eql(second_random) end - it "allows extra arguments to control the random value on a single host" do - first_random = fqdn_rand_string(10, :extra_identifier => [1, "different", "host"]) - second_different_random = fqdn_rand_string(10, :extra_identifier => [2, "different", "host"]) + it 'allows extra arguments to control the random value on a single host' do + first_random = fqdn_rand_string(10, extra_identifier: [1, 'different', 'host']) + second_different_random = fqdn_rand_string(10, extra_identifier: [2, 'different', 'host']) expect(first_random).not_to eql(second_different_random) end - it "should return different strings for different hosts" do - val1 = fqdn_rand_string(10, :host => "first.host.com") - val2 = fqdn_rand_string(10, :host => "second.host.com") + it 'returns different strings for different hosts' do + val1 = fqdn_rand_string(10, host: 'first.host.com') + val2 = fqdn_rand_string(10, host: 'second.host.com') expect(val1).not_to eql(val2) end @@ -54,10 +55,10 @@ def fqdn_rand_string(max, args = {}) # workaround not being able to use let(:facts) because some tests need # multiple different hostnames in one context - scope.stubs(:lookupvar).with("::fqdn", {}).returns(host) + scope.stubs(:lookupvar).with('::fqdn', {}).returns(host) function_args = [max] - if args.has_key?(:charset) or !extra.empty? + if args.key?(:charset) || !extra.empty? function_args << charset end function_args += extra diff --git a/spec/functions/fqdn_rotate_spec.rb b/spec/functions/fqdn_rotate_spec.rb index 7c1038a3d..8168b8d40 100755 --- a/spec/functions/fqdn_rotate_spec.rb +++ b/spec/functions/fqdn_rotate_spec.rb @@ -2,9 +2,9 @@ describe 'fqdn_rotate' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } - it { is_expected.to run.with_params(0).and_raise_error(Puppet::ParseError, /Requires either array or string to work with/) } - it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, /Requires either array or string to work with/) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } + it { is_expected.to run.with_params(0).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work with}) } + it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work with}) } it { is_expected.to run.with_params('').and_return('') } it { is_expected.to run.with_params('a').and_return('a') } it { is_expected.to run.with_params('ã').and_return('ã') } @@ -12,53 +12,51 @@ it { is_expected.to run.with_params([]).and_return([]) } it { is_expected.to run.with_params(['a']).and_return(['a']) } - it "should rotate a string and the result should be the same size" do - expect(fqdn_rotate("asdf").size).to eq(4) + it 'rotates a string and the result should be the same size' do + expect(fqdn_rotate('asdf').size).to eq(4) end - it "should rotate a string to give the same results for one host" do - val1 = fqdn_rotate("abcdefg", :host => 'one') - val2 = fqdn_rotate("abcdefg", :host => 'one') + it 'rotates a string to give the same results for one host' do + val1 = fqdn_rotate('abcdefg', host: 'one') + val2 = fqdn_rotate('abcdefg', host: 'one') expect(val1).to eq(val2) end - it "allows extra arguments to control the random rotation on a single host" do - val1 = fqdn_rotate("abcdefg", :extra_identifier => [1, "different", "host"]) - val2 = fqdn_rotate("abcdefg", :extra_identifier => [2, "different", "host"]) + it 'allows extra arguments to control the random rotation on a single host' do + val1 = fqdn_rotate('abcdefg', extra_identifier: [1, 'different', 'host']) + val2 = fqdn_rotate('abcdefg', extra_identifier: [2, 'different', 'host']) expect(val1).not_to eq(val2) end - it "considers the same host and same extra arguments to have the same random rotation" do - val1 = fqdn_rotate("abcdefg", :extra_identifier => [1, "same", "host"]) - val2 = fqdn_rotate("abcdefg", :extra_identifier => [1, "same", "host"]) + it 'considers the same host and same extra arguments to have the same random rotation' do + val1 = fqdn_rotate('abcdefg', extra_identifier: [1, 'same', 'host']) + val2 = fqdn_rotate('abcdefg', extra_identifier: [1, 'same', 'host']) expect(val1).to eq(val2) end - it "should rotate a string to give different values on different hosts" do - val1 = fqdn_rotate("abcdefg", :host => 'one') - val2 = fqdn_rotate("abcdefg", :host => 'two') + it 'rotates a string to give different values on different hosts' do + val1 = fqdn_rotate('abcdefg', host: 'one') + val2 = fqdn_rotate('abcdefg', host: 'two') expect(val1).not_to eq(val2) end - it "should accept objects which extend String" do + it 'accepts objects which extend String' do result = fqdn_rotate(AlsoString.new('asdf')) expect(result).to eq('dfas') end - it "should use the Puppet::Util.deterministic_rand function" do - if Puppet::Util.respond_to?(:deterministic_rand) - Puppet::Util.expects(:deterministic_rand).with(44489829212339698569024999901561968770,4) - fqdn_rotate("asdf") - else - skip 'Puppet::Util#deterministic_rand not available' - end + it 'uses the Puppet::Util.deterministic_rand function' do + skip 'Puppet::Util#deterministic_rand not available' unless Puppet::Util.respond_to?(:deterministic_rand) + + Puppet::Util.expects(:deterministic_rand).with(44_489_829_212_339_698_569_024_999_901_561_968_770, 4) + fqdn_rotate('asdf') end - it "should not leave the global seed in a deterministic state" do - fqdn_rotate("asdf") - rand1 = rand() - fqdn_rotate("asdf") - rand2 = rand() + it 'does not leave the global seed in a deterministic state' do + fqdn_rotate('asdf') + rand1 = rand + fqdn_rotate('asdf') + rand2 = rand expect(rand1).not_to eql(rand2) end @@ -68,7 +66,7 @@ def fqdn_rotate(value, args = {}) # workaround not being able to use let(:facts) because some tests need # multiple different hostnames in one context - scope.stubs(:lookupvar).with("::fqdn").returns(host) + scope.stubs(:lookupvar).with('::fqdn').returns(host) function_args = [value] + extra scope.function_fqdn_rotate(function_args) diff --git a/spec/functions/fqdn_uuid_spec.rb b/spec/functions/fqdn_uuid_spec.rb index d0c30d6b2..7e59bb660 100644 --- a/spec/functions/fqdn_uuid_spec.rb +++ b/spec/functions/fqdn_uuid_spec.rb @@ -1,13 +1,12 @@ require 'spec_helper' describe 'fqdn_uuid' do - - context "Invalid parameters" do - it { should run.with_params().and_raise_error(ArgumentError, /No arguments given$/) } + context 'Invalid parameters' do + it { is_expected.to run.with_params.and_raise_error(ArgumentError, %r{No arguments given$}) } end - context "given string" do - it { should run.with_params('puppetlabs.com').and_return('9c70320f-6815-5fc5-ab0f-debe68bf764c') } - it { should run.with_params('google.com').and_return('64ee70a4-8cc1-5d25-abf2-dea6c79a09c8') } + context 'given string' do + it { is_expected.to run.with_params('puppetlabs.com').and_return('9c70320f-6815-5fc5-ab0f-debe68bf764c') } + it { is_expected.to run.with_params('google.com').and_return('64ee70a4-8cc1-5d25-abf2-dea6c79a09c8') } end end diff --git a/spec/functions/get_module_path_spec.rb b/spec/functions/get_module_path_spec.rb index a39e413d5..cc922dd7b 100755 --- a/spec/functions/get_module_path_spec.rb +++ b/spec/functions/get_module_path_spec.rb @@ -2,10 +2,10 @@ describe 'get_module_path' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /Wrong number of arguments, expects one/) } - it { is_expected.to run.with_params('one', 'two').and_raise_error(Puppet::ParseError, /Wrong number of arguments, expects one/) } - it { is_expected.to run.with_params('one', 'two', 'three').and_raise_error(Puppet::ParseError, /Wrong number of arguments, expects one/) } - it { is_expected.to run.with_params('one').and_raise_error(Puppet::ParseError, /Could not find module/) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{Wrong number of arguments, expects one}) } + it { is_expected.to run.with_params('one', 'two').and_raise_error(Puppet::ParseError, %r{Wrong number of arguments, expects one}) } + it { is_expected.to run.with_params('one', 'two', 'three').and_raise_error(Puppet::ParseError, %r{Wrong number of arguments, expects one}) } + it { is_expected.to run.with_params('one').and_raise_error(Puppet::ParseError, %r{Could not find module}) } class StubModule attr_reader :path @@ -15,8 +15,8 @@ def initialize(path) end describe 'when locating a module' do - let(:modulepath) { "/tmp/does_not_exist" } - let(:path_of_module_foo) { StubModule.new("/tmp/does_not_exist/foo") } + let(:modulepath) { '/tmp/does_not_exist' } + let(:path_of_module_foo) { StubModule.new('/tmp/does_not_exist/foo') } before(:each) { Puppet[:modulepath] = modulepath } @@ -25,7 +25,7 @@ def initialize(path) it { is_expected.to run.with_params('foo').and_return(path_of_module_foo.path) } - context 'when the modulepath is a list' do + context 'when the modulepath is a list' do # rubocop:disable RSpec/NestedGroups before(:each) { Puppet[:modulepath] = modulepath + 'tmp/something_else' } it { is_expected.to run.with_params('foo').and_return(path_of_module_foo.path) } @@ -34,11 +34,12 @@ def initialize(path) context 'in a non-default default environment' do let(:environment) { 'test' } + before(:each) { Puppet::Module.expects(:find).with('foo', 'test').returns(path_of_module_foo) } it { is_expected.to run.with_params('foo').and_return(path_of_module_foo.path) } - context 'when the modulepath is a list' do + context 'when the modulepath is a list' do # rubocop:disable RSpec/NestedGroups before(:each) { Puppet[:modulepath] = modulepath + 'tmp/something_else' } it { is_expected.to run.with_params('foo').and_return(path_of_module_foo.path) } diff --git a/spec/functions/getparam_spec.rb b/spec/functions/getparam_spec.rb index 522ed3b84..3a3cc274e 100755 --- a/spec/functions/getparam_spec.rb +++ b/spec/functions/getparam_spec.rb @@ -2,11 +2,11 @@ describe 'getparam' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(ArgumentError, /Must specify a reference/) } - it { is_expected.to run.with_params('User[one]').and_raise_error(ArgumentError, /Must specify name of a parameter/) } - it { is_expected.to run.with_params('User[one]', 2).and_raise_error(ArgumentError, /Must specify name of a parameter/) } - it { is_expected.to run.with_params('User[one]', []).and_raise_error(ArgumentError, /Must specify name of a parameter/) } - it { is_expected.to run.with_params('User[one]', {}).and_raise_error(ArgumentError, /Must specify name of a parameter/) } + it { is_expected.to run.with_params.and_raise_error(ArgumentError, %r{Must specify a reference}) } + it { is_expected.to run.with_params('User[one]').and_raise_error(ArgumentError, %r{Must specify name of a parameter}) } + it { is_expected.to run.with_params('User[one]', 2).and_raise_error(ArgumentError, %r{Must specify name of a parameter}) } + it { is_expected.to run.with_params('User[one]', []).and_raise_error(ArgumentError, %r{Must specify name of a parameter}) } + it { is_expected.to run.with_params('User[one]', {}).and_raise_error(ArgumentError, %r{Must specify name of a parameter}) } describe 'when compared against a user resource with no params' do let(:pre_condition) { 'user { "one": }' } @@ -30,6 +30,5 @@ it { is_expected.to run.with_params('User[三]', 'ensure').and_return('present') } it { is_expected.to run.with_params('User[ƒốưř]', 'ensure').and_return('present') } - end end diff --git a/spec/functions/getvar_spec.rb b/spec/functions/getvar_spec.rb index 55789d85a..2cb3a13f8 100755 --- a/spec/functions/getvar_spec.rb +++ b/spec/functions/getvar_spec.rb @@ -2,19 +2,18 @@ describe 'getvar' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } - it { is_expected.to run.with_params('one', 'two').and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } + it { is_expected.to run.with_params('one', 'two').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('$::foo').and_return(nil) } context 'given variables in namespaces' do - let(:pre_condition) { + let(:pre_condition) do <<-'ENDofPUPPETcode' class site::data { $foo = 'baz' } include site::data ENDofPUPPETcode - } + end it { is_expected.to run.with_params('site::data::foo').and_return('baz') } it { is_expected.to run.with_params('::site::data::foo').and_return('baz') } @@ -22,17 +21,16 @@ class site::data { $foo = 'baz' } end context 'given variables in namespaces' do - let(:pre_condition) { + let(:pre_condition) do <<-'ENDofPUPPETcode' class site::info { $lock = 'ŧҺîš íš ắ śţřĭŋĝ' } class site::new { $item = '万Ü€‰' } include site::info include site::new ENDofPUPPETcode - } + end it { is_expected.to run.with_params('site::info::lock').and_return('ŧҺîš íš ắ śţřĭŋĝ') } it { is_expected.to run.with_params('::site::new::item').and_return('万Ü€‰') } end end - diff --git a/spec/functions/glob_spec.rb b/spec/functions/glob_spec.rb index 06439da95..209aca6c5 100755 --- a/spec/functions/glob_spec.rb +++ b/spec/functions/glob_spec.rb @@ -2,7 +2,7 @@ describe 'glob' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params('').and_return([]) } it { is_expected.to run.with_params(['']).and_return([]) } diff --git a/spec/functions/grep_spec.rb b/spec/functions/grep_spec.rb index d2152b1aa..1122ffb18 100755 --- a/spec/functions/grep_spec.rb +++ b/spec/functions/grep_spec.rb @@ -2,19 +2,19 @@ describe 'grep' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } - it { is_expected.to run.with_params('one').and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } + it { is_expected.to run.with_params('one').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { - pending("grep does not actually check this, and raises NoMethodError instead") - is_expected.to run.with_params('one', 'two').and_raise_error(Puppet::ParseError, /first argument not an array/) + pending('grep does not actually check this, and raises NoMethodError instead') + is_expected.to run.with_params('one', 'two').and_raise_error(Puppet::ParseError, %r{first argument not an array}) } it { - pending("grep does not actually check this, and raises NoMethodError instead") - is_expected.to run.with_params(1, 'two').and_raise_error(Puppet::ParseError, /first argument not an array/) + pending('grep does not actually check this, and raises NoMethodError instead') + is_expected.to run.with_params(1, 'two').and_raise_error(Puppet::ParseError, %r{first argument not an array}) } - it { is_expected.to run.with_params('one', 'two', 'three').and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params('one', 'two', 'three').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params([], 'two').and_return([]) } - it { is_expected.to run.with_params(['one', 'two', 'three'], 'two').and_return(['two']) } - it { is_expected.to run.with_params(['one', 'two', 'three'], 't(wo|hree)').and_return(['two', 'three']) } - it { is_expected.to run.with_params(['ờאּê', 'ţשּׂỡ', 'ţһŗəè'], 'ţ(שּׂỡ|һŗəè)').and_return(['ţשּׂỡ', 'ţһŗəè']) } + it { is_expected.to run.with_params(%w[one two three], 'two').and_return(['two']) } + it { is_expected.to run.with_params(%w[one two three], 't(wo|hree)').and_return(%w[two three]) } + it { is_expected.to run.with_params(%w[ờאּê ţשּׂỡ ţһŗəè], 'ţ(שּׂỡ|һŗəè)').and_return(%w[ţשּׂỡ ţһŗəè]) } end diff --git a/spec/functions/has_interface_with_spec.rb b/spec/functions/has_interface_with_spec.rb index 7334d38b9..33ff9d942 100755 --- a/spec/functions/has_interface_with_spec.rb +++ b/spec/functions/has_interface_with_spec.rb @@ -2,27 +2,28 @@ describe 'has_interface_with' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } - it { is_expected.to run.with_params("one", "two", "three").and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } + it { is_expected.to run.with_params('one', 'two', 'three').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } # We need to mock out the Facts so we can specify how we expect this function # to behave on different platforms. - context "On Mac OS X Systems" do - let(:facts) { { :interfaces => 'lo0,gif0,stf0,en1,p2p0,fw0,en0,vmnet1,vmnet8,utun0' } } + context 'On Mac OS X Systems' do + let(:facts) { { interfaces: 'lo0,gif0,stf0,en1,p2p0,fw0,en0,vmnet1,vmnet8,utun0' } } + it { is_expected.to run.with_params('lo0').and_return(true) } it { is_expected.to run.with_params('lo').and_return(false) } end - context "On Linux Systems" do + context 'On Linux Systems' do let(:facts) do { - :interfaces => 'eth0,lo', - :ipaddress => '10.0.0.1', - :ipaddress_lo => '127.0.0.1', - :ipaddress_eth0 => '10.0.0.1', - :muppet => 'kermit', - :muppet_lo => 'mspiggy', - :muppet_eth0 => 'kermit', + interfaces: 'eth0,lo', + ipaddress: '10.0.0.1', + ipaddress_lo: '127.0.0.1', + ipaddress_eth0: '10.0.0.1', + muppet: 'kermit', + muppet_lo: 'mspiggy', + muppet_eth0: 'kermit', } end diff --git a/spec/functions/has_ip_address_spec.rb b/spec/functions/has_ip_address_spec.rb index 42a5a7926..77ca1e2ba 100755 --- a/spec/functions/has_ip_address_spec.rb +++ b/spec/functions/has_ip_address_spec.rb @@ -2,16 +2,16 @@ describe 'has_ip_address' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } - it { is_expected.to run.with_params("one", "two").and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } + it { is_expected.to run.with_params('one', 'two').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } - context "On Linux Systems" do + context 'On Linux Systems' do let(:facts) do { - :interfaces => 'eth0,lo', - :ipaddress => '10.0.0.1', - :ipaddress_lo => '127.0.0.1', - :ipaddress_eth0 => '10.0.0.1', + interfaces: 'eth0,lo', + ipaddress: '10.0.0.1', + ipaddress_lo: '127.0.0.1', + ipaddress_eth0: '10.0.0.1', } end diff --git a/spec/functions/has_ip_network_spec.rb b/spec/functions/has_ip_network_spec.rb index 57cf613a2..3881132b2 100755 --- a/spec/functions/has_ip_network_spec.rb +++ b/spec/functions/has_ip_network_spec.rb @@ -2,15 +2,15 @@ describe 'has_ip_network' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } - it { is_expected.to run.with_params("one", "two").and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } + it { is_expected.to run.with_params('one', 'two').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } - context "On Linux Systems" do + context 'On Linux Systems' do let(:facts) do { - :interfaces => 'eth0,lo', - :network_lo => '127.0.0.0', - :network_eth0 => '10.0.0.0', + interfaces: 'eth0,lo', + network_lo: '127.0.0.0', + network_eth0: '10.0.0.0', } end diff --git a/spec/functions/has_key_spec.rb b/spec/functions/has_key_spec.rb index 0e0e1cc86..2416b8134 100755 --- a/spec/functions/has_key_spec.rb +++ b/spec/functions/has_key_spec.rb @@ -2,19 +2,19 @@ describe 'has_key' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } - it { is_expected.to run.with_params("one").and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } - it { is_expected.to run.with_params("one", "two", "three").and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } - it { is_expected.to run.with_params("one", "two").and_raise_error(Puppet::ParseError, /expects the first argument to be a hash/) } - it { is_expected.to run.with_params(1, "two").and_raise_error(Puppet::ParseError, /expects the first argument to be a hash/) } - it { is_expected.to run.with_params([], "two").and_raise_error(Puppet::ParseError, /expects the first argument to be a hash/) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } + it { is_expected.to run.with_params('one').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } + it { is_expected.to run.with_params('one', 'two', 'three').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } + it { is_expected.to run.with_params('one', 'two').and_raise_error(Puppet::ParseError, %r{expects the first argument to be a hash}) } + it { is_expected.to run.with_params(1, 'two').and_raise_error(Puppet::ParseError, %r{expects the first argument to be a hash}) } + it { is_expected.to run.with_params([], 'two').and_raise_error(Puppet::ParseError, %r{expects the first argument to be a hash}) } - it { is_expected.to run.with_params({ 'key' => 'value' }, "key").and_return(true) } - it { is_expected.to run.with_params({}, "key").and_return(false) } - it { is_expected.to run.with_params({ 'key' => 'value'}, "not a key").and_return(false) } + it { is_expected.to run.with_params({ 'key' => 'value' }, 'key').and_return(true) } + it { is_expected.to run.with_params({}, 'key').and_return(false) } + it { is_expected.to run.with_params({ 'key' => 'value' }, 'not a key').and_return(false) } context 'should run with UTF8 and double byte characters' do - it { is_expected.to run.with_params({ 'κéỳ ' => '٧ậļųể' }, "κéỳ ").and_return(true) } - it { is_expected.to run.with_params({ 'キー' => '٧ậļųể' }, "キー").and_return(true) } + it { is_expected.to run.with_params({ 'κéỳ ' => '٧ậļųể' }, 'κéỳ ').and_return(true) } + it { is_expected.to run.with_params({ 'キー' => '٧ậļųể' }, 'キー').and_return(true) } end end diff --git a/spec/functions/hash_spec.rb b/spec/functions/hash_spec.rb index 092474b66..f32d54f29 100755 --- a/spec/functions/hash_spec.rb +++ b/spec/functions/hash_spec.rb @@ -2,14 +2,14 @@ describe 'hash' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { - pending("Current implementation ignores parameters after the first.") - is_expected.to run.with_params([], 'two').and_raise_error(Puppet::ParseError, /wrong number of arguments/i) + pending('Current implementation ignores parameters after the first.') + is_expected.to run.with_params([], 'two').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } - it { is_expected.to run.with_params(['one']).and_raise_error(Puppet::ParseError, /Unable to compute/) } + it { is_expected.to run.with_params(['one']).and_raise_error(Puppet::ParseError, %r{Unable to compute}) } it { is_expected.to run.with_params([]).and_return({}) } - it { is_expected.to run.with_params(['key1', 'value1']).and_return({ 'key1' => 'value1' }) } - it { is_expected.to run.with_params(['κ℮ұ1', '√āĺűẻ1']).and_return({ 'κ℮ұ1' => '√āĺűẻ1' }) } - it { is_expected.to run.with_params(['key1', 'value1', 'key2', 'value2']).and_return({ 'key1' => 'value1', 'key2' => 'value2' }) } + it { is_expected.to run.with_params(%w[key1 value1]).and_return('key1' => 'value1') } + it { is_expected.to run.with_params(['κ℮ұ1', '√āĺűẻ1']).and_return('κ℮ұ1' => '√āĺűẻ1') } + it { is_expected.to run.with_params(%w[key1 value1 key2 value2]).and_return('key1' => 'value1', 'key2' => 'value2') } end diff --git a/spec/functions/intersection_spec.rb b/spec/functions/intersection_spec.rb index ec368a548..458992849 100755 --- a/spec/functions/intersection_spec.rb +++ b/spec/functions/intersection_spec.rb @@ -2,7 +2,7 @@ describe 'intersection' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params('one').and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params('one', 'two').and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params('one', 'two', 'three').and_raise_error(Puppet::ParseError) } @@ -13,10 +13,10 @@ it { is_expected.to run.with_params([], ['one']).and_return([]) } it { is_expected.to run.with_params(['one'], []).and_return([]) } it { is_expected.to run.with_params(['one'], ['one']).and_return(['one']) } - it { is_expected.to run.with_params(['one', 'two', 'three'], ['two', 'three']).and_return(['two', 'three']) } - it { is_expected.to run.with_params(['ōŋể', 'ŧשợ', 'ţђŕẽё'], ['ŧשợ', 'ţђŕẽё']).and_return(['ŧשợ', 'ţђŕẽё']) } - it { is_expected.to run.with_params(['one', 'two', 'two', 'three'], ['two', 'three']).and_return(['two', 'three']) } - it { is_expected.to run.with_params(['one', 'two', 'three'], ['two', 'two', 'three']).and_return(['two', 'three']) } - it { is_expected.to run.with_params(['one', 'two', 'three'], ['two', 'three', 'four']).and_return(['two', 'three']) } - it 'should not confuse types' do is_expected.to run.with_params(['1', '2', '3'], [1, 2]).and_return([]) end + it { is_expected.to run.with_params(%w[one two three], %w[two three]).and_return(%w[two three]) } + it { is_expected.to run.with_params(%w[ōŋể ŧשợ ţђŕẽё], %w[ŧשợ ţђŕẽё]).and_return(%w[ŧשợ ţђŕẽё]) } + it { is_expected.to run.with_params(%w[one two two three], %w[two three]).and_return(%w[two three]) } + it { is_expected.to run.with_params(%w[one two three], %w[two two three]).and_return(%w[two three]) } + it { is_expected.to run.with_params(%w[one two three], %w[two three four]).and_return(%w[two three]) } + it 'does not confuse types' do is_expected.to run.with_params(%w[1 2 3], [1, 2]).and_return([]) end end diff --git a/spec/functions/is_a_spec.rb b/spec/functions/is_a_spec.rb index 2d6cb46da..a5fe59089 100644 --- a/spec/functions/is_a_spec.rb +++ b/spec/functions/is_a_spec.rb @@ -1,6 +1,6 @@ require 'spec_helper' -if ENV["FUTURE_PARSER"] == 'yes' +if ENV['FUTURE_PARSER'] == 'yes' describe 'type_of' do pending 'teach rspec-puppet to load future-only functions under 3.7.5' do it { is_expected.not_to eq(nil) } @@ -11,7 +11,7 @@ if Puppet.version.to_f >= 4.0 describe 'is_a' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(ArgumentError) } + it { is_expected.to run.with_params.and_raise_error(ArgumentError) } it { is_expected.to run.with_params('', '').and_raise_error(ArgumentError) } it 'succeeds when comparing a string and a string' do @@ -23,8 +23,10 @@ end it 'suceeds when comparing an UTF8 and double byte characters' do - is_expected.to run.with_params('このテキスト', String).and_return(true) - is_expected.to run.with_params('ŧћịś ŧêχŧ', String).and_return(true) + comparison_array = ['このテキスト', 'ŧћịś ŧêχŧ'] + comparison_array.each do |comparison_value| + is_expected.to run.with_params(comparison_value, String).and_return(true) + end end end end diff --git a/spec/functions/is_array_spec.rb b/spec/functions/is_array_spec.rb index e89f54b79..bc8fc30bd 100755 --- a/spec/functions/is_array_spec.rb +++ b/spec/functions/is_array_spec.rb @@ -1,12 +1,11 @@ require 'spec_helper' describe 'is_array' do - it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { - pending("Current implementation ignores parameters after the first.") - is_expected.to run.with_params([], []).and_raise_error(Puppet::ParseError, /wrong number of arguments/i) + pending('Current implementation ignores parameters after the first.') + is_expected.to run.with_params([], []).and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params([]).and_return(true) } it { is_expected.to run.with_params(['one']).and_return(true) } @@ -18,17 +17,17 @@ it { is_expected.to run.with_params(1).and_return(false) } it { is_expected.to run.with_params({}).and_return(false) } context 'Checking for deprecation warning' do - after(:all) do + after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') - end + end # Checking for deprecation warning, which should only be provoked when the env variable for it is set. - it 'should display a single deprecation' do - ENV['STDLIB_LOG_DEPRECATIONS'] = "true" + it 'displays a single deprecation' do + ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' scope.expects(:warning).with(includes('This method is deprecated')) is_expected.to run.with_params(['1.2.3.4']).and_return(true) end - it 'should display no warning for deprecation' do - ENV['STDLIB_LOG_DEPRECATIONS'] = "false" + it 'displays no warning for deprecation' do + ENV['STDLIB_LOG_DEPRECATIONS'] = 'false' scope.expects(:warning).with(includes('This method is deprecated')).never is_expected.to run.with_params(['1.2.3.4']).and_return(true) end diff --git a/spec/functions/is_bool_spec.rb b/spec/functions/is_bool_spec.rb index d21345c26..85d7cad73 100755 --- a/spec/functions/is_bool_spec.rb +++ b/spec/functions/is_bool_spec.rb @@ -1,10 +1,9 @@ require 'spec_helper' describe 'is_bool' do - it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } - it { is_expected.to run.with_params(true, false).and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } + it { is_expected.to run.with_params(true, false).and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params(true).and_return(true) } it { is_expected.to run.with_params(false).and_return(true) } it { is_expected.to run.with_params([1]).and_return(false) } @@ -14,20 +13,19 @@ it { is_expected.to run.with_params('true').and_return(false) } it { is_expected.to run.with_params('false').and_return(false) } context 'Checking for deprecation warning' do - after(:all) do + after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') - end + end # Checking for deprecation warning, which should only be provoked when the env variable for it is set. - it 'should display a single deprecation' do - ENV['STDLIB_LOG_DEPRECATIONS'] = "true" + it 'displays a single deprecation' do + ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' scope.expects(:warning).with(includes('This method is deprecated')) is_expected.to run.with_params(true).and_return(true) end - it 'should display no warning for deprecation' do - ENV['STDLIB_LOG_DEPRECATIONS'] = "false" + it 'displays no warning for deprecation' do + ENV['STDLIB_LOG_DEPRECATIONS'] = 'false' scope.expects(:warning).with(includes('This method is deprecated')).never is_expected.to run.with_params(false).and_return(true) end - end + end end - diff --git a/spec/functions/is_domain_name_spec.rb b/spec/functions/is_domain_name_spec.rb index c1bf0e34b..c2d598887 100755 --- a/spec/functions/is_domain_name_spec.rb +++ b/spec/functions/is_domain_name_spec.rb @@ -2,8 +2,8 @@ describe 'is_domain_name' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } - it { is_expected.to run.with_params('one', 'two').and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } + it { is_expected.to run.with_params('one', 'two').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params(1).and_return(false) } it { is_expected.to run.with_params([]).and_return(false) } it { is_expected.to run.with_params({}).and_return(false) } @@ -28,7 +28,7 @@ it { is_expected.to run.with_params('www.foo-bar.example.com').and_return(true) } it { is_expected.to run.with_params('www.foo-bar.example.com.').and_return(true) } it { is_expected.to run.with_params('-foo.example.com').and_return(false) } - it { is_expected.to run.with_params('-foo.example.com').and_return(false) } + it { is_expected.to run.with_params('-foo.example.com.').and_return(false) } end # Values obtained from Facter values will be frozen strings # in newer versions of Facter: diff --git a/spec/functions/is_email_address_spec.rb b/spec/functions/is_email_address_spec.rb index 8b7b358da..6c291e65b 100755 --- a/spec/functions/is_email_address_spec.rb +++ b/spec/functions/is_email_address_spec.rb @@ -2,8 +2,8 @@ describe 'is_email_address' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } - it { is_expected.to run.with_params([], []).and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } + it { is_expected.to run.with_params([], []).and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('bob@gmail.com').and_return(true) } it { is_expected.to run.with_params('alice+puppetlabs.com@gmail.com').and_return(true) } it { is_expected.to run.with_params('peter.parker@gmail.com').and_return(true) } diff --git a/spec/functions/is_float_spec.rb b/spec/functions/is_float_spec.rb index af3322e7e..e5c5d8c85 100755 --- a/spec/functions/is_float_spec.rb +++ b/spec/functions/is_float_spec.rb @@ -1,11 +1,10 @@ require 'spec_helper' describe 'is_float' do - it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } - it { is_expected.to run.with_params(0.1, 0.2).and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } + it { is_expected.to run.with_params(0.1, 0.2).and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } describe 'passing a string' do it { is_expected.to run.with_params('0.1').and_return(true) } @@ -23,20 +22,19 @@ end context 'Checking for deprecation warning' do - after(:all) do + after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end # Checking for deprecation warning, which should only be provoked when the env variable for it is set. - it 'should display a single deprecation' do - ENV['STDLIB_LOG_DEPRECATIONS'] = "true" + it 'displays a single deprecation' do + ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' scope.expects(:warning).with(includes('This method is deprecated')) is_expected.to run.with_params(2.2).and_return(true) end - it 'should display no warning for deprecation' do - ENV['STDLIB_LOG_DEPRECATIONS'] = "false" + it 'displays no warning for deprecation' do + ENV['STDLIB_LOG_DEPRECATIONS'] = 'false' scope.expects(:warning).with(includes('This method is deprecated')).never is_expected.to run.with_params(1.0).and_return(true) end end - end diff --git a/spec/functions/is_function_available_spec.rb b/spec/functions/is_function_available_spec.rb index 44f08c081..887f06996 100755 --- a/spec/functions/is_function_available_spec.rb +++ b/spec/functions/is_function_available_spec.rb @@ -2,8 +2,8 @@ describe 'is_function_available' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } - it { is_expected.to run.with_params('one', 'two').and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } + it { is_expected.to run.with_params('one', 'two').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('include').and_return(true) } it { is_expected.to run.with_params('no_such_function').and_return(false) } end diff --git a/spec/functions/is_hash_spec.rb b/spec/functions/is_hash_spec.rb index c2599a02a..3ef061d99 100755 --- a/spec/functions/is_hash_spec.rb +++ b/spec/functions/is_hash_spec.rb @@ -2,8 +2,8 @@ describe 'is_hash' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } - it { is_expected.to run.with_params({}, {}).and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } + it { is_expected.to run.with_params({}, {}).and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('').and_return(false) } it { is_expected.to run.with_params({}).and_return(true) } it { is_expected.to run.with_params([]).and_return(false) } diff --git a/spec/functions/is_integer_spec.rb b/spec/functions/is_integer_spec.rb index 8118ef447..2001cd16c 100755 --- a/spec/functions/is_integer_spec.rb +++ b/spec/functions/is_integer_spec.rb @@ -1,11 +1,10 @@ require 'spec_helper' describe 'is_integer' do - it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } - it { is_expected.to run.with_params(1, 2).and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } + it { is_expected.to run.with_params(1, 2).and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params(3).and_return(true) } it { is_expected.to run.with_params('3').and_return(true) } @@ -17,7 +16,7 @@ it { is_expected.to run.with_params(3.7).and_return(false) } it { is_expected.to run.with_params('3.7').and_return(false) } it { is_expected.to run.with_params(-3.7).and_return(false) } - it { is_expected.to run.with_params('3.7').and_return(false) } + it { is_expected.to run.with_params('-3.7').and_return(false) } it { is_expected.to run.with_params('one').and_return(false) } it { is_expected.to run.with_params([]).and_return(false) } @@ -29,20 +28,19 @@ it { is_expected.to run.with_params("foo\nbar").and_return(false) } context 'Checking for deprecation warning' do - after(:all) do + after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end # Checking for deprecation warning, which should only be provoked when the env variable for it is set. - it 'should display a single deprecation' do - ENV['STDLIB_LOG_DEPRECATIONS'] = "true" + it 'displays a single deprecation' do + ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' scope.expects(:warning).with(includes('This method is deprecated')) is_expected.to run.with_params(50).and_return(true) end - it 'should display no warning for deprecation' do - ENV['STDLIB_LOG_DEPRECATIONS'] = "false" + it 'displays no warning for deprecation' do + ENV['STDLIB_LOG_DEPRECATIONS'] = 'false' scope.expects(:warning).with(includes('This method is deprecated')).never is_expected.to run.with_params(50).and_return(true) end - end - + end end diff --git a/spec/functions/is_ip_address_spec.rb b/spec/functions/is_ip_address_spec.rb index 39525d7ac..d7163897d 100755 --- a/spec/functions/is_ip_address_spec.rb +++ b/spec/functions/is_ip_address_spec.rb @@ -2,8 +2,8 @@ describe 'is_ip_address' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } - it { is_expected.to run.with_params([], []).and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } + it { is_expected.to run.with_params([], []).and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('1.2.3.4').and_return(true) } it { is_expected.to run.with_params('1.2.3.255').and_return(true) } it { is_expected.to run.with_params('1.2.3.256').and_return(false) } @@ -23,17 +23,17 @@ context 'Checking for deprecation warning', if: Puppet.version.to_f < 4.0 do # Checking for deprecation warning, which should only be provoked when the env variable for it is set. - it 'should display a single deprecation' do - ENV['STDLIB_LOG_DEPRECATIONS'] = "true" + it 'displays a single deprecation' do + ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' scope.expects(:warning).with(includes('This method is deprecated')) is_expected.to run.with_params('1.2.3.4').and_return(true) end - it 'should display no warning for deprecation' do - ENV['STDLIB_LOG_DEPRECATIONS'] = "false" + it 'displays no warning for deprecation' do + ENV['STDLIB_LOG_DEPRECATIONS'] = 'false' scope.expects(:warning).with(includes('This method is deprecated')).never is_expected.to run.with_params('1.2.3.4').and_return(true) end - after(:all) do + after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end end diff --git a/spec/functions/is_ipv4_address_spec.rb b/spec/functions/is_ipv4_address_spec.rb index 985260cd1..20d29cb7c 100644 --- a/spec/functions/is_ipv4_address_spec.rb +++ b/spec/functions/is_ipv4_address_spec.rb @@ -1,9 +1,8 @@ require 'spec_helper' describe 'is_ipv4_address' do - it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } SharedData::IPV4_PATTERNS.each do |value| it { is_expected.to run.with_params(value).and_return(true) } @@ -14,17 +13,17 @@ end context 'Checking for deprecation warning', if: Puppet.version.to_f < 4.0 do - after(:all) do + after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end # Checking for deprecation warning, which should only be provoked when the env variable for it is set. - it 'should display a single deprecation' do - ENV['STDLIB_LOG_DEPRECATIONS'] = "true" + it 'displays a single deprecation' do + ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' scope.expects(:warning).with(includes('This method is deprecated')) is_expected.to run.with_params(SharedData::IPV4_PATTERNS.first).and_return(true) end - it 'should display no warning for deprecation' do - ENV['STDLIB_LOG_DEPRECATIONS'] = "false" + it 'displays no warning for deprecation' do + ENV['STDLIB_LOG_DEPRECATIONS'] = 'false' scope.expects(:warning).with(includes('This method is deprecated')).never is_expected.to run.with_params(SharedData::IPV4_PATTERNS.first).and_return(true) end diff --git a/spec/functions/is_ipv6_address_spec.rb b/spec/functions/is_ipv6_address_spec.rb index acd6a87f1..09246a181 100644 --- a/spec/functions/is_ipv6_address_spec.rb +++ b/spec/functions/is_ipv6_address_spec.rb @@ -1,9 +1,8 @@ require 'spec_helper' describe 'is_ipv6_address' do - it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('2001:0db8:85a3:0000:0000:8a2e:0370:7334').and_return(true) } it { is_expected.to run.with_params('85a3:0000:0000:8a2e:0370:7334:100.100.100.100').and_return(true) } it { is_expected.to run.with_params('1.2.3').and_return(false) } @@ -12,17 +11,17 @@ it { is_expected.to run.with_params('one').and_return(false) } context 'Checking for deprecation warning', if: Puppet.version.to_f < 4.0 do - after(:all) do + after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end # Checking for deprecation warning, which should only be provoked when the env variable for it is set. - it 'should display a single deprecation' do - ENV['STDLIB_LOG_DEPRECATIONS'] = "true" + it 'displays a single deprecation' do + ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' scope.expects(:warning).with(includes('This method is deprecated')) is_expected.to run.with_params('2001:0db8:85a3:0000:0000:8a2e:0370:7334').and_return(true) end - it 'should display no warning for deprecation' do - ENV['STDLIB_LOG_DEPRECATIONS'] = "false" + it 'displays no warning for deprecation' do + ENV['STDLIB_LOG_DEPRECATIONS'] = 'false' scope.expects(:warning).with(includes('This method is deprecated')).never is_expected.to run.with_params('2001:0db8:85a3:0000:0000:8a2e:0370:7334').and_return(true) end diff --git a/spec/functions/is_mac_address_spec.rb b/spec/functions/is_mac_address_spec.rb index c1e33b8d1..17261b664 100755 --- a/spec/functions/is_mac_address_spec.rb +++ b/spec/functions/is_mac_address_spec.rb @@ -2,8 +2,8 @@ describe 'is_mac_address' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } - it { is_expected.to run.with_params([], []).and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } + it { is_expected.to run.with_params([], []).and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('00:a0:1f:12:7f:a0').and_return(true) } it { is_expected.to run.with_params('00:A0:1F:12:7F:A0').and_return(true) } it { is_expected.to run.with_params('00:00:00:00:00:0g').and_return(false) } @@ -16,15 +16,15 @@ end it { - pending "should properly typecheck its arguments" + pending 'should properly typecheck its arguments' is_expected.to run.with_params(1).and_return(false) } it { - pending "should properly typecheck its arguments" + pending 'should properly typecheck its arguments' is_expected.to run.with_params({}).and_return(false) } it { - pending "should properly typecheck its arguments" + pending 'should properly typecheck its arguments' is_expected.to run.with_params([]).and_return(false) } end diff --git a/spec/functions/is_numeric_spec.rb b/spec/functions/is_numeric_spec.rb index 5962d8a13..5eab31f56 100755 --- a/spec/functions/is_numeric_spec.rb +++ b/spec/functions/is_numeric_spec.rb @@ -1,21 +1,20 @@ require 'spec_helper' describe 'is_numeric' do - it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } - it { is_expected.to run.with_params(1, 2).and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } + it { is_expected.to run.with_params(1, 2).and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params(3).and_return(true) } it { is_expected.to run.with_params('3').and_return(true) } it { is_expected.to run.with_params(-3).and_return(true) } it { is_expected.to run.with_params('-3').and_return(true) } - + it { is_expected.to run.with_params(3.7).and_return(true) } it { is_expected.to run.with_params('3.7').and_return(true) } it { is_expected.to run.with_params(-3.7).and_return(true) } - it { is_expected.to run.with_params('3.7').and_return(true) } + it { is_expected.to run.with_params('-3.7').and_return(true) } it { is_expected.to run.with_params('-342.2315e-12').and_return(true) } @@ -29,20 +28,19 @@ it { is_expected.to run.with_params(' - 1234').and_return(false) } context 'Checking for deprecation warning' do - after(:all) do + after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end # Checking for deprecation warning, which should only be provoked when the env variable for it is set. - it 'should display a single deprecation' do - ENV['STDLIB_LOG_DEPRECATIONS'] = "true" + it 'displays a single deprecation' do + ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' scope.expects(:warning).with(includes('This method is deprecated')) is_expected.to run.with_params(7).and_return(true) end - it 'should display no warning for deprecation' do - ENV['STDLIB_LOG_DEPRECATIONS'] = "false" + it 'displays no warning for deprecation' do + ENV['STDLIB_LOG_DEPRECATIONS'] = 'false' scope.expects(:warning).with(includes('This method is deprecated')).never is_expected.to run.with_params(7).and_return(true) end end - end diff --git a/spec/functions/is_string_spec.rb b/spec/functions/is_string_spec.rb index e92f85cc7..99f2d22c1 100755 --- a/spec/functions/is_string_spec.rb +++ b/spec/functions/is_string_spec.rb @@ -1,12 +1,11 @@ require 'spec_helper' describe 'is_string' do - it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { - pending("Current implementation ignores parameters after the first.") - is_expected.to run.with_params('', '').and_raise_error(Puppet::ParseError, /wrong number of arguments/i) + pending('Current implementation ignores parameters after the first.') + is_expected.to run.with_params('', '').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params(3).and_return(false) } @@ -17,7 +16,7 @@ it { is_expected.to run.with_params(3.7).and_return(false) } it { is_expected.to run.with_params('3.7').and_return(false) } it { is_expected.to run.with_params(-3.7).and_return(false) } - it { is_expected.to run.with_params('3.7').and_return(false) } + it { is_expected.to run.with_params('-3.7').and_return(false) } it { is_expected.to run.with_params([]).and_return(false) } it { is_expected.to run.with_params([1]).and_return(false) } @@ -28,20 +27,19 @@ it { is_expected.to run.with_params('0001234').and_return(true) } context 'Checking for deprecation warning' do - after(:all) do + after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end # Checking for deprecation warning, which should only be provoked when the env variable for it is set. - it 'should display a single deprecation' do - ENV['STDLIB_LOG_DEPRECATIONS'] = "true" + it 'displays a single deprecation' do + ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' scope.expects(:warning).with(includes('This method is deprecated')) is_expected.to run.with_params('sponge').and_return(true) end - it 'should display no warning for deprecation' do - ENV['STDLIB_LOG_DEPRECATIONS'] = "false" + it 'displays no warning for deprecation' do + ENV['STDLIB_LOG_DEPRECATIONS'] = 'false' scope.expects(:warning).with(includes('This method is deprecated')).never is_expected.to run.with_params('bob').and_return(true) end - end - + end end diff --git a/spec/functions/join_keys_to_values_spec.rb b/spec/functions/join_keys_to_values_spec.rb index 0a2a50ccb..fba508b2f 100755 --- a/spec/functions/join_keys_to_values_spec.rb +++ b/spec/functions/join_keys_to_values_spec.rb @@ -2,29 +2,28 @@ describe 'join_keys_to_values' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /Takes exactly two arguments/) } - it { is_expected.to run.with_params({}, '', '').and_raise_error(Puppet::ParseError, /Takes exactly two arguments/) } - it { is_expected.to run.with_params('one', '').and_raise_error(TypeError, /The first argument must be a hash/) } - it { is_expected.to run.with_params({}, 2).and_raise_error(TypeError, /The second argument must be a string/) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{Takes exactly two arguments}) } + it { is_expected.to run.with_params({}, '', '').and_raise_error(Puppet::ParseError, %r{Takes exactly two arguments}) } + it { is_expected.to run.with_params('one', '').and_raise_error(TypeError, %r{The first argument must be a hash}) } + it { is_expected.to run.with_params({}, 2).and_raise_error(TypeError, %r{The second argument must be a string}) } it { is_expected.to run.with_params({}, '').and_return([]) } it { is_expected.to run.with_params({}, ':').and_return([]) } it { is_expected.to run.with_params({ 'key' => 'value' }, '').and_return(['keyvalue']) } it { is_expected.to run.with_params({ 'key' => 'value' }, ':').and_return(['key:value']) } - context 'should run with UTF8 and double byte characters' do + context 'should run with UTF8 and double byte characters' do it { is_expected.to run.with_params({ 'ҝẽγ' => '√ạĺűē' }, ':').and_return(['ҝẽγ:√ạĺűē']) } - it { is_expected.to run.with_params({ 'ҝẽγ' => '√ạĺűē' }, '万').and_return(['ҝẽγ万√ạĺűē']) } + it { is_expected.to run.with_params({ 'ҝẽγ' => '√ạĺűē' }, '万').and_return(['ҝẽγ万√ạĺűē']) } end it { is_expected.to run.with_params({ 'key' => nil }, ':').and_return(['key:']) } - it 'should run join_keys_to_values(, ":") and return the proper array' do + it 'runs join_keys_to_values(, ":") and return the proper array' do result = subject.call([{ 'key1' => 'value1', 'key2' => 'value2' }, ':']) expect(result.sort).to eq(['key1:value1', 'key2:value2'].sort) end - it 'should run join_keys_to_values(, " ") and return the proper array' do - result = subject.call([{ 'key1' => 'value1', 'key2' => ['value2', 'value3'] }, ' ']) + it 'runs join_keys_to_values(, " ") and return the proper array' do + result = subject.call([{ 'key1' => 'value1', 'key2' => %w[value2 value3] }, ' ']) expect(result.sort).to eq(['key1 value1', 'key2 value2', 'key2 value3'].sort) end end - diff --git a/spec/functions/join_spec.rb b/spec/functions/join_spec.rb index 98852d51f..a40a7f61c 100755 --- a/spec/functions/join_spec.rb +++ b/spec/functions/join_spec.rb @@ -2,19 +2,19 @@ describe 'join' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { - pending("Current implementation ignores parameters after the second.") - is_expected.to run.with_params([], '', '').and_raise_error(Puppet::ParseError, /wrong number of arguments/i) + pending('Current implementation ignores parameters after the second.') + is_expected.to run.with_params([], '', '').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } - it { is_expected.to run.with_params('one').and_raise_error(Puppet::ParseError, /Requires array to work with/) } - it { is_expected.to run.with_params([], 2).and_raise_error(Puppet::ParseError, /Requires string to work with/) } + it { is_expected.to run.with_params('one').and_raise_error(Puppet::ParseError, %r{Requires array to work with}) } + it { is_expected.to run.with_params([], 2).and_raise_error(Puppet::ParseError, %r{Requires string to work with}) } it { is_expected.to run.with_params([]).and_return('') } it { is_expected.to run.with_params([], ':').and_return('') } it { is_expected.to run.with_params(['one']).and_return('one') } it { is_expected.to run.with_params(['one'], ':').and_return('one') } - it { is_expected.to run.with_params(['one', 'two', 'three']).and_return('onetwothree') } - it { is_expected.to run.with_params(['one', 'two', 'three'], ':').and_return('one:two:three') } - it { is_expected.to run.with_params(['ōŋể', 'ŧשợ', 'ţђŕẽё'], ':').and_return('ōŋể:ŧשợ:ţђŕẽё') } + it { is_expected.to run.with_params(%w[one two three]).and_return('onetwothree') } + it { is_expected.to run.with_params(%w[one two three], ':').and_return('one:two:three') } + it { is_expected.to run.with_params(%w[ōŋể ŧשợ ţђŕẽё], ':').and_return('ōŋể:ŧשợ:ţђŕẽё') } end diff --git a/spec/functions/keys_spec.rb b/spec/functions/keys_spec.rb index fc7d6d82a..db864fb6d 100755 --- a/spec/functions/keys_spec.rb +++ b/spec/functions/keys_spec.rb @@ -2,23 +2,23 @@ describe 'keys' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { - pending("Current implementation ignores parameters after the first.") - is_expected.to run.with_params({}, {}).and_raise_error(Puppet::ParseError, /wrong number of arguments/i) + pending('Current implementation ignores parameters after the first.') + is_expected.to run.with_params({}, {}).and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } - it { is_expected.to run.with_params('').and_raise_error(Puppet::ParseError, /Requires hash to work with/) } - it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, /Requires hash to work with/) } - it { is_expected.to run.with_params([]).and_raise_error(Puppet::ParseError, /Requires hash to work with/) } + it { is_expected.to run.with_params('').and_raise_error(Puppet::ParseError, %r{Requires hash to work with}) } + it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{Requires hash to work with}) } + it { is_expected.to run.with_params([]).and_raise_error(Puppet::ParseError, %r{Requires hash to work with}) } it { is_expected.to run.with_params({}).and_return([]) } - it { is_expected.to run.with_params({ 'key' => 'value' }).and_return(['key']) } - it 'should return the array of keys' do + it { is_expected.to run.with_params('key' => 'value').and_return(['key']) } + it 'returns the array of keys' do result = subject.call([{ 'key1' => 'value1', 'key2' => 'value2' }]) - expect(result).to match_array(['key1', 'key2']) + expect(result).to match_array(%w[key1 key2]) end - it 'should run with UTF8 and double byte characters' do + it 'runs with UTF8 and double byte characters' do result = subject.call([{ 'ҝểү' => '√ẳŀμệ', 'キー' => '値' }]) - expect(result).to match_array(['ҝểү', 'キー']) + expect(result).to match_array(%w[ҝểү キー]) end end diff --git a/spec/functions/length_spec.rb b/spec/functions/length_spec.rb index 487cf21b7..71845b16a 100755 --- a/spec/functions/length_spec.rb +++ b/spec/functions/length_spec.rb @@ -2,21 +2,21 @@ describe 'length' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(ArgumentError, /'length' expects 1 argument, got none/) } - it { is_expected.to run.with_params([], 'extra').and_raise_error(ArgumentError, /'length' expects 1 argument, got 2/) } - it { is_expected.to run.with_params(1).and_raise_error(ArgumentError, /expects a value of type String, Array, or Hash, got Integer/) } - it { is_expected.to run.with_params(true).and_raise_error(ArgumentError, /expects a value of type String, Array, or Hash, got Boolean/) } + it { is_expected.to run.with_params.and_raise_error(ArgumentError, %r{'length' expects 1 argument, got none}) } + it { is_expected.to run.with_params([], 'extra').and_raise_error(ArgumentError, %r{'length' expects 1 argument, got 2}) } + it { is_expected.to run.with_params(1).and_raise_error(ArgumentError, %r{expects a value of type String, Array, or Hash, got Integer}) } + it { is_expected.to run.with_params(true).and_raise_error(ArgumentError, %r{expects a value of type String, Array, or Hash, got Boolean}) } it { is_expected.to run.with_params('1').and_return(1) } it { is_expected.to run.with_params('1.0').and_return(3) } it { is_expected.to run.with_params([]).and_return(0) } it { is_expected.to run.with_params(['a']).and_return(1) } - it { is_expected.to run.with_params(['one', 'two', 'three']).and_return(3) } - it { is_expected.to run.with_params(['one', 'two', 'three', 'four']).and_return(4) } + it { is_expected.to run.with_params(%w[one two three]).and_return(3) } + it { is_expected.to run.with_params(%w[one two three four]).and_return(4) } it { is_expected.to run.with_params({}).and_return(0) } - it { is_expected.to run.with_params({'1' => '2'}).and_return(1) } - it { is_expected.to run.with_params({'1' => '2', '4' => '4'}).and_return(2) } - it { is_expected.to run.with_params({'€' => '@', '竹' => 'ǿňè'}).and_return(2) } + it { is_expected.to run.with_params('1' => '2').and_return(1) } + it { is_expected.to run.with_params('1' => '2', '4' => '4').and_return(2) } + it { is_expected.to run.with_params('€' => '@', '竹' => 'ǿňè').and_return(2) } it { is_expected.to run.with_params('').and_return(0) } it { is_expected.to run.with_params('a').and_return(1) } diff --git a/spec/functions/load_module_metadata_spec.rb b/spec/functions/load_module_metadata_spec.rb index 9496fcb4d..21362c360 100755 --- a/spec/functions/load_module_metadata_spec.rb +++ b/spec/functions/load_module_metadata_spec.rb @@ -2,60 +2,46 @@ describe 'load_module_metadata' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } - it { is_expected.to run.with_params("one", "two", "three").and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } + it { is_expected.to run.with_params('one', 'two', 'three').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } - describe "when calling with valid arguments" do + describe 'when calling with valid arguments' do before :each do - allow(File).to receive(:read).with(/\/(stdlib|test)\/metadata.json/, {:encoding=>"utf-8"}).and_return('{"name": "puppetlabs-stdlib"}') - allow(File).to receive(:read).with(/\/(stdlib|test)\/metadata.json/).and_return('{"name": "puppetlabs-stdlib"}') + allow(File).to receive(:read).with(%r{\/(stdlib|test)\/metadata.json}, encoding: 'utf-8').and_return('{"name": "puppetlabs-stdlib"}') + allow(File).to receive(:read).with(%r{\/(stdlib|test)\/metadata.json}).and_return('{"name": "puppetlabs-stdlib"}') end - context "when calling with valid utf8 and double byte character arguments" do + context 'when calling with valid utf8 and double byte character arguments' do before :each do - allow(File).to receive(:read).with(/\/(stdlib|test)\/metadata.json/, {:encoding=>"utf-8"}).and_return('{"ĭďèʼnţĩƒіểя": "ċơņťęאּť ỡƒ ţħíš - + allow(File).to receive(:read).with(%r{\/(stdlib|test)\/metadata.json}, encoding: 'utf-8').and_return('{"ĭďèʼnţĩƒіểя": "ċơņťęאּť ỡƒ ţħíš - この文字"}') - allow(File).to receive(:read).with(/\/(stdlib|test)\/metadata.json/).and_return('{"ĭďèʼnţĩƒіểя": "ċơņťęאּť ỡƒ ţħíš - + allow(File).to receive(:read).with(%r{\/(stdlib|test)\/metadata.json}).and_return('{"ĭďèʼnţĩƒіểя": "ċơņťęאּť ỡƒ ţħíš - この文字"}') end - it "should json parse the file" do - if Puppet::Util::Platform.windows? - allow(scope).to receive(:function_get_module_path).with(['science']).and_return('C:/path/to/module/') - allow(File).to receive(:exists?).with('C:/path/to/module/metadata.json').and_return(true) - allow(File).to receive(:read).with('C:/path/to/module/metadata.json').and_return('{"name": "spencer-science"}') - else - allow(scope).to receive(:function_get_module_path).with(['science']).and_return('/path/to/module/') - allow(File).to receive(:exists?).with('/path/to/module/metadata.json').and_return(true) - allow(File).to receive(:read).with('/path/to/module/metadata.json').and_return('{"name": "spencer-science"}') - end + let(:prefix) { 'C:' if Puppet::Util::Platform.windows? } - result = subject.call(['science']) - expect(result['name']).to eq('spencer-science') - end + it 'jsons parse the file' do + allow(scope).to receive(:function_get_module_path).with(['science']).and_return("#{prefix}/path/to/module/") + allow(File).to receive(:exists?).with("#{prefix}/path/to/module/metadata.json").and_return(true) + allow(File).to receive(:read).with("#{prefix}/path/to/module/metadata.json").and_return('{"name": "spencer-science"}') - it "should fail by default if there is no metadata.json" do - if Puppet::Util::Platform.windows? - allow(scope).to receive(:function_get_module_path).with(['science']).and_return('C:/path/to/module/') - allow(File).to receive(:exists?).with('C:/path/to/module/metadata.json').and_return(false) - else - allow(scope).to receive(:function_get_module_path).with(['science']).and_return('/path/to/module/') - allow(File).to receive(:exists?).with('/path/to/module/metadata.json').and_return(false) + result = subject.call(['science']) + expect(result['name']).to eq('spencer-science') end - expect {subject.call(['science'])}.to raise_error(Puppet::ParseError) - end - it "should return nil if user allows empty metadata.json" do - if Puppet::Util::Platform.windows? - allow(scope).to receive(:function_get_module_path).with(['science']).and_return('C:/path/to/module/') - allow(File).to receive(:exists?).with('C:/path/to/module/metadata.json').and_return(false) - else - allow(scope).to receive(:function_get_module_path).with(['science']).and_return('/path/to/module/') - allow(File).to receive(:exists?).with('/path/to/module/metadata.json').and_return(false) + it 'fails by default if there is no metadata.json' do + allow(scope).to receive(:function_get_module_path).with(['science']).and_return("#{prefix}/path/to/module/") + allow(File).to receive(:exists?).with("#{prefix}/path/to/module/metadata.json").and_return(false) + expect { subject.call(['science']) }.to raise_error(Puppet::ParseError) + end + + it 'returns nil if user allows empty metadata.json' do + allow(scope).to receive(:function_get_module_path).with(['science']).and_return("#{prefix}/path/to/module/") + allow(File).to receive(:exists?).with("#{prefix}/path/to/module/metadata.json").and_return(false) + result = subject.call(['science', true]) + expect(result).to eq({}) end - result = subject.call(['science', true]) - expect(result).to eq({}) - end end end end diff --git a/spec/functions/loadjson_spec.rb b/spec/functions/loadjson_spec.rb index dbef805dc..c2416f356 100644 --- a/spec/functions/loadjson_spec.rb +++ b/spec/functions/loadjson_spec.rb @@ -2,65 +2,68 @@ describe 'loadjson' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(ArgumentError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(ArgumentError, %r{wrong number of arguments}i) } - describe "when calling with valid arguments" do + describe 'when calling with valid arguments' do before :each do - allow(File).to receive(:read).with(/\/(stdlib|test)\/metadata.json/, {:encoding=>"utf-8"}).and_return('{"name": "puppetlabs-stdlib"}') - allow(File).to receive(:read).with(/\/(stdlib|test)\/metadata.json/).and_return('{"name": "puppetlabs-stdlib"}') + allow(File).to receive(:read).with(%r{\/(stdlib|test)\/metadata.json}, encoding: 'utf-8').and_return('{"name": "puppetlabs-stdlib"}') + allow(File).to receive(:read).with(%r{\/(stdlib|test)\/metadata.json}).and_return('{"name": "puppetlabs-stdlib"}') end context 'when a non-existing file is specified' do - let(:filename) { + let(:filename) do if Puppet::Util::Platform.windows? 'C:/tmp/doesnotexist' else '/tmp/doesnotexist' end - } - before { + end + + before(:each) do allow(File).to receive(:exists?).with(filename).and_return(false).once allow(PSON).to receive(:load).never - } - it { is_expected.to run.with_params(filename, {'default' => 'value'}).and_return({'default' => 'value'}) } - it { is_expected.to run.with_params(filename, {'đẽƒằưļŧ' => '٧ẵłựέ'}).and_return({'đẽƒằưļŧ' => '٧ẵłựέ'}) } - it { is_expected.to run.with_params(filename, {'デフォルト' => '値'}).and_return({'デフォルト' => '値'}) } + end + it { is_expected.to run.with_params(filename, 'default' => 'value').and_return('default' => 'value') } + it { is_expected.to run.with_params(filename, 'đẽƒằưļŧ' => '٧ẵłựέ').and_return('đẽƒằưļŧ' => '٧ẵłựέ') } + it { is_expected.to run.with_params(filename, 'デフォルト' => '値').and_return('デフォルト' => '値') } end context 'when an existing file is specified' do - let(:filename) { + let(:filename) do if Puppet::Util::Platform.windows? 'C:/tmp/doesexist' else '/tmp/doesexist' end - } - let(:data) { { 'key' => 'value', 'ķęŷ' => 'νậŀųề', 'キー' => '値'} } + end + let(:data) { { 'key' => 'value', 'ķęŷ' => 'νậŀųề', 'キー' => '値' } } let(:json) { '{"key":"value", {"ķęŷ":"νậŀųề" }, {"キー":"値" }' } - before { + + before(:each) do allow(File).to receive(:exists?).with(filename).and_return(true).once allow(File).to receive(:read).with(filename).and_return(json).once allow(File).to receive(:read).with(filename).and_return(json).once allow(PSON).to receive(:load).with(json).and_return(data).once - } + end it { is_expected.to run.with_params(filename).and_return(data) } end context 'when the file could not be parsed' do - let(:filename) { + let(:filename) do if Puppet::Util::Platform.windows? 'C:/tmp/doesexist' else '/tmp/doesexist' end - } + end let(:json) { '{"key":"value"}' } - before { + + before(:each) do allow(File).to receive(:exists?).with(filename).and_return(true).once allow(File).to receive(:read).with(filename).and_return(json).once allow(PSON).to receive(:load).with(json).once.and_raise StandardError, 'Something terrible have happened!' - } - it { is_expected.to run.with_params(filename, {'default' => 'value'}).and_return({'default' => 'value'}) } + end + it { is_expected.to run.with_params(filename, 'default' => 'value').and_return('default' => 'value') } end end end diff --git a/spec/functions/loadyaml_spec.rb b/spec/functions/loadyaml_spec.rb index e9428e344..f104ca39f 100755 --- a/spec/functions/loadyaml_spec.rb +++ b/spec/functions/loadyaml_spec.rb @@ -2,35 +2,38 @@ describe 'loadyaml' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(ArgumentError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(ArgumentError, %r{wrong number of arguments}i) } context 'when a non-existing file is specified' do let(:filename) { '/tmp/doesnotexist' } - before { + + before(:each) do File.expects(:exists?).with(filename).returns(false).once YAML.expects(:load_file).never - } - it { is_expected.to run.with_params(filename, {'default' => 'value'}).and_return({'default' => 'value'}) } - it { is_expected.to run.with_params(filename, {'đẽƒằưļŧ' => '٧ẵłựέ'}).and_return({'đẽƒằưļŧ' => '٧ẵłựέ'}) } - it { is_expected.to run.with_params(filename, {'デフォルト' => '値'}).and_return({'デフォルト' => '値'}) } + end + it { is_expected.to run.with_params(filename, 'default' => 'value').and_return('default' => 'value') } + it { is_expected.to run.with_params(filename, 'đẽƒằưļŧ' => '٧ẵłựέ').and_return('đẽƒằưļŧ' => '٧ẵłựέ') } + it { is_expected.to run.with_params(filename, 'デフォルト' => '値').and_return('デフォルト' => '値') } end context 'when an existing file is specified' do let(:filename) { '/tmp/doesexist' } - let(:data) { { 'key' => 'value', 'ķęŷ' => 'νậŀųề', 'キー' => '値'} } - before { + let(:data) { { 'key' => 'value', 'ķęŷ' => 'νậŀųề', 'キー' => '値' } } + + before(:each) do File.expects(:exists?).with(filename).returns(true).once YAML.expects(:load_file).with(filename).returns(data).once - } + end it { is_expected.to run.with_params(filename).and_return(data) } end context 'when the file could not be parsed' do let(:filename) { '/tmp/doesexist' } - before { + + before(:each) do File.expects(:exists?).with(filename).returns(true).once YAML.stubs(:load_file).with(filename).once.raises StandardError, 'Something terrible have happened!' - } - it { is_expected.to run.with_params(filename, {'default' => 'value'}).and_return({'default' => 'value'}) } + end + it { is_expected.to run.with_params(filename, 'default' => 'value').and_return('default' => 'value') } end end diff --git a/spec/functions/lstrip_spec.rb b/spec/functions/lstrip_spec.rb index a5a09edcc..7c215d9b4 100755 --- a/spec/functions/lstrip_spec.rb +++ b/spec/functions/lstrip_spec.rb @@ -2,13 +2,13 @@ describe 'lstrip' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { - pending("Current implementation ignores parameters after the first.") - is_expected.to run.with_params('', '').and_raise_error(Puppet::ParseError, /wrong number of arguments/i) + pending('Current implementation ignores parameters after the first.') + is_expected.to run.with_params('', '').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } - it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, /Requires either array or string to work with/) } - it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, /Requires either array or string to work with/) } + it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work with}) } + it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work with}) } it { is_expected.to run.with_params('').and_return('') } it { is_expected.to run.with_params(' ').and_return('') } it { is_expected.to run.with_params(' ').and_return('') } diff --git a/spec/functions/max_spec.rb b/spec/functions/max_spec.rb index 66fb0c869..bacd2fcd2 100755 --- a/spec/functions/max_spec.rb +++ b/spec/functions/max_spec.rb @@ -2,7 +2,7 @@ describe 'max' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params(1).and_return(1) } it { is_expected.to run.with_params(1, 2).and_return(2) } it { is_expected.to run.with_params(1, 2, 3).and_return(3) } diff --git a/spec/functions/member_spec.rb b/spec/functions/member_spec.rb index 8988632a2..410c4651d 100755 --- a/spec/functions/member_spec.rb +++ b/spec/functions/member_spec.rb @@ -2,11 +2,11 @@ describe 'member' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } - it { is_expected.to run.with_params([]).and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } + it { is_expected.to run.with_params([]).and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { - pending("Current implementation ignores parameters after the first.") - is_expected.to run.with_params([], [], []).and_raise_error(Puppet::ParseError, /wrong number of arguments/i) + pending('Current implementation ignores parameters after the first.') + is_expected.to run.with_params([], [], []).and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params([], '').and_return(false) } it { is_expected.to run.with_params([], ['']).and_return(false) } @@ -16,8 +16,8 @@ it { is_expected.to run.with_params([], ['one']).and_return(false) } it { is_expected.to run.with_params(['one'], 'one').and_return(true) } it { is_expected.to run.with_params(['one'], ['one']).and_return(true) } - it { is_expected.to run.with_params(['one', 'two', 'three', 'four'], ['four', 'two']).and_return(true) } - it { is_expected.to run.with_params(['ọאּẹ', 'ŧẅồ', 'ţҺŗęē', 'ƒơџŕ'], ['ƒơџŕ', 'ŧẅồ']).and_return(true) } - it { is_expected.to run.with_params(['one', 'two', 'three', 'four'], ['four', 'five']).and_return(false) } - it { is_expected.to run.with_params(['ọאּẹ', 'ŧẅồ', 'ţҺŗęē', 'ƒơџŕ'], ['ƒơџŕ', 'ƒί√ə']).and_return(false) } + it { is_expected.to run.with_params(%w[one two three four], %w[four two]).and_return(true) } + it { is_expected.to run.with_params(%w[ọאּẹ ŧẅồ ţҺŗęē ƒơџŕ], %w[ƒơџŕ ŧẅồ]).and_return(true) } + it { is_expected.to run.with_params(%w[one two three four], %w[four five]).and_return(false) } + it { is_expected.to run.with_params(%w[ọאּẹ ŧẅồ ţҺŗęē ƒơџŕ], ['ƒơџŕ', 'ƒί√ə']).and_return(false) } end diff --git a/spec/functions/merge_spec.rb b/spec/functions/merge_spec.rb index 3b2e3ef4e..25e2658f6 100755 --- a/spec/functions/merge_spec.rb +++ b/spec/functions/merge_spec.rb @@ -2,9 +2,9 @@ describe 'merge' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } - it { is_expected.to run.with_params({}, 'two').and_raise_error(Puppet::ParseError, /unexpected argument type String/) } - it { is_expected.to run.with_params({}, 1).and_raise_error(Puppet::ParseError, /unexpected argument type (Fixnum|Integer)/) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } + it { is_expected.to run.with_params({}, 'two').and_raise_error(Puppet::ParseError, %r{unexpected argument type String}) } + it { is_expected.to run.with_params({}, 1).and_raise_error(Puppet::ParseError, %r{unexpected argument type (Fixnum|Integer)}) } it { pending 'should not special case this' is_expected.to run.with_params({}).and_return({}) @@ -14,12 +14,12 @@ describe 'should accept empty strings as puppet undef' do it { is_expected.to run.with_params({}, '').and_return({}) } end - it { is_expected.to run.with_params({ 'key' => 'value' }, {}).and_return({ 'key' => 'value' }) } - it { is_expected.to run.with_params({}, { 'key' => 'value' }).and_return({ 'key' => 'value' }) } - it { is_expected.to run.with_params({ 'key' => 'value1' }, { 'key' => 'value2' }).and_return({ 'key' => 'value2' }) } + it { is_expected.to run.with_params({ 'key' => 'value' }, {}).and_return('key' => 'value') } + it { is_expected.to run.with_params({}, 'key' => 'value').and_return('key' => 'value') } + it { is_expected.to run.with_params({ 'key' => 'value1' }, 'key' => 'value2').and_return('key' => 'value2') } it { is_expected.to run \ - .with_params({ 'key1' => 'value1' }, { 'key2' => 'value2' }, { 'key3' => 'value3' }) \ - .and_return({ 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3' }) + .with_params({ 'key1' => 'value1' }, { 'key2' => 'value2' }, 'key3' => 'value3') \ + .and_return('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3') } end diff --git a/spec/functions/min_spec.rb b/spec/functions/min_spec.rb index c840a72c9..fd2c9227e 100755 --- a/spec/functions/min_spec.rb +++ b/spec/functions/min_spec.rb @@ -2,7 +2,7 @@ describe 'min' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params(1).and_return(1) } it { is_expected.to run.with_params(1, 2).and_return(1) } it { is_expected.to run.with_params(1, 2, 3).and_return(1) } diff --git a/spec/functions/num2bool_spec.rb b/spec/functions/num2bool_spec.rb index 494afff9f..60533e390 100755 --- a/spec/functions/num2bool_spec.rb +++ b/spec/functions/num2bool_spec.rb @@ -2,9 +2,9 @@ describe 'num2bool' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } - it { is_expected.to run.with_params(1, 2).and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } - it { is_expected.to run.with_params('abc').and_raise_error(Puppet::ParseError, /does not look like a number/) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } + it { is_expected.to run.with_params(1, 2).and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } + it { is_expected.to run.with_params('abc').and_raise_error(Puppet::ParseError, %r{does not look like a number}) } it { is_expected.to run.with_params(1).and_return(true) } it { is_expected.to run.with_params('1').and_return(true) } it { is_expected.to run.with_params(1.5).and_return(true) } @@ -16,7 +16,7 @@ it { is_expected.to run.with_params(0).and_return(false) } it { is_expected.to run.with_params('0').and_return(false) } it { is_expected.to run.with_params([]).and_return(false) } - it { is_expected.to run.with_params('[]').and_raise_error(Puppet::ParseError, /does not look like a number/) } + it { is_expected.to run.with_params('[]').and_raise_error(Puppet::ParseError, %r{does not look like a number}) } it { is_expected.to run.with_params({}).and_return(false) } - it { is_expected.to run.with_params('{}').and_raise_error(Puppet::ParseError, /does not look like a number/) } + it { is_expected.to run.with_params('{}').and_raise_error(Puppet::ParseError, %r{does not look like a number}) } end diff --git a/spec/functions/parsejson_spec.rb b/spec/functions/parsejson_spec.rb index 7b07e4988..45abe3b0c 100755 --- a/spec/functions/parsejson_spec.rb +++ b/spec/functions/parsejson_spec.rb @@ -1,69 +1,66 @@ require 'spec_helper' describe 'parsejson' do - it 'should exist' do + it 'exists' do is_expected.not_to eq(nil) end - it 'should raise an error if called without any arguments' do - is_expected.to run.with_params(). - and_raise_error(/wrong number of arguments/i) + it 'raises an error if called without any arguments' do + is_expected.to run.with_params + .and_raise_error(%r{wrong number of arguments}i) end context 'with correct JSON data' do - - it 'should be able to parse JSON data with a Hash' do - is_expected.to run.with_params('{"a":"1","b":"2"}'). - and_return({'a'=>'1', 'b'=>'2'}) + it 'is able to parse JSON data with a Hash' do + is_expected.to run.with_params('{"a":"1","b":"2"}') + .and_return('a' => '1', 'b' => '2') end - it 'should be able to parse JSON data with an Array' do - is_expected.to run.with_params('["a","b","c"]'). - and_return(['a', 'b', 'c']) + it 'is able to parse JSON data with an Array' do + is_expected.to run.with_params('["a","b","c"]') + .and_return(%w[a b c]) end - it 'should be able to parse empty JSON values' do - is_expected.to run.with_params('[]'). - and_return([]) - is_expected.to run.with_params('{}'). - and_return({}) + it 'is able to parse empty JSON values' do + actual_array = %w[[] {}] + expected = [[], {}] + actual_array.each_with_index do |actual, index| + is_expected.to run.with_params(actual).and_return(expected[index]) + end end - it 'should be able to parse JSON data with a mixed structure' do - is_expected.to run.with_params('{"a":"1","b":2,"c":{"d":[true,false]}}'). - and_return({'a' =>'1', 'b' => 2, 'c' => { 'd' => [true, false] } }) + it 'is able to parse JSON data with a mixed structure' do + is_expected.to run.with_params('{"a":"1","b":2,"c":{"d":[true,false]}}') + .and_return('a' => '1', 'b' => 2, 'c' => { 'd' => [true, false] }) end - it 'should be able to parse JSON data with a UTF8 and double byte characters' do - is_expected.to run.with_params('{"×":"これ","ý":"記号","です":{"©":["Á","ß"]}}'). - and_return({'×' =>'これ', 'ý' => '記号', 'です' => { '©' => ['Á', 'ß'] } }) + it 'is able to parse JSON data with a UTF8 and double byte characters' do + is_expected.to run.with_params('{"×":"これ","ý":"記号","です":{"©":["Á","ß"]}}') + .and_return('×' => 'これ', 'ý' => '記号', 'です' => { '©' => %w[Á ß] }) end - it 'should not return the default value if the data was parsed correctly' do - is_expected.to run.with_params('{"a":"1"}', 'default_value'). - and_return({'a' => '1'}) + it 'does not return the default value if the data was parsed correctly' do + is_expected.to run.with_params('{"a":"1"}', 'default_value') + .and_return('a' => '1') end - end context 'with incorrect JSON data' do - it 'should raise an error with invalid JSON and no default' do - is_expected.to run.with_params(''). - and_raise_error(PSON::ParserError) + it 'raises an error with invalid JSON and no default' do + is_expected.to run.with_params('') + .and_raise_error(PSON::ParserError) end - it 'should support a structure for a default value' do - is_expected.to run.with_params('', {'a' => '1'}). - and_return({'a' => '1'}) + it 'supports a structure for a default value' do + is_expected.to run.with_params('', 'a' => '1') + .and_return('a' => '1') end ['', 1, 1.2, nil, true, false, [], {}, :yaml].each do |value| it "should return the default value for an incorrect #{value.inspect} (#{value.class}) parameter" do - is_expected.to run.with_params(value, 'default_value'). - and_return('default_value') + is_expected.to run.with_params(value, 'default_value') + .and_return('default_value') end end - end - end diff --git a/spec/functions/parseyaml_spec.rb b/spec/functions/parseyaml_spec.rb index c2a138c0e..7ff6b2056 100755 --- a/spec/functions/parseyaml_spec.rb +++ b/spec/functions/parseyaml_spec.rb @@ -1,86 +1,83 @@ require 'spec_helper' describe 'parseyaml' do - it 'should exist' do + it 'exists' do is_expected.not_to eq(nil) end - it 'should raise an error if called without any arguments' do - is_expected.to run.with_params(). - and_raise_error(/wrong number of arguments/i) + it 'raises an error if called without any arguments' do + is_expected.to run.with_params + .and_raise_error(%r{wrong number of arguments}i) end context 'with correct YAML data' do - it 'should be able to parse a YAML data with a String' do - is_expected.to run.with_params('--- just a string'). - and_return('just a string') - is_expected.to run.with_params('just a string'). - and_return('just a string') + it 'is able to parse a YAML data with a String' do + actual_array = ['--- just a string', 'just a string'] + actual_array.each do |actual| + is_expected.to run.with_params(actual).and_return('just a string') + end end - it 'should be able to parse YAML data with a Hash' do - is_expected.to run.with_params("---\na: '1'\nb: '2'\n"). - and_return({'a' => '1', 'b' => '2'}) + it 'is able to parse YAML data with a Hash' do + is_expected.to run.with_params("---\na: '1'\nb: '2'\n") + .and_return('a' => '1', 'b' => '2') end - it 'should be able to parse YAML data with an Array' do - is_expected.to run.with_params("---\n- a\n- b\n- c\n"). - and_return(['a', 'b', 'c']) + it 'is able to parse YAML data with an Array' do + is_expected.to run.with_params("---\n- a\n- b\n- c\n") + .and_return(%w[a b c]) end - it 'should be able to parse YAML data with a mixed structure' do - is_expected.to run.with_params("---\na: '1'\nb: 2\nc:\n d:\n - :a\n - true\n - false\n"). - and_return({'a' => '1', 'b' => 2, 'c' => {'d' => [:a, true, false]}}) + it 'is able to parse YAML data with a mixed structure' do + is_expected.to run.with_params("---\na: '1'\nb: 2\nc:\n d:\n - :a\n - true\n - false\n") + .and_return('a' => '1', 'b' => 2, 'c' => { 'd' => [:a, true, false] }) end - it 'should be able to parse YAML data with a UTF8 and double byte characters' do - is_expected.to run.with_params("---\na: ×\nこれ: 記号\nです:\n ©:\n - Á\n - ß\n"). - and_return({"a"=>"×", "これ"=>"記号", "です"=>{"©"=>["Á", "ß"]} }) + it 'is able to parse YAML data with a UTF8 and double byte characters' do + is_expected.to run.with_params("---\na: ×\nこれ: 記号\nです:\n ©:\n - Á\n - ß\n") + .and_return('a' => '×', 'これ' => '記号', 'です' => { '©' => %w[Á ß] }) end - it 'should not return the default value if the data was parsed correctly' do - is_expected.to run.with_params("---\na: '1'\n", 'default_value'). - and_return({'a' => '1'}) + it 'does not return the default value if the data was parsed correctly' do + is_expected.to run.with_params("---\na: '1'\n", 'default_value') + .and_return('a' => '1') end - end - context 'on a modern ruby', :unless => RUBY_VERSION == '1.8.7' do - it 'should raise an error with invalid YAML and no default' do - is_expected.to run.with_params('["one"'). - and_raise_error(Psych::SyntaxError) + context 'on a modern ruby', unless: RUBY_VERSION == '1.8.7' do + it 'raises an error with invalid YAML and no default' do + is_expected.to run.with_params('["one"') + .and_raise_error(Psych::SyntaxError) end end - context 'when running on ruby 1.8.7, which does not have Psych', :if => RUBY_VERSION == '1.8.7' do - it 'should raise an error with invalid YAML and no default' do - is_expected.to run.with_params('["one"'). - and_raise_error(ArgumentError) - end + context 'when running on ruby 1.8.7, which does not have Psych', if: RUBY_VERSION == '1.8.7' do + it 'raises an error with invalid YAML and no default' do + is_expected.to run.with_params('["one"') + .and_raise_error(ArgumentError) end + end context 'with incorrect YAML data' do - it 'should support a structure for a default value' do - is_expected.to run.with_params('', {'a' => '1'}). - and_return({'a' => '1'}) + it 'supports a structure for a default value' do + is_expected.to run.with_params('', 'a' => '1') + .and_return('a' => '1') end [1, 1.2, nil, true, false, [], {}, :yaml].each do |value| it "should return the default value for an incorrect #{value.inspect} (#{value.class}) parameter" do - is_expected.to run.with_params(value, 'default_value'). - and_return('default_value') + is_expected.to run.with_params(value, 'default_value') + .and_return('default_value') end end - context 'when running on modern rubies', :unless => RUBY_VERSION == '1.8.7' do + context 'when running on modern rubies', unless: RUBY_VERSION == '1.8.7' do ['---', '...', '*8', ''].each do |value| it "should return the default value for an incorrect #{value.inspect} string parameter" do - is_expected.to run.with_params(value, 'default_value'). - and_return('default_value') + is_expected.to run.with_params(value, 'default_value') + .and_return('default_value') end end end - end - end diff --git a/spec/functions/pick_default_spec.rb b/spec/functions/pick_default_spec.rb index a7ffc8637..2ddaa4b1b 100755 --- a/spec/functions/pick_default_spec.rb +++ b/spec/functions/pick_default_spec.rb @@ -2,7 +2,7 @@ describe 'pick_default' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::Error, /Must receive at least one argument/) } + it { is_expected.to run.with_params.and_raise_error(RuntimeError, %r{Must receive at least one argument}) } it { is_expected.to run.with_params('one', 'two').and_return('one') } it { is_expected.to run.with_params('ớņệ', 'ťωơ').and_return('ớņệ') } @@ -11,7 +11,7 @@ it { is_expected.to run.with_params(:undefined, 'two').and_return('two') } it { is_expected.to run.with_params(nil, 'two').and_return('two') } - [ '', :undef, :undefined, nil, {}, [], 1, 'default' ].each do |value| + ['', :undef, :undefined, nil, {}, [], 1, 'default'].each do |value| describe "when providing #{value.inspect} as default" do it { is_expected.to run.with_params('one', value).and_return('one') } it { is_expected.to run.with_params('ớņệ', value).and_return('ớņệ') } diff --git a/spec/functions/pick_spec.rb b/spec/functions/pick_spec.rb index 438553ba8..52ba706cb 100755 --- a/spec/functions/pick_spec.rb +++ b/spec/functions/pick_spec.rb @@ -2,8 +2,8 @@ describe 'pick' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /must receive at least one non empty value/) } - it { is_expected.to run.with_params('', nil, :undef, :undefined).and_raise_error(Puppet::ParseError, /must receive at least one non empty value/) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{must receive at least one non empty value}) } + it { is_expected.to run.with_params('', nil, :undef, :undefined).and_raise_error(Puppet::ParseError, %r{must receive at least one non empty value}) } it { is_expected.to run.with_params('one', 'two').and_return('one') } it { is_expected.to run.with_params('', 'two').and_return('two') } it { is_expected.to run.with_params(:undef, 'two').and_return('two') } @@ -11,7 +11,7 @@ it { is_expected.to run.with_params(nil, 'two').and_return('two') } context 'should run with UTF8 and double byte characters' do - it { is_expected.to run.with_params(nil, 'このテキスト').and_return('このテキスト') } - it { is_expected.to run.with_params('', 'ŝẳмрłề џţƒ8 ţẽם', 'このテキスト').and_return('ŝẳмрłề џţƒ8 ţẽם') } + it { is_expected.to run.with_params(nil, 'このテキスト').and_return('このテキスト') } + it { is_expected.to run.with_params('', 'ŝẳмрłề џţƒ8 ţẽם', 'このテキスト').and_return('ŝẳмрłề џţƒ8 ţẽם') } end end diff --git a/spec/functions/prefix_spec.rb b/spec/functions/prefix_spec.rb index 5510c58d6..b4c61babf 100755 --- a/spec/functions/prefix_spec.rb +++ b/spec/functions/prefix_spec.rb @@ -2,28 +2,28 @@ describe 'prefix' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { - pending("Current implementation ignores parameters after the second.") - is_expected.to run.with_params([], 'a', '').and_raise_error(Puppet::ParseError, /wrong number of arguments/i) + pending('Current implementation ignores parameters after the second.') + is_expected.to run.with_params([], 'a', '').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } - it { is_expected.to run.with_params('', '').and_raise_error(Puppet::ParseError, /expected first argument to be an Array or a Hash/) } - it { is_expected.to run.with_params([], 2).and_raise_error(Puppet::ParseError, /expected second argument to be a String/) } + it { is_expected.to run.with_params('', '').and_raise_error(Puppet::ParseError, %r{expected first argument to be an Array or a Hash}) } + it { is_expected.to run.with_params([], 2).and_raise_error(Puppet::ParseError, %r{expected second argument to be a String}) } it { is_expected.to run.with_params([]).and_return([]) } - it { is_expected.to run.with_params(['one', 2]).and_return(['one', '2']) } - it { is_expected.to run.with_params(['ớņệ', 2]).and_return(['ớņệ', '2']) } + it { is_expected.to run.with_params(['one', 2]).and_return(%w[one 2]) } + it { is_expected.to run.with_params(['ớņệ', 2]).and_return(%w[ớņệ 2]) } it { is_expected.to run.with_params([], '').and_return([]) } it { is_expected.to run.with_params([''], '').and_return(['']) } it { is_expected.to run.with_params(['one'], 'pre').and_return(['preone']) } - it { is_expected.to run.with_params(['one', 'two', 'three'], 'pre').and_return(['preone', 'pretwo', 'prethree']) } + it { is_expected.to run.with_params(%w[one two three], 'pre').and_return(%w[preone pretwo prethree]) } it { is_expected.to run.with_params({}).and_return({}) } - it { is_expected.to run.with_params({ 'key1' => 'value1', 2 => 3}).and_return({ 'key1' => 'value1', '2' => 3 }) } + it { is_expected.to run.with_params('key1' => 'value1', 2 => 3).and_return('key1' => 'value1', '2' => 3) } it { is_expected.to run.with_params({}, '').and_return({}) } - it { is_expected.to run.with_params({ 'key' => 'value' }, '').and_return({ 'key' => 'value' }) } - it { is_expected.to run.with_params({ 'key' => 'value' }, 'pre').and_return({ 'prekey' => 'value' }) } + it { is_expected.to run.with_params({ 'key' => 'value' }, '').and_return('key' => 'value') } + it { is_expected.to run.with_params({ 'key' => 'value' }, 'pre').and_return('prekey' => 'value') } it { is_expected.to run \ .with_params({ 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3' }, 'pre') \ - .and_return({ 'prekey1' => 'value1', 'prekey2' => 'value2', 'prekey3' => 'value3' }) + .and_return('prekey1' => 'value1', 'prekey2' => 'value2', 'prekey3' => 'value3') } end diff --git a/spec/functions/private_spec.rb b/spec/functions/private_spec.rb index a13be6439..1efc04512 100644 --- a/spec/functions/private_spec.rb +++ b/spec/functions/private_spec.rb @@ -1,17 +1,17 @@ require 'spec_helper' describe 'private' do - it 'should issue a warning' do - scope.expects(:warning).with("private() DEPRECATED: This function will cease to function on Puppet 4; please use assert_private() before upgrading to puppet 4 for backwards-compatibility, or migrate to the new parser's typing system.") + it 'issues a warning' do + scope.expects(:warning).with("private() DEPRECATED: This function will cease to function on Puppet 4; please use assert_private() before upgrading to puppet 4 for backwards-compatibility, or migrate to the new parser's typing system.") # rubocop:disable Metrics/LineLength : unable to cut line to required length begin subject.call [] - rescue + rescue # rubocop:disable Lint/HandleExceptions # ignore this end end - context "when called from inside module" do - it "should not fail" do + context 'when called from inside module' do + it 'does not fail' do scope.expects(:lookupvar).with('module_name').returns('foo') scope.expects(:lookupvar).with('caller_module_name').returns('foo') expect { @@ -20,37 +20,33 @@ end end - context "with an explicit failure message" do - it "prints the failure message on error" do + context 'with an explicit failure message' do + it 'prints the failure message on error' do scope.expects(:lookupvar).with('module_name').returns('foo') scope.expects(:lookupvar).with('caller_module_name').returns('bar') expect { subject.call ['failure message!'] - }.to raise_error Puppet::ParseError, /failure message!/ + }.to raise_error Puppet::ParseError, %r{failure message!} end end - context "when called from private class" do - it "should fail with a class error message" do + context 'when called from private class' do + it 'fails with a class error message' do scope.expects(:lookupvar).with('module_name').returns('foo') scope.expects(:lookupvar).with('caller_module_name').returns('bar') scope.source.expects(:name).returns('foo::baz') scope.source.expects(:type).returns('hostclass') - expect { - subject.call [] - }.to raise_error Puppet::ParseError, /Class foo::baz is private/ + expect { subject.call [] }.to raise_error Puppet::ParseError, %r{Class foo::baz is private} end end - context "when called from private definition" do - it "should fail with a class error message" do + context 'when called from private definition' do + it 'fails with a class error message' do scope.expects(:lookupvar).with('module_name').returns('foo') scope.expects(:lookupvar).with('caller_module_name').returns('bar') scope.source.expects(:name).returns('foo::baz') scope.source.expects(:type).returns('definition') - expect { - subject.call [] - }.to raise_error Puppet::ParseError, /Definition foo::baz is private/ + expect { subject.call [] }.to raise_error Puppet::ParseError, %r{Definition foo::baz is private} end end end diff --git a/spec/functions/pw_hash_spec.rb b/spec/functions/pw_hash_spec.rb index 9e0346491..31010d621 100644 --- a/spec/functions/pw_hash_spec.rb +++ b/spec/functions/pw_hash_spec.rb @@ -1,25 +1,24 @@ require 'spec_helper' describe 'pw_hash' do - it { is_expected.not_to eq(nil) } context 'when there are less than 3 arguments' do - it { is_expected.to run.with_params().and_raise_error(ArgumentError, /wrong number of arguments/i) } - it { is_expected.to run.with_params('password').and_raise_error(ArgumentError, /wrong number of arguments/i) } - it { is_expected.to run.with_params('password', 'sha-256').and_raise_error(ArgumentError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(ArgumentError, %r{wrong number of arguments}i) } + it { is_expected.to run.with_params('password').and_raise_error(ArgumentError, %r{wrong number of arguments}i) } + it { is_expected.to run.with_params('password', 'sha-256').and_raise_error(ArgumentError, %r{wrong number of arguments}i) } end context 'when there are more than 3 arguments' do - it { is_expected.to run.with_params('password', 'sha-256', 'salt', 'extra').and_raise_error(ArgumentError, /wrong number of arguments/i) } - it { is_expected.to run.with_params('password', 'sha-256', 'salt', 'extra', 'extra').and_raise_error(ArgumentError, /wrong number of arguments/i) } + it { is_expected.to run.with_params('password', 'sha-256', 'salt', 'extra').and_raise_error(ArgumentError, %r{wrong number of arguments}i) } + it { is_expected.to run.with_params('password', 'sha-256', 'salt', 'extra', 'extra').and_raise_error(ArgumentError, %r{wrong number of arguments}i) } end context 'when the first argument is not a string' do - it { is_expected.to run.with_params([], 'sha-256', 'salt').and_raise_error(ArgumentError, /first argument must be a string/) } - it { is_expected.to run.with_params({}, 'sha-256', 'salt').and_raise_error(ArgumentError, /first argument must be a string/) } - it { is_expected.to run.with_params(1, 'sha-256', 'salt').and_raise_error(ArgumentError, /first argument must be a string/) } - it { is_expected.to run.with_params(true, 'sha-256', 'salt').and_raise_error(ArgumentError, /first argument must be a string/) } + it { is_expected.to run.with_params([], 'sha-256', 'salt').and_raise_error(ArgumentError, %r{first argument must be a string}) } + it { is_expected.to run.with_params({}, 'sha-256', 'salt').and_raise_error(ArgumentError, %r{first argument must be a string}) } + it { is_expected.to run.with_params(1, 'sha-256', 'salt').and_raise_error(ArgumentError, %r{first argument must be a string}) } + it { is_expected.to run.with_params(true, 'sha-256', 'salt').and_raise_error(ArgumentError, %r{first argument must be a string}) } end context 'when the first argument is undefined' do @@ -28,39 +27,39 @@ end context 'when the second argument is not a string' do - it { is_expected.to run.with_params('password', [], 'salt').and_raise_error(ArgumentError, /second argument must be a string/) } - it { is_expected.to run.with_params('password', {}, 'salt').and_raise_error(ArgumentError, /second argument must be a string/) } - it { is_expected.to run.with_params('password', 1, 'salt').and_raise_error(ArgumentError, /second argument must be a string/) } - it { is_expected.to run.with_params('password', true, 'salt').and_raise_error(ArgumentError, /second argument must be a string/) } + it { is_expected.to run.with_params('password', [], 'salt').and_raise_error(ArgumentError, %r{second argument must be a string}) } + it { is_expected.to run.with_params('password', {}, 'salt').and_raise_error(ArgumentError, %r{second argument must be a string}) } + it { is_expected.to run.with_params('password', 1, 'salt').and_raise_error(ArgumentError, %r{second argument must be a string}) } + it { is_expected.to run.with_params('password', true, 'salt').and_raise_error(ArgumentError, %r{second argument must be a string}) } end context 'when the second argument is not one of the supported hashing algorithms' do - it { is_expected.to run.with_params('password', 'no such algo', 'salt').and_raise_error(ArgumentError, /is not a valid hash type/) } + it { is_expected.to run.with_params('password', 'no such algo', 'salt').and_raise_error(ArgumentError, %r{is not a valid hash type}) } end context 'when the third argument is not a string' do - it { is_expected.to run.with_params('password', 'sha-256', []).and_raise_error(ArgumentError, /third argument must be a string/) } - it { is_expected.to run.with_params('password', 'sha-256', {}).and_raise_error(ArgumentError, /third argument must be a string/) } - it { is_expected.to run.with_params('password', 'sha-256', 1).and_raise_error(ArgumentError, /third argument must be a string/) } - it { is_expected.to run.with_params('password', 'sha-256', true).and_raise_error(ArgumentError, /third argument must be a string/) } + it { is_expected.to run.with_params('password', 'sha-256', []).and_raise_error(ArgumentError, %r{third argument must be a string}) } + it { is_expected.to run.with_params('password', 'sha-256', {}).and_raise_error(ArgumentError, %r{third argument must be a string}) } + it { is_expected.to run.with_params('password', 'sha-256', 1).and_raise_error(ArgumentError, %r{third argument must be a string}) } + it { is_expected.to run.with_params('password', 'sha-256', true).and_raise_error(ArgumentError, %r{third argument must be a string}) } end context 'when the third argument is empty' do - it { is_expected.to run.with_params('password', 'sha-512', '').and_raise_error(ArgumentError, /third argument must not be empty/) } + it { is_expected.to run.with_params('password', 'sha-512', '').and_raise_error(ArgumentError, %r{third argument must not be empty}) } end context 'when the third argument contains invalid characters' do - it { is_expected.to run.with_params('password', 'sha-512', 'one%').and_raise_error(ArgumentError, /characters in salt must be in the set/) } + it { is_expected.to run.with_params('password', 'sha-512', 'one%').and_raise_error(ArgumentError, %r{characters in salt must be in the set}) } end context 'when running on a platform with a weak String#crypt implementation' do - before(:each) { allow_any_instance_of(String).to receive(:crypt).with('$1$1').and_return('a bad hash') } + before(:each) { allow_any_instance_of(String).to receive(:crypt).with('$1$1').and_return('a bad hash') } # rubocop:disable RSpec/AnyInstance : Unable to find a viable replacement - it { is_expected.to run.with_params('password', 'sha-512', 'salt').and_raise_error(Puppet::ParseError, /system does not support enhanced salts/) } + it { is_expected.to run.with_params('password', 'sha-512', 'salt').and_raise_error(Puppet::ParseError, %r{system does not support enhanced salts}) } end - if RUBY_PLATFORM == 'java' or 'test'.crypt('$1$1') == '$1$1$Bp8CU9Oujr9SSEw53WV6G.' - describe "on systems with enhanced salts support" do + if RUBY_PLATFORM == 'java' || 'test'.crypt('$1$1') == '$1$1$Bp8CU9Oujr9SSEw53WV6G.' + describe 'on systems with enhanced salts support' do it { is_expected.to run.with_params('password', 'md5', 'salt').and_return('$1$salt$qJH7.N4xYta3aEG/dfqo/0') } it { is_expected.to run.with_params('password', 'sha-256', 'salt').and_return('$5$salt$Gcm6FsVtF/Qa77ZKD.iwsJlCVPY0XSMgLJL0Hnww/c1') } it { is_expected.to run.with_params('password', 'sha-512', 'salt').and_return('$6$salt$IxDD3jeSOb5eB1CX5LBsqZFVkJdido3OUILO5Ifz5iwMuTS4XMS130MTSuDDl3aCI6WouIL9AjRbLCelDCy.g.') } @@ -69,7 +68,10 @@ if Puppet::Util::Package.versioncmp(Puppet.version, '4.7.0') >= 0 describe 'when arguments are sensitive' do it { is_expected.to run.with_params(Puppet::Pops::Types::PSensitiveType::Sensitive.new('password'), 'md5', 'salt').and_return('$1$salt$qJH7.N4xYta3aEG/dfqo/0') } - it { is_expected.to run.with_params(Puppet::Pops::Types::PSensitiveType::Sensitive.new('password'), 'md5', Puppet::Pops::Types::PSensitiveType::Sensitive.new('salt')).and_return('$1$salt$qJH7.N4xYta3aEG/dfqo/0') } + it { + is_expected.to run.with_params(Puppet::Pops::Types::PSensitiveType::Sensitive.new('password'), 'md5', Puppet::Pops::Types::PSensitiveType::Sensitive.new('salt')) + .and_return('$1$salt$qJH7.N4xYta3aEG/dfqo/0') + } it { is_expected.to run.with_params('password', 'md5', Puppet::Pops::Types::PSensitiveType::Sensitive.new('salt')).and_return('$1$salt$qJH7.N4xYta3aEG/dfqo/0') } end end diff --git a/spec/functions/range_spec.rb b/spec/functions/range_spec.rb index ca569d5d4..66dfd8166 100755 --- a/spec/functions/range_spec.rb +++ b/spec/functions/range_spec.rb @@ -3,46 +3,77 @@ describe 'range' do it { is_expected.not_to eq(nil) } - describe 'signature validation in puppet3', :unless => RSpec.configuration.puppet_future do - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + describe 'signature validation in puppet3', unless: RSpec.configuration.puppet_future do + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { - pending("Current implementation ignores parameters after the third.") - is_expected.to run.with_params(1, 2, 3, 4).and_raise_error(Puppet::ParseError, /wrong number of arguments/i) + pending('Current implementation ignores parameters after the third.') + is_expected.to run.with_params(1, 2, 3, 4).and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } - it { is_expected.to run.with_params('1..2..3').and_raise_error(Puppet::ParseError, /Unable to compute range/i) } - it { is_expected.to run.with_params('').and_raise_error(Puppet::ParseError, /Unknown range format/i) } + it { is_expected.to run.with_params('1..2..3').and_raise_error(Puppet::ParseError, %r{Unable to compute range}i) } + it { is_expected.to run.with_params('').and_raise_error(Puppet::ParseError, %r{Unknown range format}i) } end - describe 'signature validation in puppet4', :if => RSpec.configuration.puppet_future do - it { pending "the puppet 4 implementation"; is_expected.to run.with_params().and_raise_error(ArgumentError) } - it { pending "the puppet 4 implementation"; is_expected.to run.with_params('').and_raise_error(ArgumentError) } - it { pending "the puppet 4 implementation"; is_expected.to run.with_params({}).and_raise_error(ArgumentError) } - it { pending "the puppet 4 implementation"; is_expected.to run.with_params([]).and_raise_error(ArgumentError) } - it { pending "the puppet 4 implementation"; is_expected.to run.with_params(true).and_raise_error(ArgumentError) } - it { pending "the puppet 4 implementation"; is_expected.to run.with_params(true).and_raise_error(ArgumentError) } - it { is_expected.to run.with_params(1, 2, 'foo').and_raise_error(ArgumentError) } - it { pending "the puppet 4 implementation"; is_expected.to run.with_params(1, 2, []).and_raise_error(ArgumentError) } - it { pending "the puppet 4 implementation"; is_expected.to run.with_params(1, 2, {}).and_raise_error(ArgumentError) } - it { pending "the puppet 4 implementation"; is_expected.to run.with_params(1, 2, true).and_raise_error(ArgumentError) } - it { pending "the puppet 4 implementation"; is_expected.to run.with_params(1, 2, 3, 4).and_raise_error(ArgumentError) } - it { pending "the puppet 4 implementation"; is_expected.to run.with_params('1..2..3').and_raise_error(ArgumentError) } + describe 'signature validation in puppet4', if: RSpec.configuration.puppet_future do + it { + pending 'the puppet 4 implementation' + is_expected.to run.with_params.and_raise_error(ArgumentError) + } + it { + pending 'the puppet 4 implementation' + is_expected.to run.with_params('').and_raise_error(ArgumentError) + } + it { + pending 'the puppet 4 implementation' + is_expected.to run.with_params({}).and_raise_error(ArgumentError) + } + it { + pending 'the puppet 4 implementation' + is_expected.to run.with_params([]).and_raise_error(ArgumentError) + } + it { + pending 'the puppet 4 implementation' + is_expected.to run.with_params(true).and_raise_error(ArgumentError) + } + it { + is_expected.to run.with_params(1, 2, 'foo').and_raise_error(ArgumentError) + } + it { + pending 'the puppet 4 implementation' + is_expected.to run.with_params(1, 2, []).and_raise_error(ArgumentError) + } + it { + pending 'the puppet 4 implementation' + is_expected.to run.with_params(1, 2, {}).and_raise_error(ArgumentError) + } + it { + pending 'the puppet 4 implementation' + is_expected.to run.with_params(1, 2, true).and_raise_error(ArgumentError) + } + it { + pending 'the puppet 4 implementation' + is_expected.to run.with_params(1, 2, 3, 4).and_raise_error(ArgumentError) + } + it { + pending 'the puppet 4 implementation' + is_expected.to run.with_params('1..2..3').and_raise_error(ArgumentError) + } end context 'with characters as bounds' do it { is_expected.to run.with_params('d', 'a').and_return([]) } it { is_expected.to run.with_params('a', 'a').and_return(['a']) } - it { is_expected.to run.with_params('a', 'b').and_return(['a', 'b']) } - it { is_expected.to run.with_params('a', 'd').and_return(['a', 'b', 'c', 'd']) } - it { is_expected.to run.with_params('a', 'd', 1).and_return(['a', 'b', 'c', 'd']) } - it { is_expected.to run.with_params('a', 'd', '1').and_return(['a', 'b', 'c', 'd']) } - it { is_expected.to run.with_params('a', 'd', 2).and_return(['a', 'c']) } - it { is_expected.to run.with_params('a', 'd', -2).and_return(['a', 'c']) } - it { is_expected.to run.with_params('a', 'd', 3).and_return(['a', 'd']) } + it { is_expected.to run.with_params('a', 'b').and_return(%w[a b]) } + it { is_expected.to run.with_params('a', 'd').and_return(%w[a b c d]) } + it { is_expected.to run.with_params('a', 'd', 1).and_return(%w[a b c d]) } + it { is_expected.to run.with_params('a', 'd', '1').and_return(%w[a b c d]) } + it { is_expected.to run.with_params('a', 'd', 2).and_return(%w[a c]) } + it { is_expected.to run.with_params('a', 'd', -2).and_return(%w[a c]) } + it { is_expected.to run.with_params('a', 'd', 3).and_return(%w[a d]) } it { is_expected.to run.with_params('a', 'd', 4).and_return(['a']) } end context 'with strings as bounds' do - it { is_expected.to run.with_params('onea', 'oned').and_return(['onea', 'oneb', 'onec', 'oned']) } + it { is_expected.to run.with_params('onea', 'oned').and_return(%w[onea oneb onec oned]) } it { is_expected.to run.with_params('two', 'one').and_return([]) } it { is_expected.to run.with_params('true', 'false').and_return([]) } it { is_expected.to run.with_params('false', 'true').and_return(['false']) } @@ -75,16 +106,16 @@ end context 'with prefixed numbers as strings as bounds' do - it { is_expected.to run.with_params('host01', 'host04').and_return(['host01', 'host02', 'host03', 'host04']) } + it { is_expected.to run.with_params('host01', 'host04').and_return(%w[host01 host02 host03 host04]) } it { is_expected.to run.with_params('01', '04').and_return([1, 2, 3, 4]) } end context 'with prefixed numbers as utf8 strings as bounds' do - it { is_expected.to run.with_params('ħөŝŧ01', 'ħөŝŧ04').and_return(['ħөŝŧ01', 'ħөŝŧ02', 'ħөŝŧ03', 'ħөŝŧ04']) } + it { is_expected.to run.with_params('ħөŝŧ01', 'ħөŝŧ04').and_return(%w[ħөŝŧ01 ħөŝŧ02 ħөŝŧ03 ħөŝŧ04]) } end context 'with prefixed numbers as double byte character strings as bounds' do - it { is_expected.to run.with_params('ホスト01', 'ホスト04').and_return(['ホスト01', 'ホスト02', 'ホスト03', 'ホスト04']) } + it { is_expected.to run.with_params('ホスト01', 'ホスト04').and_return(%w[ホスト01 ホスト02 ホスト03 ホスト04]) } end context 'with dash-range syntax' do @@ -111,16 +142,16 @@ describe 'when passing mixed arguments as bounds' do it { - pending('these bounds should not be allowed as ruby will OOM hard. e.g. `(\'host0\'..\'hosta\').to_a` has 3239930 elements on ruby 1.9, adding more \'0\'s and \'a\'s increases that exponentially') - is_expected.to run.with_params('0', 'a').and_raise_error(Puppet::ParseError, /cannot interpolate between numeric and non-numeric bounds/) + pending('these bounds should not be allowed as ruby will OOM hard. e.g. `(\'host0\'..\'hosta\').to_a` has 3239930 elements on ruby 1.9, adding more \'0\'s and \'a\'s increases that exponentially') # rubocop:disable Metrics/LineLength : unable to cut line to required length + is_expected.to run.with_params('0', 'a').and_raise_error(Puppet::ParseError, %r{cannot interpolate between numeric and non-numeric bounds}) } it { - pending('these bounds should not be allowed as ruby will OOM hard. e.g. `(\'host0\'..\'hosta\').to_a` has 3239930 elements on ruby 1.9, adding more \'0\'s and \'a\'s increases that exponentially') - is_expected.to run.with_params(0, 'a').and_raise_error(Puppet::ParseError, /cannot interpolate between numeric and non-numeric bounds/) + pending('these bounds should not be allowed as ruby will OOM hard. e.g. `(\'host0\'..\'hosta\').to_a` has 3239930 elements on ruby 1.9, adding more \'0\'s and \'a\'s increases that exponentially') # rubocop:disable Metrics/LineLength : unable to cut line to required length + is_expected.to run.with_params(0, 'a').and_raise_error(Puppet::ParseError, %r{cannot interpolate between numeric and non-numeric bounds}) } it { - pending('these bounds should not be allowed as ruby will OOM hard. e.g. `(\'host0\'..\'hosta\').to_a` has 3239930 elements on ruby 1.9, adding more \'0\'s and \'a\'s increases that exponentially') - is_expected.to run.with_params('h0', 'ha').and_raise_error(Puppet::ParseError, /cannot interpolate between numeric and non-numeric bounds/) + pending('these bounds should not be allowed as ruby will OOM hard. e.g. `(\'host0\'..\'hosta\').to_a` has 3239930 elements on ruby 1.9, adding more \'0\'s and \'a\'s increases that exponentially') # rubocop:disable Metrics/LineLength : unable to cut line to required length + is_expected.to run.with_params('h0', 'ha').and_raise_error(Puppet::ParseError, %r{cannot interpolate between numeric and non-numeric bounds}) } end end diff --git a/spec/functions/regexpescape_spec.rb b/spec/functions/regexpescape_spec.rb index 36dbe70e6..8a40e20bc 100644 --- a/spec/functions/regexpescape_spec.rb +++ b/spec/functions/regexpescape_spec.rb @@ -3,35 +3,35 @@ describe 'regexpescape' do describe 'signature validation' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { - pending("Current implementation ignores parameters after the first.") - is_expected.to run.with_params('', '').and_raise_error(Puppet::ParseError, /wrong number of arguments/i) + pending('Current implementation ignores parameters after the first.') + is_expected.to run.with_params('', '').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } - it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, /Requires either array or string to work/) } - it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, /Requires either array or string to work/) } - it { is_expected.to run.with_params(true).and_raise_error(Puppet::ParseError, /Requires either array or string to work/) } + it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work}) } + it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work}) } + it { is_expected.to run.with_params(true).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work}) } end describe 'handling normal strings' do - it 'should call ruby\'s Regexp.escape function' do + it 'calls ruby\'s Regexp.escape function' do Regexp.expects(:escape).with('regexp_string').returns('escaped_regexp_string').once is_expected.to run.with_params('regexp_string').and_return('escaped_regexp_string') end end describe 'handling classes derived from String' do - it 'should call ruby\'s Regexp.escape function' do + it 'calls ruby\'s Regexp.escape function' do regexp_string = AlsoString.new('regexp_string') Regexp.expects(:escape).with(regexp_string).returns('escaped_regexp_string').once - is_expected.to run.with_params(regexp_string).and_return("escaped_regexp_string") + is_expected.to run.with_params(regexp_string).and_return('escaped_regexp_string') end end describe 'strings in arrays handling' do it { is_expected.to run.with_params([]).and_return([]) } - it { is_expected.to run.with_params(['one*', "two"]).and_return(['one\*', "two"]) } - it { is_expected.to run.with_params(['one*', 1, true, {}, "two"]).and_return(['one\*', 1, true, {}, "two"]) } + it { is_expected.to run.with_params(['one*', 'two']).and_return(['one\*', 'two']) } + it { is_expected.to run.with_params(['one*', 1, true, {}, 'two']).and_return(['one\*', 1, true, {}, 'two']) } context 'should run with UTF8 and double byte characters' do it { is_expected.to run.with_params(['ŏʼnε*']).and_return(['ŏʼnε\*']) } diff --git a/spec/functions/reject_spec.rb b/spec/functions/reject_spec.rb index 86db7c7d6..f083e746c 100755 --- a/spec/functions/reject_spec.rb +++ b/spec/functions/reject_spec.rb @@ -2,19 +2,19 @@ describe 'reject' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } - it { is_expected.to run.with_params([], 'pattern', 'extra').and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } + it { is_expected.to run.with_params([], 'pattern', 'extra').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { - pending("reject does not actually check this, and raises NoMethodError instead") - is_expected.to run.with_params('one', 'two').and_raise_error(Puppet::ParseError, /first argument not an array/) + pending('reject does not actually check this, and raises NoMethodError instead') + is_expected.to run.with_params('one', 'two').and_raise_error(Puppet::ParseError, %r{first argument not an array}) } it { - pending("reject does not actually check this, and raises NoMethodError instead") - is_expected.to run.with_params(1, 'two').and_raise_error(Puppet::ParseError, /first argument not an array/) + pending('reject does not actually check this, and raises NoMethodError instead') + is_expected.to run.with_params(1, 'two').and_raise_error(Puppet::ParseError, %r{first argument not an array}) } it { is_expected.to run.with_params([], 'two').and_return([]) } - it { is_expected.to run.with_params(['one', 'two', 'three'], 'two').and_return(['one', 'three']) } - it { is_expected.to run.with_params(['one', 'two', 'three'], 't(wo|hree)').and_return(['one']) } - it { is_expected.to run.with_params(['όʼnệ', 'ţщồ', 'ţңяέέ'], 'ţ(щồ|ңяέέ)').and_return(['όʼnệ']) } + it { is_expected.to run.with_params(%w[one two three], 'two').and_return(%w[one three]) } + it { is_expected.to run.with_params(%w[one two three], 't(wo|hree)').and_return(['one']) } + it { is_expected.to run.with_params(%w[όʼnệ ţщồ ţңяέέ], 'ţ(щồ|ңяέέ)').and_return(['όʼnệ']) } end diff --git a/spec/functions/reverse_spec.rb b/spec/functions/reverse_spec.rb index 79bc0ad81..6573fa744 100755 --- a/spec/functions/reverse_spec.rb +++ b/spec/functions/reverse_spec.rb @@ -2,20 +2,20 @@ describe 'reverse' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { - pending("Current implementation ignores parameters after the first.") - is_expected.to run.with_params([], 'extra').and_raise_error(Puppet::ParseError, /wrong number of arguments/i) + pending('Current implementation ignores parameters after the first.') + is_expected.to run.with_params([], 'extra').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } - it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, /Requires either array or string to work/) } - it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, /Requires either array or string to work/) } - it { is_expected.to run.with_params(true).and_raise_error(Puppet::ParseError, /Requires either array or string to work/) } + it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work}) } + it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work}) } + it { is_expected.to run.with_params(true).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work}) } it { is_expected.to run.with_params([]).and_return([]) } it { is_expected.to run.with_params(['a']).and_return(['a']) } it { is_expected.to run.with_params(['one']).and_return(['one']) } - it { is_expected.to run.with_params(['one', 'two', 'three']).and_return(['three', 'two', 'one']) } - it { is_expected.to run.with_params(['one', 'two', 'three', 'four']).and_return(['four', 'three', 'two', 'one']) } - it { is_expected.to run.with_params(['ổňë', 'ťŵọ', 'ŧңяəė', 'ƒŏůŗ']).and_return(['ƒŏůŗ', 'ŧңяəė', 'ťŵọ', 'ổňë']) } + it { is_expected.to run.with_params(%w[one two three]).and_return(%w[three two one]) } + it { is_expected.to run.with_params(%w[one two three four]).and_return(%w[four three two one]) } + it { is_expected.to run.with_params(%w[ổňë ťŵọ ŧңяəė ƒŏůŗ]).and_return(%w[ƒŏůŗ ŧңяəė ťŵọ ổňë]) } it { is_expected.to run.with_params('').and_return('') } it { is_expected.to run.with_params('a').and_return('a') } @@ -24,7 +24,7 @@ it { is_expected.to run.with_params('āβćđ').and_return('đćβā') } context 'when using a class extending String' do - it 'should call its reverse method' do + it 'calls its reverse method' do value = AlsoString.new('asdfghjkl') value.expects(:reverse).returns('foo') expect(subject).to run.with_params(value).and_return('foo') diff --git a/spec/functions/round_spec.rb b/spec/functions/round_spec.rb index 8b13478f2..af99afdf2 100755 --- a/spec/functions/round_spec.rb +++ b/spec/functions/round_spec.rb @@ -8,7 +8,7 @@ it { is_expected.to run.with_params(-34.5).and_return(-35) } it { is_expected.to run.with_params(34.7).and_return(35) } it { is_expected.to run.with_params(-34.7).and_return(-35) } - it { is_expected.to run.with_params("test").and_raise_error Puppet::ParseError } - it { is_expected.to run.with_params("test", "best").and_raise_error Puppet::ParseError } + it { is_expected.to run.with_params('test').and_raise_error Puppet::ParseError } + it { is_expected.to run.with_params('test', 'best').and_raise_error Puppet::ParseError } it { is_expected.to run.with_params(3, 4).and_raise_error Puppet::ParseError } end diff --git a/spec/functions/rstrip_spec.rb b/spec/functions/rstrip_spec.rb index a7663e21d..c8cbeb1a3 100755 --- a/spec/functions/rstrip_spec.rb +++ b/spec/functions/rstrip_spec.rb @@ -2,13 +2,13 @@ describe 'rstrip' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { - pending("Current implementation ignores parameters after the first.") - is_expected.to run.with_params('', '').and_raise_error(Puppet::ParseError, /wrong number of arguments/i) + pending('Current implementation ignores parameters after the first.') + is_expected.to run.with_params('', '').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } - it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, /Requires either array or string to work with/) } - it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, /Requires either array or string to work with/) } + it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work with}) } + it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work with}) } it { is_expected.to run.with_params('').and_return('') } it { is_expected.to run.with_params(' ').and_return('') } it { is_expected.to run.with_params(' ').and_return('') } diff --git a/spec/functions/seeded_rand_spec.rb b/spec/functions/seeded_rand_spec.rb index ac108f455..79daeec01 100644 --- a/spec/functions/seeded_rand_spec.rb +++ b/spec/functions/seeded_rand_spec.rb @@ -2,41 +2,41 @@ describe 'seeded_rand' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(ArgumentError, /wrong number of arguments/i) } - it { is_expected.to run.with_params(1).and_raise_error(ArgumentError, /wrong number of arguments/i) } - it { is_expected.to run.with_params(0, '').and_raise_error(ArgumentError, /first argument must be a positive integer/) } - it { is_expected.to run.with_params(1.5, '').and_raise_error(ArgumentError, /first argument must be a positive integer/) } - it { is_expected.to run.with_params(-10, '').and_raise_error(ArgumentError, /first argument must be a positive integer/) } - it { is_expected.to run.with_params("-10", '').and_raise_error(ArgumentError, /first argument must be a positive integer/) } - it { is_expected.to run.with_params("string", '').and_raise_error(ArgumentError, /first argument must be a positive integer/) } - it { is_expected.to run.with_params([], '').and_raise_error(ArgumentError, /first argument must be a positive integer/) } - it { is_expected.to run.with_params({}, '').and_raise_error(ArgumentError, /first argument must be a positive integer/) } - it { is_expected.to run.with_params(1, 1).and_raise_error(ArgumentError, /second argument must be a string/) } - it { is_expected.to run.with_params(1, []).and_raise_error(ArgumentError, /second argument must be a string/) } - it { is_expected.to run.with_params(1, {}).and_raise_error(ArgumentError, /second argument must be a string/) } - - it "provides a random number strictly less than the given max" do - expect(seeded_rand(3, 'seed')).to satisfy {|n| n.to_i < 3 } + it { is_expected.to run.with_params.and_raise_error(ArgumentError, %r{wrong number of arguments}i) } + it { is_expected.to run.with_params(1).and_raise_error(ArgumentError, %r{wrong number of arguments}i) } + it { is_expected.to run.with_params(0, '').and_raise_error(ArgumentError, %r{first argument must be a positive integer}) } + it { is_expected.to run.with_params(1.5, '').and_raise_error(ArgumentError, %r{first argument must be a positive integer}) } + it { is_expected.to run.with_params(-10, '').and_raise_error(ArgumentError, %r{first argument must be a positive integer}) } + it { is_expected.to run.with_params('-10', '').and_raise_error(ArgumentError, %r{first argument must be a positive integer}) } + it { is_expected.to run.with_params('string', '').and_raise_error(ArgumentError, %r{first argument must be a positive integer}) } + it { is_expected.to run.with_params([], '').and_raise_error(ArgumentError, %r{first argument must be a positive integer}) } + it { is_expected.to run.with_params({}, '').and_raise_error(ArgumentError, %r{first argument must be a positive integer}) } + it { is_expected.to run.with_params(1, 1).and_raise_error(ArgumentError, %r{second argument must be a string}) } + it { is_expected.to run.with_params(1, []).and_raise_error(ArgumentError, %r{second argument must be a string}) } + it { is_expected.to run.with_params(1, {}).and_raise_error(ArgumentError, %r{second argument must be a string}) } + + it 'provides a random number strictly less than the given max' do + expect(seeded_rand(3, 'seed')).to satisfy { |n| n.to_i < 3 } # rubocop:disable Lint/AmbiguousBlockAssociation : Cannot parenthesize without break code or violating other Rubocop rules end - it "provides a random number greater or equal to zero" do - expect(seeded_rand(3, 'seed')).to satisfy {|n| n.to_i >= 0 } + it 'provides a random number greater or equal to zero' do + expect(seeded_rand(3, 'seed')).to satisfy { |n| n.to_i >= 0 } # rubocop:disable Lint/AmbiguousBlockAssociation : Cannot parenthesize without break code or violating other Rubocop rules end it "provides the same 'random' value on subsequent calls for the same host" do expect(seeded_rand(10, 'seed')).to eql(seeded_rand(10, 'seed')) end - it "allows seed to control the random value on a single host" do + it 'allows seed to control the random value on a single host' do first_random = seeded_rand(1000, 'seed1') second_different_random = seeded_rand(1000, 'seed2') expect(first_random).not_to eql(second_different_random) end - it "should not return different values for different hosts" do - val1 = seeded_rand(1000, 'foo', :host => "first.host.com") - val2 = seeded_rand(1000, 'foo', :host => "second.host.com") + it 'does not return different values for different hosts' do + val1 = seeded_rand(1000, 'foo', host: 'first.host.com') + val2 = seeded_rand(1000, 'foo', host: 'second.host.com') expect(val1).to eql(val2) end @@ -46,13 +46,13 @@ def seeded_rand(max, seed, args = {}) # workaround not being able to use let(:facts) because some tests need # multiple different hostnames in one context - scope.stubs(:lookupvar).with("::fqdn", {}).returns(host) + scope.stubs(:lookupvar).with('::fqdn', {}).returns(host) scope.function_seeded_rand([max, seed]) end context 'should run with UTF8 and double byte characters' do - it { is_expected.to run.with_params(1000, 'ǿňè')} - it { is_expected.to run.with_params(1000, '文字列')} + it { is_expected.to run.with_params(1000, 'ǿňè') } + it { is_expected.to run.with_params(1000, '文字列') } end end diff --git a/spec/functions/shell_escape_spec.rb b/spec/functions/shell_escape_spec.rb index 77917ddb8..14b88c290 100644 --- a/spec/functions/shell_escape_spec.rb +++ b/spec/functions/shell_escape_spec.rb @@ -4,8 +4,8 @@ it { is_expected.not_to eq(nil) } describe 'signature validation' do - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } - it { is_expected.to run.with_params('foo', 'bar').and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } + it { is_expected.to run.with_params('foo', 'bar').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } end describe 'stringification' do @@ -16,12 +16,14 @@ describe 'escaping' do it { is_expected.to run.with_params('foo').and_return('foo') } it { is_expected.to run.with_params('foo bar').and_return('foo\ bar') } - it { is_expected.to run.with_params('~`!@#$%^&*()_+-=[]\{}|;\':",./<>?') - .and_return('\~\`\!@\#\$\%\^\&\*\(\)_\+-\=\[\]\\\\\{\}\|\;\\\':\",./\<\>\?') } + it { + is_expected.to run.with_params('~`!@#$%^&*()_+-=[]\{}|;\':",./<>?') + .and_return('\~\`\!@\#\$\%\^\&\*\(\)_\+-\=\[\]\\\\\{\}\|\;\\\':\",./\<\>\?') + } end context 'should run with UTF8 and double byte characters' do - it { is_expected.to run.with_params('スペー スを含むテ キスト').and_return('\\ス\\ペ\\ー\\ \\ス\\を\\含\\む\\テ\\ \\ \\キ\\ス\\ト') } - it { is_expected.to run.with_params('μťƒ 8 ŧĕχť').and_return('\\μ\\ť\\ƒ\\ 8\\ \\ \\ŧ\\ĕ\\χ\\ť') } + it { is_expected.to run.with_params('スペー スを含むテ キスト').and_return('\\ス\\ペ\\ー\\ \\ス\\を\\含\\む\\テ\\ \\ \\キ\\ス\\ト') } + it { is_expected.to run.with_params('μťƒ 8 ŧĕχť').and_return('\\μ\\ť\\ƒ\\ 8\\ \\ \\ŧ\\ĕ\\χ\\ť') } end end diff --git a/spec/functions/shell_join_spec.rb b/spec/functions/shell_join_spec.rb index 46305bf0b..545b0ce20 100644 --- a/spec/functions/shell_join_spec.rb +++ b/spec/functions/shell_join_spec.rb @@ -4,20 +4,22 @@ it { is_expected.not_to eq(nil) } describe 'signature validation' do - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } - it { is_expected.to run.with_params(['foo'], ['bar']).and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } - it { is_expected.to run.with_params('foo').and_raise_error(Puppet::ParseError, /is not an Array/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } + it { is_expected.to run.with_params(['foo'], ['bar']).and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } + it { is_expected.to run.with_params('foo').and_raise_error(Puppet::ParseError, %r{is not an Array}i) } end describe 'shell argument joining' do it { is_expected.to run.with_params(['foo']).and_return('foo') } - it { is_expected.to run.with_params(['foo', 'bar']).and_return('foo bar') } + it { is_expected.to run.with_params(%w[foo bar]).and_return('foo bar') } it { is_expected.to run.with_params(['foo', 'bar baz']).and_return('foo bar\ baz') } - it { is_expected.to run.with_params(['~`!@#$', '%^&*()_+-=', '[]\{}|;\':"', ',./<>?']) - .and_return('\~\`\!@\#\$ \%\^\&\*\(\)_\+-\= \[\]\\\\\{\}\|\;\\\':\" ,./\<\>\?') } + it { + is_expected.to run.with_params(['~`!@#$', '%^&*()_+-=', '[]\{}|;\':"', ',./<>?']) + .and_return('\~\`\!@\#\$ \%\^\&\*\(\)_\+-\= \[\]\\\\\{\}\|\;\\\':\" ,./\<\>\?') + } - context 'should run with UTF8 and double byte characters' do - it { is_expected.to run.with_params(['μťƒ', '8', 'ŧĕχť']).and_return('\\μ\\ť\\ƒ 8 \\ŧ\\ĕ\\χ\\ť') } + context 'should run with UTF8 and double byte characters' do + it { is_expected.to run.with_params(%w[μťƒ 8 ŧĕχť]).and_return('\\μ\\ť\\ƒ 8 \\ŧ\\ĕ\\χ\\ť') } it { is_expected.to run.with_params(['スペー', 'スを含むテ', ' キスト']).and_return('\\ス\\ペ\\ー \\ス\\を\\含\\む\\テ \\ \\キ\\ス\\ト') } end end diff --git a/spec/functions/shell_split_spec.rb b/spec/functions/shell_split_spec.rb index f8f9c9090..94e387174 100644 --- a/spec/functions/shell_split_spec.rb +++ b/spec/functions/shell_split_spec.rb @@ -4,8 +4,8 @@ it { is_expected.not_to eq(nil) } describe 'signature validation' do - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } - it { is_expected.to run.with_params('foo', 'bar').and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } + it { is_expected.to run.with_params('foo', 'bar').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } end describe 'stringification' do @@ -15,15 +15,19 @@ describe 'shell line spliting' do it { is_expected.to run.with_params('foo').and_return(['foo']) } - it { is_expected.to run.with_params('foo bar').and_return(['foo', 'bar']) } - it { is_expected.to run.with_params('\~\`\!@\#\$\%\^\&\*\(\)_\+-\=\[\]\\\\\{\}\|\;\\\':\",./\<\>\?') - .and_return(['~`!@#$%^&*()_+-=[]\{}|;\':",./<>?']) } - it { is_expected.to run.with_params('\~\`\!@\#\$ \%\^\&\*\(\)_\+-\= \[\]\\\\\{\}\|\;\\\':\" ,./\<\>\?') - .and_return(['~`!@#$', '%^&*()_+-=', '[]\{}|;\':"', ',./<>?']) } + it { is_expected.to run.with_params('foo bar').and_return(%w[foo bar]) } + it { + is_expected.to run.with_params('\~\`\!@\#\$\%\^\&\*\(\)_\+-\=\[\]\\\\\{\}\|\;\\\':\",./\<\>\?') + .and_return(['~`!@#$%^&*()_+-=[]\{}|;\':",./<>?']) + } + it { + is_expected.to run.with_params('\~\`\!@\#\$ \%\^\&\*\(\)_\+-\= \[\]\\\\\{\}\|\;\\\':\" ,./\<\>\?') + .and_return(['~`!@#$', '%^&*()_+-=', '[]\{}|;\':"', ',./<>?']) + } - context 'should run with UTF8 and double byte characters' do - it { is_expected.to run.with_params('\\μ\\ť\\ƒ 8 \\ŧ\\ĕ\\χ\\ť').and_return(['μťƒ', '8', 'ŧĕχť']) } - it { is_expected.to run.with_params('\\ス\\ペ\\ー \\ス\\を\\含\\む\\テ \\ \\キ\\ス\\ト').and_return(['スペー', 'スを含むテ', ' キスト']) } + context 'should run with UTF8 and double byte characters' do + it { is_expected.to run.with_params('\\μ\\ť\\ƒ 8 \\ŧ\\ĕ\\χ\\ť').and_return(%w[μťƒ 8 ŧĕχť]) } + it { is_expected.to run.with_params('\\ス\\ペ\\ー \\ス\\を\\含\\む\\テ \\ \\キ\\ス\\ト').and_return(['スペー', 'スを含むテ', ' キスト']) } end end end diff --git a/spec/functions/shuffle_spec.rb b/spec/functions/shuffle_spec.rb index 4673daaa6..99784977d 100755 --- a/spec/functions/shuffle_spec.rb +++ b/spec/functions/shuffle_spec.rb @@ -2,14 +2,14 @@ describe 'shuffle' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { - pending("Current implementation ignores parameters after the first.") - is_expected.to run.with_params([], 'extra').and_raise_error(Puppet::ParseError, /wrong number of arguments/i) + pending('Current implementation ignores parameters after the first.') + is_expected.to run.with_params([], 'extra').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } - it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, /Requires either array or string to work/) } - it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, /Requires either array or string to work/) } - it { is_expected.to run.with_params(true).and_raise_error(Puppet::ParseError, /Requires either array or string to work/) } + it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work}) } + it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work}) } + it { is_expected.to run.with_params(true).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work}) } context 'when running with a specific seed' do # make tests deterministic @@ -18,8 +18,8 @@ it { is_expected.to run.with_params([]).and_return([]) } it { is_expected.to run.with_params(['a']).and_return(['a']) } it { is_expected.to run.with_params(['one']).and_return(['one']) } - it { is_expected.to run.with_params(['one', 'two', 'three']).and_return(['two', 'one', 'three']) } - it { is_expected.to run.with_params(['one', 'two', 'three', 'four']).and_return(['four', 'three', 'two', 'one']) } + it { is_expected.to run.with_params(%w[one two three]).and_return(%w[two one three]) } + it { is_expected.to run.with_params(%w[one two three four]).and_return(%w[four three two one]) } it { is_expected.to run.with_params('').and_return('') } it { is_expected.to run.with_params('a').and_return('a') } diff --git a/spec/functions/size_spec.rb b/spec/functions/size_spec.rb index 2047423a9..a4079ea5b 100755 --- a/spec/functions/size_spec.rb +++ b/spec/functions/size_spec.rb @@ -2,24 +2,24 @@ describe 'size' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { - pending("Current implementation ignores parameters after the first.") - is_expected.to run.with_params([], 'extra').and_raise_error(Puppet::ParseError, /wrong number of arguments/i) + pending('Current implementation ignores parameters after the first.') + is_expected.to run.with_params([], 'extra').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } - it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, /Unknown type given/) } - it { is_expected.to run.with_params(true).and_raise_error(Puppet::ParseError, /Unknown type given/) } - it { is_expected.to run.with_params('1').and_raise_error(Puppet::ParseError, /Requires either string, array or hash to work/) } - it { is_expected.to run.with_params('1.0').and_raise_error(Puppet::ParseError, /Requires either string, array or hash to work/) } + it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{Unknown type given}) } + it { is_expected.to run.with_params(true).and_raise_error(Puppet::ParseError, %r{Unknown type given}) } + it { is_expected.to run.with_params('1').and_raise_error(Puppet::ParseError, %r{Requires either string, array or hash to work}) } + it { is_expected.to run.with_params('1.0').and_raise_error(Puppet::ParseError, %r{Requires either string, array or hash to work}) } it { is_expected.to run.with_params([]).and_return(0) } it { is_expected.to run.with_params(['a']).and_return(1) } - it { is_expected.to run.with_params(['one', 'two', 'three']).and_return(3) } - it { is_expected.to run.with_params(['one', 'two', 'three', 'four']).and_return(4) } + it { is_expected.to run.with_params(%w[one two three]).and_return(3) } + it { is_expected.to run.with_params(%w[one two three four]).and_return(4) } it { is_expected.to run.with_params({}).and_return(0) } - it { is_expected.to run.with_params({'1' => '2'}).and_return(1) } - it { is_expected.to run.with_params({'1' => '2', '4' => '4'}).and_return(2) } - it { is_expected.to run.with_params({'€' => '@', '竹' => 'ǿňè'}).and_return(2) } + it { is_expected.to run.with_params('1' => '2').and_return(1) } + it { is_expected.to run.with_params('1' => '2', '4' => '4').and_return(2) } + it { is_expected.to run.with_params('€' => '@', '竹' => 'ǿňè').and_return(2) } it { is_expected.to run.with_params('').and_return(0) } it { is_expected.to run.with_params('a').and_return(1) } @@ -29,7 +29,7 @@ it { is_expected.to run.with_params('āβćđ').and_return(4) } context 'when using a class extending String' do - it 'should call its size method' do + it 'calls its size method' do value = AlsoString.new('asdfghjkl') value.expects(:size).returns('foo') expect(subject).to run.with_params(value).and_return('foo') diff --git a/spec/functions/sort_spec.rb b/spec/functions/sort_spec.rb index 9abd039c1..f21d19fd3 100755 --- a/spec/functions/sort_spec.rb +++ b/spec/functions/sort_spec.rb @@ -3,17 +3,26 @@ describe 'sort' do describe 'signature validation' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } - it { is_expected.to run.with_params([], 'extra').and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } - it { pending('stricter input checking'); is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, /requires string or array/) } - it { pending('stricter input checking'); is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, /requires string or array/) } - it { pending('stricter input checking'); is_expected.to run.with_params(true).and_raise_error(Puppet::ParseError, /requires string or array/) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } + it { is_expected.to run.with_params([], 'extra').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } + it { + pending('stricter input checking') + is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, %r{requires string or array}) + } + it { + pending('stricter input checking') + is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{requires string or array}) + } + it { + pending('stricter input checking') + is_expected.to run.with_params(true).and_raise_error(Puppet::ParseError, %r{requires string or array}) + } end context 'when called with an array' do it { is_expected.to run.with_params([]).and_return([]) } it { is_expected.to run.with_params(['a']).and_return(['a']) } - it { is_expected.to run.with_params(['c', 'b', 'a']).and_return(['a', 'b', 'c']) } + it { is_expected.to run.with_params(%w[c b a]).and_return(%w[a b c]) } end context 'when called with a string' do diff --git a/spec/functions/sprintf_hash_spec.rb b/spec/functions/sprintf_hash_spec.rb index 1323094a8..297c903aa 100644 --- a/spec/functions/sprintf_hash_spec.rb +++ b/spec/functions/sprintf_hash_spec.rb @@ -27,6 +27,7 @@ end it 'prints formats with name placeholders' do - is_expected.to run.with_params('string %s and integer %b', 'foo' => '_foo_', 'bar' => 5).and_return('string _foo_ and integer 101') + is_expected.to run.with_params('string %s and integer %b', 'foo' => '_foo_', 'bar' => 5) # rubocop:disable Style/FormatStringToken : Template tokens needed for purposes of test + .and_return('string _foo_ and integer 101') end end diff --git a/spec/functions/squeeze_spec.rb b/spec/functions/squeeze_spec.rb index b267d9ad5..ced6e4ff1 100755 --- a/spec/functions/squeeze_spec.rb +++ b/spec/functions/squeeze_spec.rb @@ -2,8 +2,8 @@ describe 'squeeze' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } - it { is_expected.to run.with_params('', '', '').and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } + it { is_expected.to run.with_params('', '', '').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params(1).and_raise_error(NoMethodError) } it { is_expected.to run.with_params({}).and_raise_error(NoMethodError) } it { is_expected.to run.with_params(true).and_raise_error(NoMethodError) } @@ -26,22 +26,22 @@ it { is_expected.to run \ .with_params(['', 'a', 'aaaaaaaaa', 'aaaaaaaaabbbbbbbbbbcccccccccc']) \ - .and_return( ['', 'a', 'a', 'abc']) + .and_return(['', 'a', 'a', 'abc']) } it { is_expected.to run \ .with_params(['', 'a', 'aaaaaaaaa', 'aaaaaaaaabbbbbbbbbbcccccccccc'], 'a') \ - .and_return( ['', 'a', 'a', 'abbbbbbbbbbcccccccccc']) + .and_return(['', 'a', 'a', 'abbbbbbbbbbcccccccccc']) } it { is_expected.to run \ .with_params(['', 'a', 'aaaaaaaaa', 'aaaaaaaaabbbbbbbbbbcccccccccc'], 'b-c') \ - .and_return( ['', 'a', 'aaaaaaaaa', 'aaaaaaaaabc']) + .and_return(['', 'a', 'aaaaaaaaa', 'aaaaaaaaabc']) } end context 'when using a class extending String' do - it 'should call its squeeze method' do + it 'calls its squeeze method' do value = AlsoString.new('aaaaaaaaa') value.expects(:squeeze).returns('foo') expect(subject).to run.with_params(value).and_return('foo') diff --git a/spec/functions/str2bool_spec.rb b/spec/functions/str2bool_spec.rb index 7d8c47c19..fe43c4c24 100755 --- a/spec/functions/str2bool_spec.rb +++ b/spec/functions/str2bool_spec.rb @@ -2,21 +2,21 @@ describe 'str2bool' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { - pending("Current implementation ignores parameters after the first.") - is_expected.to run.with_params('true', 'extra').and_raise_error(Puppet::ParseError, /wrong number of arguments/i) + pending('Current implementation ignores parameters after the first.') + is_expected.to run.with_params('true', 'extra').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } - it { is_expected.to run.with_params('one').and_raise_error(Puppet::ParseError, /Unknown type of boolean given/) } + it { is_expected.to run.with_params('one').and_raise_error(Puppet::ParseError, %r{Unknown type of boolean given}) } describe 'when testing values that mean "true"' do - [ 'TRUE','1', 't', 'y', 'true', 'yes', true ].each do |value| + ['TRUE', '1', 't', 'y', 'true', 'yes', true].each do |value| it { is_expected.to run.with_params(value).and_return(true) } end end describe 'when testing values that mean "false"' do - [ 'FALSE','', '0', 'f', 'n', 'false', 'no', false, 'undef', 'undefined' ].each do |value| + ['FALSE', '', '0', 'f', 'n', 'false', 'no', false, 'undef', 'undefined'].each do |value| it { is_expected.to run.with_params(value).and_return(false) } end end diff --git a/spec/functions/str2saltedsha512_spec.rb b/spec/functions/str2saltedsha512_spec.rb index 2e1e818b5..e7513c97b 100755 --- a/spec/functions/str2saltedsha512_spec.rb +++ b/spec/functions/str2saltedsha512_spec.rb @@ -2,16 +2,25 @@ describe 'str2saltedsha512' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } - it { is_expected.to run.with_params('password', 2).and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } - it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, /Requires a String argument/) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } + it { is_expected.to run.with_params('password', 2).and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } + it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{Requires a String argument}) } context 'when running with a specific seed' do # make tests deterministic before(:each) { srand(2) } - it { is_expected.to run.with_params('').and_return('0f8a612f4eeed08e47b3875d00f33c5688f7926298f2d9b5fe19d1323f910bc78b6f7b5892596d2fabaa65e7a8d99b3768c102610cf0432c4827eee01f09451e3fae4f7a') } - it { is_expected.to run.with_params('password').and_return('0f8a612f43134376566c5707718d600effcfb17581fc9d3fa64d7f447dfda317c174ffdb498d2c5bd5c2075dab41c9d7ada5afbdc6b55354980eb5ba61802371e6b64956') } - it { is_expected.to run.with_params('verylongpassword').and_return('0f8a612f7a448537540e062daa8621f9bae326ca8ccb899e1bdb10e7c218cebfceae2530b856662565fdc4d81e986fc50cfbbc46d50436610ed9429ff5e43f2c45b5d039') } + it { + is_expected.to run.with_params('') + .and_return('0f8a612f4eeed08e47b3875d00f33c5688f7926298f2d9b5fe19d1323f910bc78b6f7b5892596d2fabaa65e7a8d99b3768c102610cf0432c4827eee01f09451e3fae4f7a') + } + it { + is_expected.to run.with_params('password') + .and_return('0f8a612f43134376566c5707718d600effcfb17581fc9d3fa64d7f447dfda317c174ffdb498d2c5bd5c2075dab41c9d7ada5afbdc6b55354980eb5ba61802371e6b64956') + } + it { + is_expected.to run.with_params('verylongpassword') + .and_return('0f8a612f7a448537540e062daa8621f9bae326ca8ccb899e1bdb10e7c218cebfceae2530b856662565fdc4d81e986fc50cfbbc46d50436610ed9429ff5e43f2c45b5d039') + } end end diff --git a/spec/functions/strftime_spec.rb b/spec/functions/strftime_spec.rb index 41cda6a20..92a6893ba 100755 --- a/spec/functions/strftime_spec.rb +++ b/spec/functions/strftime_spec.rb @@ -1,26 +1,26 @@ require 'spec_helper' describe 'strftime' do - it "should exist" do - expect(Puppet::Parser::Functions.function("strftime")).to eq("function_strftime") + it 'exists' do + expect(Puppet::Parser::Functions.function('strftime')).to eq('function_strftime') end - it "should raise a ParseError if there is less than 1 arguments" do - expect { scope.function_strftime([]) }.to( raise_error(Puppet::ParseError)) + it 'raises a ParseError if there is less than 1 arguments' do + expect { scope.function_strftime([]) }.to(raise_error(Puppet::ParseError)) end - it "using %s should be higher then when I wrote this test" do - result = scope.function_strftime(["%s"]) - expect(result.to_i).to(be > 1311953157) + it 'using %s should be higher then when I wrote this test' do + result = scope.function_strftime(['%s']) + expect(result.to_i).to(be > 1_311_953_157) end - it "using %s should be greater than 1.5 trillion" do - result = scope.function_strftime(["%s"]) - expect(result.to_i).to(be > 1500000000) + it 'using %s should be greater than 1.5 trillion' do + result = scope.function_strftime(['%s']) + expect(result.to_i).to(be > 1_500_000_000) end - it "should return a date when given %Y-%m-%d" do - result = scope.function_strftime(["%Y-%m-%d"]) - expect(result).to match(/^\d{4}-\d{2}-\d{2}$/) + it 'returns a date when given %Y-%m-%d' do + result = scope.function_strftime(['%Y-%m-%d']) + expect(result).to match(%r{^\d{4}-\d{2}-\d{2}$}) end end diff --git a/spec/functions/strip_spec.rb b/spec/functions/strip_spec.rb index 18e943dcf..e13f33abf 100755 --- a/spec/functions/strip_spec.rb +++ b/spec/functions/strip_spec.rb @@ -2,13 +2,13 @@ describe 'strip' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { - pending("Current implementation ignores parameters after the first.") - is_expected.to run.with_params('', '').and_raise_error(Puppet::ParseError, /wrong number of arguments/i) + pending('Current implementation ignores parameters after the first.') + is_expected.to run.with_params('', '').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } - it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, /Requires either array or string to work with/) } - it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, /Requires either array or string to work with/) } + it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work with}) } + it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work with}) } it { is_expected.to run.with_params('').and_return('') } it { is_expected.to run.with_params(' ').and_return('') } it { is_expected.to run.with_params(' ').and_return('') } diff --git a/spec/functions/suffix_spec.rb b/spec/functions/suffix_spec.rb index e0eafb1cc..f4d5bc1d3 100755 --- a/spec/functions/suffix_spec.rb +++ b/spec/functions/suffix_spec.rb @@ -2,39 +2,39 @@ describe 'suffix' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { - pending("Current implementation ignores parameters after the second.") - is_expected.to run.with_params([], 'a', '').and_raise_error(Puppet::ParseError, /wrong number of arguments/i) + pending('Current implementation ignores parameters after the second.') + is_expected.to run.with_params([], 'a', '').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } - it { is_expected.to run.with_params('', '').and_raise_error(Puppet::ParseError, /expected first argument to be an Array/) } - it { is_expected.to run.with_params([], 2).and_raise_error(Puppet::ParseError, /expected second argument to be a String/) } + it { is_expected.to run.with_params('', '').and_raise_error(Puppet::ParseError, %r{expected first argument to be an Array}) } + it { is_expected.to run.with_params([], 2).and_raise_error(Puppet::ParseError, %r{expected second argument to be a String}) } it { is_expected.to run.with_params([]).and_return([]) } - it { is_expected.to run.with_params(['one', 2]).and_return(['one', '2']) } + it { is_expected.to run.with_params(['one', 2]).and_return(%w[one 2]) } it { is_expected.to run.with_params([], '').and_return([]) } it { is_expected.to run.with_params([''], '').and_return(['']) } it { is_expected.to run.with_params(['one'], 'post').and_return(['onepost']) } - it { is_expected.to run.with_params(['one', 'two', 'three'], 'post').and_return(['onepost', 'twopost', 'threepost']) } + it { is_expected.to run.with_params(%w[one two three], 'post').and_return(%w[onepost twopost threepost]) } it { is_expected.to run.with_params(['ỗńέ', 'ťשׂǿ', 'ŧҺř℮ə'], 'рổŝţ').and_return(['ỗńέрổŝţ', 'ťשׂǿрổŝţ', 'ŧҺř℮əрổŝţ']) } it { is_expected.to run.with_params({}).and_return({}) } it { - is_expected.to run.with_params({ 'key1' => 'value1', 2 => 3}).and_return({ 'key1' => 'value1', '2' => 3 }) + is_expected.to run.with_params('key1' => 'value1', 2 => 3).and_return('key1' => 'value1', '2' => 3) } it { is_expected.to run.with_params({}, '').and_return({}) } it { - is_expected.to run.with_params({ 'key' => 'value' }, '').and_return({ 'key' => 'value' }) + is_expected.to run.with_params({ 'key' => 'value' }, '').and_return('key' => 'value') } it { - is_expected.to run.with_params({ 'key' => 'value' }, 'post').and_return({ 'keypost' => 'value' }) + is_expected.to run.with_params({ 'key' => 'value' }, 'post').and_return('keypost' => 'value') } it { is_expected.to run \ .with_params({ 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3' }, 'post') \ - .and_return({ 'key1post' => 'value1', 'key2post' => 'value2', 'key3post' => 'value3' }) + .and_return('key1post' => 'value1', 'key2post' => 'value2', 'key3post' => 'value3') } end diff --git a/spec/functions/swapcase_spec.rb b/spec/functions/swapcase_spec.rb index c175a1588..a970d71c2 100755 --- a/spec/functions/swapcase_spec.rb +++ b/spec/functions/swapcase_spec.rb @@ -2,14 +2,14 @@ describe 'swapcase' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { - pending("Current implementation ignores parameters after the first.") - is_expected.to run.with_params('a', '').and_raise_error(Puppet::ParseError, /wrong number of arguments/i) + pending('Current implementation ignores parameters after the first.') + is_expected.to run.with_params('a', '').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } - it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, /Requires either array or string to work/) } - it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, /Requires either array or string to work/) } - it { is_expected.to run.with_params(true).and_raise_error(Puppet::ParseError, /Requires either array or string to work/) } + it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work}) } + it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work}) } + it { is_expected.to run.with_params(true).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work}) } describe 'with strings as inputs' do it { is_expected.to run.with_params('').and_return('') } it { is_expected.to run.with_params('one').and_return('ONE') } @@ -23,9 +23,9 @@ it { is_expected.to run.with_params(['one']).and_return(['ONE']) } it { is_expected.to run.with_params(['ONE']).and_return(['one']) } it { is_expected.to run.with_params(['oNe']).and_return(['OnE']) } - it { is_expected.to run.with_params(['one', 'ONE']).and_return(['ONE', 'one']) } - it { is_expected.to run.with_params(['ONE', 'OnE']).and_return(['one', 'oNe']) } - it { is_expected.to run.with_params(['oNe', 'one']).and_return(['OnE', 'ONE']) } + it { is_expected.to run.with_params(%w[one ONE]).and_return(%w[ONE one]) } + it { is_expected.to run.with_params(%w[ONE OnE]).and_return(%w[one oNe]) } + it { is_expected.to run.with_params(%w[oNe one]).and_return(%w[OnE ONE]) } end describe 'containing mixed types' do it { is_expected.to run.with_params(['OnE', {}]).and_return(['oNe', {}]) } @@ -34,7 +34,7 @@ it { is_expected.to run.with_params(['OnE', ['two']]).and_return(['oNe', ['two']]) } end end - it "should accept objects which extend String" do - is_expected.to run.with_params(AlsoString.new("OnE")).and_return('oNe') + it 'accepts objects which extend String' do + is_expected.to run.with_params(AlsoString.new('OnE')).and_return('oNe') end end diff --git a/spec/functions/time_spec.rb b/spec/functions/time_spec.rb index d157939e9..2d9472bd5 100755 --- a/spec/functions/time_spec.rb +++ b/spec/functions/time_spec.rb @@ -2,20 +2,20 @@ describe 'time' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params('a', '').and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params('a', '').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } context 'when running at a specific time' do - before(:each) { + before(:each) do # get a value before stubbing the function test_time = Time.utc(2006, 10, 13, 8, 15, 11) - Time.expects(:new).with().returns(test_time).once - } - it { is_expected.to run.with_params().and_return(1160727311) } - it { is_expected.to run.with_params('').and_return(1160727311) } - it { is_expected.to run.with_params([]).and_return(1160727311) } - it { is_expected.to run.with_params({}).and_return(1160727311) } - it { is_expected.to run.with_params('foo').and_return(1160727311) } - it { is_expected.to run.with_params('UTC').and_return(1160727311) } - it { is_expected.to run.with_params('America/New_York').and_return(1160727311) } + Time.expects(:new).with.returns(test_time).once + end + it { is_expected.to run.with_params.and_return(1_160_727_311) } + it { is_expected.to run.with_params('').and_return(1_160_727_311) } + it { is_expected.to run.with_params([]).and_return(1_160_727_311) } + it { is_expected.to run.with_params({}).and_return(1_160_727_311) } + it { is_expected.to run.with_params('foo').and_return(1_160_727_311) } + it { is_expected.to run.with_params('UTC').and_return(1_160_727_311) } + it { is_expected.to run.with_params('America/New_York').and_return(1_160_727_311) } end end diff --git a/spec/functions/to_bytes_spec.rb b/spec/functions/to_bytes_spec.rb index 2be23ff2d..f3efd90f0 100755 --- a/spec/functions/to_bytes_spec.rb +++ b/spec/functions/to_bytes_spec.rb @@ -2,11 +2,11 @@ describe 'to_bytes' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } - it { is_expected.to run.with_params('1', 'extras').and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } - it { is_expected.to run.with_params([]).and_raise_error(TypeError, /(can't convert|no implicit conversion of) Array (in)?to String/) } - it { is_expected.to run.with_params({}).and_raise_error(TypeError, /(can't convert|no implicit conversion of) Hash (in)?to String/) } - it { is_expected.to run.with_params(true).and_raise_error(TypeError, /(can't convert|no implicit conversion of) (TrueClass|true) (in)?to String/) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } + it { is_expected.to run.with_params('1', 'extras').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } + it { is_expected.to run.with_params([]).and_raise_error(TypeError, %r{(can't convert|no implicit conversion of) Array (in)?to String}) } + it { is_expected.to run.with_params({}).and_raise_error(TypeError, %r{(can't convert|no implicit conversion of) Hash (in)?to String}) } + it { is_expected.to run.with_params(true).and_raise_error(TypeError, %r{(can't convert|no implicit conversion of) (TrueClass|true) (in)?to String}) } describe 'when passing numbers' do it { is_expected.to run.with_params(0).and_return(0) } @@ -28,22 +28,20 @@ describe 'with a unit' do it { is_expected.to run.with_params('1k').and_return(1024) } it { is_expected.to run.with_params('-1kB').and_return(-1024) } - it { is_expected.to run.with_params('1k').and_return(1024) } - it { is_expected.to run.with_params('1M').and_return(1024*1024) } - it { is_expected.to run.with_params('1G').and_return(1024*1024*1024) } - it { is_expected.to run.with_params('1T').and_return(1024*1024*1024*1024) } - it { is_expected.to run.with_params('1P').and_return(1024*1024*1024*1024*1024) } - it { is_expected.to run.with_params('1E').and_return(1024*1024*1024*1024*1024*1024) } - it { is_expected.to run.with_params('1.5e3M').and_return(1572864000) } + it { is_expected.to run.with_params('1M').and_return(1024 * 1024) } + it { is_expected.to run.with_params('1G').and_return(1024 * 1024 * 1024) } + it { is_expected.to run.with_params('1T').and_return(1024 * 1024 * 1024 * 1024) } + it { is_expected.to run.with_params('1P').and_return(1024 * 1024 * 1024 * 1024 * 1024) } + it { is_expected.to run.with_params('1E').and_return(1024 * 1024 * 1024 * 1024 * 1024 * 1024) } + it { is_expected.to run.with_params('1.5e3M').and_return(1_572_864_000) } - it { is_expected.to run.with_params('4k').and_return(4*1024) } - it { is_expected.to run.with_params('-4kB').and_return(4*-1024) } - it { is_expected.to run.with_params('4k').and_return(4*1024) } - it { is_expected.to run.with_params('4M').and_return(4*1024*1024) } - it { is_expected.to run.with_params('4G').and_return(4*1024*1024*1024) } - it { is_expected.to run.with_params('4T').and_return(4*1024*1024*1024*1024) } - it { is_expected.to run.with_params('4P').and_return(4*1024*1024*1024*1024*1024) } - it { is_expected.to run.with_params('4E').and_return(4*1024*1024*1024*1024*1024*1024) } + it { is_expected.to run.with_params('4k').and_return(4 * 1024) } + it { is_expected.to run.with_params('-4kB').and_return(4 * -1024) } + it { is_expected.to run.with_params('4M').and_return(4 * 1024 * 1024) } + it { is_expected.to run.with_params('4G').and_return(4 * 1024 * 1024 * 1024) } + it { is_expected.to run.with_params('4T').and_return(4 * 1024 * 1024 * 1024 * 1024) } + it { is_expected.to run.with_params('4P').and_return(4 * 1024 * 1024 * 1024 * 1024 * 1024) } + it { is_expected.to run.with_params('4E').and_return(4 * 1024 * 1024 * 1024 * 1024 * 1024 * 1024) } # these are so wrong it { is_expected.to run.with_params('1.0001 k').and_return(1024) } @@ -51,12 +49,12 @@ end describe 'with a unknown unit' do - it { is_expected.to run.with_params('1KB').and_raise_error(Puppet::ParseError, /Unknown prefix/) } - it { is_expected.to run.with_params('1K').and_raise_error(Puppet::ParseError, /Unknown prefix/) } - it { is_expected.to run.with_params('1mb').and_raise_error(Puppet::ParseError, /Unknown prefix/) } - it { is_expected.to run.with_params('1m').and_raise_error(Puppet::ParseError, /Unknown prefix/) } - it { is_expected.to run.with_params('1%').and_raise_error(Puppet::ParseError, /Unknown prefix/) } - it { is_expected.to run.with_params('1 p').and_raise_error(Puppet::ParseError, /Unknown prefix/) } + it { is_expected.to run.with_params('1KB').and_raise_error(Puppet::ParseError, %r{Unknown prefix}) } + it { is_expected.to run.with_params('1K').and_raise_error(Puppet::ParseError, %r{Unknown prefix}) } + it { is_expected.to run.with_params('1mb').and_raise_error(Puppet::ParseError, %r{Unknown prefix}) } + it { is_expected.to run.with_params('1m').and_raise_error(Puppet::ParseError, %r{Unknown prefix}) } + it { is_expected.to run.with_params('1%').and_raise_error(Puppet::ParseError, %r{Unknown prefix}) } + it { is_expected.to run.with_params('1 p').and_raise_error(Puppet::ParseError, %r{Unknown prefix}) } end end diff --git a/spec/functions/to_json_pretty_spec.rb b/spec/functions/to_json_pretty_spec.rb index abbcc2c47..f7c245c61 100755 --- a/spec/functions/to_json_pretty_spec.rb +++ b/spec/functions/to_json_pretty_spec.rb @@ -4,8 +4,11 @@ it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params([]).and_return("[\n\n]") } it { is_expected.to run.with_params(['one']).and_return("[\n \"one\"\n]") } - it { is_expected.to run.with_params(['one', 'two']).and_return("[\n \"one\",\n \"two\"\n]") } + it { is_expected.to run.with_params(%w[one two]).and_return("[\n \"one\",\n \"two\"\n]") } it { is_expected.to run.with_params({}).and_return("{\n}") } - it { is_expected.to run.with_params({ 'key' => 'value' }).and_return("{\n \"key\": \"value\"\n}") } - it { is_expected.to run.with_params({"one" => {"oneA" => "A","oneB" => {"oneB1" => "1","oneB2" => "2"}},"two" => ["twoA","twoB"]}).and_return("{\n \"one\": {\n \"oneA\": \"A\",\n \"oneB\": {\n \"oneB1\": \"1\",\n \"oneB2\": \"2\"\n }\n },\n \"two\": [\n \"twoA\",\n \"twoB\"\n ]\n}") } + it { is_expected.to run.with_params('key' => 'value').and_return("{\n \"key\": \"value\"\n}") } + it { + is_expected.to run.with_params('one' => { 'oneA' => 'A', 'oneB' => { 'oneB1' => '1', 'oneB2' => '2' } }, 'two' => %w[twoA twoB]) + .and_return("{\n \"one\": {\n \"oneA\": \"A\",\n \"oneB\": {\n \"oneB1\": \"1\",\n \"oneB2\": \"2\"\n }\n },\n \"two\": [\n \"twoA\",\n \"twoB\"\n ]\n}") # rubocop:disable Metrics/LineLength : Unable to reduce line to required length + } end diff --git a/spec/functions/to_json_spec.rb b/spec/functions/to_json_spec.rb index 925523c2e..187ca3c94 100755 --- a/spec/functions/to_json_spec.rb +++ b/spec/functions/to_json_spec.rb @@ -2,15 +2,18 @@ describe 'to_json' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params('').and_return("\"\"") } - it { is_expected.to run.with_params(true).and_return("true") } - it { is_expected.to run.with_params('one').and_return("\"one\"") } - it { is_expected.to run.with_params([]).and_return("[]") } - it { is_expected.to run.with_params(['one']).and_return("[\"one\"]") } - it { is_expected.to run.with_params(['one', 'two']).and_return("[\"one\",\"two\"]") } - it { is_expected.to run.with_params({}).and_return("{}") } - it { is_expected.to run.with_params({ 'key' => 'value' }).and_return("{\"key\":\"value\"}") } - it { is_expected.to run.with_params({"one" => {"oneA" => "A","oneB" => {"oneB1" => "1","oneB2" => "2"}},"two" => ["twoA","twoB"]}).and_return("{\"one\":{\"oneA\":\"A\",\"oneB\":{\"oneB1\":\"1\",\"oneB2\":\"2\"}},\"two\":[\"twoA\",\"twoB\"]}") } + it { is_expected.to run.with_params('').and_return('""') } + it { is_expected.to run.with_params(true).and_return('true') } + it { is_expected.to run.with_params('one').and_return('"one"') } + it { is_expected.to run.with_params([]).and_return('[]') } + it { is_expected.to run.with_params(['one']).and_return('["one"]') } + it { is_expected.to run.with_params(%w[one two]).and_return('["one","two"]') } + it { is_expected.to run.with_params({}).and_return('{}') } + it { is_expected.to run.with_params('key' => 'value').and_return('{"key":"value"}') } + it { + is_expected.to run.with_params('one' => { 'oneA' => 'A', 'oneB' => { 'oneB1' => '1', 'oneB2' => '2' } }, 'two' => %w[twoA twoB]) + .and_return('{"one":{"oneA":"A","oneB":{"oneB1":"1","oneB2":"2"}},"two":["twoA","twoB"]}') + } it { is_expected.to run.with_params('‰').and_return('"‰"') } it { is_expected.to run.with_params('竹').and_return('"竹"') } diff --git a/spec/functions/to_yaml_spec.rb b/spec/functions/to_yaml_spec.rb index 3f69a70a2..16948f61a 100755 --- a/spec/functions/to_yaml_spec.rb +++ b/spec/functions/to_yaml_spec.rb @@ -7,10 +7,13 @@ it { is_expected.to run.with_params('one').and_return("--- one\n...\n") } it { is_expected.to run.with_params([]).and_return("--- []\n") } it { is_expected.to run.with_params(['one']).and_return("---\n- one\n") } - it { is_expected.to run.with_params(['one', 'two']).and_return("---\n- one\n- two\n") } + it { is_expected.to run.with_params(%w[one two]).and_return("---\n- one\n- two\n") } it { is_expected.to run.with_params({}).and_return("--- {}\n") } - it { is_expected.to run.with_params({ 'key' => 'value' }).and_return("---\nkey: value\n") } - it { is_expected.to run.with_params({"one" => {"oneA" => "A","oneB" => {"oneB1" => "1","oneB2" => "2"}},"two" => ["twoA","twoB"]}).and_return("---\none:\n oneA: A\n oneB:\n oneB1: '1'\n oneB2: '2'\ntwo:\n- twoA\n- twoB\n") } + it { is_expected.to run.with_params('key' => 'value').and_return("---\nkey: value\n") } + it { + is_expected.to run.with_params('one' => { 'oneA' => 'A', 'oneB' => { 'oneB1' => '1', 'oneB2' => '2' } }, 'two' => %w[twoA twoB]) + .and_return("---\none:\n oneA: A\n oneB:\n oneB1: '1'\n oneB2: '2'\ntwo:\n- twoA\n- twoB\n") + } it { is_expected.to run.with_params('‰').and_return("--- \"‰\"\n") } it { is_expected.to run.with_params('∇').and_return("--- \"∇\"\n") } diff --git a/spec/functions/try_get_value_spec.rb b/spec/functions/try_get_value_spec.rb index 38c0efdd2..dc3c9864a 100644 --- a/spec/functions/try_get_value_spec.rb +++ b/spec/functions/try_get_value_spec.rb @@ -1,99 +1,107 @@ require 'spec_helper' describe 'try_get_value' do - let(:data) do { - 'a' => { - 'g' => '2', - 'e' => [ - 'f0', - 'f1', - { - 'x' => { - 'y' => 'z' - } - }, - 'f3', - ] - }, - 'b' => true, - 'c' => false, - 'd' => '1', + 'a' => { + 'g' => '2', + 'e' => [ + 'f0', + 'f1', + { + 'x' => { + 'y' => 'z', + }, + }, + 'f3', + ], + }, + 'b' => true, + 'c' => false, + 'd' => '1', } end context 'single values' do - it 'should exist' do + it 'exists' do is_expected.not_to eq(nil) end - it 'should be able to return a single value' do + it 'is able to return a single value' do is_expected.to run.with_params('test').and_return('test') end - it 'should use the default value if data is a single value and path is present' do + it 'uses the default value if data is a single value and path is present' do is_expected.to run.with_params('test', 'path', 'default').and_return('default') end - it 'should return default if there is no data' do + it 'returns default if there is no data' do is_expected.to run.with_params(nil, nil, 'default').and_return('default') end - it 'should be able to use data structures as default values' do + it 'is able to use data structures as default values' do is_expected.to run.with_params('test', 'path', data).and_return(data) end end context 'structure values' do - it 'should be able to extracts a single hash value' do + it 'is able to extracts a single hash value' do is_expected.to run.with_params(data, 'd', 'default').and_return('1') end - it 'should be able to extract a deeply nested hash value' do + it 'is able to extract a deeply nested hash value' do is_expected.to run.with_params(data, 'a/g', 'default').and_return('2') end - it 'should return the default value if the path is not found' do + it 'returns the default value if the path is not found' do is_expected.to run.with_params(data, 'missing', 'default').and_return('default') end - it 'should return the default value if the path is too long' do + it 'returns the default value if the path is too long' do is_expected.to run.with_params(data, 'a/g/c/d', 'default').and_return('default') end - it 'should support an array index in the path' do + it 'supports an array index in the path' do is_expected.to run.with_params(data, 'a/e/1', 'default').and_return('f1') end - it 'should return the default value if an array index is not a number' do + it 'returns the default value if an array index is not a number' do is_expected.to run.with_params(data, 'a/b/c', 'default').and_return('default') end - it 'should return the default value if and index is out of array length' do + it 'returns the default value if and index is out of array length' do is_expected.to run.with_params(data, 'a/e/5', 'default').and_return('default') end - it 'should be able to path though both arrays and hashes' do + it 'is able to path though both arrays and hashes' do is_expected.to run.with_params(data, 'a/e/2/x/y', 'default').and_return('z') end - it 'should be able to return "true" value' do + it 'is able to return "true" value: default' do is_expected.to run.with_params(data, 'b', 'default').and_return(true) + end + + it 'is able to return "true" value' do is_expected.to run.with_params(data, 'm', true).and_return(true) end - it 'should be able to return "false" value' do + it 'is able to return "false" value: default' do is_expected.to run.with_params(data, 'c', 'default').and_return(false) + end + + it 'is able to return "false" value' do is_expected.to run.with_params(data, 'm', false).and_return(false) end - it 'should return "nil" if value is not found and no default value is provided' do + it 'returns "nil" if value is not found and no default value is provided' do is_expected.to run.with_params(data, 'a/1').and_return(nil) end - it 'should be able to use a custom path separator' do + it 'is able to use a custom path separator' do is_expected.to run.with_params(data, 'a::g', 'default', '::').and_return('2') + end + + it 'is able to use a custom path separator: default' do is_expected.to run.with_params(data, 'a::c', 'default', '::').and_return('default') end end diff --git a/spec/functions/type3x_spec.rb b/spec/functions/type3x_spec.rb index c3eb1deee..3a71ed9f0 100644 --- a/spec/functions/type3x_spec.rb +++ b/spec/functions/type3x_spec.rb @@ -1,40 +1,40 @@ require 'spec_helper' describe 'type3x' do - it "should exist" do - expect(Puppet::Parser::Functions.function("type3x")).to eq("function_type3x") + it 'exists' do + expect(Puppet::Parser::Functions.function('type3x')).to eq('function_type3x') end - it "should raise a ParseError if there is less than 1 arguments" do - expect { scope.function_type3x([]) }.to( raise_error(Puppet::ParseError)) + it 'raises a ParseError if there is less than 1 arguments' do + expect { scope.function_type3x([]) }.to(raise_error(Puppet::ParseError)) end - it "should return string when given a string" do - result = scope.function_type3x(["aaabbbbcccc"]) + it 'returns string when given a string' do + result = scope.function_type3x(['aaabbbbcccc']) expect(result).to(eq('string')) end - it "should return array when given an array" do - result = scope.function_type3x([["aaabbbbcccc","asdf"]]) + it 'returns array when given an array' do + result = scope.function_type3x([%w[aaabbbbcccc asdf]]) expect(result).to(eq('array')) end - it "should return hash when given a hash" do - result = scope.function_type3x([{"a"=>1,"b"=>2}]) + it 'returns hash when given a hash' do + result = scope.function_type3x([{ 'a' => 1, 'b' => 2 }]) expect(result).to(eq('hash')) end - it "should return integer when given an integer" do - result = scope.function_type3x(["1"]) + it 'returns integer when given an integer' do + result = scope.function_type3x(['1']) expect(result).to(eq('integer')) end - it "should return float when given a float" do - result = scope.function_type3x(["1.34"]) + it 'returns float when given a float' do + result = scope.function_type3x(['1.34']) expect(result).to(eq('float')) end - it "should return boolean when given a boolean" do + it 'returns boolean when given a boolean' do result = scope.function_type3x([true]) expect(result).to(eq('boolean')) end diff --git a/spec/functions/type_of_spec.rb b/spec/functions/type_of_spec.rb index cc9ef781c..4f55b2c03 100644 --- a/spec/functions/type_of_spec.rb +++ b/spec/functions/type_of_spec.rb @@ -1,6 +1,6 @@ require 'spec_helper' -if ENV["FUTURE_PARSER"] == 'yes' +if ENV['FUTURE_PARSER'] == 'yes' describe 'type_of' do pending 'teach rspec-puppet to load future-only functions under 3.7.5' do it { is_expected.not_to eq(nil) } @@ -11,7 +11,7 @@ if Puppet.version.to_f >= 4.0 describe 'type_of' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(ArgumentError) } + it { is_expected.to run.with_params.and_raise_error(ArgumentError) } it { is_expected.to run.with_params('', '').and_raise_error(ArgumentError) } it 'gives the type of a string' do diff --git a/spec/functions/type_spec.rb b/spec/functions/type_spec.rb index 4288df09b..a28a91338 100755 --- a/spec/functions/type_spec.rb +++ b/spec/functions/type_spec.rb @@ -1,41 +1,41 @@ require 'spec_helper' describe 'type' do - it "should exist" do - expect(Puppet::Parser::Functions.function("type")).to eq("function_type") + it 'exists' do + expect(Puppet::Parser::Functions.function('type')).to eq('function_type') end - it "should give a deprecation warning when called" do - scope.expects(:warning).with("type() DEPRECATED: This function will cease to function on Puppet 4; please use type3x() before upgrading to puppet 4 for backwards-compatibility, or migrate to the new parser's typing system.") - scope.function_type(["aoeu"]) + it 'gives a deprecation warning when called' do + scope.expects(:warning).with("type() DEPRECATED: This function will cease to function on Puppet 4; please use type3x() before upgrading to puppet 4 for backwards-compatibility, or migrate to the new parser's typing system.") # rubocop:disable Metrics/LineLength : Unable to reduce to required length + scope.function_type(['aoeu']) end - it "should return string when given a string" do - result = scope.function_type(["aaabbbbcccc"]) + it 'returns string when given a string' do + result = scope.function_type(['aaabbbbcccc']) expect(result).to(eq('string')) end - it "should return array when given an array" do - result = scope.function_type([["aaabbbbcccc","asdf"]]) + it 'returns array when given an array' do + result = scope.function_type([%w[aaabbbbcccc asdf]]) expect(result).to(eq('array')) end - it "should return hash when given a hash" do - result = scope.function_type([{"a"=>1,"b"=>2}]) + it 'returns hash when given a hash' do + result = scope.function_type([{ 'a' => 1, 'b' => 2 }]) expect(result).to(eq('hash')) end - it "should return integer when given an integer" do - result = scope.function_type(["1"]) + it 'returns integer when given an integer' do + result = scope.function_type(['1']) expect(result).to(eq('integer')) end - it "should return float when given a float" do - result = scope.function_type(["1.34"]) + it 'returns float when given a float' do + result = scope.function_type(['1.34']) expect(result).to(eq('float')) end - it "should return boolean when given a boolean" do + it 'returns boolean when given a boolean' do result = scope.function_type([true]) expect(result).to(eq('boolean')) end diff --git a/spec/functions/union_spec.rb b/spec/functions/union_spec.rb index 3f36f24a3..d8dfc4fa8 100755 --- a/spec/functions/union_spec.rb +++ b/spec/functions/union_spec.rb @@ -3,23 +3,23 @@ describe 'union' do describe 'argument checking' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } - it { is_expected.to run.with_params('one').and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } - it { is_expected.to run.with_params('one', []).and_raise_error(Puppet::ParseError, /Every parameter must be an array/) } - it { is_expected.to run.with_params([], 'two').and_raise_error(Puppet::ParseError, /Every parameter must be an array/) } - it { is_expected.to run.with_params({}, {}).and_raise_error(Puppet::ParseError, /Every parameter must be an array/) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } + it { is_expected.to run.with_params('one').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } + it { is_expected.to run.with_params('one', []).and_raise_error(Puppet::ParseError, %r{Every parameter must be an array}) } + it { is_expected.to run.with_params([], 'two').and_raise_error(Puppet::ParseError, %r{Every parameter must be an array}) } + it { is_expected.to run.with_params({}, {}).and_raise_error(Puppet::ParseError, %r{Every parameter must be an array}) } end it { is_expected.to run.with_params([], []).and_return([]) } it { is_expected.to run.with_params([], ['one']).and_return(['one']) } it { is_expected.to run.with_params(['one'], []).and_return(['one']) } it { is_expected.to run.with_params(['one'], ['one']).and_return(['one']) } - it { is_expected.to run.with_params(['one'], ['two']).and_return(['one', 'two']) } - it { is_expected.to run.with_params(['one', 'two', 'three'], ['two', 'three']).and_return(['one', 'two', 'three']) } - it { is_expected.to run.with_params(['one', 'two', 'two', 'three'], ['two', 'three']).and_return(['one', 'two', 'three']) } - it { is_expected.to run.with_params(['one', 'two', 'three'], ['two', 'two', 'three']).and_return(['one', 'two', 'three']) } - it { is_expected.to run.with_params(['one', 'two'], ['two', 'three'], ['one', 'three']).and_return(['one', 'two', 'three']) } - it { is_expected.to run.with_params(['one', 'two'], ['three', 'four'], ['one', 'two', 'three'], ['four']).and_return(['one', 'two', 'three', 'four']) } - it { is_expected.to run.with_params(['ốńə', 'ţשׂợ'], ['ŧĥяếệ', 'ƒởųŗ'], ['ốńə', 'ţשׂợ', 'ŧĥяếệ'], ['ƒởųŗ']).and_return(['ốńə', 'ţשׂợ', 'ŧĥяếệ', 'ƒởųŗ']) } - it 'should not confuse types' do is_expected.to run.with_params(['1', '2', '3'], [1, 2]).and_return(['1', '2', '3', 1, 2]) end + it { is_expected.to run.with_params(['one'], ['two']).and_return(%w[one two]) } + it { is_expected.to run.with_params(%w[one two three], %w[two three]).and_return(%w[one two three]) } + it { is_expected.to run.with_params(%w[one two two three], %w[two three]).and_return(%w[one two three]) } + it { is_expected.to run.with_params(%w[one two three], %w[two two three]).and_return(%w[one two three]) } + it { is_expected.to run.with_params(%w[one two], %w[two three], %w[one three]).and_return(%w[one two three]) } + it { is_expected.to run.with_params(%w[one two], %w[three four], %w[one two three], ['four']).and_return(%w[one two three four]) } + it { is_expected.to run.with_params(%w[ốńə ţשׂợ], %w[ŧĥяếệ ƒởųŗ], %w[ốńə ţשׂợ ŧĥяếệ], ['ƒởųŗ']).and_return(%w[ốńə ţשׂợ ŧĥяếệ ƒởųŗ]) } + it 'does not confuse types' do is_expected.to run.with_params(%w[1 2 3], [1, 2]).and_return(['1', '2', '3', 1, 2]) end end diff --git a/spec/functions/unique_spec.rb b/spec/functions/unique_spec.rb index 76932ecac..b8481e029 100755 --- a/spec/functions/unique_spec.rb +++ b/spec/functions/unique_spec.rb @@ -4,21 +4,21 @@ if Puppet.version.to_f < 5.0 describe 'signature validation' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { - pending("Current implementation ignores parameters after the first.") - is_expected.to run.with_params([], 'extra').and_raise_error(Puppet::ParseError, /wrong number of arguments/i) + pending('Current implementation ignores parameters after the first.') + is_expected.to run.with_params([], 'extra').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } - it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, /Requires either array or string to work/) } - it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, /Requires either array or string to work/) } - it { is_expected.to run.with_params(true).and_raise_error(Puppet::ParseError, /Requires either array or string to work/) } + it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work}) } + it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work}) } + it { is_expected.to run.with_params(true).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work}) } end context 'when called with an array' do it { is_expected.to run.with_params([]).and_return([]) } it { is_expected.to run.with_params(['a']).and_return(['a']) } - it { is_expected.to run.with_params(['a', 'b', 'a']).and_return(['a', 'b']) } - it { is_expected.to run.with_params(['ã', 'ъ', 'ã']).and_return(['ã', 'ъ']) } + it { is_expected.to run.with_params(%w[a b a]).and_return(%w[a b]) } + it { is_expected.to run.with_params(%w[ã ъ ã]).and_return(%w[ã ъ]) } end context 'when called with a string' do diff --git a/spec/functions/unix2dos_spec.rb b/spec/functions/unix2dos_spec.rb index 8537a26fa..49fb408cf 100644 --- a/spec/functions/unix2dos_spec.rb +++ b/spec/functions/unix2dos_spec.rb @@ -4,10 +4,10 @@ context 'Checking parameter validity' do it { is_expected.not_to eq(nil) } it do - is_expected.to run.with_params.and_raise_error(ArgumentError, /Wrong number of arguments/) + is_expected.to run.with_params.and_raise_error(ArgumentError, %r{Wrong number of arguments}) end it do - is_expected.to run.with_params('one', 'two').and_raise_error(ArgumentError, /Wrong number of arguments/) + is_expected.to run.with_params('one', 'two').and_raise_error(ArgumentError, %r{Wrong number of arguments}) end it do is_expected.to run.with_params([]).and_raise_error(Puppet::ParseError) @@ -24,8 +24,8 @@ sample_text = "Hello\nWorld\n" desired_output = "Hello\r\nWorld\r\n" - it 'should output dos format' do - should run.with_params(sample_text).and_return(desired_output) + it 'outputs dos format' do + is_expected.to run.with_params(sample_text).and_return(desired_output) end end @@ -33,8 +33,8 @@ sample_text = "Hello\r\nWorld\r\n" desired_output = "Hello\r\nWorld\r\n" - it 'should output dos format' do - should run.with_params(sample_text).and_return(desired_output) + it 'outputs dos format' do + is_expected.to run.with_params(sample_text).and_return(desired_output) end end end diff --git a/spec/functions/upcase_spec.rb b/spec/functions/upcase_spec.rb index 3b7b02d47..2ef52824a 100755 --- a/spec/functions/upcase_spec.rb +++ b/spec/functions/upcase_spec.rb @@ -3,24 +3,24 @@ describe 'upcase' do describe 'signature validation' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } - it { is_expected.to run.with_params('', '').and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } - it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, /Requires an array, hash or object that responds to upcase/) } - it { is_expected.to run.with_params([1]).and_raise_error(Puppet::ParseError, /Requires an array, hash or object that responds to upcase/) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } + it { is_expected.to run.with_params('', '').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } + it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{Requires an array, hash or object that responds to upcase}) } + it { is_expected.to run.with_params([1]).and_raise_error(Puppet::ParseError, %r{Requires an array, hash or object that responds to upcase}) } end describe 'normal string handling' do - it { is_expected.to run.with_params("abc").and_return("ABC") } - it { is_expected.to run.with_params("Abc").and_return("ABC") } - it { is_expected.to run.with_params("ABC").and_return("ABC") } + it { is_expected.to run.with_params('abc').and_return('ABC') } + it { is_expected.to run.with_params('Abc').and_return('ABC') } + it { is_expected.to run.with_params('ABC').and_return('ABC') } end describe 'handling classes derived from String' do - it { is_expected.to run.with_params(AlsoString.new("ABC")).and_return("ABC") } + it { is_expected.to run.with_params(AlsoString.new('ABC')).and_return('ABC') } end describe 'strings in arrays handling' do it { is_expected.to run.with_params([]).and_return([]) } - it { is_expected.to run.with_params(["One", "twO"]).and_return(["ONE", "TWO"]) } + it { is_expected.to run.with_params(%w[One twO]).and_return(%w[ONE TWO]) } end end diff --git a/spec/functions/uriescape_spec.rb b/spec/functions/uriescape_spec.rb index f05ec088c..3f1fd9d4e 100755 --- a/spec/functions/uriescape_spec.rb +++ b/spec/functions/uriescape_spec.rb @@ -3,34 +3,34 @@ describe 'uriescape' do describe 'signature validation' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { - pending("Current implementation ignores parameters after the first.") - is_expected.to run.with_params('', '').and_raise_error(Puppet::ParseError, /wrong number of arguments/i) + pending('Current implementation ignores parameters after the first.') + is_expected.to run.with_params('', '').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } - it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, /Requires either array or string to work/) } - it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, /Requires either array or string to work/) } - it { is_expected.to run.with_params(true).and_raise_error(Puppet::ParseError, /Requires either array or string to work/) } + it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work}) } + it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work}) } + it { is_expected.to run.with_params(true).and_raise_error(Puppet::ParseError, %r{Requires either array or string to work}) } end describe 'handling normal strings' do - it 'should call ruby\'s URI.escape function' do + it 'calls ruby\'s URI.escape function' do URI.expects(:escape).with('uri_string').returns('escaped_uri_string').once - is_expected.to run.with_params('uri_string').and_return('escaped_uri_string') + is_expected.to run.with_params('uri_string').and_return('escaped_uri_string') end end describe 'handling classes derived from String' do - it 'should call ruby\'s URI.escape function' do + it 'calls ruby\'s URI.escape function' do uri_string = AlsoString.new('uri_string') URI.expects(:escape).with(uri_string).returns('escaped_uri_string').once - is_expected.to run.with_params(uri_string).and_return("escaped_uri_string") + is_expected.to run.with_params(uri_string).and_return('escaped_uri_string') end end describe 'strings in arrays handling' do it { is_expected.to run.with_params([]).and_return([]) } - it { is_expected.to run.with_params(["one}", "two"]).and_return(["one%7D", "two"]) } - it { is_expected.to run.with_params(["one}", 1, true, {}, "two"]).and_return(["one%7D", 1, true, {}, "two"]) } + it { is_expected.to run.with_params(['one}', 'two']).and_return(['one%7D', 'two']) } + it { is_expected.to run.with_params(['one}', 1, true, {}, 'two']).and_return(['one%7D', 1, true, {}, 'two']) } end end diff --git a/spec/functions/validate_absolute_path_spec.rb b/spec/functions/validate_absolute_path_spec.rb index 9397da5cc..54f8cb427 100755 --- a/spec/functions/validate_absolute_path_spec.rb +++ b/spec/functions/validate_absolute_path_spec.rb @@ -1,24 +1,24 @@ require 'spec_helper' describe 'validate_absolute_path' do - after(:all) do + after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end # Checking for deprecation warning - it 'should display a single deprecation' do - ENV['STDLIB_LOG_DEPRECATIONS'] = "true" + it 'displays a single deprecation' do + ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' scope.expects(:warning).with(includes('This method is deprecated')) is_expected.to run.with_params('c:/') end describe 'signature validation' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } end - describe "valid paths handling" do - %w{ + describe 'valid paths handling' do + %w[ C:/ C:\\ C:\\WINDOWS\\System32 @@ -30,7 +30,7 @@ / /var/tmp /var/opt/../lib/puppet - }.each do |path| + ].each do |path| it { is_expected.to run.with_params(path) } it { is_expected.to run.with_params(['/tmp', path]) } end @@ -40,20 +40,20 @@ context 'garbage inputs' do [ nil, - [ nil ], - [ nil, nil ], + [nil], + [nil, nil], { 'foo' => 'bar' }, - { }, + {}, '', ].each do |path| - it { is_expected.to run.with_params(path).and_raise_error(Puppet::ParseError, /is not an absolute path/) } - it { is_expected.to run.with_params([path]).and_raise_error(Puppet::ParseError, /is not an absolute path/) } - it { is_expected.to run.with_params(['/tmp', path]).and_raise_error(Puppet::ParseError, /is not an absolute path/) } + it { is_expected.to run.with_params(path).and_raise_error(Puppet::ParseError, %r{is not an absolute path}) } + it { is_expected.to run.with_params([path]).and_raise_error(Puppet::ParseError, %r{is not an absolute path}) } + it { is_expected.to run.with_params(['/tmp', path]).and_raise_error(Puppet::ParseError, %r{is not an absolute path}) } end end context 'relative paths' do - %w{ + %w[ relative1 . .. @@ -62,12 +62,11 @@ etc/puppetlabs/puppet opt/puppet/bin relative\\windows - }.each do |path| - it { is_expected.to run.with_params(path).and_raise_error(Puppet::ParseError, /is not an absolute path/) } - it { is_expected.to run.with_params([path]).and_raise_error(Puppet::ParseError, /is not an absolute path/) } - it { is_expected.to run.with_params(['/tmp', path]).and_raise_error(Puppet::ParseError, /is not an absolute path/) } + ].each do |path| + it { is_expected.to run.with_params(path).and_raise_error(Puppet::ParseError, %r{is not an absolute path}) } + it { is_expected.to run.with_params([path]).and_raise_error(Puppet::ParseError, %r{is not an absolute path}) } + it { is_expected.to run.with_params(['/tmp', path]).and_raise_error(Puppet::ParseError, %r{is not an absolute path}) } end end end end - diff --git a/spec/functions/validate_array_spec.rb b/spec/functions/validate_array_spec.rb index 409b3dc71..660974ae4 100755 --- a/spec/functions/validate_array_spec.rb +++ b/spec/functions/validate_array_spec.rb @@ -1,19 +1,18 @@ require 'spec_helper' describe 'validate_array' do - describe 'signature validation' do - after(:all) do + after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end it { is_expected.not_to eq(nil) } # Checking for deprecation warning - it 'should display a single deprecation' do - ENV['STDLIB_LOG_DEPRECATIONS'] = "true" + it 'displays a single deprecation' do + ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' scope.expects(:warning).with(includes('This method is deprecated')) is_expected.to run.with_params([]) end - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } describe 'valid inputs' do it { is_expected.to run.with_params([]) } @@ -23,15 +22,14 @@ end describe 'invalid inputs' do - it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, /is not an Array/) } - it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, /is not an Array/) } - it { is_expected.to run.with_params(true).and_raise_error(Puppet::ParseError, /is not an Array/) } - it { is_expected.to run.with_params('one').and_raise_error(Puppet::ParseError, /is not an Array/) } - it { is_expected.to run.with_params([], {}).and_raise_error(Puppet::ParseError, /is not an Array/) } - it { is_expected.to run.with_params([], 1).and_raise_error(Puppet::ParseError, /is not an Array/) } - it { is_expected.to run.with_params([], true).and_raise_error(Puppet::ParseError, /is not an Array/) } - it { is_expected.to run.with_params([], 'one').and_raise_error(Puppet::ParseError, /is not an Array/) } + it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, %r{is not an Array}) } + it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{is not an Array}) } + it { is_expected.to run.with_params(true).and_raise_error(Puppet::ParseError, %r{is not an Array}) } + it { is_expected.to run.with_params('one').and_raise_error(Puppet::ParseError, %r{is not an Array}) } + it { is_expected.to run.with_params([], {}).and_raise_error(Puppet::ParseError, %r{is not an Array}) } + it { is_expected.to run.with_params([], 1).and_raise_error(Puppet::ParseError, %r{is not an Array}) } + it { is_expected.to run.with_params([], true).and_raise_error(Puppet::ParseError, %r{is not an Array}) } + it { is_expected.to run.with_params([], 'one').and_raise_error(Puppet::ParseError, %r{is not an Array}) } end end end - diff --git a/spec/functions/validate_augeas_spec.rb b/spec/functions/validate_augeas_spec.rb index 4236649d6..2dd0df897 100755 --- a/spec/functions/validate_augeas_spec.rb +++ b/spec/functions/validate_augeas_spec.rb @@ -1,21 +1,19 @@ require 'spec_helper' describe 'validate_augeas' do - unless Puppet.features.augeas? - skip "ruby-augeas not installed" - else + if Puppet.features.augeas? describe 'signature validation' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } - it { is_expected.to run.with_params('').and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } - it { is_expected.to run.with_params('', '', [], '', 'extra').and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } + it { is_expected.to run.with_params('').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } + it { is_expected.to run.with_params('', '', [], '', 'extra').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('one', 'one', 'MSG to User', '4th arg').and_raise_error(NoMethodError) } end describe 'valid inputs' do inputs = [ - [ "root:x:0:0:root:/root:/bin/bash\n", 'Passwd.lns' ], - [ "proc /proc proc nodev,noexec,nosuid 0 0\n", 'Fstab.lns'], + ["root:x:0:0:root:/root:/bin/bash\n", 'Passwd.lns'], + ["proc /proc proc nodev,noexec,nosuid 0 0\n", 'Fstab.lns'], ] inputs.each do |input| @@ -28,32 +26,32 @@ # don't specify an error message to display. This is the behvior in # 2.2.x and prior. inputs = [ - [ "root:x:0:0:root\n", 'Passwd.lns' ], - [ "127.0.1.1\n", 'Hosts.lns' ], + ["root:x:0:0:root\n", 'Passwd.lns'], + ["127.0.1.1\n", 'Hosts.lns'], ] inputs.each do |input| - it { is_expected.to run.with_params(*input).and_raise_error(Puppet::ParseError, /validate_augeas.*?matched less than it should/) } + it { is_expected.to run.with_params(*input).and_raise_error(Puppet::ParseError, %r{validate_augeas.*?matched less than it should}) } end end - describe "when specifying nice error messages" do + describe 'when specifying nice error messages' do # The intent here is to make sure the function returns the 4th argument # in the exception thrown inputs = [ - [ "root:x:0:0:root\n", 'Passwd.lns', [], 'Failed to validate passwd content' ], - [ "127.0.1.1\n", 'Hosts.lns', [], 'Wrong hosts content' ], + ["root:x:0:0:root\n", 'Passwd.lns', [], 'Failed to validate passwd content'], + ["127.0.1.1\n", 'Hosts.lns', [], 'Wrong hosts content'], ] inputs.each do |input| - it { is_expected.to run.with_params(*input).and_raise_error(Puppet::ParseError, /#{input[3]}/) } + it { is_expected.to run.with_params(*input).and_raise_error(Puppet::ParseError, %r{#{input[3]}}) } end end - describe "matching additional tests" do + describe 'matching additional tests' do inputs = [ - [ "root:x:0:0:root:/root:/bin/bash\n", 'Passwd.lns', ['$file/foobar']], - [ "root:x:0:0:root:/root:/bin/bash\n", 'Passwd.lns', ['$file/root/shell[.="/bin/sh"]', 'foobar']], + ["root:x:0:0:root:/root:/bin/bash\n", 'Passwd.lns', ['$file/foobar']], + ["root:x:0:0:root:/root:/bin/bash\n", 'Passwd.lns', ['$file/root/shell[.="/bin/sh"]', 'foobar']], ] inputs.each do |input| @@ -61,15 +59,17 @@ end end - describe "failing additional tests" do + describe 'failing additional tests' do inputs = [ - [ "foobar:x:0:0:root:/root:/bin/bash\n", 'Passwd.lns', ['$file/foobar']], - [ "root:x:0:0:root:/root:/bin/sh\n", 'Passwd.lns', ['$file/root/shell[.="/bin/sh"]', 'foobar']], + ["foobar:x:0:0:root:/root:/bin/bash\n", 'Passwd.lns', ['$file/foobar']], + ["root:x:0:0:root:/root:/bin/sh\n", 'Passwd.lns', ['$file/root/shell[.="/bin/sh"]', 'foobar']], ] inputs.each do |input| - it { is_expected.to run.with_params(*input).and_raise_error(Puppet::ParseError, /testing path/) } + it { is_expected.to run.with_params(*input).and_raise_error(Puppet::ParseError, %r{testing path}) } end end + else + skip 'ruby-augeas not installed' end end diff --git a/spec/functions/validate_bool_spec.rb b/spec/functions/validate_bool_spec.rb index 3074d8853..565d52e33 100755 --- a/spec/functions/validate_bool_spec.rb +++ b/spec/functions/validate_bool_spec.rb @@ -1,20 +1,20 @@ require 'spec_helper' describe 'validate_bool' do - after(:all) do + after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end # Checking for deprecation warning - it 'should display a single deprecation' do - ENV['STDLIB_LOG_DEPRECATIONS'] = "true" + it 'displays a single deprecation' do + ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' scope.expects(:warning).with(includes('This method is deprecated')) is_expected.to run.with_params(true) end describe 'signature validation' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } end describe 'acceptable values' do @@ -24,13 +24,13 @@ end describe 'validation failures' do - it { is_expected.to run.with_params('one').and_raise_error(Puppet::ParseError, /is not a boolean/) } - it { is_expected.to run.with_params(true, 'one').and_raise_error(Puppet::ParseError, /is not a boolean/) } - it { is_expected.to run.with_params('one', false).and_raise_error(Puppet::ParseError, /is not a boolean/) } - it { is_expected.to run.with_params("true").and_raise_error(Puppet::ParseError, /is not a boolean/) } - it { is_expected.to run.with_params("false").and_raise_error(Puppet::ParseError, /is not a boolean/) } - it { is_expected.to run.with_params(true, "false").and_raise_error(Puppet::ParseError, /is not a boolean/) } - it { is_expected.to run.with_params("true", false).and_raise_error(Puppet::ParseError, /is not a boolean/) } - it { is_expected.to run.with_params("true", false, false, false, false, false).and_raise_error(Puppet::ParseError, /is not a boolean/) } + it { is_expected.to run.with_params('one').and_raise_error(Puppet::ParseError, %r{is not a boolean}) } + it { is_expected.to run.with_params(true, 'one').and_raise_error(Puppet::ParseError, %r{is not a boolean}) } + it { is_expected.to run.with_params('one', false).and_raise_error(Puppet::ParseError, %r{is not a boolean}) } + it { is_expected.to run.with_params('true').and_raise_error(Puppet::ParseError, %r{is not a boolean}) } + it { is_expected.to run.with_params('false').and_raise_error(Puppet::ParseError, %r{is not a boolean}) } + it { is_expected.to run.with_params(true, 'false').and_raise_error(Puppet::ParseError, %r{is not a boolean}) } + it { is_expected.to run.with_params('true', false).and_raise_error(Puppet::ParseError, %r{is not a boolean}) } + it { is_expected.to run.with_params('true', false, false, false, false, false).and_raise_error(Puppet::ParseError, %r{is not a boolean}) } end end diff --git a/spec/functions/validate_cmd_spec.rb b/spec/functions/validate_cmd_spec.rb index c6559e8c2..589846f16 100755 --- a/spec/functions/validate_cmd_spec.rb +++ b/spec/functions/validate_cmd_spec.rb @@ -1,35 +1,41 @@ require 'spec_helper' -describe 'validate_cmd', :unless => Puppet::Util::Platform.windows? do - let(:touch) { File.exists?('/usr/bin/touch') ? '/usr/bin/touch' : '/bin/touch' } +describe 'validate_cmd', unless: Puppet::Util::Platform.windows? do + let(:touch) { File.exist?('/usr/bin/touch') ? '/usr/bin/touch' : '/bin/touch' } describe 'signature validation' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } - it { is_expected.to run.with_params('').and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } - it { is_expected.to run.with_params('', '', '', 'extra').and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } + it { is_expected.to run.with_params('').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } + it { is_expected.to run.with_params('', '', '', 'extra').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { pending('should implement stricter type checking') - is_expected.to run.with_params([], '', '').and_raise_error(Puppet::ParseError, /content must be a string/) + is_expected.to run.with_params([], '', '').and_raise_error(Puppet::ParseError, %r{content must be a string}) } it { pending('should implement stricter type checking') - is_expected.to run.with_params('', [], '').and_raise_error(Puppet::ParseError, /checkscript must be a string/) + is_expected.to run.with_params('', [], '').and_raise_error(Puppet::ParseError, %r{checkscript must be a string}) } it { pending('should implement stricter type checking') - is_expected.to run.with_params('', '', []).and_raise_error(Puppet::ParseError, /custom error message must be a string/) + is_expected.to run.with_params('', '', []).and_raise_error(Puppet::ParseError, %r{custom error message must be a string}) } end context 'when validation fails' do context 'with % placeholder' do - it { is_expected.to run.with_params('', "#{touch} % /no/such/file").and_raise_error(Puppet::ParseError, /Execution of '#{touch} \S+ \/no\/such\/file' returned 1:.*(cannot touch|o such file or)/) } - it { is_expected.to run.with_params('', "#{touch} % /no/such/file", 'custom error').and_raise_error(Puppet::ParseError, /custom error/) } + it { + is_expected.to run + .with_params('', "#{touch} % /no/such/file").and_raise_error(Puppet::ParseError, %r{Execution of '#{touch} \S+ \/no\/such\/file' returned 1:.*(cannot touch|o such file or)}) + } + it { is_expected.to run.with_params('', "#{touch} % /no/such/file", 'custom error').and_raise_error(Puppet::ParseError, %r{custom error}) } end context 'without % placeholder' do - it { is_expected.to run.with_params('', "#{touch} /no/such/file").and_raise_error(Puppet::ParseError, /Execution of '#{touch} \/no\/such\/file \S+' returned 1:.*(cannot touch|o such file or)/) } - it { is_expected.to run.with_params('', "#{touch} /no/such/file", 'custom error').and_raise_error(Puppet::ParseError, /custom error/) } + it { + is_expected.to run + .with_params('', "#{touch} /no/such/file").and_raise_error(Puppet::ParseError, %r{Execution of '#{touch} \/no\/such\/file \S+' returned 1:.*(cannot touch|o such file or)}) + } + it { is_expected.to run.with_params('', "#{touch} /no/such/file", 'custom error').and_raise_error(Puppet::ParseError, %r{custom error}) } end end end diff --git a/spec/functions/validate_domain_name_spec.rb b/spec/functions/validate_domain_name_spec.rb index 69fcae4a2..0ac1a3d35 100644 --- a/spec/functions/validate_domain_name_spec.rb +++ b/spec/functions/validate_domain_name_spec.rb @@ -3,7 +3,7 @@ describe 'validate_domain_name' do describe 'signature validation' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } end describe 'valid inputs' do @@ -16,20 +16,20 @@ end describe 'invalid inputs' do - it { is_expected.to run.with_params([]).and_raise_error(Puppet::ParseError, /is not a string/) } - it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, /is not a string/) } - it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, /is not a string/) } - it { is_expected.to run.with_params(true).and_raise_error(Puppet::ParseError, /is not a string/) } + it { is_expected.to run.with_params([]).and_raise_error(Puppet::ParseError, %r{is not a string}) } + it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, %r{is not a string}) } + it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{is not a string}) } + it { is_expected.to run.with_params(true).and_raise_error(Puppet::ParseError, %r{is not a string}) } - it { is_expected.to run.with_params('foo.example.com', []).and_raise_error(Puppet::ParseError, /is not a string/) } - it { is_expected.to run.with_params('foo.example.com', {}).and_raise_error(Puppet::ParseError, /is not a string/) } - it { is_expected.to run.with_params('foo.example.com', 1).and_raise_error(Puppet::ParseError, /is not a string/) } - it { is_expected.to run.with_params('foo.example.com', true).and_raise_error(Puppet::ParseError, /is not a string/) } + it { is_expected.to run.with_params('foo.example.com', []).and_raise_error(Puppet::ParseError, %r{is not a string}) } + it { is_expected.to run.with_params('foo.example.com', {}).and_raise_error(Puppet::ParseError, %r{is not a string}) } + it { is_expected.to run.with_params('foo.example.com', 1).and_raise_error(Puppet::ParseError, %r{is not a string}) } + it { is_expected.to run.with_params('foo.example.com', true).and_raise_error(Puppet::ParseError, %r{is not a string}) } - it { is_expected.to run.with_params('').and_raise_error(Puppet::ParseError, /is not a syntactically correct domain name/) } - it { is_expected.to run.with_params('invalid domain').and_raise_error(Puppet::ParseError, /is not a syntactically correct domain name/) } - it { is_expected.to run.with_params('-foo.example.com').and_raise_error(Puppet::ParseError, /is not a syntactically correct domain name/) } - it { is_expected.to run.with_params('www.example.2com').and_raise_error(Puppet::ParseError, /is not a syntactically correct domain name/) } - it { is_expected.to run.with_params('192.168.1.1').and_raise_error(Puppet::ParseError, /is not a syntactically correct domain name/) } + it { is_expected.to run.with_params('').and_raise_error(Puppet::ParseError, %r{is not a syntactically correct domain name}) } + it { is_expected.to run.with_params('invalid domain').and_raise_error(Puppet::ParseError, %r{is not a syntactically correct domain name}) } + it { is_expected.to run.with_params('-foo.example.com').and_raise_error(Puppet::ParseError, %r{is not a syntactically correct domain name}) } + it { is_expected.to run.with_params('www.example.2com').and_raise_error(Puppet::ParseError, %r{is not a syntactically correct domain name}) } + it { is_expected.to run.with_params('192.168.1.1').and_raise_error(Puppet::ParseError, %r{is not a syntactically correct domain name}) } end end diff --git a/spec/functions/validate_email_address_spec.rb b/spec/functions/validate_email_address_spec.rb index 762838344..520c7a486 100644 --- a/spec/functions/validate_email_address_spec.rb +++ b/spec/functions/validate_email_address_spec.rb @@ -3,7 +3,7 @@ describe 'validate_email_address' do describe 'signature validation' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } end describe 'valid inputs' do @@ -12,12 +12,12 @@ end describe 'invalid inputs' do - it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, /is not a string/) } - it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, /is not a string/) } - it { is_expected.to run.with_params(true).and_raise_error(Puppet::ParseError, /is not a string/) } - it { is_expected.to run.with_params('one').and_raise_error(Puppet::ParseError, /is not a valid email/) } - it { is_expected.to run.with_params('bob@gmail.com', {}).and_raise_error(Puppet::ParseError, /is not a string/) } - it { is_expected.to run.with_params('bob@gmail.com', true).and_raise_error(Puppet::ParseError, /is not a string/) } - it { is_expected.to run.with_params('bob@gmail.com', 'one').and_raise_error(Puppet::ParseError, /is not a valid email/) } + it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, %r{is not a string}) } + it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{is not a string}) } + it { is_expected.to run.with_params(true).and_raise_error(Puppet::ParseError, %r{is not a string}) } + it { is_expected.to run.with_params('one').and_raise_error(Puppet::ParseError, %r{is not a valid email}) } + it { is_expected.to run.with_params('bob@gmail.com', {}).and_raise_error(Puppet::ParseError, %r{is not a string}) } + it { is_expected.to run.with_params('bob@gmail.com', true).and_raise_error(Puppet::ParseError, %r{is not a string}) } + it { is_expected.to run.with_params('bob@gmail.com', 'one').and_raise_error(Puppet::ParseError, %r{is not a valid email}) } end end diff --git a/spec/functions/validate_hash_spec.rb b/spec/functions/validate_hash_spec.rb index 7533abe19..be212de19 100755 --- a/spec/functions/validate_hash_spec.rb +++ b/spec/functions/validate_hash_spec.rb @@ -3,36 +3,36 @@ describe 'validate_hash' do describe 'signature validation' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } describe 'check for deprecation warning' do - after(:all) do + after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end # Checking for deprecation warning - it 'should display a single deprecation' do - ENV['STDLIB_LOG_DEPRECATIONS'] = "true" + it 'displays a single deprecation' do + ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' scope.expects(:warning).with(includes('This method is deprecated')) - is_expected.to run.with_params({'key' => 'value'}) + is_expected.to run.with_params('key' => 'value') end end describe 'valid inputs' do it { is_expected.to run.with_params({}) } - it { is_expected.to run.with_params({'key' => 'value'}) } - it { is_expected.to run.with_params({}, {'key' => 'value'}) } - it { is_expected.to run.with_params({'key1' => 'value1'}, {'key2' => 'value2'}) } + it { is_expected.to run.with_params('key' => 'value') } + it { is_expected.to run.with_params({}, 'key' => 'value') } + it { is_expected.to run.with_params({ 'key1' => 'value1' }, 'key2' => 'value2') } end describe 'invalid inputs' do - it { is_expected.to run.with_params([]).and_raise_error(Puppet::ParseError, /is not a Hash/) } - it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, /is not a Hash/) } - it { is_expected.to run.with_params(true).and_raise_error(Puppet::ParseError, /is not a Hash/) } - it { is_expected.to run.with_params('one').and_raise_error(Puppet::ParseError, /is not a Hash/) } - it { is_expected.to run.with_params({}, []).and_raise_error(Puppet::ParseError, /is not a Hash/) } - it { is_expected.to run.with_params({}, 1).and_raise_error(Puppet::ParseError, /is not a Hash/) } - it { is_expected.to run.with_params({}, true).and_raise_error(Puppet::ParseError, /is not a Hash/) } - it { is_expected.to run.with_params({}, 'one').and_raise_error(Puppet::ParseError, /is not a Hash/) } + it { is_expected.to run.with_params([]).and_raise_error(Puppet::ParseError, %r{is not a Hash}) } + it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{is not a Hash}) } + it { is_expected.to run.with_params(true).and_raise_error(Puppet::ParseError, %r{is not a Hash}) } + it { is_expected.to run.with_params('one').and_raise_error(Puppet::ParseError, %r{is not a Hash}) } + it { is_expected.to run.with_params({}, []).and_raise_error(Puppet::ParseError, %r{is not a Hash}) } + it { is_expected.to run.with_params({}, 1).and_raise_error(Puppet::ParseError, %r{is not a Hash}) } + it { is_expected.to run.with_params({}, true).and_raise_error(Puppet::ParseError, %r{is not a Hash}) } + it { is_expected.to run.with_params({}, 'one').and_raise_error(Puppet::ParseError, %r{is not a Hash}) } end end end diff --git a/spec/functions/validate_integer_spec.rb b/spec/functions/validate_integer_spec.rb index 6558d00ff..01bff7af1 100755 --- a/spec/functions/validate_integer_spec.rb +++ b/spec/functions/validate_integer_spec.rb @@ -1,41 +1,41 @@ require 'spec_helper' describe 'validate_integer' do - after(:all) do + after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end # Checking for deprecation warning - it 'should display a single deprecation' do - ENV['STDLIB_LOG_DEPRECATIONS'] = "true" + it 'displays a single deprecation' do + ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' scope.expects(:warning).with(includes('This method is deprecated')) is_expected.to run.with_params(3) end describe 'signature validation' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } - it { is_expected.to run.with_params(1, 2, 3, 4).and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } + it { is_expected.to run.with_params(1, 2, 3, 4).and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } - [ true, 'true', false, 'false', 'iAmAString', '1test', '1 test', 'test 1', 'test 1 test', 7.0, -7.0, {}, { 'key' => 'value' }, { 1=> 2 }, '', :undef , 'x'].each do |invalid| - it { is_expected.to run.with_params(invalid).and_raise_error(Puppet::ParseError, /to be an Integer/) } - it { is_expected.to run.with_params(invalid, 10).and_raise_error(Puppet::ParseError, /to be an Integer/) } - it { is_expected.to run.with_params(invalid, 10, -10).and_raise_error(Puppet::ParseError, /to be an Integer/) } - it { is_expected.to run.with_params([0, 1, 2, invalid, 3, 4], 10, -10).and_raise_error(Puppet::ParseError, /to be an Integer/) } + [true, 'true', false, 'false', 'iAmAString', '1test', '1 test', 'test 1', 'test 1 test', 7.0, -7.0, {}, { 'key' => 'value' }, { 1 => 2 }, '', :undef, 'x'].each do |invalid| + it { is_expected.to run.with_params(invalid).and_raise_error(Puppet::ParseError, %r{to be an Integer}) } + it { is_expected.to run.with_params(invalid, 10).and_raise_error(Puppet::ParseError, %r{to be an Integer}) } + it { is_expected.to run.with_params(invalid, 10, -10).and_raise_error(Puppet::ParseError, %r{to be an Integer}) } + it { is_expected.to run.with_params([0, 1, 2, invalid, 3, 4], 10, -10).and_raise_error(Puppet::ParseError, %r{to be an Integer}) } end - context 'when running on modern rubies', :unless => RUBY_VERSION == '1.8.7' do - it { is_expected.to run.with_params([0, 1, 2, {1=>2}, 3, 4], 10, -10).and_raise_error(Puppet::ParseError, /to be an Integer/) } + context 'when running on modern rubies', unless: RUBY_VERSION == '1.8.7' do + it { is_expected.to run.with_params([0, 1, 2, { 1 => 2 }, 3, 4], 10, -10).and_raise_error(Puppet::ParseError, %r{to be an Integer}) } end - context 'when running on ruby, which munges hashes weirdly', :if => RUBY_VERSION == '1.8.7' do - it { is_expected.to run.with_params([0, 1, 2, {1=>2}, 3, 4], 10, -10).and_raise_error(Puppet::ParseError) } - it { is_expected.to run.with_params([0, 1, 2, {0=>2}, 3, 4], 10, -10).and_raise_error(Puppet::ParseError) } + context 'when running on ruby, which munges hashes weirdly', if: RUBY_VERSION == '1.8.7' do + it { is_expected.to run.with_params([0, 1, 2, { 1 => 2 }, 3, 4], 10, -10).and_raise_error(Puppet::ParseError) } + it { is_expected.to run.with_params([0, 1, 2, { 0 => 2 }, 3, 4], 10, -10).and_raise_error(Puppet::ParseError) } end - it { is_expected.to run.with_params(1, '').and_raise_error(Puppet::ParseError, /to be unset or an Integer/) } - it { is_expected.to run.with_params(1, 2, '').and_raise_error(Puppet::ParseError, /to be unset or an Integer/) } - it { is_expected.to run.with_params(1, 2, 3).and_raise_error(Puppet::ParseError, /second argument to be larger than third argument/) } + it { is_expected.to run.with_params(1, '').and_raise_error(Puppet::ParseError, %r{to be unset or an Integer}) } + it { is_expected.to run.with_params(1, 2, '').and_raise_error(Puppet::ParseError, %r{to be unset or an Integer}) } + it { is_expected.to run.with_params(1, 2, 3).and_raise_error(Puppet::ParseError, %r{second argument to be larger than third argument}) } end context 'with no range constraints' do @@ -47,12 +47,12 @@ it { is_expected.to run.with_params([1, '2', '3', 4]) } end - context "with a maximum limit of 10" do + context 'with a maximum limit of 10' do describe 'rejects numbers greater than the limit' do - it { is_expected.to run.with_params(11, 10).and_raise_error(Puppet::ParseError, /to be smaller or equal/) } - it { is_expected.to run.with_params(100, 10).and_raise_error(Puppet::ParseError, /to be smaller or equal/) } - it { is_expected.to run.with_params(2**65, 10).and_raise_error(Puppet::ParseError, /to be smaller or equal/) } - it { is_expected.to run.with_params([1,2,10,100], 10).and_raise_error(Puppet::ParseError, /to be smaller or equal/) } + it { is_expected.to run.with_params(11, 10).and_raise_error(Puppet::ParseError, %r{to be smaller or equal}) } + it { is_expected.to run.with_params(100, 10).and_raise_error(Puppet::ParseError, %r{to be smaller or equal}) } + it { is_expected.to run.with_params(2**65, 10).and_raise_error(Puppet::ParseError, %r{to be smaller or equal}) } + it { is_expected.to run.with_params([1, 2, 10, 100], 10).and_raise_error(Puppet::ParseError, %r{to be smaller or equal}) } end describe 'accepts numbers less or equal to the limit' do @@ -64,32 +64,32 @@ it { is_expected.to run.with_params([1, 2, 3, 4], 10) } it { is_expected.to run.with_params([1, '2', '3', 4], 10) } end + end - context "with a minimum limit of -10" do - describe 'rejects numbers greater than the upper limit' do - it { is_expected.to run.with_params(11, 10, -10).and_raise_error(Puppet::ParseError, /to be smaller or equal/) } - it { is_expected.to run.with_params(100, 10, -10).and_raise_error(Puppet::ParseError, /to be smaller or equal/) } - it { is_expected.to run.with_params(2**65, 10, -10).and_raise_error(Puppet::ParseError, /to be smaller or equal/) } - it { is_expected.to run.with_params([1,2,10,100], 10, -10).and_raise_error(Puppet::ParseError, /to be smaller or equal/) } - end + context 'with a minimum limit of -10' do + describe 'rejects numbers greater than the upper limit' do + it { is_expected.to run.with_params(11, 10, -10).and_raise_error(Puppet::ParseError, %r{to be smaller or equal}) } + it { is_expected.to run.with_params(100, 10, -10).and_raise_error(Puppet::ParseError, %r{to be smaller or equal}) } + it { is_expected.to run.with_params(2**65, 10, -10).and_raise_error(Puppet::ParseError, %r{to be smaller or equal}) } + it { is_expected.to run.with_params([1, 2, 10, 100], 10, -10).and_raise_error(Puppet::ParseError, %r{to be smaller or equal}) } + end - describe 'rejects numbers smaller than the lower limit' do - it { is_expected.to run.with_params(-11, 10, -10).and_raise_error(Puppet::ParseError, /to be greater or equal/) } - it { is_expected.to run.with_params(-100, 10, -10).and_raise_error(Puppet::ParseError, /to be greater or equal/) } - it { is_expected.to run.with_params(-2**65, 10, -10).and_raise_error(Puppet::ParseError, /to be greater or equal/) } - it { is_expected.to run.with_params([-10, 1,2,10,-100], 10, -10).and_raise_error(Puppet::ParseError, /to be greater or equal/) } - end + describe 'rejects numbers smaller than the lower limit' do + it { is_expected.to run.with_params(-11, 10, -10).and_raise_error(Puppet::ParseError, %r{to be greater or equal}) } + it { is_expected.to run.with_params(-100, 10, -10).and_raise_error(Puppet::ParseError, %r{to be greater or equal}) } + it { is_expected.to run.with_params(-2**65, 10, -10).and_raise_error(Puppet::ParseError, %r{to be greater or equal}) } + it { is_expected.to run.with_params([-10, 1, 2, 10, -100], 10, -10).and_raise_error(Puppet::ParseError, %r{to be greater or equal}) } + end - describe 'accepts numbers between and including the limits' do - it { is_expected.to run.with_params(10, 10, -10) } - it { is_expected.to run.with_params(-10, 10, -10) } - it { is_expected.to run.with_params(1, 10, -10) } - it { is_expected.to run.with_params(-1, 10, -10) } - it { is_expected.to run.with_params('1', 10, -10) } - it { is_expected.to run.with_params('-1', 10, -10) } - it { is_expected.to run.with_params([1, 2, 3, 4], 10, -10) } - it { is_expected.to run.with_params([1, '2', '3', 4], 10, -10) } - end + describe 'accepts numbers between and including the limits' do + it { is_expected.to run.with_params(10, 10, -10) } + it { is_expected.to run.with_params(-10, 10, -10) } + it { is_expected.to run.with_params(1, 10, -10) } + it { is_expected.to run.with_params(-1, 10, -10) } + it { is_expected.to run.with_params('1', 10, -10) } + it { is_expected.to run.with_params('-1', 10, -10) } + it { is_expected.to run.with_params([1, 2, 3, 4], 10, -10) } + it { is_expected.to run.with_params([1, '2', '3', 4], 10, -10) } end end diff --git a/spec/functions/validate_ip_address_spec.rb b/spec/functions/validate_ip_address_spec.rb index 0414f5e5b..d4182db91 100644 --- a/spec/functions/validate_ip_address_spec.rb +++ b/spec/functions/validate_ip_address_spec.rb @@ -1,10 +1,9 @@ require 'spec_helper' describe 'validate_ip_address' do - describe 'signature validation' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } end describe 'valid inputs' do @@ -22,22 +21,22 @@ it { is_expected.to run.with_params('fe80::a00:27ff:fe94:44d6/64') } context 'Checking for deprecation warning', if: Puppet.version.to_f < 4.0 do - after(:all) do + after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end # Checking for deprecation warning, which should only be provoked when the env variable for it is set. - it 'should display a single deprecation' do - ENV['STDLIB_LOG_DEPRECATIONS'] = "true" + it 'displays a single deprecation' do + ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' scope.expects(:warning).with(includes('This method is deprecated')) is_expected.to run.with_params('1.2.3.4') end - it 'should display no warning for deprecation' do - ENV['STDLIB_LOG_DEPRECATIONS'] = "false" + it 'displays no warning for deprecation' do + ENV['STDLIB_LOG_DEPRECATIONS'] = 'false' scope.expects(:warning).with(includes('This method is deprecated')).never is_expected.to run.with_params('1.2.3.4') end end - + context 'with netmasks' do it { is_expected.to run.with_params('8.8.8.8/0') } it { is_expected.to run.with_params('8.8.8.8/16') } @@ -47,19 +46,19 @@ end describe 'invalid inputs' do - it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, /is not a string/) } - it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, /is not a string/) } - it { is_expected.to run.with_params(true).and_raise_error(Puppet::ParseError, /is not a string/) } - it { is_expected.to run.with_params('one').and_raise_error(Puppet::ParseError, /is not a valid IP/) } - it { is_expected.to run.with_params('0.0.0').and_raise_error(Puppet::ParseError, /is not a valid IP/) } - it { is_expected.to run.with_params('0.0.0.256').and_raise_error(Puppet::ParseError, /is not a valid IP/) } - it { is_expected.to run.with_params('0.0.0.0.0').and_raise_error(Puppet::ParseError, /is not a valid IP/) } - it { is_expected.to run.with_params('1.2.3.4', {}).and_raise_error(Puppet::ParseError, /is not a string/) } - it { is_expected.to run.with_params('1.2.3.4', 1).and_raise_error(Puppet::ParseError, /is not a string/) } - it { is_expected.to run.with_params('1.2.3.4', true).and_raise_error(Puppet::ParseError, /is not a string/) } - it { is_expected.to run.with_params('1.2.3.4', 'one').and_raise_error(Puppet::ParseError, /is not a valid IP/) } - it { is_expected.to run.with_params('::1', {}).and_raise_error(Puppet::ParseError, /is not a string/) } - it { is_expected.to run.with_params('::1', true).and_raise_error(Puppet::ParseError, /is not a string/) } - it { is_expected.to run.with_params('::1', 'one').and_raise_error(Puppet::ParseError, /is not a valid IP/) } + it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, %r{is not a string}) } + it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{is not a string}) } + it { is_expected.to run.with_params(true).and_raise_error(Puppet::ParseError, %r{is not a string}) } + it { is_expected.to run.with_params('one').and_raise_error(Puppet::ParseError, %r{is not a valid IP}) } + it { is_expected.to run.with_params('0.0.0').and_raise_error(Puppet::ParseError, %r{is not a valid IP}) } + it { is_expected.to run.with_params('0.0.0.256').and_raise_error(Puppet::ParseError, %r{is not a valid IP}) } + it { is_expected.to run.with_params('0.0.0.0.0').and_raise_error(Puppet::ParseError, %r{is not a valid IP}) } + it { is_expected.to run.with_params('1.2.3.4', {}).and_raise_error(Puppet::ParseError, %r{is not a string}) } + it { is_expected.to run.with_params('1.2.3.4', 1).and_raise_error(Puppet::ParseError, %r{is not a string}) } + it { is_expected.to run.with_params('1.2.3.4', true).and_raise_error(Puppet::ParseError, %r{is not a string}) } + it { is_expected.to run.with_params('1.2.3.4', 'one').and_raise_error(Puppet::ParseError, %r{is not a valid IP}) } + it { is_expected.to run.with_params('::1', {}).and_raise_error(Puppet::ParseError, %r{is not a string}) } + it { is_expected.to run.with_params('::1', true).and_raise_error(Puppet::ParseError, %r{is not a string}) } + it { is_expected.to run.with_params('::1', 'one').and_raise_error(Puppet::ParseError, %r{is not a valid IP}) } end end diff --git a/spec/functions/validate_ipv4_address_spec.rb b/spec/functions/validate_ipv4_address_spec.rb index 6e4ca0546..eab040834 100755 --- a/spec/functions/validate_ipv4_address_spec.rb +++ b/spec/functions/validate_ipv4_address_spec.rb @@ -1,24 +1,23 @@ require 'spec_helper' describe 'validate_ipv4_address' do - describe 'signature validation' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } end context 'Checking for deprecation warning', if: Puppet.version.to_f < 4.0 do - after(:all) do + after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end # Checking for deprecation warning, which should only be provoked when the env variable for it is set. - it 'should display a single deprecation' do - ENV['STDLIB_LOG_DEPRECATIONS'] = "true" + it 'displays a single deprecation' do + ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' scope.expects(:warning).with(includes('This method is deprecated')) is_expected.to run.with_params(SharedData::IPV4_PATTERNS.first) end - it 'should display no warning for deprecation' do - ENV['STDLIB_LOG_DEPRECATIONS'] = "false" + it 'displays no warning for deprecation' do + ENV['STDLIB_LOG_DEPRECATIONS'] = 'false' scope.expects(:warning).with(includes('This method is deprecated')).never is_expected.to run.with_params(SharedData::IPV4_PATTERNS.first) end @@ -29,13 +28,13 @@ end SharedData::IPV4_NEGATIVE_PATTERNS.each do |value| - it { is_expected.to run.with_params(value).and_raise_error(Puppet::ParseError, /is not a valid IPv4/) } + it { is_expected.to run.with_params(value).and_raise_error(Puppet::ParseError, %r{is not a valid IPv4}) } end describe 'invalid inputs' do - [ {}, [], 1, true ].each do |invalid| - it { is_expected.to run.with_params(invalid).and_raise_error(Puppet::ParseError, /is not a string/) } - it { is_expected.to run.with_params(SharedData::IPV4_PATTERNS.first, invalid).and_raise_error(Puppet::ParseError, /is not a string/) } + [{}, [], 1, true].each do |invalid| + it { is_expected.to run.with_params(invalid).and_raise_error(Puppet::ParseError, %r{is not a string}) } + it { is_expected.to run.with_params(SharedData::IPV4_PATTERNS.first, invalid).and_raise_error(Puppet::ParseError, %r{is not a string}) } end end end diff --git a/spec/functions/validate_ipv6_address_spec.rb b/spec/functions/validate_ipv6_address_spec.rb index 137db36c5..66fb9c6d9 100755 --- a/spec/functions/validate_ipv6_address_spec.rb +++ b/spec/functions/validate_ipv6_address_spec.rb @@ -1,28 +1,27 @@ require 'spec_helper' describe 'validate_ipv6_address' do - describe 'signature validation' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } end context 'Checking for deprecation warning', if: Puppet.version.to_f < 4.0 do - after(:all) do + after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end # Checking for deprecation warning, which should only be provoked when the env variable for it is set. - it 'should display a single deprecation' do - ENV['STDLIB_LOG_DEPRECATIONS'] = "true" + it 'displays a single deprecation' do + ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' scope.expects(:warning).with(includes('This method is deprecated')) is_expected.to run.with_params('3ffe:0505:0002::') end - it 'should display no warning for deprecation' do - ENV['STDLIB_LOG_DEPRECATIONS'] = "false" + it 'displays no warning for deprecation' do + ENV['STDLIB_LOG_DEPRECATIONS'] = 'false' scope.expects(:warning).with(includes('This method is deprecated')).never is_expected.to run.with_params('3ffe:0505:0002::') end - end + end describe 'valid inputs' do it { is_expected.to run.with_params('3ffe:0505:0002::') } @@ -39,22 +38,22 @@ end describe 'invalid inputs' do - it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, /is not a string/) } - it { is_expected.to run.with_params(true).and_raise_error(Puppet::ParseError, /is not a string/) } - it { is_expected.to run.with_params('one').and_raise_error(Puppet::ParseError, /is not a valid IPv6/) } - it { is_expected.to run.with_params('0.0.0').and_raise_error(Puppet::ParseError, /is not a valid IPv6/) } - it { is_expected.to run.with_params('0.0.0.256').and_raise_error(Puppet::ParseError, /is not a valid IPv6/) } - it { is_expected.to run.with_params('0.0.0.0.0').and_raise_error(Puppet::ParseError, /is not a valid IPv6/) } - it { is_expected.to run.with_params('::ffff:2.3.4').and_raise_error(Puppet::ParseError, /is not a valid IPv6/) } - it { is_expected.to run.with_params('::ffff:257.1.2.3').and_raise_error(Puppet::ParseError, /is not a valid IPv6/) } - it { is_expected.to run.with_params('::ffff:12345678901234567890.1.26').and_raise_error(Puppet::ParseError, /is not a valid IPv6/) } - it { is_expected.to run.with_params('affe:beef').and_raise_error(Puppet::ParseError, /is not a valid IPv6/) } - it { is_expected.to run.with_params('::1', {}).and_raise_error(Puppet::ParseError, /is not a string/) } - it { is_expected.to run.with_params('::1', true).and_raise_error(Puppet::ParseError, /is not a string/) } - it { is_expected.to run.with_params('::1', 'one').and_raise_error(Puppet::ParseError, /is not a valid IPv6/) } - context 'unless running on ruby 1.8.7', :if => RUBY_VERSION != '1.8.7' do - it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, /is not a string/) } - it { is_expected.to run.with_params('::1', 1).and_raise_error(Puppet::ParseError, /is not a string/) } + it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, %r{is not a string}) } + it { is_expected.to run.with_params(true).and_raise_error(Puppet::ParseError, %r{is not a string}) } + it { is_expected.to run.with_params('one').and_raise_error(Puppet::ParseError, %r{is not a valid IPv6}) } + it { is_expected.to run.with_params('0.0.0').and_raise_error(Puppet::ParseError, %r{is not a valid IPv6}) } + it { is_expected.to run.with_params('0.0.0.256').and_raise_error(Puppet::ParseError, %r{is not a valid IPv6}) } + it { is_expected.to run.with_params('0.0.0.0.0').and_raise_error(Puppet::ParseError, %r{is not a valid IPv6}) } + it { is_expected.to run.with_params('::ffff:2.3.4').and_raise_error(Puppet::ParseError, %r{is not a valid IPv6}) } + it { is_expected.to run.with_params('::ffff:257.1.2.3').and_raise_error(Puppet::ParseError, %r{is not a valid IPv6}) } + it { is_expected.to run.with_params('::ffff:12345678901234567890.1.26').and_raise_error(Puppet::ParseError, %r{is not a valid IPv6}) } + it { is_expected.to run.with_params('affe:beef').and_raise_error(Puppet::ParseError, %r{is not a valid IPv6}) } + it { is_expected.to run.with_params('::1', {}).and_raise_error(Puppet::ParseError, %r{is not a string}) } + it { is_expected.to run.with_params('::1', true).and_raise_error(Puppet::ParseError, %r{is not a string}) } + it { is_expected.to run.with_params('::1', 'one').and_raise_error(Puppet::ParseError, %r{is not a valid IPv6}) } + context 'unless running on ruby 1.8.7', if: RUBY_VERSION != '1.8.7' do + it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{is not a string}) } + it { is_expected.to run.with_params('::1', 1).and_raise_error(Puppet::ParseError, %r{is not a string}) } end end end diff --git a/spec/functions/validate_legacy_spec.rb b/spec/functions/validate_legacy_spec.rb index 7b48f1220..06c3b5106 100644 --- a/spec/functions/validate_legacy_spec.rb +++ b/spec/functions/validate_legacy_spec.rb @@ -6,7 +6,7 @@ it { is_expected.to run.with_params.and_raise_error(ArgumentError) } describe 'when passing the type assertion and passing the previous validation' do - before do + before(:each) do scope.expects(:function_validate_foo).with([5]).once Puppet.expects(:notice).never end @@ -16,7 +16,7 @@ end describe 'when passing the type assertion and failing the previous validation' do - before do + before(:each) do scope.expects(:function_validate_foo).with([5]).raises(Puppet::ParseError, 'foo').once Puppet.expects(:notice).with(includes('Accepting previously invalid value for target type')) end @@ -26,7 +26,7 @@ end describe 'when failing the type assertion and passing the previous validation' do - before do + before(:each) do scope.expects(:function_validate_foo).with(['5']).once subject.func.expects(:call_function).with('deprecation', 'validate_legacy', includes('Integer')).once end @@ -36,7 +36,7 @@ end describe 'when failing the type assertion and failing the previous validation' do - before do + before(:each) do scope.expects(:function_validate_foo).with(['5']).raises(Puppet::ParseError, 'foo').once subject.func.expects(:call_function).with('fail', includes('Integer')).once end @@ -46,7 +46,7 @@ end describe 'when passing in undef' do - before do + before(:each) do scope.expects(:function_validate_foo).with([:undef]).once Puppet.expects(:notice).never end @@ -56,7 +56,7 @@ end describe 'when passing in multiple arguments' do - before do + before(:each) do scope.expects(:function_validate_foo).with([:undef, 1, 'foo']).once Puppet.expects(:notice).never end diff --git a/spec/functions/validate_numeric_spec.rb b/spec/functions/validate_numeric_spec.rb index 4c0e24dd3..f9ea1c829 100755 --- a/spec/functions/validate_numeric_spec.rb +++ b/spec/functions/validate_numeric_spec.rb @@ -1,40 +1,40 @@ require 'spec_helper' describe 'validate_numeric' do - after(:all) do + after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end - + # Checking for deprecation warning - it 'should display a single deprecation' do - ENV['STDLIB_LOG_DEPRECATIONS'] = "true" + it 'displays a single deprecation' do + ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' scope.expects(:warning).with(includes('This method is deprecated')) is_expected.to run.with_params(3) end describe 'signature validation' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } - it { is_expected.to run.with_params(1, 2, 3, 4).and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } + it { is_expected.to run.with_params(1, 2, 3, 4).and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } - [ true, 'true', false, 'false', 'iAmAString', '1test', '1 test', 'test 1', 'test 1 test', {}, { 'key' => 'value' }, { 1=> 2 }, '', :undef , 'x'].each do |invalid| - it { is_expected.to run.with_params(invalid).and_raise_error(Puppet::ParseError, /to be a Numeric/) } - it { is_expected.to run.with_params(invalid, 10.0).and_raise_error(Puppet::ParseError, /to be a Numeric/) } - it { is_expected.to run.with_params(invalid, 10.0, -10.0).and_raise_error(Puppet::ParseError, /to be a Numeric/) } + [true, 'true', false, 'false', 'iAmAString', '1test', '1 test', 'test 1', 'test 1 test', {}, { 'key' => 'value' }, { 1 => 2 }, '', :undef, 'x'].each do |invalid| + it { is_expected.to run.with_params(invalid).and_raise_error(Puppet::ParseError, %r{to be a Numeric}) } + it { is_expected.to run.with_params(invalid, 10.0).and_raise_error(Puppet::ParseError, %r{to be a Numeric}) } + it { is_expected.to run.with_params(invalid, 10.0, -10.0).and_raise_error(Puppet::ParseError, %r{to be a Numeric}) } end - context 'when running on modern rubies', :unless => RUBY_VERSION == '1.8.7' do - it { is_expected.to run.with_params([0, 1, 2, {1=>2}, 3, 4], 10, -10).and_raise_error(Puppet::ParseError, /to be a Numeric/) } + context 'when running on modern rubies', unless: RUBY_VERSION == '1.8.7' do + it { is_expected.to run.with_params([0, 1, 2, { 1 => 2 }, 3, 4], 10, -10).and_raise_error(Puppet::ParseError, %r{to be a Numeric}) } end - context 'when running on ruby, which munges hashes weirdly', :if => RUBY_VERSION == '1.8.7' do - it { is_expected.to run.with_params([0, 1, 2, {1=>2}, 3, 4], 10, -10).and_raise_error(Puppet::ParseError) } - it { is_expected.to run.with_params([0, 1, 2, {0=>2}, 3, 4], 10, -10).and_raise_error(Puppet::ParseError) } + context 'when running on ruby, which munges hashes weirdly', if: RUBY_VERSION == '1.8.7' do + it { is_expected.to run.with_params([0, 1, 2, { 1 => 2 }, 3, 4], 10, -10).and_raise_error(Puppet::ParseError) } + it { is_expected.to run.with_params([0, 1, 2, { 0 => 2 }, 3, 4], 10, -10).and_raise_error(Puppet::ParseError) } end - it { is_expected.to run.with_params(1, '').and_raise_error(Puppet::ParseError, /to be unset or a Numeric/) } - it { is_expected.to run.with_params(1, 2, '').and_raise_error(Puppet::ParseError, /to be unset or a Numeric/) } - it { is_expected.to run.with_params(1, 2, 3).and_raise_error(Puppet::ParseError, /second argument to be larger than third argument/) } + it { is_expected.to run.with_params(1, '').and_raise_error(Puppet::ParseError, %r{to be unset or a Numeric}) } + it { is_expected.to run.with_params(1, 2, '').and_raise_error(Puppet::ParseError, %r{to be unset or a Numeric}) } + it { is_expected.to run.with_params(1, 2, 3).and_raise_error(Puppet::ParseError, %r{second argument to be larger than third argument}) } end context 'with no range constraints' do @@ -46,12 +46,12 @@ it { is_expected.to run.with_params([1, '2', '3', 4]) } end - context "with a maximum limit of 10.0" do + context 'with a maximum limit of 10.0' do describe 'rejects numbers greater than the limit' do - it { is_expected.to run.with_params(11, 10.0).and_raise_error(Puppet::ParseError, /to be smaller or equal/) } - it { is_expected.to run.with_params(100, 10.0).and_raise_error(Puppet::ParseError, /to be smaller or equal/) } - it { is_expected.to run.with_params(2**65, 10.0).and_raise_error(Puppet::ParseError, /to be smaller or equal/) } - it { is_expected.to run.with_params([1,2,10.0,100], 10.0).and_raise_error(Puppet::ParseError, /to be smaller or equal/) } + it { is_expected.to run.with_params(11, 10.0).and_raise_error(Puppet::ParseError, %r{to be smaller or equal}) } + it { is_expected.to run.with_params(100, 10.0).and_raise_error(Puppet::ParseError, %r{to be smaller or equal}) } + it { is_expected.to run.with_params(2**65, 10.0).and_raise_error(Puppet::ParseError, %r{to be smaller or equal}) } + it { is_expected.to run.with_params([1, 2, 10.0, 100], 10.0).and_raise_error(Puppet::ParseError, %r{to be smaller or equal}) } end describe 'accepts numbers less or equal to the limit' do @@ -63,32 +63,32 @@ it { is_expected.to run.with_params([1, 2, 3, 4], 10.0) } it { is_expected.to run.with_params([1, '2', '3', 4], 10.0) } end + end - context "with a minimum limit of -10.0" do - describe 'rejects numbers greater than the upper limit' do - it { is_expected.to run.with_params(11, 10.0, -10.0).and_raise_error(Puppet::ParseError, /to be smaller or equal/) } - it { is_expected.to run.with_params(100, 10.0, -10.0).and_raise_error(Puppet::ParseError, /to be smaller or equal/) } - it { is_expected.to run.with_params(2**65, 10.0, -10.0).and_raise_error(Puppet::ParseError, /to be smaller or equal/) } - it { is_expected.to run.with_params([1,2,10.0,100], 10.0, -10.0).and_raise_error(Puppet::ParseError, /to be smaller or equal/) } - end + context 'with a minimum limit of -10.0' do + describe 'rejects numbers greater than the upper limit' do + it { is_expected.to run.with_params(11, 10.0, -10.0).and_raise_error(Puppet::ParseError, %r{to be smaller or equal}) } + it { is_expected.to run.with_params(100, 10.0, -10.0).and_raise_error(Puppet::ParseError, %r{to be smaller or equal}) } + it { is_expected.to run.with_params(2**65, 10.0, -10.0).and_raise_error(Puppet::ParseError, %r{to be smaller or equal}) } + it { is_expected.to run.with_params([1, 2, 10.0, 100], 10.0, -10.0).and_raise_error(Puppet::ParseError, %r{to be smaller or equal}) } + end - describe 'rejects numbers smaller than the lower limit' do - it { is_expected.to run.with_params(-11, 10.0, -10.0).and_raise_error(Puppet::ParseError, /to be greater or equal/) } - it { is_expected.to run.with_params(-100, 10.0, -10.0).and_raise_error(Puppet::ParseError, /to be greater or equal/) } - it { is_expected.to run.with_params(-2**65, 10.0, -10.0).and_raise_error(Puppet::ParseError, /to be greater or equal/) } - it { is_expected.to run.with_params([-10.0, 1,2,10.0,-100], 10.0, -10.0).and_raise_error(Puppet::ParseError, /to be greater or equal/) } - end + describe 'rejects numbers smaller than the lower limit' do + it { is_expected.to run.with_params(-11, 10.0, -10.0).and_raise_error(Puppet::ParseError, %r{to be greater or equal}) } + it { is_expected.to run.with_params(-100, 10.0, -10.0).and_raise_error(Puppet::ParseError, %r{to be greater or equal}) } + it { is_expected.to run.with_params(-2**65, 10.0, -10.0).and_raise_error(Puppet::ParseError, %r{to be greater or equal}) } + it { is_expected.to run.with_params([-10.0, 1, 2, 10.0, -100], 10.0, -10.0).and_raise_error(Puppet::ParseError, %r{to be greater or equal}) } + end - describe 'accepts numbers between and including the limits' do - it { is_expected.to run.with_params(10.0, 10.0, -10.0) } - it { is_expected.to run.with_params(-10.0, 10.0, -10.0) } - it { is_expected.to run.with_params(1, 10.0, -10.0) } - it { is_expected.to run.with_params(-1, 10.0, -10.0) } - it { is_expected.to run.with_params('1', 10.0, -10.0) } - it { is_expected.to run.with_params('-1', 10.0, -10.0) } - it { is_expected.to run.with_params([1, 2, 3, 4], 10.0, -10.0) } - it { is_expected.to run.with_params([1, '2', '3', 4], 10.0, -10.0) } - end + describe 'accepts numbers between and including the limits' do + it { is_expected.to run.with_params(10.0, 10.0, -10.0) } + it { is_expected.to run.with_params(-10.0, 10.0, -10.0) } + it { is_expected.to run.with_params(1, 10.0, -10.0) } + it { is_expected.to run.with_params(-1, 10.0, -10.0) } + it { is_expected.to run.with_params('1', 10.0, -10.0) } + it { is_expected.to run.with_params('-1', 10.0, -10.0) } + it { is_expected.to run.with_params([1, 2, 3, 4], 10.0, -10.0) } + it { is_expected.to run.with_params([1, '2', '3', 4], 10.0, -10.0) } end end diff --git a/spec/functions/validate_re_spec.rb b/spec/functions/validate_re_spec.rb index 353118297..29297742f 100755 --- a/spec/functions/validate_re_spec.rb +++ b/spec/functions/validate_re_spec.rb @@ -1,55 +1,55 @@ require 'spec_helper' describe 'validate_re' do - after(:all) do + after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end # Checking for deprecation warning - it 'should display a single deprecation' do - ENV['STDLIB_LOG_DEPRECATIONS'] = "true" + it 'displays a single deprecation' do + ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' scope.expects(:warning).with(includes('This method is deprecated')) is_expected.to run.with_params('', '') end describe 'signature validation' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } - it { is_expected.to run.with_params('').and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } - it { is_expected.to run.with_params('', '', '', 'extra').and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } + it { is_expected.to run.with_params('').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } + it { is_expected.to run.with_params('', '', '', 'extra').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } describe 'valid inputs' do it { is_expected.to run.with_params('', '') } it { is_expected.to run.with_params('', ['']) } it { is_expected.to run.with_params('', [''], 'custom error') } it { is_expected.to run.with_params('one', '^one') } - it { is_expected.to run.with_params('one', [ '^one', '^two' ]) } - it { is_expected.to run.with_params('one', [ '^one', '^two' ], 'custom error') } + it { is_expected.to run.with_params('one', ['^one', '^two']) } + it { is_expected.to run.with_params('one', ['^one', '^two'], 'custom error') } end describe 'invalid inputs' do - it { is_expected.to run.with_params('', []).and_raise_error(Puppet::ParseError, /does not match/) } - it { is_expected.to run.with_params('one', 'two').and_raise_error(Puppet::ParseError, /does not match/) } - it { is_expected.to run.with_params('', 'two').and_raise_error(Puppet::ParseError, /does not match/) } - it { is_expected.to run.with_params('', ['two']).and_raise_error(Puppet::ParseError, /does not match/) } - it { is_expected.to run.with_params('', ['two'], 'custom error').and_raise_error(Puppet::ParseError, /custom error/) } - it { is_expected.to run.with_params('notone', '^one').and_raise_error(Puppet::ParseError, /does not match/) } - it { is_expected.to run.with_params('notone', [ '^one', '^two' ]).and_raise_error(Puppet::ParseError, /does not match/) } - it { is_expected.to run.with_params('notone', [ '^one', '^two' ], 'custom error').and_raise_error(Puppet::ParseError, /custom error/) } + it { is_expected.to run.with_params('', []).and_raise_error(Puppet::ParseError, %r{does not match}) } + it { is_expected.to run.with_params('one', 'two').and_raise_error(Puppet::ParseError, %r{does not match}) } + it { is_expected.to run.with_params('', 'two').and_raise_error(Puppet::ParseError, %r{does not match}) } + it { is_expected.to run.with_params('', ['two']).and_raise_error(Puppet::ParseError, %r{does not match}) } + it { is_expected.to run.with_params('', ['two'], 'custom error').and_raise_error(Puppet::ParseError, %r{custom error}) } + it { is_expected.to run.with_params('notone', '^one').and_raise_error(Puppet::ParseError, %r{does not match}) } + it { is_expected.to run.with_params('notone', ['^one', '^two']).and_raise_error(Puppet::ParseError, %r{does not match}) } + it { is_expected.to run.with_params('notone', ['^one', '^two'], 'custom error').and_raise_error(Puppet::ParseError, %r{custom error}) } + end - describe 'non-string inputs' do - [ - 1, # Fixnum - 3.14, # Float - nil, # NilClass - true, # TrueClass - false, # FalseClass - ["10"], # Array - :key, # Symbol - {:key=>"val"}, # Hash - ].each do |input| - it { is_expected.to run.with_params(input, '.*').and_raise_error(Puppet::ParseError, /needs to be a String/) } - end + describe 'non-string inputs' do + [ + 1, # Fixnum + 3.14, # Float + nil, # NilClass + true, # TrueClass + false, # FalseClass + ['10'], # Array + :key, # Symbol + { key: 'val' }, # Hash + ].each do |input| + it { is_expected.to run.with_params(input, '.*').and_raise_error(Puppet::ParseError, %r{needs to be a String}) } end end end diff --git a/spec/functions/validate_slength_spec.rb b/spec/functions/validate_slength_spec.rb index e4162dee1..bde989b66 100755 --- a/spec/functions/validate_slength_spec.rb +++ b/spec/functions/validate_slength_spec.rb @@ -1,72 +1,81 @@ require 'spec_helper' describe 'validate_slength' do - after(:all) do + after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end # Checking for deprecation warning - it 'should display a single deprecation' do - ENV['STDLIB_LOG_DEPRECATIONS'] = "true" + it 'displays a single deprecation' do + ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' scope.expects(:warning).with(includes('This method is deprecated')) is_expected.to run.with_params('1234567890', 10) end - + describe 'signature validation' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } - it { is_expected.to run.with_params('').and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } - it { is_expected.to run.with_params('', 2, 3, 'extra').and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } - it { is_expected.to run.with_params('', '').and_raise_error(Puppet::ParseError, /second argument to be a positive Numeric/) } - it { is_expected.to run.with_params('', -1).and_raise_error(Puppet::ParseError, /second argument to be a positive Numeric/) } - it { is_expected.to run.with_params('', 1, '').and_raise_error(Puppet::ParseError, /third argument to be unset or a positive Numeric/) } - it { is_expected.to run.with_params('', 1, -1).and_raise_error(Puppet::ParseError, /third argument to be unset or a positive Numeric/) } - it { is_expected.to run.with_params('', 1, 2).and_raise_error(Puppet::ParseError, /argument to be equal to or larger than third argument/) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } + it { is_expected.to run.with_params('').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } + it { is_expected.to run.with_params('', 2, 3, 'extra').and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } + it { is_expected.to run.with_params('', '').and_raise_error(Puppet::ParseError, %r{second argument to be a positive Numeric}) } + it { is_expected.to run.with_params('', -1).and_raise_error(Puppet::ParseError, %r{second argument to be a positive Numeric}) } + it { is_expected.to run.with_params('', 1, '').and_raise_error(Puppet::ParseError, %r{third argument to be unset or a positive Numeric}) } + it { is_expected.to run.with_params('', 1, -1).and_raise_error(Puppet::ParseError, %r{third argument to be unset or a positive Numeric}) } + it { is_expected.to run.with_params('', 1, 2).and_raise_error(Puppet::ParseError, %r{argument to be equal to or larger than third argument}) } end - context "with a maximum length of 10" do + context 'with a maximum length of 10' do describe 'rejects strings longer than the limit' do - it { is_expected.to run.with_params('1234567890a', 10).and_raise_error(Puppet::ParseError, /Expected length/) } - it { is_expected.to run.with_params('1234567890abcdef', 10).and_raise_error(Puppet::ParseError, /Expected length/) } - it { is_expected.to run.with_params([ 'one', '1234567890abcdef' ], 10).and_raise_error(Puppet::ParseError, /Expected length/) } + it { is_expected.to run.with_params('1234567890a', 10).and_raise_error(Puppet::ParseError, %r{Expected length}) } + it { is_expected.to run.with_params('1234567890abcdef', 10).and_raise_error(Puppet::ParseError, %r{Expected length}) } + it { is_expected.to run.with_params(%w[one 1234567890abcdef], 10).and_raise_error(Puppet::ParseError, %r{Expected length}) } end describe 'accepts strings shorter or equal to the limit' do it { is_expected.to run.with_params('1234567890', 10) } it { is_expected.to run.with_params('12345', 10) } - it { is_expected.to run.with_params([ 'one', 'two' ], 10) } + it { is_expected.to run.with_params(%w[one two], 10) } end + end - context "with a minimum length of 5" do - describe 'rejects strings longer than the upper limit' do - it { is_expected.to run.with_params('1234567890a', 10, 5).and_raise_error(Puppet::ParseError, /Expected length/) } - it { is_expected.to run.with_params('1234567890abcdef', 10, 5).and_raise_error(Puppet::ParseError, /Expected length/) } - end + context 'with a minimum length of 5' do + describe 'rejects strings longer than the upper limit' do + it { is_expected.to run.with_params('1234567890a', 10, 5).and_raise_error(Puppet::ParseError, %r{Expected length}) } + it { is_expected.to run.with_params('1234567890abcdef', 10, 5).and_raise_error(Puppet::ParseError, %r{Expected length}) } + end - describe 'rejects numbers shorter than the lower limit' do - it { is_expected.to run.with_params('one', 10, 5).and_raise_error(Puppet::ParseError, /Expected length/) } - it { is_expected.to run.with_params(['12345678', 'two'], 10, 5).and_raise_error(Puppet::ParseError, /Expected length/) } - end + describe 'rejects numbers shorter than the lower limit' do + it { is_expected.to run.with_params('one', 10, 5).and_raise_error(Puppet::ParseError, %r{Expected length}) } + it { is_expected.to run.with_params(%w[12345678 two], 10, 5).and_raise_error(Puppet::ParseError, %r{Expected length}) } + end - describe 'accepts strings of length between and including the limits' do - it { is_expected.to run.with_params('12345', 10, 5) } - it { is_expected.to run.with_params('123456', 10, 5) } - it { is_expected.to run.with_params('1234567', 10, 5) } - it { is_expected.to run.with_params('12345678', 10, 5) } - it { is_expected.to run.with_params('123456789', 10, 5) } - it { is_expected.to run.with_params('1234567890', 10, 5) } - it { is_expected.to run.with_params(['1233456', '12345678'], 10, 5) } - end + describe 'accepts strings of length between and including the limits' do + it { is_expected.to run.with_params('12345', 10, 5) } + it { is_expected.to run.with_params('123456', 10, 5) } + it { is_expected.to run.with_params('1234567', 10, 5) } + it { is_expected.to run.with_params('12345678', 10, 5) } + it { is_expected.to run.with_params('123456789', 10, 5) } + it { is_expected.to run.with_params('1234567890', 10, 5) } + it { is_expected.to run.with_params(%w[1233456 12345678], 10, 5) } end end describe 'corner cases' do - it { pending('this should work'); is_expected.to run.with_params('', 0, 0) } + it { + pending('this should work') + is_expected.to run.with_params('', 0, 0) + } it { is_expected.to run.with_params('1234567890', 10, 10) } end describe 'empty upper limit is interpreted as infinity' do - it { pending('not implemented'); is_expected.to run.with_params('1234567890ab', '', 10) } - it { pending('not implemented'); is_expected.to run.with_params('12345678', '', 10).and_raise_error(Puppet::ParseError, /Expected length/) } + it { + pending('not implemented') + is_expected.to run.with_params('1234567890ab', '', 10) + } + it { + pending('not implemented') + is_expected.to run.with_params('12345678', '', 10).and_raise_error(Puppet::ParseError, %r{Expected length}) + } end end diff --git a/spec/functions/validate_string_spec.rb b/spec/functions/validate_string_spec.rb index 0907ede97..4459f002f 100755 --- a/spec/functions/validate_string_spec.rb +++ b/spec/functions/validate_string_spec.rb @@ -1,20 +1,20 @@ require 'spec_helper' describe 'validate_string' do - after(:all) do + after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end - + # Checking for deprecation warning - it 'should display a single deprecation' do - ENV['STDLIB_LOG_DEPRECATIONS'] = "true" + it 'displays a single deprecation' do + ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' scope.expects(:warning).with(includes('This method is deprecated')) is_expected.to run.with_params('', '') end describe 'signature validation' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } describe 'valid inputs' do it { is_expected.to run.with_params('') } @@ -24,10 +24,10 @@ end describe 'invalid inputs' do - it { is_expected.to run.with_params([]).and_raise_error(Puppet::ParseError, /is not a string/) } - it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, /is not a string/) } - it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, /is not a string/) } - it { is_expected.to run.with_params(true).and_raise_error(Puppet::ParseError, /is not a string/) } + it { is_expected.to run.with_params([]).and_raise_error(Puppet::ParseError, %r{is not a string}) } + it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, %r{is not a string}) } + it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{is not a string}) } + it { is_expected.to run.with_params(true).and_raise_error(Puppet::ParseError, %r{is not a string}) } end end end diff --git a/spec/functions/validate_x509_rsa_key_pair_spec.rb b/spec/functions/validate_x509_rsa_key_pair_spec.rb index eb6331005..3a5913d77 100755 --- a/spec/functions/validate_x509_rsa_key_pair_spec.rb +++ b/spec/functions/validate_x509_rsa_key_pair_spec.rb @@ -1,9 +1,9 @@ require 'spec_helper' describe 'validate_x509_rsa_key_pair' do - + # rubocop:disable Lint/IndentHeredoc : Heredoc's are meant to be indented in this way let(:valid_cert) do - < 'value' }).and_return(['value']) } - it 'should return the array of values' do + it { is_expected.to run.with_params('key' => 'value').and_return(['value']) } + it 'returns the array of values' do result = subject.call([{ 'key1' => 'value1', 'key2' => 'value2', 'duplicate_value_key' => 'value2' }]) - expect(result).to match_array(['value1', 'value2', 'value2']) + expect(result).to match_array(%w[value1 value2 value2]) end - it 'should run with UTF8 and double byte characters' do + it 'runs with UTF8 and double byte characters' do result = subject.call([{ 'かぎ' => '使用', 'ҝĕұ' => '√ẩŀứệ', 'ҝĕұďŭрļǐçằťè' => '√ẩŀứệ' }]) expect(result).to match_array(['使用', '√ẩŀứệ', '√ẩŀứệ']) end diff --git a/spec/functions/zip_spec.rb b/spec/functions/zip_spec.rb index e1ae8ee12..5386de762 100755 --- a/spec/functions/zip_spec.rb +++ b/spec/functions/zip_spec.rb @@ -2,20 +2,19 @@ describe 'zip' do it { is_expected.not_to eq(nil) } - it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } - it { is_expected.to run.with_params([]).and_raise_error(Puppet::ParseError, /wrong number of arguments/i) } + it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } + it { is_expected.to run.with_params([]).and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { - pending("Current implementation ignores parameters after the third.") - is_expected.to run.with_params([], [], true, []).and_raise_error(Puppet::ParseError, /wrong number of arguments/i) + pending('Current implementation ignores parameters after the third.') + is_expected.to run.with_params([], [], true, []).and_raise_error(Puppet::ParseError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params([], []).and_return([]) } - it { is_expected.to run.with_params([1,2,3], [4,5,6]).and_return([[1,4], [2,5], [3,6]]) } - it { is_expected.to run.with_params([1,2,3], [4,5,6], false).and_return([[1,4], [2,5], [3,6]]) } - it { is_expected.to run.with_params([1,2,3], [4,5,6], true).and_return([1, 4, 2, 5, 3, 6]) } + it { is_expected.to run.with_params([1, 2, 3], [4, 5, 6]).and_return([[1, 4], [2, 5], [3, 6]]) } + it { is_expected.to run.with_params([1, 2, 3], [4, 5, 6], false).and_return([[1, 4], [2, 5], [3, 6]]) } + it { is_expected.to run.with_params([1, 2, 3], [4, 5, 6], true).and_return([1, 4, 2, 5, 3, 6]) } context 'should run with UTF8 and double byte characters' do - it { is_expected.to run.with_params(['ầ', 'ь', 'ć'], ['đ', 'ề', 'ƒ']).and_return([['ầ','đ'], ['ь','ề'], ['ć', 'ƒ']]) } - it { is_expected.to run.with_params(['ペ', '含', '値'], ['ッ', '文', 'イ']).and_return([['ペ','ッ'], ['含','文'], ['値', 'イ']]) } + it { is_expected.to run.with_params(%w[ầ ь ć], %w[đ ề ƒ]).and_return([%w[ầ đ], %w[ь ề], %w[ć ƒ]]) } + it { is_expected.to run.with_params(%w[ペ 含 値], %w[ッ 文 イ]).and_return([%w[ペ ッ], %w[含 文], %w[値 イ]]) } end end - diff --git a/spec/monkey_patches/alias_should_to_must.rb b/spec/monkey_patches/alias_should_to_must.rb index 505e24092..ec61923d7 100755 --- a/spec/monkey_patches/alias_should_to_must.rb +++ b/spec/monkey_patches/alias_should_to_must.rb @@ -4,6 +4,6 @@ class Object # This is necessary because the RAL has a 'should' # method. - alias :must :should - alias :must_not :should_not + alias must should + alias must_not should_not end diff --git a/spec/monkey_patches/publicize_methods.rb b/spec/monkey_patches/publicize_methods.rb index 3ae59f978..3fc3a765b 100755 --- a/spec/monkey_patches/publicize_methods.rb +++ b/spec/monkey_patches/publicize_methods.rb @@ -1,11 +1,11 @@ #! /usr/bin/env ruby -S rspec # Some monkey-patching to allow us to test private methods. class Class - def publicize_methods(*methods) - saved_private_instance_methods = methods.empty? ? self.private_instance_methods : methods + def publicize_methods(*methods) + saved_private_instance_methods = methods.empty? ? private_instance_methods : methods - self.class_eval { public(*saved_private_instance_methods) } - yield - self.class_eval { private(*saved_private_instance_methods) } - end + class_eval { public(*saved_private_instance_methods) } + yield + class_eval { private(*saved_private_instance_methods) } + end end diff --git a/spec/spec_helper_acceptance.rb b/spec/spec_helper_acceptance.rb index 4d85e7dc8..7be1a52ad 100755 --- a/spec/spec_helper_acceptance.rb +++ b/spec/spec_helper_acceptance.rb @@ -5,7 +5,7 @@ require 'beaker/module_install_helper' run_puppet_install_helper -install_ca_certs unless ENV['PUPPET_INSTALL_TYPE'] =~ /pe/i +install_ca_certs unless ENV['PUPPET_INSTALL_TYPE'] =~ %r{pe}i install_module_on(hosts) install_module_dependencies_on(hosts) @@ -18,20 +18,20 @@ end end -def get_puppet_version +def return_puppet_version (on default, puppet('--version')).output.chomp end -RSpec.shared_context "with faked facts" do +RSpec.shared_context 'with faked facts' do let(:facts_d) do - puppet_version = get_puppet_version - if fact('osfamily') =~ /windows/i + puppet_version = return_puppet_version + if fact('osfamily') =~ %r{windows}i if fact('kernelmajversion').to_f < 6.0 'C:/Documents and Settings/All Users/Application Data/PuppetLabs/facter/facts.d' else 'C:/ProgramData/PuppetLabs/facter/facts.d' end - elsif Puppet::Util::Package.versioncmp(puppet_version, '4.0.0') < 0 and fact('is_pe', '--puppet') == "true" + elsif Puppet::Util::Package.versioncmp(puppet_version, '4.0.0') < 0 && fact('is_pe', '--puppet') == 'true' '/etc/puppetlabs/facter/facts.d' else '/etc/facter/facts.d' @@ -39,14 +39,14 @@ def get_puppet_version end before :each do - #No need to create on windows, PE creates by default - if fact('osfamily') !~ /windows/i + # No need to create on windows, PE creates by default + if fact('osfamily') !~ %r{windows}i shell("mkdir -p '#{facts_d}'") end end after :each do - shell("rm -f '#{facts_d}/fqdn.txt'", :acceptable_exit_codes => [0,1]) + shell("rm -f '#{facts_d}/fqdn.txt'", acceptable_exit_codes: [0, 1]) end def fake_fact(name, value) diff --git a/spec/spec_helper_local.rb b/spec/spec_helper_local.rb index 616490c6e..5fea4da4a 100644 --- a/spec/spec_helper_local.rb +++ b/spec/spec_helper_local.rb @@ -1,7 +1,7 @@ # automatically load any shared examples or contexts -Dir["./spec/support/**/*.rb"].sort.each { |f| require f } +Dir['./spec/support/**/*.rb'].sort.each { |f| require f } -# hack to enable all the expect syntax (like allow_any_instance_of) in rspec-puppet examples +# HACK: to enable all the expect syntax (like allow_any_instance_of) in rspec-puppet examples RSpec::Mocks::Syntax.enable_expect(RSpec::Puppet::ManifestMatchers) RSpec.configure do |config| @@ -16,7 +16,7 @@ # Facter.collection.loader.load(:ipaddress) Facter.clear Facter.clear_messages - + RSpec::Mocks.setup end diff --git a/spec/support/shared_data.rb b/spec/support/shared_data.rb index ea9b7a0a1..013ec105a 100644 --- a/spec/support/shared_data.rb +++ b/spec/support/shared_data.rb @@ -14,7 +14,7 @@ module SharedData '8.8.8.8/16', '8.8.8.8/255.255.0.0', '8.8.8.8/32', - ] + ].freeze IPV4_NEGATIVE_PATTERNS = [ '', '0000', @@ -34,5 +34,5 @@ module SharedData '9999.9999.9999.9999', 'affe::beef', 'nope', - ] + ].freeze end diff --git a/spec/unit/facter/facter_dot_d_spec.rb b/spec/unit/facter/facter_dot_d_spec.rb index 0afadb25f..e3c88426a 100755 --- a/spec/unit/facter/facter_dot_d_spec.rb +++ b/spec/unit/facter/facter_dot_d_spec.rb @@ -2,8 +2,7 @@ require 'spec_helper' require 'facter/facter_dot_d' -describe Facter::Util::DotD do - +describe Facter::Util::DotD do # rubocop:disable RSpec/FilePath : Spec path is as it should be context 'returns a simple fact' do before :each do Facter.stubs(:version).returns('1.6.1') @@ -12,7 +11,7 @@ subject.create end - it 'should return successfully' do + it 'returns successfully' do expect(Facter.fact(:fake_fact).value).to eq('fake fact') end end @@ -25,7 +24,7 @@ subject.create end - it 'should return successfully' do + it 'returns successfully' do expect(Facter.fact(:foo).value).to eq('1+1=2') end end diff --git a/spec/unit/facter/package_provider_spec.rb b/spec/unit/facter/package_provider_spec.rb index 3954faf02..f298726cb 100644 --- a/spec/unit/facter/package_provider_spec.rb +++ b/spec/unit/facter/package_provider_spec.rb @@ -1,11 +1,11 @@ -#! /usr/bin/env ruby -S rspec +#! /usr/bin/env ruby -S rspec # rubocop:disable Lint/ScriptPermission : Rubocop error?? require 'spec_helper' require 'puppet/type' require 'puppet/type/package' -describe 'package_provider', :type => :fact do - before { Facter.clear } - after { Facter.clear } +describe 'package_provider', type: :fact do + before(:each) { Facter.clear } + after(:each) { Facter.clear } ['4.2.2', '3.7.1 (Puppet Enterprise 3.2.1)'].each do |puppetversion| describe "on puppet ''#{puppetversion}''" do @@ -13,8 +13,8 @@ Facter.stubs(:value).returns puppetversion end - context "darwin" do - it "should return pkgdmg" do + context 'darwin' do + it 'returns pkgdmg' do provider = Puppet::Type.type(:package).provider(:pkgdmg) Puppet::Type.type(:package).stubs(:defaultprovider).returns provider @@ -22,8 +22,8 @@ end end - context "centos 7" do - it "should return yum" do + context 'centos 7' do + it 'returns yum' do provider = Puppet::Type.type(:package).provider(:yum) Puppet::Type.type(:package).stubs(:defaultprovider).returns provider @@ -31,8 +31,8 @@ end end - context "ubuntu" do - it "should return apt" do + context 'ubuntu' do + it 'returns apt' do provider = Puppet::Type.type(:package).provider(:apt) Puppet::Type.type(:package).stubs(:defaultprovider).returns provider diff --git a/spec/unit/facter/pe_version_spec.rb b/spec/unit/facter/pe_version_spec.rb index c11a1cd09..1d706ad8f 100755 --- a/spec/unit/facter/pe_version_spec.rb +++ b/spec/unit/facter/pe_version_spec.rb @@ -2,7 +2,7 @@ require 'spec_helper' -describe "PE Version specs" do +describe 'PE Version specs' do before :each do # Explicitly load the pe_version.rb file which contains generated facts # that cannot be automatically loaded. Puppet 2.x implements @@ -14,29 +14,32 @@ Facter.collection.loader.load(:pe_version) end end - - context "When puppetversion is nil" do + + context 'When puppetversion is nil' do before :each do Facter.fact(:puppetversion).stubs(:value).returns(nil) end - - it "pe_version is nil" do + + it 'puppetversion is nil' do expect(Facter.fact(:puppetversion).value).to be_nil + end + + it 'pe_version is nil' do expect(Facter.fact(:pe_version).value).to be_nil end end - context "If PE is installed" do - %w{ 2.6.1 2.10.300 }.each do |version| + context 'If PE is installed' do + %w[2.6.1 2.10.300].each do |version| puppetversion = "2.7.19 (Puppet Enterprise #{version})" context "puppetversion => #{puppetversion}" do before :each do Facter.fact(:puppetversion).stubs(:value).returns(puppetversion) end - (major,minor,patch) = version.split(".") + (major, minor, patch) = version.split('.') - it "Should return true" do + it 'returns true' do expect(Facter.fact(:is_pe).value).to eq(true) end @@ -59,30 +62,29 @@ end end - context "When PE is not installed" do + context 'When PE is not installed' do before :each do - Facter.fact(:puppetversion).stubs(:value).returns("2.7.19") + Facter.fact(:puppetversion).stubs(:value).returns('2.7.19') end - it "is_pe is false" do + it 'is_pe is false' do expect(Facter.fact(:is_pe).value).to eq(false) end - it "pe_version is nil" do + it 'pe_version is nil' do expect(Facter.fact(:pe_version).value).to be_nil end - it "pe_major_version is nil" do + it 'pe_major_version is nil' do expect(Facter.fact(:pe_major_version).value).to be_nil end - it "pe_minor_version is nil" do + it 'pe_minor_version is nil' do expect(Facter.fact(:pe_minor_version).value).to be_nil end - it "Should have a patch version" do + it 'has a patch version' do expect(Facter.fact(:pe_patch_version).value).to be_nil end end - end diff --git a/spec/unit/facter/root_home_spec.rb b/spec/unit/facter/root_home_spec.rb index a5c2846ec..d45db75f3 100755 --- a/spec/unit/facter/root_home_spec.rb +++ b/spec/unit/facter/root_home_spec.rb @@ -1,65 +1,68 @@ #! /usr/bin/env ruby -S rspec require 'spec_helper' require 'facter/root_home' +describe 'Root Home Specs' do + describe Facter::Util::RootHome do + context 'solaris' do + let(:root_ent) { 'root:x:0:0:Super-User:/:/sbin/sh' } + let(:expected_root_home) { '/' } -describe Facter::Util::RootHome do - context "solaris" do - let(:root_ent) { "root:x:0:0:Super-User:/:/sbin/sh" } - let(:expected_root_home) { "/" } - - it "should return /" do - Facter::Util::Resolution.expects(:exec).with("getent passwd root").returns(root_ent) - expect(Facter::Util::RootHome.get_root_home).to eq(expected_root_home) + it 'returns /' do + Facter::Util::Resolution.expects(:exec).with('getent passwd root').returns(root_ent) + expect(described_class.returnt_root_home).to eq(expected_root_home) + end end - end - context "linux" do - let(:root_ent) { "root:x:0:0:root:/root:/bin/bash" } - let(:expected_root_home) { "/root" } + context 'linux' do + let(:root_ent) { 'root:x:0:0:root:/root:/bin/bash' } + let(:expected_root_home) { '/root' } - it "should return /root" do - Facter::Util::Resolution.expects(:exec).with("getent passwd root").returns(root_ent) - expect(Facter::Util::RootHome.get_root_home).to eq(expected_root_home) + it 'returns /root' do + Facter::Util::Resolution.expects(:exec).with('getent passwd root').returns(root_ent) + expect(described_class.returnt_root_home).to eq(expected_root_home) + end end - end - context "windows" do - before :each do - Facter::Util::Resolution.expects(:exec).with("getent passwd root").returns(nil) - end - it "should be nil on windows" do - expect(Facter::Util::RootHome.get_root_home).to be_nil + context 'windows' do + before :each do + Facter::Util::Resolution.expects(:exec).with('getent passwd root').returns(nil) + end + it 'is nil on windows' do + expect(described_class.returnt_root_home).to be_nil + end end end -end -describe 'root_home', :type => :fact do - before { Facter.clear } - after { Facter.clear } + describe 'root_home', type: :fact do + before(:each) { Facter.clear } + after(:each) { Facter.clear } - context "macosx" do - before do - Facter.fact(:kernel).stubs(:value).returns("Darwin") - Facter.fact(:osfamily).stubs(:value).returns("Darwin") - end - let(:expected_root_home) { "/var/root" } - sample_dscacheutil = File.read(fixtures('dscacheutil','root')) + context 'macosx' do + before(:each) do + Facter.fact(:kernel).stubs(:value).returns('Darwin') + Facter.fact(:osfamily).stubs(:value).returns('Darwin') + end + let(:expected_root_home) { '/var/root' } - it "should return /var/root" do - Facter::Util::Resolution.stubs(:exec).with("dscacheutil -q user -a name root").returns(sample_dscacheutil) - expect(Facter.fact(:root_home).value).to eq(expected_root_home) - end - end + sample_dscacheutil = File.read(fixtures('dscacheutil', 'root')) - context "aix" do - before do - Facter.fact(:kernel).stubs(:value).returns("AIX") - Facter.fact(:osfamily).stubs(:value).returns("AIX") + it 'returns /var/root' do + Facter::Util::Resolution.stubs(:exec).with('dscacheutil -q user -a name root').returns(sample_dscacheutil) + expect(Facter.fact(:root_home).value).to eq(expected_root_home) + end end - let(:expected_root_home) { "/root" } - sample_lsuser = File.read(fixtures('lsuser','root')) - it "should return /root" do - Facter::Util::Resolution.stubs(:exec).with("lsuser -c -a home root").returns(sample_lsuser) - expect(Facter.fact(:root_home).value).to eq(expected_root_home) + context 'aix' do + before(:each) do + Facter.fact(:kernel).stubs(:value).returns('AIX') + Facter.fact(:osfamily).stubs(:value).returns('AIX') + end + let(:expected_root_home) { '/root' } + + sample_lsuser = File.read(fixtures('lsuser', 'root')) + + it 'returns /root' do + Facter::Util::Resolution.stubs(:exec).with('lsuser -c -a home root').returns(sample_lsuser) + expect(Facter.fact(:root_home).value).to eq(expected_root_home) + end end end end diff --git a/spec/unit/facter/service_provider_spec.rb b/spec/unit/facter/service_provider_spec.rb index ad8a5fc53..7acece215 100644 --- a/spec/unit/facter/service_provider_spec.rb +++ b/spec/unit/facter/service_provider_spec.rb @@ -1,14 +1,14 @@ -#! /usr/bin/env ruby -S rspec +#! /usr/bin/env ruby -S rspec # rubocop:disable Lint/ScriptPermission : Rubocop error?? require 'spec_helper' require 'puppet/type' require 'puppet/type/service' -describe 'service_provider', :type => :fact do - before { Facter.clear } - after { Facter.clear } +describe 'service_provider', type: :fact do + before(:each) { Facter.clear } + after(:each) { Facter.clear } - context "macosx" do - it "should return launchd" do + context 'macosx' do + it 'returns launchd' do provider = Puppet::Type.type(:service).provider(:launchd) Puppet::Type.type(:service).stubs(:defaultprovider).returns provider @@ -16,8 +16,8 @@ end end - context "systemd" do - it "should return systemd" do + context 'systemd' do + it 'returns systemd' do provider = Puppet::Type.type(:service).provider(:systemd) Puppet::Type.type(:service).stubs(:defaultprovider).returns provider @@ -25,13 +25,12 @@ end end - context "redhat" do - it "should return redhat" do + context 'redhat' do + it 'returns redhat' do provider = Puppet::Type.type(:service).provider(:redhat) Puppet::Type.type(:service).stubs(:defaultprovider).returns provider expect(Facter.fact(:service_provider).value).to eq('redhat') end end - end diff --git a/spec/unit/facter/util/puppet_settings_spec.rb b/spec/unit/facter/util/puppet_settings_spec.rb index c278b7984..55d6e3cf6 100755 --- a/spec/unit/facter/util/puppet_settings_spec.rb +++ b/spec/unit/facter/util/puppet_settings_spec.rb @@ -3,33 +3,32 @@ require 'facter/util/puppet_settings' describe Facter::Util::PuppetSettings do - - describe "#with_puppet" do - context "Without Puppet loaded" do + describe '#with_puppet' do + context 'Without Puppet loaded' do before(:each) do - Module.expects(:const_get).with("Puppet").raises(NameError) + Module.expects(:const_get).with('Puppet').raises(NameError) end - it 'should be nil' do + it 'is nil' do expect(subject.with_puppet { Puppet[:vardir] }).to be_nil end - it 'should not yield to the block' do + it 'does not yield to the block' do Puppet.expects(:[]).never expect(subject.with_puppet { Puppet[:vardir] }).to be_nil end end - context "With Puppet loaded" do + context 'With Puppet loaded' do module Puppet; end - let(:vardir) { "/var/lib/puppet" } + let(:vardir) { '/var/lib/puppet' } before :each do Puppet.expects(:[]).with(:vardir).returns vardir end - it 'should yield to the block' do + it 'yields to the block' do subject.with_puppet { Puppet[:vardir] } end - it 'should return the nodes vardir' do + it 'returns the nodes vardir' do expect(subject.with_puppet { Puppet[:vardir] }).to eq vardir end end diff --git a/spec/unit/puppet/parser/functions/enclose_ipv6_spec.rb b/spec/unit/puppet/parser/functions/enclose_ipv6_spec.rb index b162127d0..e605efa67 100644 --- a/spec/unit/puppet/parser/functions/enclose_ipv6_spec.rb +++ b/spec/unit/puppet/parser/functions/enclose_ipv6_spec.rb @@ -1,68 +1,68 @@ -#! /usr/bin/env ruby -S rspec +#! /usr/bin/env ruby -S rspec # rubocop:disable Lint/ScriptPermission : Rubocop error?? require 'spec_helper' -describe "the enclose_ipv6 function" do +describe 'the enclose_ipv6 function' do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } - it "should exist" do - expect(Puppet::Parser::Functions.function("enclose_ipv6")).to eq("function_enclose_ipv6") + it 'exists' do + expect(Puppet::Parser::Functions.function('enclose_ipv6')).to eq('function_enclose_ipv6') end - it "should raise a ParseError if there is less than 1 arguments" do - expect { scope.function_enclose_ipv6([]) }.to( raise_error(Puppet::ParseError) ) + it 'raises a ParseError if there is less than 1 arguments' do + expect { scope.function_enclose_ipv6([]) }.to(raise_error(Puppet::ParseError)) end - it "should raise a ParseError if there is more than 1 arguments" do - expect { scope.function_enclose_ipv6(['argument1','argument2']) }.to( raise_error(Puppet::ParseError) ) + it 'raises a ParseError if there is more than 1 arguments' do + expect { scope.function_enclose_ipv6(%w[argument1 argument2]) }.to(raise_error(Puppet::ParseError)) end - it "should raise a ParseError when given garbage" do - expect { scope.function_enclose_ipv6(['garbage']) }.to( raise_error(Puppet::ParseError) ) + it 'raises a ParseError when given garbage' do + expect { scope.function_enclose_ipv6(['garbage']) }.to(raise_error(Puppet::ParseError)) end - it "should raise a ParseError when given something else than a string or an array" do - expect { scope.function_enclose_ipv6([['1' => '127.0.0.1']]) }.to( raise_error(Puppet::ParseError) ) + it 'raises a ParseError when given something else than a string or an array' do + expect { scope.function_enclose_ipv6([['1' => '127.0.0.1']]) }.to(raise_error(Puppet::ParseError)) end - it "should not raise a ParseError when given a single ip string" do - expect { scope.function_enclose_ipv6(['127.0.0.1']) }.to_not raise_error + it 'does not raise a ParseError when given a single ip string' do + expect { scope.function_enclose_ipv6(['127.0.0.1']) }.not_to raise_error end - it "should not raise a ParseError when given * as ip string" do - expect { scope.function_enclose_ipv6(['*']) }.to_not raise_error + it 'does not raise a ParseError when given * as ip string' do + expect { scope.function_enclose_ipv6(['*']) }.not_to raise_error end - it "should not raise a ParseError when given an array of ip strings" do - expect { scope.function_enclose_ipv6([['127.0.0.1','fe80::1']]) }.to_not raise_error + it 'does not raise a ParseError when given an array of ip strings' do + expect { scope.function_enclose_ipv6([['127.0.0.1', 'fe80::1']]) }.not_to raise_error end - it "should not raise a ParseError when given differently notations of ip addresses" do - expect { scope.function_enclose_ipv6([['127.0.0.1','fe80::1','[fe80::1]']]) }.to_not raise_error + it 'does not raise a ParseError when given differently notations of ip addresses' do + expect { scope.function_enclose_ipv6([['127.0.0.1', 'fe80::1', '[fe80::1]']]) }.not_to raise_error end - it "should raise a ParseError when given a wrong ipv4 address" do - expect { scope.function_enclose_ipv6(['127..0.0.1']) }.to( raise_error(Puppet::ParseError) ) + it 'raises a ParseError when given a wrong ipv4 address' do + expect { scope.function_enclose_ipv6(['127..0.0.1']) }.to(raise_error(Puppet::ParseError)) end - it "should raise a ParseError when given a ipv4 address with square brackets" do - expect { scope.function_enclose_ipv6(['[127.0.0.1]']) }.to( raise_error(Puppet::ParseError) ) + it 'raises a ParseError when given a ipv4 address with square brackets' do + expect { scope.function_enclose_ipv6(['[127.0.0.1]']) }.to(raise_error(Puppet::ParseError)) end - it "should raise a ParseError when given a wrong ipv6 address" do - expect { scope.function_enclose_ipv6(['fe80:::1']) }.to( raise_error(Puppet::ParseError) ) + it 'raises a ParseError when given a wrong ipv6 address' do + expect { scope.function_enclose_ipv6(['fe80:::1']) }.to(raise_error(Puppet::ParseError)) end - it "should embrace ipv6 adresses within an array of ip addresses" do - result = scope.function_enclose_ipv6([['127.0.0.1','fe80::1','[fe80::2]']]) - expect(result).to(eq(['127.0.0.1','[fe80::1]','[fe80::2]'])) + it 'embraces ipv6 adresses within an array of ip addresses' do + result = scope.function_enclose_ipv6([['127.0.0.1', 'fe80::1', '[fe80::2]']]) + expect(result).to(eq(['127.0.0.1', '[fe80::1]', '[fe80::2]'])) end - it "should embrace a single ipv6 adresse" do + it 'embraces a single ipv6 adresse' do result = scope.function_enclose_ipv6(['fe80::1']) expect(result).to(eq(['[fe80::1]'])) end - it "should not embrace a single ipv4 adresse" do + it 'does not embrace a single ipv4 adresse' do result = scope.function_enclose_ipv6(['127.0.0.1']) expect(result).to(eq(['127.0.0.1'])) end diff --git a/spec/unit/puppet/parser/functions/is_absolute_path_spec.rb b/spec/unit/puppet/parser/functions/is_absolute_path_spec.rb index 89312081a..589ad8228 100644 --- a/spec/unit/puppet/parser/functions/is_absolute_path_spec.rb +++ b/spec/unit/puppet/parser/functions/is_absolute_path_spec.rb @@ -1,6 +1,6 @@ require 'spec_helper' -describe :is_absolute_path do +describe 'is_absolute_path' do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } let(:function_args) do @@ -11,31 +11,28 @@ scope.function_is_absolute_path(function_args) end - describe 'validate arity' do let(:function_args) do - [1,2] - end - it "should raise a ParseError if there is more than 1 arguments" do - lambda { function }.should( raise_error(ArgumentError)) + [1, 2] end + it 'raises a ParseError if there is more than 1 arguments' do + -> { function }.should(raise_error(ArgumentError)) + end end - - it "should exist" do + + it 'exists' do Puppet::Parser::Functions.function(subject).should == "function_#{subject}" end # help enforce good function defination - it 'should contain arity' do - + it 'contains arity' do end - it "should raise a ParseError if there is less than 1 arguments" do - lambda { function }.should( raise_error(ArgumentError)) + it 'raises a ParseError if there is less than 1 arguments' do + -> { function }.should(raise_error(ArgumentError)) end - describe 'should retrun true' do let(:return_value) do true @@ -45,7 +42,8 @@ let(:function_args) do ['c:\temp\test.txt'] end - it 'should return data' do + + it 'returns data' do function.should eq(return_value) end end @@ -55,7 +53,7 @@ ['/temp/test.txt'] end - it 'should return data' do + it 'returns data' do function.should eq(return_value) end end @@ -65,11 +63,13 @@ let(:return_value) do false end + describe 'windows' do let(:function_args) do ['..\temp\test.txt'] end - it 'should return data' do + + it 'returns data' do function.should eq(return_value) end end @@ -78,9 +78,10 @@ let(:function_args) do ['../var/lib/puppet'] end - it 'should return data' do + + it 'returns data' do function.should eq(return_value) end end end -end \ No newline at end of file +end diff --git a/spec/unit/puppet/provider/file_line/ruby_spec.rb b/spec/unit/puppet/provider/file_line/ruby_spec.rb index bd133e6af..2fb27b19c 100755 --- a/spec/unit/puppet/provider/file_line/ruby_spec.rb +++ b/spec/unit/puppet/provider/file_line/ruby_spec.rb @@ -2,21 +2,21 @@ require 'spec_helper' provider_class = Puppet::Type.type(:file_line).provider(:ruby) -# These tests fail on windows when run as part of the rake task. Individually they pass -describe provider_class, :unless => Puppet::Util::Platform.windows? do +#  These tests fail on windows when run as part of the rake task. Individually they pass +describe provider_class, unless: Puppet::Util::Platform.windows? do include PuppetlabsSpec::Files let :tmpfile do - tmpfilename("file_line_test") + tmpfilename('file_line_test') end let :content do '' end let :params do - { } + {} end let :resource do - Puppet::Type::File_line.new( { + Puppet::Type::File_line.new({ name: 'foo', path: tmpfile, line: 'foo', @@ -25,23 +25,26 @@ let :provider do provider_class.new(resource) end + before :each do File.open(tmpfile, 'w') do |fh| fh.write(content) end end - describe "line parameter" do - context "line exists" do + describe 'line parameter' do + context 'line exists' do let(:content) { 'foo' } + it 'detects the line' do - expect(provider.exists?).to be_truthy + expect(provider).to be_exists end end - context "line does not exist" do + context 'line does not exist' do let(:content) { 'foo bar' } + it 'requests changes' do - expect(provider.exists?).to be_falsy + expect(provider).not_to be_exists end it 'appends the line' do provider.create @@ -49,64 +52,75 @@ end end end - describe "match parameter" do - context "does not match line" do - let(:params) { { match: '^bar' } } - context "line does not exist" do - describe "replacing" do - let(:content) { "foo bar\nbar" } - it 'requests changes' do - expect(provider.exists?).to be_falsy - end - it 'replaces the match' do - provider.create - expect(File.read(tmpfile).chomp).to eq("foo bar\nfoo") - end - end - describe "appending" do - let(:params) { super().merge({ replace: false }) } - let(:content) { "foo bar\nbar" } - it 'does not request changes' do - expect(provider.exists?).to be_truthy - end - end + + describe 'match parameter' do + let(:params) { { match: '^bar' } } + + describe 'does not match line - line does not exist - replacing' do + let(:content) { "foo bar\nbar" } + + it 'requests changes' do + expect(provider).not_to be_exists + end + it 'replaces the match' do + provider.create + expect(File.read(tmpfile).chomp).to eq("foo bar\nfoo") end - context "line exists" do - let(:content) { "foo\nbar" } - it 'detects the line' do - expect(provider.exists?).to be_truthy - end + end + + describe 'does not match line - line does not exist - appending' do + let(:params) { super().merge(replace: false) } + let(:content) { "foo bar\nbar" } + + it 'does not request changes' do + expect(provider).to be_exists + end + end + + context 'does not match line - line exists' do + let(:content) { "foo\nbar" } + + it 'detects the line' do + expect(provider).to be_exists + end + end + + context 'matches line - line exists' do + let(:params) { { match: '^foo' } } + let(:content) { "foo\nbar" } + + it 'detects the line' do + expect(provider).to be_exists end end - context "matches line" do + + context 'matches line - line does not exist' do let(:params) { { match: '^foo' } } - context "line exists" do - let(:content) { "foo\nbar" } - it 'detects the line' do - expect(provider.exists?).to be_truthy - end + let(:content) { "foo bar\nbar" } + + it 'requests changes' do + expect(provider).not_to be_exists end - context "line does not exist" do - let(:content) { "foo bar\nbar" } - it 'requests changes' do - expect(provider.exists?).to be_falsy - end - it 'replaces the match' do - provider.create - expect(File.read(tmpfile).chomp).to eq("foo\nbar") - end + it 'replaces the match' do + provider.create + expect(File.read(tmpfile).chomp).to eq("foo\nbar") end end end + describe 'append_on_no_match' do - let(:params) { { - append_on_no_match: false, - match: '^foo1$', - } } + let(:params) do + { + append_on_no_match: false, + match: '^foo1$', + } + end + context 'when matching' do let(:content) { "foo1\nbar" } + it 'requests changes' do - expect(provider.exists?).to be_falsy + expect(provider).not_to be_exists end it 'replaces the match' do provider.create @@ -115,686 +129,131 @@ end context 'when not matching' do let(:content) { "foo3\nbar" } + it 'does not affect the file' do - expect(provider.exists?).to be_truthy + expect(provider).to be_exists end end end + describe 'replace_all_matches_not_matching_line' do context 'when replace is false' do - let(:params) { { - replace_all_matches_not_matching_line: true, - replace: false, - } } - it 'raises an error' do - expect { provider.exists? }.to raise_error(Puppet::Error, /replace must be true/) - end - end - context 'when match matches line' do - let(:params) { { - replace_all_matches_not_matching_line: true, - match: '^foo', - multiple: true, - } } - context 'when there are more matches than lines' do - let(:content) { "foo\nfoo bar\nbar\nfoo baz" } - it 'requests changes' do - expect(provider.exists?).to be_falsy - end - it 'replaces the matches' do - provider.create - expect(File.read(tmpfile).chomp).to eql("foo\nfoo\nbar\nfoo") - end - end - context 'when there are the same matches and lines' do - let(:content) { "foo\nfoo\nbar" } - it 'does not request changes' do - expect(provider.exists?).to be_truthy - end - end - end - context 'when match does not match line' do - let(:params) { { - replace_all_matches_not_matching_line: true, - match: '^bar', - multiple: true, - } } - context 'when there are more matches than lines' do - let(:content) { "foo\nfoo bar\nbar\nbar baz" } - it 'requests changes' do - expect(provider.exists?).to be_falsy - end - it 'replaces the matches' do - provider.create - expect(File.read(tmpfile).chomp).to eql("foo\nfoo bar\nfoo\nfoo") - end - end - context 'when there are the same matches and lines' do - let(:content) { "foo\nfoo\nbar\nbar baz" } - it 'requests changes' do - expect(provider.exists?).to be_falsy - end - it 'replaces the matches' do - provider.create - expect(File.read(tmpfile).chomp).to eql("foo\nfoo\nfoo\nfoo") - end - end - context 'when there are no matches' do - let(:content) { "foo\nfoo bar" } - it 'does not request changes' do - expect(provider.exists?).to be_truthy - end - end - context 'when there are no matches or lines' do - let(:content) { "foo bar" } - it 'requests changes' do - expect(provider.exists?).to be_falsy - end - it 'appends the line' do - provider.create - expect(File.read(tmpfile).chomp).to eql("foo bar\nfoo") - end - end - end - end - describe 'match_for_absence' do - end - describe 'customer use cases' do - describe 'MODULES-5003' do - let(:params) { { - line: "*\thard\tcore\t0", - match: "^[ \t]*\\*[ \t]+hard[ \t]+core[ \t]+.*", - multiple: true, - } } - context 'no lines' do - let(:content) { "* hard core 90\n* hard core 10\n" } - it 'requests changes' do - expect(provider.exists?).to be_falsy - end - it 'replaces the matches' do - provider.create - expect(File.read(tmpfile).chomp).to eq("* hard core 0\n* hard core 0") - end - end - context 'one match, one line' do - let(:content) { "* hard core 90\n* hard core 0\n" } - describe 'just ensure the line exists' do - it 'does not request changes' do - expect(provider.exists?).to be_truthy - end - end - describe 'replace all matches, even when line exists' do - let(:params) { super().merge(replace_all_matches_not_matching_line: true) } - it 'requests changes' do - expect(provider.exists?).to be_falsy - end - it 'replaces the matches' do - provider.create - expect(File.read(tmpfile).chomp).to eq("* hard core 0\n* hard core 0") - end - end - end - end - describe 'MODULES-5651' do - let(:params) { { - line: 'LogLevel=notice', - match: '^#LogLevel$', - } } - context "match, no line" do - let(:content) { "#LogLevel\nstuff" } - it 'requests changes' do - expect(provider.exists?).to be_falsy - end - it 'replaces the match' do - provider.create - expect(File.read(tmpfile).chomp).to eq("LogLevel=notice\nstuff") - end - end - context "match, line" do - let(:content) { "#Loglevel\nLogLevel=notice\nstuff" } - it 'does not request changes' do - expect(provider.exists?).to be_truthy - end - end - context "no match, line" do - let(:content) { "LogLevel=notice\nstuff" } - it 'does not request changes' do - expect(provider.exists?).to be_truthy - end - end - end - end - describe "#create" do - context "when adding" do - end - context 'when replacing' do - let :params do + let(:params) do { - line: 'foo = bar', - match: '^foo\s*=.*$', + replace_all_matches_not_matching_line: true, replace: false, } end - let(:content) { "foo1\nfoo=blah\nfoo2\nfoo3" } - it 'should not replace the matching line' do - expect(provider.exists?).to be_truthy - provider.create - expect(File.read(tmpfile).chomp).to eql("foo1\nfoo=blah\nfoo2\nfoo3") - end - it 'should append the line if no matches are found' do - File.open(tmpfile, 'w') do |fh| - fh.write("foo1\nfoo2") - end - expect(provider.exists?).to eql (false) - provider.create - expect(File.read(tmpfile).chomp).to eql("foo1\nfoo2\nfoo = bar") - end - it 'should raise an error with invalid values' do - expect { - @resource = Puppet::Type::File_line.new( - { - :name => 'foo', - :path => tmpfile, - :line => 'foo = bar', - :match => '^foo\s*=.*$', - :replace => 'asgadga', - } - ) - }.to raise_error(Puppet::Error, /Invalid value "asgadga"\. Valid values are true, false\./) + it 'raises an error' do + expect { provider.exists? }.to raise_error(Puppet::Error, %r{replace must be true}) end end - end - describe "#destroy" do - end - context "when matching" do - before :each do - @resource = Puppet::Type::File_line.new( - { - :name => 'foo', - :path => tmpfile, - :line => 'foo = bar', - :match => '^foo\s*=.*$', - } - ) - @provider = provider_class.new(@resource) - end - describe 'using match' do - it 'should raise an error if more than one line matches, and should not have modified the file' do - File.open(tmpfile, 'w') do |fh| - fh.write("foo1\nfoo=blah\nfoo2\nfoo=baz") - end - expect(@provider.exists?).to eql(false) - expect { @provider.create }.to raise_error(Puppet::Error, /More than one line.*matches/) - expect(File.read(tmpfile)).to eql("foo1\nfoo=blah\nfoo2\nfoo=baz") - end - - it 'should replace all lines that matches' do - @resource = Puppet::Type::File_line.new( - { - :name => 'foo', - :path => tmpfile, - :line => 'foo = bar', - :match => '^foo\s*=.*$', - :multiple => true, - } - ) - @provider = provider_class.new(@resource) - File.open(tmpfile, 'w') do |fh| - fh.write("foo1\nfoo=blah\nfoo2\nfoo=baz") - end - expect(@provider.exists?).to eql(false) - @provider.create - expect(File.read(tmpfile).chomp).to eql("foo1\nfoo = bar\nfoo2\nfoo = bar") - end - - it 'should replace all lines that match, even when some lines are correct' do - @resource = Puppet::Type::File_line.new( - { - :name => 'neil', - :path => tmpfile, - :line => "\thard\tcore\t0\n", - :match => '^[ \t]hard[ \t]+core[ \t]+.*', - :multiple => true, - } - ) - @provider = provider_class.new(@resource) - File.open(tmpfile, 'w') do |fh| - fh.write("\thard\tcore\t90\n\thard\tcore\t0\n") - end - expect(@provider.exists?).to eql(false) - @provider.create - expect(File.read(tmpfile).chomp).to eql("\thard\tcore\t0\n\thard\tcore\t0") - end - - it 'should raise an error with invalid values' do - expect { - @resource = Puppet::Type::File_line.new( - { - :name => 'foo', - :path => tmpfile, - :line => 'foo = bar', - :match => '^foo\s*=.*$', - :multiple => 'asgadga', - } - ) - }.to raise_error(Puppet::Error, /Invalid value "asgadga"\. Valid values are true, false\./) - end - - it 'should replace a line that matches' do - File.open(tmpfile, 'w') do |fh| - fh.write("foo1\nfoo=blah\nfoo2") - end - expect(@provider.exists?).to eql(false) - @provider.create - expect(File.read(tmpfile).chomp).to eql("foo1\nfoo = bar\nfoo2") - end - it 'should add a new line if no lines match' do - File.open(tmpfile, 'w') do |fh| - fh.write("foo1\nfoo2") - end - expect(@provider.exists?).to eql(false) - @provider.create - expect(File.read(tmpfile)).to eql("foo1\nfoo2\nfoo = bar\n") - end - it 'should do nothing if the exact line already exists' do - File.open(tmpfile, 'w') do |fh| - fh.write("foo1\nfoo = bar\nfoo2") - end - expect(@provider.exists?).to eql(true) - @provider.create - expect(File.read(tmpfile).chomp).to eql("foo1\nfoo = bar\nfoo2") - end - end - describe 'using match+append_on_no_match' do - context 'when there is a match' do - it 'should replace line' do - @resource = Puppet::Type::File_line.new( - { - :name => 'foo', - :path => tmpfile, - :line => 'inserted = line', - :match => '^foo3$', - :append_on_no_match => false, - } - ) - @provider = provider_class.new(@resource) - File.open(tmpfile, 'w') do |fh| - fh.write("foo1\nfoo = blah\nfoo2\nfoo = baz") - end - expect(@provider.exists?).to be true - expect(File.read(tmpfile).chomp).to eql("foo1\nfoo = blah\nfoo2\nfoo = baz") - end - end - context 'when there is no match' do - it 'should not add line after no matches found' do - @resource = Puppet::Type::File_line.new( - { - :name => 'foo', - :path => tmpfile, - :line => 'inserted = line', - :match => '^foo3$', - :append_on_no_match => false, - } - ) - @provider = provider_class.new(@resource) - File.open(tmpfile, 'w') do |fh| - fh.write("foo1\nfoo = blah\nfoo2\nfoo = baz") - end - expect(@provider.exists?).to be true - expect(File.read(tmpfile).chomp).to eql("foo1\nfoo = blah\nfoo2\nfoo = baz") - end - end - end - end - context "when match+replace+append_on_no_match" do - end - context 'when after' do - let :resource do - Puppet::Type::File_line.new( + context 'when match matches line - when there are more matches than lines' do + let(:params) do { - :name => 'foo', - :path => tmpfile, - :line => 'inserted = line', - :after => '^foo1', + replace_all_matches_not_matching_line: true, + match: '^foo', + multiple: true, } - ) - end - - let :provider do - provider_class.new(resource) - end - context 'match and after set' do - shared_context 'resource_create' do - let(:match) { '^foo2$' } - let(:after) { '^foo1$' } - let(:resource) { - Puppet::Type::File_line.new( - { - :name => 'foo', - :path => tmpfile, - :line => 'inserted = line', - :after => after, - :match => match, - } - ) - } - end - before :each do - File.open(tmpfile, 'w') do |fh| - fh.write("foo1\nfoo2\nfoo = baz") - end - end - describe 'inserts at match' do - include_context 'resource_create' - it { - provider.create - expect(File.read(tmpfile).chomp).to eq("foo1\ninserted = line\nfoo = baz") - } - end - describe 'inserts a new line after when no match' do - include_context 'resource_create' do - let(:match) { '^nevergoingtomatch$' } - end - it { - provider.create - expect(File.read(tmpfile).chomp).to eq("foo1\ninserted = line\nfoo2\nfoo = baz") - } - end - describe 'append to end of file if no match for both after and match' do - include_context 'resource_create' do - let(:match) { '^nevergoingtomatch$' } - let(:after) { '^stillneverafter' } - end - it { - provider.create - expect(File.read(tmpfile).chomp).to eq("foo1\nfoo2\nfoo = baz\ninserted = line") - } - end - end - context 'with one line matching the after expression' do - before :each do - File.open(tmpfile, 'w') do |fh| - fh.write("foo1\nfoo = blah\nfoo2\nfoo = baz") - end - end - - it 'inserts the specified line after the line matching the "after" expression' do - provider.create - expect(File.read(tmpfile).chomp).to eql("foo1\ninserted = line\nfoo = blah\nfoo2\nfoo = baz") - end - end - context 'with multiple lines matching the after expression' do - before :each do - File.open(tmpfile, 'w') do |fh| - fh.write("foo1\nfoo = blah\nfoo2\nfoo1\nfoo = baz") - end end + let(:content) { "foo\nfoo bar\nbar\nfoo baz" } - it 'errors out stating "One or no line must match the pattern"' do - expect { provider.create }.to raise_error(Puppet::Error, /One or no line must match the pattern/) - end - - it 'adds the line after all lines matching the after expression' do - @resource = Puppet::Type::File_line.new( - { - :name => 'foo', - :path => tmpfile, - :line => 'inserted = line', - :after => '^foo1$', - :multiple => true, - } - ) - @provider = provider_class.new(@resource) - expect(@provider.exists?).to eql (false) - @provider.create - expect(File.read(tmpfile).chomp).to eql("foo1\ninserted = line\nfoo = blah\nfoo2\nfoo1\ninserted = line\nfoo = baz") - end - end - context 'with no lines matching the after expression' do - let :content do - "foo3\nfoo = blah\nfoo2\nfoo = baz\n" - end - - before :each do - File.open(tmpfile, 'w') do |fh| - fh.write(content) - end + it 'requests changes' do + expect(provider).not_to be_exists end - - it 'appends the specified line to the file' do + it 'replaces the matches' do provider.create - expect(File.read(tmpfile)).to eq(content << resource[:line] << "\n") + expect(File.read(tmpfile).chomp).to eql("foo\nfoo\nbar\nfoo") end end - end - context "when removing with a line" do - before :each do - # TODO: these should be ported over to use the PuppetLabs spec_helper - # file fixtures once the following pull request has been merged: - # https://github.com/puppetlabs/puppetlabs-stdlib/pull/73/files - @resource = Puppet::Type::File_line.new( + + context 'when match matches line - when there are the same matches and lines' do + let(:params) do { - :name => 'foo', - :path => tmpfile, - :line => 'foo', - :ensure => 'absent', + replace_all_matches_not_matching_line: true, + match: '^foo', + multiple: true, } - ) - @provider = provider_class.new(@resource) - end - it 'should remove the line if it exists' do - File.open(tmpfile, 'w') do |fh| - fh.write("foo1\nfoo\nfoo2") - end - @provider.destroy - expect(File.read(tmpfile)).to eql("foo1\nfoo2") - end - it 'should remove the line without touching the last new line' do - File.open(tmpfile, 'w') do |fh| - fh.write("foo1\nfoo\nfoo2\n") end - @provider.destroy - expect(File.read(tmpfile)).to eql("foo1\nfoo2\n") - end - it 'should remove any occurence of the line' do - File.open(tmpfile, 'w') do |fh| - fh.write("foo1\nfoo\nfoo2\nfoo\nfoo") + let(:content) { "foo\nfoo\nbar" } + + it 'does not request changes' do + expect(provider).to be_exists end - @provider.destroy - expect(File.read(tmpfile)).to eql("foo1\nfoo2\n") end - it 'example in the docs' do - @resource = Puppet::Type::File_line.new( + + context 'when match does not match line - when there are more matches than lines' do + let(:params) do { - :name => 'bashrc_proxy', - :ensure => 'absent', - :path => tmpfile, - :line => 'export HTTP_PROXY=http://squid.puppetlabs.vm:3128', + replace_all_matches_not_matching_line: true, + match: '^bar', + multiple: true, } - ) - @provider = provider_class.new(@resource) - File.open(tmpfile, 'w') do |fh| - fh.write("foo1\nfoo2\nexport HTTP_PROXY=http://squid.puppetlabs.vm:3128\nfoo4\n") end - @provider.destroy - expect(File.read(tmpfile)).to eql("foo1\nfoo2\nfoo4\n") - end - end - context "when removing with a match" do - before :each do - @resource = Puppet::Type::File_line.new( - { - :name => 'foo', - :path => tmpfile, - :line => 'foo2', - :ensure => 'absent', - :match => 'o$', - :match_for_absence => true, - } - ) - @provider = provider_class.new(@resource) - end + let(:content) { "foo\nfoo bar\nbar\nbar baz" } - it 'should find a line to match' do - File.open(tmpfile, 'w') do |fh| - fh.write("foo1\nfoo\nfoo2") + it 'requests changes' do + expect(provider).not_to be_exists end - expect(@provider.exists?).to eql (true) - end - - it 'should remove one line if it matches' do - File.open(tmpfile, 'w') do |fh| - fh.write("foo1\nfoo\nfoo2") + it 'replaces the matches' do + provider.create + expect(File.read(tmpfile).chomp).to eql("foo\nfoo bar\nfoo\nfoo") end - @provider.destroy - expect(File.read(tmpfile)).to eql("foo1\nfoo2") end - it 'the line parameter is actually not used at all but is silently ignored if here' do - @resource = Puppet::Type::File_line.new( + context 'when match does not match line - when there are the same matches and lines' do + let(:params) do { - :name => 'foo', - :path => tmpfile, - :line => 'supercalifragilisticexpialidocious', - :ensure => 'absent', - :match => 'o$', - :match_for_absence => true, + replace_all_matches_not_matching_line: true, + match: '^bar', + multiple: true, } - ) - @provider = provider_class.new(@resource) - File.open(tmpfile, 'w') do |fh| - fh.write("foo1\nfoo\nfoo2") end - expect(@provider.exists?).to eql (true) - @provider.destroy - expect(File.read(tmpfile)).to eql("foo1\nfoo2") - end + let(:content) { "foo\nfoo\nbar\nbar baz" } - it 'and may not be here and does not need to be here' do - @resource = Puppet::Type::File_line.new( - { - :name => 'foo', - :path => tmpfile, - :ensure => 'absent', - :match => 'o$', - :match_for_absence => true, - } - ) - @provider = provider_class.new(@resource) - File.open(tmpfile, 'w') do |fh| - fh.write("foo1\nfoo\nfoo2") + it 'requests changes' do + expect(provider).not_to be_exists end - expect(@provider.exists?).to eql (true) - @provider.destroy - expect(File.read(tmpfile)).to eql("foo1\nfoo2") - end - - it 'should raise an error if more than one line matches' do - File.open(tmpfile, 'w') do |fh| - fh.write("foo1\nfoo\nfoo2\nfoo\nfoo") + it 'replaces the matches' do + provider.create + expect(File.read(tmpfile).chomp).to eql("foo\nfoo\nfoo\nfoo") end - expect { @provider.destroy }.to raise_error(Puppet::Error, /More than one line/) end + end - it 'should remove multiple lines if :multiple is true' do - @resource = Puppet::Type::File_line.new( - { - :name => 'foo', - :path => tmpfile, - :line => 'foo2', - :ensure => 'absent', - :match => 'o$', - :multiple => true, - :match_for_absence => true, - } - ) - @provider = provider_class.new(@resource) - File.open(tmpfile, 'w') do |fh| - fh.write("foo1\nfoo\nfoo2\nfoo\nfoo") - end - expect(@provider.exists?).to eql (true) - @provider.destroy - expect(File.read(tmpfile)).to eql("foo1\nfoo2\n") + context 'when match does not match line - when there are no matches' do + let(:params) do + { + replace_all_matches_not_matching_line: true, + match: '^bar', + multiple: true, + } end + let(:content) { "foo\nfoo bar" } - it 'should ignore the match if match_for_absence is not specified' do - @resource = Puppet::Type::File_line.new( - { - :name => 'foo', - :path => tmpfile, - :line => 'foo2', - :ensure => 'absent', - :match => 'o$', - } - ) - @provider = provider_class.new(@resource) - File.open(tmpfile, 'w') do |fh| - fh.write("foo1\nfoo\nfoo2") - end - expect(@provider.exists?).to eql (true) - @provider.destroy - expect(File.read(tmpfile)).to eql("foo1\nfoo\n") + it 'does not request changes' do + expect(provider).to be_exists end + end - it 'should ignore the match if match_for_absence is false' do - @resource = Puppet::Type::File_line.new( - { - :name => 'foo', - :path => tmpfile, - :line => 'foo2', - :ensure => 'absent', - :match => 'o$', - :match_for_absence => false, - } - ) - @provider = provider_class.new(@resource) - File.open(tmpfile, 'w') do |fh| - fh.write("foo1\nfoo\nfoo2") - end - expect(@provider.exists?).to eql (true) - @provider.destroy - expect(File.read(tmpfile)).to eql("foo1\nfoo\n") + context 'when match does not match line - when there are no matches or lines' do + let(:params) do + { + replace_all_matches_not_matching_line: true, + match: '^bar', + multiple: true, + } end + let(:content) { 'foo bar' } - it 'example in the docs' do - @resource = Puppet::Type::File_line.new( - { - :name => 'bashrc_proxy', - :ensure => 'absent', - :path => tmpfile, - :line => 'export HTTP_PROXY=http://squid.puppetlabs.vm:3128', - :match => '^export\ HTTP_PROXY\=', - :match_for_absence => true, - } - ) - @provider = provider_class.new(@resource) - File.open(tmpfile, 'w') do |fh| - fh.write("foo1\nfoo2\nexport HTTP_PROXY=foo\nfoo4\n") - end - expect(@provider.exists?).to eql (true) - @provider.destroy - expect(File.read(tmpfile)).to eql("foo1\nfoo2\nfoo4\n") + it 'requests changes' do + expect(provider).not_to be_exists end - - it 'example in the docs showing line is redundant' do - @resource = Puppet::Type::File_line.new( - { - :name => 'bashrc_proxy', - :ensure => 'absent', - :path => tmpfile, - :match => '^export\ HTTP_PROXY\=', - :match_for_absence => true, - } - ) - @provider = provider_class.new(@resource) - File.open(tmpfile, 'w') do |fh| - fh.write("foo1\nfoo2\nexport HTTP_PROXY=foo\nfoo4\n") - end - expect(@provider.exists?).to eql (true) - @provider.destroy - expect(File.read(tmpfile)).to eql("foo1\nfoo2\nfoo4\n") + it 'appends the line' do + provider.create + expect(File.read(tmpfile).chomp).to eql("foo bar\nfoo") end end end diff --git a/spec/unit/puppet/provider/file_line/ruby_spec_alter.rb b/spec/unit/puppet/provider/file_line/ruby_spec_alter.rb new file mode 100755 index 000000000..e9b7541c7 --- /dev/null +++ b/spec/unit/puppet/provider/file_line/ruby_spec_alter.rb @@ -0,0 +1,377 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +provider_class = Puppet::Type.type(:file_line).provider(:ruby) +#  These tests fail on windows when run as part of the rake task. Individually they pass +describe provider_class, unless: Puppet::Util::Platform.windows? do + include PuppetlabsSpec::Files + + let :tmpfile do + tmpfilename('file_line_test') + end + let :content do + '' + end + let :params do + {} + end + let :resource do + Puppet::Type::File_line.new({ + name: 'foo', + path: tmpfile, + line: 'foo', + }.merge(params)) + end + let :provider do + provider_class.new(resource) + end + + before :each do + File.open(tmpfile, 'w') do |fh| + fh.write(content) + end + end + + describe '#create' do + context 'when adding' do + pending('To be added.') + end + context 'when replacing' do + let :params do + { + line: 'foo = bar', + match: '^foo\s*=.*$', + replace: false, + } + end + let(:content) { "foo1\nfoo=blah\nfoo2\nfoo3" } + + it "providor 'be_exists'" do + expect(provider).to be_exists + end + it 'does not replace the matching line' do + provider.create + expect(File.read(tmpfile).chomp).to eql("foo1\nfoo=blah\nfoo2\nfoo3") + end + it 'appends the line if no matches are found' do # rubocop:disable RSpec/MultipleExpectations : separating expectations breaks the tests + File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo2") } + expect(provider.exists?).to be false + provider.create + expect(File.read(tmpfile).chomp).to eql("foo1\nfoo2\nfoo = bar") + end + it 'raises an error with invalid values' do + expect { + @resource = Puppet::Type::File_line.new( + name: 'foo', path: tmpfile, line: 'foo = bar', match: '^foo\s*=.*$', replace: 'asgadga', + ) + }.to raise_error(Puppet::Error, %r{Invalid value "asgadga"\. Valid values are true, false\.}) + end + end + end + describe '#destroy' do + pending('To be added?') + end + context 'when matching' do + # rubocop:disable RSpec/InstanceVariable : replacing before with let breaks the tests, variables need to be altered within it block : multi + before :each do + @resource = Puppet::Type::File_line.new( + name: 'foo', + path: tmpfile, + line: 'foo = bar', + match: '^foo\s*=.*$', + ) + @provider = provider_class.new(@resource) + end + describe 'using match' do + it 'raises an error if more than one line matches, and should not have modified the file' do # rubocop:disable RSpec/MultipleExpectations : multiple expectations required + File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo=blah\nfoo2\nfoo=baz") } + expect { @provider.create }.to raise_error(Puppet::Error, %r{More than one line.*matches}) + expect(File.read(tmpfile)).to eql("foo1\nfoo=blah\nfoo2\nfoo=baz") + end + + it 'replaces all lines that matches' do + @resource = Puppet::Type::File_line.new(name: 'foo', path: tmpfile, line: 'foo = bar', match: '^foo\s*=.*$', multiple: true) + @provider = provider_class.new(@resource) + File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo=blah\nfoo2\nfoo=baz") } + @provider.create + expect(File.read(tmpfile).chomp).to eql("foo1\nfoo = bar\nfoo2\nfoo = bar") + end + + it 'replaces all lines that match, even when some lines are correct' do + @resource = Puppet::Type::File_line.new(name: 'neil', path: tmpfile, line: "\thard\tcore\t0\n", match: '^[ \t]hard[ \t]+core[ \t]+.*', multiple: true) + @provider = provider_class.new(@resource) + File.open(tmpfile, 'w') { |fh| fh.write("\thard\tcore\t90\n\thard\tcore\t0\n") } + @provider.create + expect(File.read(tmpfile).chomp).to eql("\thard\tcore\t0\n\thard\tcore\t0") + end + + it 'raises an error with invalid values' do + expect { + @resource = Puppet::Type::File_line.new( + name: 'foo', path: tmpfile, line: 'foo = bar', match: '^foo\s*=.*$', multiple: 'asgadga', + ) + }.to raise_error(Puppet::Error, %r{Invalid value "asgadga"\. Valid values are true, false\.}) + end + + it 'replaces a line that matches' do + File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo=blah\nfoo2") } + @provider.create + expect(File.read(tmpfile).chomp).to eql("foo1\nfoo = bar\nfoo2") + end + it 'adds a new line if no lines match' do + File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo2") } + @provider.create + expect(File.read(tmpfile)).to eql("foo1\nfoo2\nfoo = bar\n") + end + it 'does nothing if the exact line already exists' do + File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo = bar\nfoo2") } + @provider.create + expect(File.read(tmpfile).chomp).to eql("foo1\nfoo = bar\nfoo2") + end + end + describe 'using match+append_on_no_match - when there is a match' do + it 'replaces line' do + @resource = Puppet::Type::File_line.new(name: 'foo', path: tmpfile, line: 'inserted = line', match: '^foo3$', append_on_no_match: false) + @provider = provider_class.new(@resource) + File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo = blah\nfoo2\nfoo = baz") } + expect(File.read(tmpfile).chomp).to eql("foo1\nfoo = blah\nfoo2\nfoo = baz") + end + end + describe 'using match+append_on_no_match - when there is no match' do + it 'does not add line after no matches found' do + @resource = Puppet::Type::File_line.new(name: 'foo', path: tmpfile, line: 'inserted = line', match: '^foo3$', append_on_no_match: false) + @provider = provider_class.new(@resource) + File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo = blah\nfoo2\nfoo = baz") } + expect(File.read(tmpfile).chomp).to eql("foo1\nfoo = blah\nfoo2\nfoo = baz") + end + end + end + context 'when match+replace+append_on_no_match' do + pending('to do') + end + context 'when after' do + let :resource do + Puppet::Type::File_line.new( + name: 'foo', + path: tmpfile, + line: 'inserted = line', + after: '^foo1', + ) + end + + let :provider do + provider_class.new(resource) + end + + context 'match and after set' do + shared_context 'resource_create' do + let(:match) { '^foo2$' } + let(:after) { '^foo1$' } + let(:resource) do + Puppet::Type::File_line.new( + name: 'foo', + path: tmpfile, + line: 'inserted = line', + after: after, + match: match, + ) + end + end + before :each do + File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo2\nfoo = baz") } + end + # rubocop:disable RSpec/NestedGroups : Reducing the nesting would needlesly complicate the code + describe 'inserts at match' do + include_context 'resource_create' + it { + provider.create + expect(File.read(tmpfile).chomp).to eq("foo1\ninserted = line\nfoo = baz") + } + end + describe 'inserts a new line after when no match' do + include_context 'resource_create' do + let(:match) { '^nevergoingtomatch$' } + end + it { + provider.create + expect(File.read(tmpfile).chomp).to eq("foo1\ninserted = line\nfoo2\nfoo = baz") + } + end + describe 'append to end of file if no match for both after and match' do + include_context 'resource_create' do + let(:match) { '^nevergoingtomatch$' } + let(:after) { '^stillneverafter' } + end + it { + provider.create + expect(File.read(tmpfile).chomp).to eq("foo1\nfoo2\nfoo = baz\ninserted = line") + } + end + end + context 'with one line matching the after expression' do + before :each do + File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo = blah\nfoo2\nfoo = baz") } + end + + it 'inserts the specified line after the line matching the "after" expression' do + provider.create + expect(File.read(tmpfile).chomp).to eql("foo1\ninserted = line\nfoo = blah\nfoo2\nfoo = baz") + end + end + context 'with multiple lines matching the after expression' do + before :each do + File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo = blah\nfoo2\nfoo1\nfoo = baz") } + end + + it 'errors out stating "One or no line must match the pattern"' do + expect { provider.create }.to raise_error(Puppet::Error, %r{One or no line must match the pattern}) + end + + it 'adds the line after all lines matching the after expression' do + @resource = Puppet::Type::File_line.new(name: 'foo', path: tmpfile, line: 'inserted = line', after: '^foo1$', multiple: true) + @provider = provider_class.new(@resource) + @provider.create + expect(File.read(tmpfile).chomp).to eql("foo1\ninserted = line\nfoo = blah\nfoo2\nfoo1\ninserted = line\nfoo = baz") + end + end + context 'with no lines matching the after expression' do + let :content do + "foo3\nfoo = blah\nfoo2\nfoo = baz\n" + end + + before :each do + File.open(tmpfile, 'w') { |fh| fh.write(content) } + end + + it 'appends the specified line to the file' do + provider.create + expect(File.read(tmpfile)).to eq(content << resource[:line] << "\n") + end + end + end + context 'when removing with a line' do + before :each do + # TODO: these should be ported over to use the PuppetLabs spec_helper + # file fixtures once the following pull request has been merged: + # https://github.com/puppetlabs/puppetlabs-stdlib/pull/73/files + @resource = Puppet::Type::File_line.new( + name: 'foo', + path: tmpfile, + line: 'foo', + ensure: 'absent', + ) + @provider = provider_class.new(@resource) + end + it 'removes the line if it exists' do + File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo\nfoo2") } + @provider.destroy + expect(File.read(tmpfile)).to eql("foo1\nfoo2") + end + it 'removes the line without touching the last new line' do + File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo\nfoo2\n") } + @provider.destroy + expect(File.read(tmpfile)).to eql("foo1\nfoo2\n") + end + it 'removes any occurence of the line' do + File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo\nfoo2\nfoo\nfoo") } + @provider.destroy + expect(File.read(tmpfile)).to eql("foo1\nfoo2\n") + end + it 'example in the docs' do + @resource = Puppet::Type::File_line.new(name: 'bashrc_proxy', ensure: 'absent', path: tmpfile, line: 'export HTTP_PROXY=http://squid.puppetlabs.vm:3128') + @provider = provider_class.new(@resource) + File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo2\nexport HTTP_PROXY=http://squid.puppetlabs.vm:3128\nfoo4\n") } + @provider.destroy + expect(File.read(tmpfile)).to eql("foo1\nfoo2\nfoo4\n") + end + end + context 'when removing with a match' do + before :each do + @resource = Puppet::Type::File_line.new( + name: 'foo', + path: tmpfile, + line: 'foo2', + ensure: 'absent', + match: 'o$', + match_for_absence: true, + ) + @provider = provider_class.new(@resource) + end + + it 'finds a line to match' do + File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo\nfoo2") } + expect(@provider.exists?).to be true + end + + it 'removes one line if it matches' do + File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo\nfoo2") } + @provider.destroy + expect(File.read(tmpfile)).to eql("foo1\nfoo2") + end + + it 'the line parameter is actually not used at all but is silently ignored if here' do + @resource = Puppet::Type::File_line.new(name: 'foo', path: tmpfile, line: 'supercalifragilisticexpialidocious', ensure: 'absent', match: 'o$', match_for_absence: true) + @provider = provider_class.new(@resource) + File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo\nfoo2") } + @provider.destroy + expect(File.read(tmpfile)).to eql("foo1\nfoo2") + end + + it 'and may not be here and does not need to be here' do + @resource = Puppet::Type::File_line.new(name: 'foo', path: tmpfile, ensure: 'absent', match: 'o$', match_for_absence: true) + @provider = provider_class.new(@resource) + File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo\nfoo2") } + @provider.destroy + expect(File.read(tmpfile)).to eql("foo1\nfoo2") + end + + it 'raises an error if more than one line matches' do + File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo\nfoo2\nfoo\nfoo") } + expect { @provider.destroy }.to raise_error(Puppet::Error, %r{More than one line}) + end + + it 'removes multiple lines if :multiple is true' do + @resource = Puppet::Type::File_line.new(name: 'foo', path: tmpfile, line: 'foo2', ensure: 'absent', match: 'o$', multiple: true, match_for_absence: true) + @provider = provider_class.new(@resource) + File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo\nfoo2\nfoo\nfoo") } + @provider.destroy + expect(File.read(tmpfile)).to eql("foo1\nfoo2\n") + end + + it 'ignores the match if match_for_absence is not specified' do + @resource = Puppet::Type::File_line.new(name: 'foo', path: tmpfile, line: 'foo2', ensure: 'absent', match: 'o$') + @provider = provider_class.new(@resource) + File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo\nfoo2") } + @provider.destroy + expect(File.read(tmpfile)).to eql("foo1\nfoo\n") + end + + it 'ignores the match if match_for_absence is false' do + @resource = Puppet::Type::File_line.new(name: 'foo', path: tmpfile, line: 'foo2', ensure: 'absent', match: 'o$', match_for_absence: false) + @provider = provider_class.new(@resource) + File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo\nfoo2") } + @provider.destroy + expect(File.read(tmpfile)).to eql("foo1\nfoo\n") + end + + it 'example in the docs' do # rubocop:disable RSpec/ExampleLength : Cannot reduce without violating line length rule + @resource = Puppet::Type::File_line.new( + name: 'bashrc_proxy', ensure: 'absent', path: tmpfile, line: 'export HTTP_PROXY=http://squid.puppetlabs.vm:3128', + match: '^export\ HTTP_PROXY\=', match_for_absence: true + ) + @provider = provider_class.new(@resource) + File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo2\nexport HTTP_PROXY=foo\nfoo4\n") } + @provider.destroy + expect(File.read(tmpfile)).to eql("foo1\nfoo2\nfoo4\n") + end + + it 'example in the docs showing line is redundant' do + @resource = Puppet::Type::File_line.new(name: 'bashrc_proxy', ensure: 'absent', path: tmpfile, match: '^export\ HTTP_PROXY\=', match_for_absence: true) + @provider = provider_class.new(@resource) + File.open(tmpfile, 'w') { |fh| fh.write("foo1\nfoo2\nexport HTTP_PROXY=foo\nfoo4\n") } + @provider.destroy + expect(File.read(tmpfile)).to eql("foo1\nfoo2\nfoo4\n") + end + end + # rubocop:enable RSpec/InstanceVariable : multi +end diff --git a/spec/unit/puppet/provider/file_line/ruby_spec_use_cases.rb b/spec/unit/puppet/provider/file_line/ruby_spec_use_cases.rb new file mode 100755 index 000000000..ed9a64ea7 --- /dev/null +++ b/spec/unit/puppet/provider/file_line/ruby_spec_use_cases.rb @@ -0,0 +1,136 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +provider_class = Puppet::Type.type(:file_line).provider(:ruby) +#  These tests fail on windows when run as part of the rake task. Individually they pass +describe provider_class, unless: Puppet::Util::Platform.windows? do + include PuppetlabsSpec::Files + + let :tmpfile do + tmpfilename('file_line_test') + end + let :content do + '' + end + let :params do + {} + end + let :resource do + Puppet::Type::File_line.new({ + name: 'foo', + path: tmpfile, + line: 'foo', + }.merge(params)) + end + let :provider do + provider_class.new(resource) + end + + before :each do + File.open(tmpfile, 'w') do |fh| + fh.write(content) + end + end + + describe 'customer use cases - no lines' do + describe 'MODULES-5003' do + let(:params) do + { + line: "*\thard\tcore\t0", + match: "^[ \t]*\\*[ \t]+hard[ \t]+core[ \t]+.*", + multiple: true, + } + end + let(:content) { "* hard core 90\n* hard core 10\n" } + + it 'requests changes' do + expect(provider).not_to be_exists + end + it 'replaces the matches' do + provider.create + expect(File.read(tmpfile).chomp).to eq("* hard core 0\n* hard core 0") + end + end + + describe 'MODULES-5003 - one match, one line - just ensure the line exists' do + let(:params) do + { + line: "*\thard\tcore\t0", + match: "^[ \t]*\\*[ \t]+hard[ \t]+core[ \t]+.*", + multiple: true, + } + end + let(:content) { "* hard core 90\n* hard core 0\n" } + + it 'does not request changes' do + expect(provider).to be_exists + end + end + + describe 'MODULES-5003 - one match, one line - replace all matches, even when line exists' do + let(:params) do + { + line: "*\thard\tcore\t0", + match: "^[ \t]*\\*[ \t]+hard[ \t]+core[ \t]+.*", + multiple: true, + + }.merge(replace_all_matches_not_matching_line: true) + end + let(:content) { "* hard core 90\n* hard core 0\n" } + + it 'requests changes' do + expect(provider).not_to be_exists + end + it 'replaces the matches' do + provider.create + expect(File.read(tmpfile).chomp).to eq("* hard core 0\n* hard core 0") + end + end + + describe 'MODULES-5651 - match, no line' do + let(:params) do + { + line: 'LogLevel=notice', + match: '^#LogLevel$', + } + end + let(:content) { "#LogLevel\nstuff" } + + it 'requests changes' do + expect(provider).not_to be_exists + end + it 'replaces the match' do + provider.create + expect(File.read(tmpfile).chomp).to eq("LogLevel=notice\nstuff") + end + end + + describe 'MODULES-5651 - match, line' do + let(:params) do + { + line: 'LogLevel=notice', + match: '^#LogLevel$', + } + end + let(:content) { "#Loglevel\nLogLevel=notice\nstuff" } + + it 'does not request changes' do + expect(provider).to be_exists + end + end + + describe 'MODULES-5651 - no match, line' do + let(:params) do + { + line: 'LogLevel=notice', + match: '^#LogLevel$', + } + end + let(:content) { "LogLevel=notice\nstuff" } + + it 'does not request changes' do + expect(provider).to be_exists + end + end + end +end diff --git a/spec/unit/puppet/type/anchor_spec.rb b/spec/unit/puppet/type/anchor_spec.rb index c738a272b..63cdb468a 100755 --- a/spec/unit/puppet/type/anchor_spec.rb +++ b/spec/unit/puppet/type/anchor_spec.rb @@ -2,10 +2,10 @@ require 'spec_helper' -anchor = Puppet::Type.type(:anchor).new(:name => "ntp::begin") +anchor = Puppet::Type.type(:anchor).new(name: 'ntp::begin') describe anchor do - it "should stringify normally" do - expect(anchor.to_s).to eq("Anchor[ntp::begin]") + it 'stringifies normally' do + expect(anchor.to_s).to eq('Anchor[ntp::begin]') end end diff --git a/spec/unit/puppet/type/file_line_spec.rb b/spec/unit/puppet/type/file_line_spec.rb index db073528d..2e742dd2e 100755 --- a/spec/unit/puppet/type/file_line_spec.rb +++ b/spec/unit/puppet/type/file_line_spec.rb @@ -17,98 +17,94 @@ end end let :file_line do - Puppet::Type.type(:file_line).new(:name => 'foo', :line => 'line', :path => tmp_path) + Puppet::Type.type(:file_line).new(name: 'foo', line: 'line', path: tmp_path) end - it 'should accept a line and path' do + + it 'accepts a line' do file_line[:line] = 'my_line' expect(file_line[:line]).to eq('my_line') + end + it 'accepts a path' do file_line[:path] = my_path expect(file_line[:path]).to eq(my_path) end - it 'should accept a match regex' do + it 'accepts a match regex' do file_line[:match] = '^foo.*$' expect(file_line[:match]).to eq('^foo.*$') end - it 'should accept a match regex that does not match the specified line' do + + it 'accepts a match regex that does not match the specified line' do expect { Puppet::Type.type(:file_line).new( - :name => 'foo', - :path => my_path, - :line => 'foo=bar', - :match => '^bar=blah$' - )}.not_to raise_error + name: 'foo', path: my_path, line: 'foo=bar', match: '^bar=blah$', + ) + }.not_to raise_error end - it 'should accept a match regex that does match the specified line' do + it 'accepts a match regex that does match the specified line' do expect { Puppet::Type.type(:file_line).new( - :name => 'foo', - :path => my_path, - :line => 'foo=bar', - :match => '^\s*foo=.*$' - )}.not_to raise_error + name: 'foo', path: my_path, line: 'foo=bar', match: '^\s*foo=.*$', + ) + }.not_to raise_error end - it 'should accept utf8 characters' do + it 'accepts utf8 characters' do expect { Puppet::Type.type(:file_line).new( - :name => 'ƒồỗ', - :path => my_path, - :line => 'ƒồỗ=ьåя', - :match => '^ьåя=βļάħ$' - )}.not_to raise_error + name: 'ƒồỗ', path: my_path, line: 'ƒồỗ=ьåя', match: '^ьåя=βļάħ$', + ) + }.not_to raise_error end - it 'should accept double byte characters' do + it 'accepts double byte characters' do expect { Puppet::Type.type(:file_line).new( - :name => 'フーバー', - :path => my_path, - :line => 'この=それ', - :match => '^この=ああ$' - )}.not_to raise_error + name: 'フーバー', path: my_path, line: 'この=それ', match: '^この=ああ$', + ) + }.not_to raise_error end - it 'should accept posix filenames' do + it 'accepts posix filenames' do file_line[:path] = tmp_path expect(file_line[:path]).to eq(tmp_path) end - it 'should not accept unqualified path' do - expect { file_line[:path] = 'file' }.to raise_error(Puppet::Error, /File paths must be fully qualified/) + it 'does not accept unqualified path' do + expect { file_line[:path] = 'file' }.to raise_error(Puppet::Error, %r{File paths must be fully qualified}) end - it 'should require that a line is specified' do - expect { Puppet::Type.type(:file_line).new(:name => 'foo', :path => tmp_path) }.to raise_error(Puppet::Error, /line is a required attribute/) + it 'requires that a line is specified' do + expect { Puppet::Type.type(:file_line).new(name: 'foo', path: tmp_path) }.to raise_error(Puppet::Error, %r{line is a required attribute}) end - it 'should not require that a line is specified when matching for absence' do - expect { Puppet::Type.type(:file_line).new(:name => 'foo', :path => tmp_path, :ensure => :absent, :match_for_absence => :true, :match => 'match') }.not_to raise_error + it 'does not require that a line is specified when matching for absence' do + expect { Puppet::Type.type(:file_line).new(name: 'foo', path: tmp_path, ensure: :absent, match_for_absence: :true, match: 'match') }.not_to raise_error end it 'although if a line is specified anyway when matching for absence it still works and the line is silently ignored' do - expect { Puppet::Type.type(:file_line).new(:name => 'foo', :path => tmp_path, :line => 'i_am_irrelevant', :ensure => :absent, :match_for_absence => :true, :match => 'match') }.not_to raise_error + expect { Puppet::Type.type(:file_line).new(name: 'foo', path: tmp_path, line: 'i_am_irrelevant', ensure: :absent, match_for_absence: :true, match: 'match') }.not_to raise_error end - it 'should require that a file is specified' do - expect { Puppet::Type.type(:file_line).new(:name => 'foo', :line => 'path') }.to raise_error(Puppet::Error, /path is a required attribute/) + it 'requires that a file is specified' do + expect { Puppet::Type.type(:file_line).new(name: 'foo', line: 'path') }.to raise_error(Puppet::Error, %r{path is a required attribute}) end - it 'should default to ensure => present' do + it 'defaults to ensure => present' do expect(file_line[:ensure]).to eq :present end - it 'should default to replace => true' do + it 'defaults to replace => true' do expect(file_line[:replace]).to eq :true end - it 'should default to encoding => UTF-8' do + it 'defaults to encoding => UTF-8' do expect(file_line[:encoding]).to eq 'UTF-8' end - it 'should accept encoding => iso-8859-1' do - expect { Puppet::Type.type(:file_line).new(:name => 'foo', :path => tmp_path, :ensure => :present, :encoding => 'iso-8859-1', :line => 'bar') }.not_to raise_error + it 'accepts encoding => iso-8859-1' do + expect { Puppet::Type.type(:file_line).new(name: 'foo', path: tmp_path, ensure: :present, encoding: 'iso-8859-1', line: 'bar') }.not_to raise_error end - it "should autorequire the file it manages" do + + it 'autorequires the file it manages' do # rubocop:disable RSpec/ExampleLength : example size cannot be reduced catalog = Puppet::Resource::Catalog.new - file = Puppet::Type.type(:file).new(:name => tmp_path) + file = Puppet::Type.type(:file).new(name: tmp_path) catalog.add_resource file catalog.add_resource file_line - relationship = file_line.autorequire.find do |rel| - (rel.source.to_s == "File[#{tmp_path}]") and (rel.target.to_s == file_line.to_s) + (rel.source.to_s == "File[#{tmp_path}]") && (rel.target.to_s == file_line.to_s) end expect(relationship).to be_a Puppet::Relationship end - it "should not autorequire the file it manages if it is not managed" do + it 'does not autorequire the file it manages if it is not managed' do catalog = Puppet::Resource::Catalog.new catalog.add_resource file_line expect(file_line.autorequire).to be_empty