diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index 7c48aff..4021da7 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -1,230 +1,217 @@ name: "nightly" on: schedule: - cron: '0 0 * * *' env: HONEYCOMB_WRITEKEY: 7f3c63a70eecc61d635917de46bea4e6 HONEYCOMB_DATASET: litmus tests jobs: setup_matrix: name: "Setup Test Matrix" runs-on: ubuntu-20.04 outputs: matrix: ${{ steps.get-matrix.outputs.matrix }} steps: - name: "Honeycomb: Start recording" - uses: kvrhdn/gha-buildevents@v1.0.2 + uses: kvrhdn/gha-buildevents@5be4636b81803713c94d7cb7e3a4b85d759df112 # pin@v1.0.2 with: apikey: ${{ env.HONEYCOMB_WRITEKEY }} dataset: ${{ env.HONEYCOMB_DATASET }} job-status: ${{ job.status }} - name: "Honeycomb: Start first step" run: | echo STEP_ID=0 >> $GITHUB_ENV echo STEP_START=$(date +%s) >> $GITHUB_ENV - name: Checkout Source uses: actions/checkout@v2 if: ${{ github.repository_owner == 'puppetlabs' }} - name: Activate Ruby 2.7 uses: actions/setup-ruby@v1 if: ${{ github.repository_owner == 'puppetlabs' }} with: ruby-version: "2.7" - name: Cache gems uses: actions/cache@v2 if: ${{ github.repository_owner == 'puppetlabs' }} with: path: vendor/gems key: ${{ runner.os }}-${{ github.event_name }}-${{ hashFiles('**/Gemfile') }} restore-keys: | ${{ runner.os }}-${{ github.event_name }}- ${{ runner.os }}- - name: Install gems if: ${{ github.repository_owner == 'puppetlabs' }} run: | buildevents cmd $TRACE_ID $STEP_ID 'bundle config path vendor/gems' -- bundle config path vendor/gems buildevents cmd $TRACE_ID $STEP_ID 'bundle config jobs 8' -- bundle config jobs 8 buildevents cmd $TRACE_ID $STEP_ID 'bundle config retry 3' -- bundle config retry 3 buildevents cmd $TRACE_ID $STEP_ID 'bundle install' -- bundle install buildevents cmd $TRACE_ID $STEP_ID 'bundle clean' -- bundle clean - name: Setup Acceptance Test Matrix id: get-matrix if: ${{ github.repository_owner == 'puppetlabs' }} run: | if [ '${{ github.repository_owner }}' == 'puppetlabs' ]; then buildevents cmd $TRACE_ID $STEP_ID matrix_from_metadata -- bundle exec matrix_from_metadata else echo "::set-output name=matrix::{}" fi - name: "Honeycomb: Record setup time" if: ${{ always() }} run: | buildevents step $TRACE_ID $STEP_ID $STEP_START 'Setup Test Matrix' Acceptance: needs: - setup_matrix runs-on: ubuntu-20.04 strategy: fail-fast: false matrix: ${{fromJson(needs.setup_matrix.outputs.matrix)}} env: BUILDEVENT_FILE: '../buildevents.txt' steps: - run: | echo 'platform=${{ matrix.platform }}' >> $BUILDEVENT_FILE echo 'collection=${{ matrix.collection }}' >> $BUILDEVENT_FILE - name: "Honeycomb: Start recording" - uses: kvrhdn/gha-buildevents@v1.0.2 + uses: kvrhdn/gha-buildevents@5be4636b81803713c94d7cb7e3a4b85d759df112 # pin@v1.0.2 with: apikey: ${{ env.HONEYCOMB_WRITEKEY }} dataset: ${{ env.HONEYCOMB_DATASET }} job-status: ${{ job.status }} matrix-key: ${{ matrix.platform }}-${{ matrix.collection }} - name: "Honeycomb: start first step" run: | echo STEP_ID=${{ matrix.platform }}-${{ matrix.collection }}-1 >> $GITHUB_ENV echo STEP_START=$(date +%s) >> $GITHUB_ENV - name: Checkout Source uses: actions/checkout@v2 - name: Activate Ruby 2.7 uses: actions/setup-ruby@v1 with: ruby-version: "2.7" - name: Cache gems uses: actions/cache@v2 with: path: vendor/gems key: ${{ runner.os }}-${{ github.event_name }}-${{ hashFiles('**/Gemfile') }} restore-keys: | ${{ runner.os }}-${{ github.event_name }}- ${{ runner.os }}- - name: "Honeycomb: Record cache setup time" if: ${{ always() }} run: | buildevents step $TRACE_ID $STEP_ID $STEP_START 'Cache retrieval' echo STEP_ID=${{ matrix.platform }}-${{ matrix.collection }}-2 >> $GITHUB_ENV echo STEP_START=$(date +%s) >> $GITHUB_ENV - name: Bundler Setup run: | buildevents cmd $TRACE_ID $STEP_ID 'bundle config path vendor/gems' -- bundle config path vendor/gems buildevents cmd $TRACE_ID $STEP_ID 'bundle config jobs 8' -- bundle config jobs 8 buildevents cmd $TRACE_ID $STEP_ID 'bundle config retry 3' -- bundle config retry 3 buildevents cmd $TRACE_ID $STEP_ID 'bundle install' -- bundle install buildevents cmd $TRACE_ID $STEP_ID 'bundle clean' -- bundle clean echo ::group::bundler environment buildevents cmd $TRACE_ID $STEP_ID 'bundle env' -- bundle env echo ::endgroup:: - name: "Honeycomb: Record Bundler Setup time" if: ${{ always() }} run: | buildevents step $TRACE_ID $STEP_ID $STEP_START 'Bundler Setup' echo STEP_ID=${{ matrix.platform }}-${{ matrix.collection }}-3 >> $GITHUB_ENV echo STEP_START=$(date +%s) >> $GITHUB_ENV - name: Provision test environment run: | buildevents cmd $TRACE_ID $STEP_ID 'rake litmus:provision ${{ matrix.platform }}' -- bundle exec rake 'litmus:provision[provision::provision_service,${{ matrix.platform }}]' echo ::group::=== REQUEST === cat request.json || true echo echo ::endgroup:: echo ::group::=== INVENTORY === sed -e 's/password: .*/password: "[redacted]"/' < inventory.yaml || true echo ::endgroup:: - # The provision service hands out machines as soon as they're provisioned. - # The GCP VMs might still take a while to spool up and configure themselves fully. - # This retry loop spins until all agents have been installed successfully. - name: Install agent - uses: nick-invision/retry@v1 - with: - timeout_minutes: 30 - max_attempts: 5 - retry_wait_seconds: 60 - command: buildevents cmd $TRACE_ID $STEP_ID 'rake litmus:install_agent ${{ matrix.collection }}' -- bundle exec rake 'litmus:install_agent[${{ matrix.collection }}]' + run: | + buildevents cmd $TRACE_ID $STEP_ID 'rake litmus:install_agent ${{ matrix.collection }}' -- bundle exec rake 'litmus:install_agent[${{ matrix.collection }}]' - # The agent installer on windows does not finish in time for this to work. To - # work around this for now, retry after a minute if installing the module failed. - name: Install module - uses: nick-invision/retry@v1 - with: - timeout_minutes: 30 - max_attempts: 2 - retry_wait_seconds: 60 - command: buildevents cmd $TRACE_ID $STEP_ID 'rake litmus:install_module' -- bundle exec rake 'litmus:install_module' + run: | + buildevents cmd $TRACE_ID $STEP_ID 'rake litmus:install_module' -- bundle exec rake 'litmus:install_module' - name: "Honeycomb: Record deployment times" if: ${{ always() }} run: | echo ::group::honeycomb step buildevents step $TRACE_ID $STEP_ID $STEP_START 'Deploy test system' echo STEP_ID=${{ matrix.platform }}-${{ matrix.collection }}-4 >> $GITHUB_ENV echo STEP_START=$(date +%s) >> $GITHUB_ENV echo ::endgroup:: - name: Run acceptance tests run: | buildevents cmd $TRACE_ID $STEP_ID 'rake litmus:acceptance:parallel' -- bundle exec rake 'litmus:acceptance:parallel' - name: "Honeycomb: Record acceptance testing times" if: ${{ always() }} run: | buildevents step $TRACE_ID $STEP_ID $STEP_START 'Run acceptance tests' echo STEP_ID=${{ matrix.platform }}-${{ matrix.collection }}-5 >> $GITHUB_ENV echo STEP_START=$(date +%s) >> $GITHUB_ENV - name: Remove test environment if: ${{ always() }} run: | if [ -f inventory.yaml ]; then buildevents cmd $TRACE_ID $STEP_ID 'rake litmus:tear_down' -- bundle exec rake 'litmus:tear_down' echo ::group::=== REQUEST === cat request.json || true echo echo ::endgroup:: fi - name: "Honeycomb: Record removal times" if: ${{ always() }} run: | buildevents step $TRACE_ID $STEP_ID $STEP_START 'Remove test environment' slack-workflow-status: if: always() name: Post Workflow Status To Slack needs: - Acceptance runs-on: ubuntu-20.04 steps: - name: Slack Workflow Notification - uses: Gamesight/slack-workflow-status@v1.0.1 + uses: Gamesight/slack-workflow-status@88ee95b73b4669825883ddf22747966204663e58 # pin@master with: # Required Input repo_token: ${{ secrets.GITHUB_TOKEN }} slack_webhook_url: ${{ secrets.SLACK_WEBHOOK }} # Optional Input channel: '#team-ia-bots' name: 'GABot' diff --git a/.github/workflows/pr_test.yml b/.github/workflows/pr_test.yml index 17f5a64..2b5ab1f 100644 --- a/.github/workflows/pr_test.yml +++ b/.github/workflows/pr_test.yml @@ -1,211 +1,198 @@ name: "PR Testing" on: [pull_request] env: HONEYCOMB_WRITEKEY: 7f3c63a70eecc61d635917de46bea4e6 HONEYCOMB_DATASET: litmus tests jobs: setup_matrix: name: "Setup Test Matrix" runs-on: ubuntu-20.04 outputs: matrix: ${{ steps.get-matrix.outputs.matrix }} steps: - name: "Honeycomb: Start recording" - uses: kvrhdn/gha-buildevents@v1.0.2 + uses: kvrhdn/gha-buildevents@5be4636b81803713c94d7cb7e3a4b85d759df112 # pin@v1.0.2 with: apikey: ${{ env.HONEYCOMB_WRITEKEY }} dataset: ${{ env.HONEYCOMB_DATASET }} job-status: ${{ job.status }} - name: "Honeycomb: Start first step" run: | echo STEP_ID=0 >> $GITHUB_ENV echo STEP_START=$(date +%s) >> $GITHUB_ENV - name: Checkout Source uses: actions/checkout@v2 if: ${{ github.repository_owner == 'puppetlabs' }} - name: Activate Ruby 2.7 uses: actions/setup-ruby@v1 if: ${{ github.repository_owner == 'puppetlabs' }} with: ruby-version: "2.7" - name: Cache gems uses: actions/cache@v2 if: ${{ github.repository_owner == 'puppetlabs' }} with: path: vendor/gems key: ${{ runner.os }}-${{ github.event_name }}-${{ hashFiles('**/Gemfile') }} restore-keys: | ${{ runner.os }}-${{ github.event_name }}- ${{ runner.os }}- - name: Install gems if: ${{ github.repository_owner == 'puppetlabs' }} run: | buildevents cmd $TRACE_ID $STEP_ID 'bundle config path vendor/gems' -- bundle config path vendor/gems buildevents cmd $TRACE_ID $STEP_ID 'bundle config jobs 8' -- bundle config jobs 8 buildevents cmd $TRACE_ID $STEP_ID 'bundle config retry 3' -- bundle config retry 3 buildevents cmd $TRACE_ID $STEP_ID 'bundle install' -- bundle install buildevents cmd $TRACE_ID $STEP_ID 'bundle clean' -- bundle clean - name: Setup Acceptance Test Matrix id: get-matrix if: ${{ github.repository_owner == 'puppetlabs' }} run: | if [ '${{ github.repository_owner }}' == 'puppetlabs' ]; then buildevents cmd $TRACE_ID $STEP_ID matrix_from_metadata -- bundle exec matrix_from_metadata else echo "::set-output name=matrix::{}" fi - name: "Honeycomb: Record setup time" if: ${{ always() }} run: | buildevents step $TRACE_ID $STEP_ID $STEP_START 'Setup Test Matrix' Acceptance: needs: - setup_matrix runs-on: ubuntu-20.04 strategy: fail-fast: false matrix: ${{fromJson(needs.setup_matrix.outputs.matrix)}} env: BUILDEVENT_FILE: '../buildevents.txt' steps: - run: | echo 'platform=${{ matrix.platform }}' >> $BUILDEVENT_FILE echo 'collection=${{ matrix.collection }}' >> $BUILDEVENT_FILE - name: "Honeycomb: Start recording" - uses: kvrhdn/gha-buildevents@v1.0.2 + uses: kvrhdn/gha-buildevents@5be4636b81803713c94d7cb7e3a4b85d759df112 # pin@v1.0.2 with: apikey: ${{ env.HONEYCOMB_WRITEKEY }} dataset: ${{ env.HONEYCOMB_DATASET }} job-status: ${{ job.status }} matrix-key: ${{ matrix.platform }}-${{ matrix.collection }} - name: "Honeycomb: start first step" run: | echo STEP_ID=${{ matrix.platform }}-${{ matrix.collection }}-1 >> $GITHUB_ENV echo STEP_START=$(date +%s) >> $GITHUB_ENV - name: Checkout Source uses: actions/checkout@v2 - name: Activate Ruby 2.7 uses: actions/setup-ruby@v1 with: ruby-version: "2.7" - name: Cache gems uses: actions/cache@v2 with: path: vendor/gems key: ${{ runner.os }}-${{ github.event_name }}-${{ hashFiles('**/Gemfile') }} restore-keys: | ${{ runner.os }}-${{ github.event_name }}- ${{ runner.os }}- - name: "Honeycomb: Record cache setup time" if: ${{ always() }} run: | buildevents step $TRACE_ID $STEP_ID $STEP_START 'Cache retrieval' echo STEP_ID=${{ matrix.platform }}-${{ matrix.collection }}-2 >> $GITHUB_ENV echo STEP_START=$(date +%s) >> $GITHUB_ENV - name: Bundler Setup run: | buildevents cmd $TRACE_ID $STEP_ID 'bundle config path vendor/gems' -- bundle config path vendor/gems buildevents cmd $TRACE_ID $STEP_ID 'bundle config jobs 8' -- bundle config jobs 8 buildevents cmd $TRACE_ID $STEP_ID 'bundle config retry 3' -- bundle config retry 3 buildevents cmd $TRACE_ID $STEP_ID 'bundle install' -- bundle install buildevents cmd $TRACE_ID $STEP_ID 'bundle clean' -- bundle clean echo ::group::bundler environment buildevents cmd $TRACE_ID $STEP_ID 'bundle env' -- bundle env echo ::endgroup:: - name: "Honeycomb: Record Bundler Setup time" if: ${{ always() }} run: | buildevents step $TRACE_ID $STEP_ID $STEP_START 'Bundler Setup' echo STEP_ID=${{ matrix.platform }}-${{ matrix.collection }}-3 >> $GITHUB_ENV echo STEP_START=$(date +%s) >> $GITHUB_ENV - name: Provision test environment run: | buildevents cmd $TRACE_ID $STEP_ID 'rake litmus:provision ${{ matrix.platform }}' -- bundle exec rake 'litmus:provision[provision::provision_service,${{ matrix.platform }}]' echo ::group::=== REQUEST === cat request.json || true echo echo ::endgroup:: echo ::group::=== INVENTORY === sed -e 's/password: .*/password: "[redacted]"/' < inventory.yaml || true echo ::endgroup:: - # The provision service hands out machines as soon as they're provisioned. - # The GCP VMs might still take a while to spool up and configure themselves fully. - # This retry loop spins until all agents have been installed successfully. - name: Install agent - uses: nick-invision/retry@v1 - with: - timeout_minutes: 30 - max_attempts: 5 - retry_wait_seconds: 60 - command: buildevents cmd $TRACE_ID $STEP_ID 'rake litmus:install_agent ${{ matrix.collection }}' -- bundle exec rake 'litmus:install_agent[${{ matrix.collection }}]' + run: | + buildevents cmd $TRACE_ID $STEP_ID 'rake litmus:install_agent ${{ matrix.collection }}' -- bundle exec rake 'litmus:install_agent[${{ matrix.collection }}]' - # The agent installer on windows does not finish in time for this to work. To - # work around this for now, retry after a minute if installing the module failed. - name: Install module - uses: nick-invision/retry@v1 - with: - timeout_minutes: 30 - max_attempts: 2 - retry_wait_seconds: 60 - command: buildevents cmd $TRACE_ID $STEP_ID 'rake litmus:install_module' -- bundle exec rake 'litmus:install_module' + run: | + buildevents cmd $TRACE_ID $STEP_ID 'rake litmus:install_module' -- bundle exec rake 'litmus:install_module' - name: "Honeycomb: Record deployment times" if: ${{ always() }} run: | echo ::group::honeycomb step buildevents step $TRACE_ID $STEP_ID $STEP_START 'Deploy test system' echo STEP_ID=${{ matrix.platform }}-${{ matrix.collection }}-4 >> $GITHUB_ENV echo STEP_START=$(date +%s) >> $GITHUB_ENV echo ::endgroup:: - name: Run acceptance tests run: | buildevents cmd $TRACE_ID $STEP_ID 'rake litmus:acceptance:parallel' -- bundle exec rake 'litmus:acceptance:parallel' - name: "Honeycomb: Record acceptance testing times" if: ${{ always() }} run: | buildevents step $TRACE_ID $STEP_ID $STEP_START 'Run acceptance tests' echo STEP_ID=${{ matrix.platform }}-${{ matrix.collection }}-5 >> $GITHUB_ENV echo STEP_START=$(date +%s) >> $GITHUB_ENV - name: Remove test environment if: ${{ always() }} run: | if [ -f inventory.yaml ]; then buildevents cmd $TRACE_ID $STEP_ID 'rake litmus:tear_down' -- bundle exec rake 'litmus:tear_down' echo ::group::=== REQUEST === cat request.json || true echo echo ::endgroup:: fi - name: "Honeycomb: Record removal times" if: ${{ always() }} run: | buildevents step $TRACE_ID $STEP_ID $STEP_START 'Remove test environment' diff --git a/.rubocop.yml b/.rubocop.yml index b7c972b..6a240fe 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -1,138 +1,515 @@ --- require: +- rubocop-performance - rubocop-rspec -- rubocop-i18n AllCops: DisplayCopNames: true - TargetRubyVersion: '2.1' + TargetRubyVersion: '2.4' Include: - - "./**/*.rb" + - "**/*.rb" Exclude: - bin/* - ".vendor/**/*" - "**/Gemfile" - "**/Rakefile" - pkg/**/* - spec/fixtures/**/* - vendor/**/* - "**/Puppetfile" - "**/Vagrantfile" - "**/Guardfile" -Metrics/LineLength: +inherit_from: ".rubocop_todo.yml" +Layout/LineLength: Description: People have wide screens, use them. Max: 200 -GetText: - Enabled: false -GetText/DecorateString: - Description: We don't want to decorate test output. - Exclude: - - spec/**/* - Enabled: false 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/BracesAroundHashParameters: - Description: Braces are required by Ruby 2.7. Cop removed from RuboCop v0.80.0. - See https://github.com/rubocop-hq/rubocop/pull/7643 - Enabled: false Style/ClassAndModuleChildren: Description: Compact style reduces the required amount of indentation. EnforcedStyle: compact Style/EmptyElse: Description: Enforce against empty else clauses, but allow `nil` for clarity. EnforcedStyle: empty Style/FormatString: Description: Following the main puppet project's style, prefer the % format format. EnforcedStyle: percent Style/FormatStringToken: Description: Following the main puppet project's style, prefer the simpler template tokens over annotated ones. EnforcedStyle: template Style/Lambda: Description: Prefer the keyword for easier discoverability. EnforcedStyle: literal Style/RegexpLiteral: Description: Community preference. See https://github.com/voxpupuli/modulesync_config/issues/168 EnforcedStyle: percent_r Style/TernaryParentheses: Description: Checks for use of parentheses around ternary conditions. Enforce parentheses on complex expressions for better readability, but seriously consider breaking it up. EnforcedStyle: require_parentheses_when_complex Style/TrailingCommaInArguments: Description: Prefer always trailing comma on multiline argument lists. This makes diffs, and re-ordering nicer. EnforcedStyleForMultiline: comma -Style/TrailingCommaInLiteral: +Style/TrailingCommaInArrayLiteral: 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 -inherit_from: ".rubocop_todo.yml" RSpec/MessageSpies: EnforcedStyle: receive Style/Documentation: Exclude: - lib/puppet/parser/functions/**/* - spec/**/* Style/WordArray: EnforcedStyle: brackets +Performance/AncestorsInclude: + Enabled: true +Performance/BigDecimalWithNumericArgument: + Enabled: true +Performance/BlockGivenWithExplicitBlock: + Enabled: true +Performance/CaseWhenSplat: + Enabled: true +Performance/ConstantRegexp: + Enabled: true +Performance/MethodObjectAsBlock: + Enabled: true +Performance/RedundantSortBlock: + Enabled: true +Performance/RedundantStringChars: + Enabled: true +Performance/ReverseFirst: + Enabled: true +Performance/SortReverse: + Enabled: true +Performance/Squeeze: + Enabled: true +Performance/StringInclude: + Enabled: true +Performance/Sum: + Enabled: true Style/CollectionMethods: Enabled: true Style/MethodCalledOnDoEndBlock: Enabled: true Style/StringMethods: Enabled: true -GetText/DecorateFunctionMessage: +Bundler/InsecureProtocolSource: + Enabled: false +Gemspec/DuplicatedAssignment: + Enabled: false +Gemspec/OrderedDependencies: + Enabled: false +Gemspec/RequiredRubyVersion: + Enabled: false +Gemspec/RubyVersionGlobalsUsage: + Enabled: false +Layout/ArgumentAlignment: + Enabled: false +Layout/BeginEndAlignment: Enabled: false -GetText/DecorateStringFormattingUsingInterpolation: +Layout/ClosingHeredocIndentation: Enabled: false -GetText/DecorateStringFormattingUsingPercent: +Layout/EmptyComment: + Enabled: false +Layout/EmptyLineAfterGuardClause: + Enabled: false +Layout/EmptyLinesAroundArguments: + Enabled: false +Layout/EmptyLinesAroundAttributeAccessor: Enabled: false Layout/EndOfLine: Enabled: false -Layout/IndentHeredoc: +Layout/FirstArgumentIndentation: + Enabled: false +Layout/HashAlignment: + Enabled: false +Layout/HeredocIndentation: + Enabled: false +Layout/LeadingEmptyLines: + Enabled: false +Layout/SpaceAroundMethodCallOperator: + Enabled: false +Layout/SpaceInsideArrayLiteralBrackets: + Enabled: false +Layout/SpaceInsideReferenceBrackets: + Enabled: false +Lint/BigDecimalNew: + Enabled: false +Lint/BooleanSymbol: + Enabled: false +Lint/ConstantDefinitionInBlock: + Enabled: false +Lint/DeprecatedOpenSSLConstant: + Enabled: false +Lint/DisjunctiveAssignmentInConstructor: + Enabled: false +Lint/DuplicateElsifCondition: + Enabled: false +Lint/DuplicateRequire: + Enabled: false +Lint/DuplicateRescueException: + Enabled: false +Lint/EmptyConditionalBody: + Enabled: false +Lint/EmptyFile: + Enabled: false +Lint/ErbNewArguments: + Enabled: false +Lint/FloatComparison: + Enabled: false +Lint/HashCompareByIdentity: + Enabled: false +Lint/IdentityComparison: + Enabled: false +Lint/InterpolationCheck: + Enabled: false +Lint/MissingCopEnableDirective: + Enabled: false +Lint/MixedRegexpCaptureTypes: + Enabled: false +Lint/NestedPercentLiteral: + Enabled: false +Lint/NonDeterministicRequireOrder: + Enabled: false +Lint/OrderedMagicComments: + Enabled: false +Lint/OutOfRangeRegexpRef: + Enabled: false +Lint/RaiseException: + Enabled: false +Lint/RedundantCopEnableDirective: + Enabled: false +Lint/RedundantRequireStatement: + Enabled: false +Lint/RedundantSafeNavigation: + Enabled: false +Lint/RedundantWithIndex: + Enabled: false +Lint/RedundantWithObject: + Enabled: false +Lint/RegexpAsCondition: + Enabled: false +Lint/ReturnInVoidContext: + Enabled: false +Lint/SafeNavigationConsistency: + Enabled: false +Lint/SafeNavigationWithEmpty: + Enabled: false +Lint/SelfAssignment: + Enabled: false +Lint/SendWithMixinArgument: + Enabled: false +Lint/ShadowedArgument: + Enabled: false +Lint/StructNewOverride: + Enabled: false +Lint/ToJSON: + Enabled: false +Lint/TopLevelReturnWithArgument: + Enabled: false +Lint/TrailingCommaInAttributeDeclaration: + Enabled: false +Lint/UnreachableLoop: + Enabled: false +Lint/UriEscapeUnescape: + Enabled: false +Lint/UriRegexp: + Enabled: false +Lint/UselessMethodDefinition: + Enabled: false +Lint/UselessTimes: Enabled: false Metrics/AbcSize: Enabled: false Metrics/BlockLength: Enabled: false +Metrics/BlockNesting: + 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 +Migration/DepartmentName: + Enabled: false +Naming/AccessorMethodName: + Enabled: false +Naming/BlockParameterName: + Enabled: false +Naming/HeredocDelimiterCase: + Enabled: false +Naming/HeredocDelimiterNaming: + Enabled: false +Naming/MemoizedInstanceVariableName: + Enabled: false +Naming/MethodParameterName: + Enabled: false +Naming/RescuedExceptionsVariableName: + Enabled: false +Naming/VariableNumber: + Enabled: false +Performance/BindCall: + Enabled: false +Performance/DeletePrefix: + Enabled: false +Performance/DeleteSuffix: + Enabled: false +Performance/InefficientHashSearch: + Enabled: false +Performance/UnfreezeString: + Enabled: false +Performance/UriDefaultParser: + Enabled: false +RSpec/Be: + Enabled: false +RSpec/Capybara/CurrentPathExpectation: + Enabled: false +RSpec/Capybara/FeatureMethods: + Enabled: false +RSpec/Capybara/VisibilityMatcher: + Enabled: false +RSpec/ContextMethod: + Enabled: false +RSpec/ContextWording: + Enabled: false RSpec/DescribeClass: Enabled: false +RSpec/EmptyHook: + Enabled: false +RSpec/EmptyLineAfterExample: + Enabled: false +RSpec/EmptyLineAfterExampleGroup: + Enabled: false +RSpec/EmptyLineAfterHook: + Enabled: false RSpec/ExampleLength: Enabled: false -RSpec/MessageExpectation: +RSpec/ExampleWithoutDescription: + Enabled: false +RSpec/ExpectChange: + Enabled: false +RSpec/ExpectInHook: + Enabled: false +RSpec/FactoryBot/AttributeDefinedStatically: + Enabled: false +RSpec/FactoryBot/CreateList: + Enabled: false +RSpec/FactoryBot/FactoryClassName: + Enabled: false +RSpec/HooksBeforeExamples: + Enabled: false +RSpec/ImplicitBlockExpectation: + Enabled: false +RSpec/ImplicitSubject: + Enabled: false +RSpec/LeakyConstantDeclaration: + Enabled: false +RSpec/LetBeforeExamples: + Enabled: false +RSpec/MissingExampleGroupArgument: Enabled: false RSpec/MultipleExpectations: Enabled: false +RSpec/MultipleMemoizedHelpers: + Enabled: false +RSpec/MultipleSubjects: + Enabled: false RSpec/NestedGroups: Enabled: false +RSpec/PredicateMatcher: + Enabled: false +RSpec/ReceiveCounts: + Enabled: false +RSpec/ReceiveNever: + Enabled: false +RSpec/RepeatedExampleGroupBody: + Enabled: false +RSpec/RepeatedExampleGroupDescription: + Enabled: false +RSpec/RepeatedIncludeExample: + Enabled: false +RSpec/ReturnFromStub: + Enabled: false +RSpec/SharedExamples: + Enabled: false +RSpec/StubbedMock: + Enabled: false +RSpec/UnspecifiedException: + Enabled: false +RSpec/VariableDefinition: + Enabled: false +RSpec/VoidExpect: + Enabled: false +RSpec/Yield: + Enabled: false +Security/Open: + Enabled: false +Style/AccessModifierDeclarations: + Enabled: false +Style/AccessorGrouping: + Enabled: false Style/AsciiComments: Enabled: false +Style/BisectedAttrAccessor: + Enabled: false +Style/CaseLikeIf: + Enabled: false +Style/ClassEqualityComparison: + Enabled: false +Style/ColonMethodDefinition: + Enabled: false +Style/CombinableLoops: + Enabled: false +Style/CommentedKeyword: + Enabled: false +Style/Dir: + Enabled: false +Style/DoubleCopDisableDirective: + Enabled: false +Style/EmptyBlockParameter: + Enabled: false +Style/EmptyLambdaParameter: + Enabled: false +Style/Encoding: + Enabled: false +Style/EvalWithLocation: + Enabled: false +Style/ExpandPathArguments: + Enabled: false +Style/ExplicitBlockArgument: + Enabled: false +Style/ExponentialNotation: + Enabled: false +Style/FloatDivision: + Enabled: false +Style/GlobalStdStream: + Enabled: false +Style/HashAsLastArrayItem: + Enabled: false +Style/HashLikeCase: + Enabled: false +Style/HashTransformKeys: + Enabled: false +Style/HashTransformValues: + Enabled: false Style/IfUnlessModifier: Enabled: false +Style/KeywordParametersOrder: + Enabled: false +Style/MinMax: + Enabled: false +Style/MixinUsage: + Enabled: false +Style/MultilineWhenThen: + Enabled: false +Style/NegatedUnless: + Enabled: false +Style/NumericPredicate: + Enabled: false +Style/OptionalBooleanParameter: + Enabled: false +Style/OrAssignment: + Enabled: false +Style/RandomWithOffset: + Enabled: false +Style/RedundantAssignment: + Enabled: false +Style/RedundantCondition: + Enabled: false +Style/RedundantConditional: + Enabled: false +Style/RedundantFetchBlock: + Enabled: false +Style/RedundantFileExtensionInRequire: + Enabled: false +Style/RedundantRegexpCharacterClass: + Enabled: false +Style/RedundantRegexpEscape: + Enabled: false +Style/RedundantSelfAssignment: + Enabled: false +Style/RedundantSort: + Enabled: false +Style/RescueStandardError: + Enabled: false +Style/SingleArgumentDig: + Enabled: false +Style/SlicingWithRange: + Enabled: false +Style/SoleNestedConditional: + Enabled: false +Style/StderrPuts: + Enabled: false +Style/StringConcatenation: + Enabled: false +Style/Strip: + Enabled: false Style/SymbolProc: Enabled: false +Style/TrailingBodyOnClass: + Enabled: false +Style/TrailingBodyOnMethodDefinition: + Enabled: false +Style/TrailingBodyOnModule: + Enabled: false +Style/TrailingCommaInHashLiteral: + Enabled: false +Style/TrailingMethodEndStatement: + Enabled: false +Style/UnpackFirst: + Enabled: false +Lint/DuplicateBranch: + Enabled: false +Lint/DuplicateRegexpCharacterClassElement: + Enabled: false +Lint/EmptyBlock: + Enabled: false +Lint/EmptyClass: + Enabled: false +Lint/NoReturnInBeginEndBlocks: + Enabled: false +Lint/ToEnumArguments: + Enabled: false +Lint/UnexpectedBlockArity: + Enabled: false +Lint/UnmodifiedReduceAccumulator: + Enabled: false +Performance/CollectionLiteralInLoop: + Enabled: false +Style/ArgumentsForwarding: + Enabled: false +Style/CollectionCompact: + Enabled: false +Style/DocumentDynamicEvalDefinition: + Enabled: false +Style/NegatedIfElseCondition: + Enabled: false +Style/NilLambda: + Enabled: false +Style/RedundantArgument: + Enabled: false +Style/SwapValues: + Enabled: false diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index 198402c..c3fb692 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -1,10 +1,26 @@ +# This configuration was generated by +# `rubocop --auto-gen-config` +# on 2020-12-17 20:35:36 UTC using RuboCop version 1.6.1. +# The point is for the user to remove these configuration records +# one by one as the offenses are removed from the code base. +# Note that changes in the inspected code, or installation of new +# versions of RuboCop, may require this file to be generated again. + +# Offense count: 6 +# Configuration parameters: AllowComments. +Lint/SuppressedException: + Exclude: + - 'lib/facter/facter_dot_d.rb' + - 'lib/puppet/functions/merge.rb' + - 'lib/puppet/parser/functions/getvar.rb' + - 'lib/puppet/parser/functions/has_interface_with.rb' + +# Offense count: 62 +# Configuration parameters: IgnoreSharedExamples. RSpec/NamedSubject: Enabled: false -Lint/ScriptPermission: - Enabled: false -Style/HashSyntax: + +# Offense count: 2 +RSpec/SubjectStub: Exclude: - - spec/spec_helper.rb - EnforcedStyle: hash_rockets -Layout/IndentHeredoc: - Enabled: false + - 'spec/unit/facter/facter_dot_d_spec.rb' diff --git a/.sync.yml b/.sync.yml index b1ac9cd..92c9a14 100644 --- a/.sync.yml +++ b/.sync.yml @@ -1,75 +1,67 @@ --- ".gitlab-ci.yml": delete: true ".rubocop.yml": - default_configs: - inherit_from: ".rubocop_todo.yml" + include_todos: true ".travis.yml": global_env: - HONEYCOMB_WRITEKEY="7f3c63a70eecc61d635917de46bea4e6",HONEYCOMB_DATASET="litmus tests" deploy_to_forge: enabled: false dist: trusty user: puppet secure: '' branches: - release use_litmus: true litmus: provision_list: - ---travis_el - travis_deb - travis_el7 - travis_el8 complex: - collection: puppet_collection: - puppet6 provision_list: - travis_ub_6 - collection: puppet_collection: - puppet5 provision_list: - travis_ub_5 simplecov: true notifications: slack: secure: j5y9T97u6QlDPs4eEnDNch2IGAzbfWycVcMutP3u9Klvkgqu33xtxHgyAQOW+2A/Xw2sKQs/LzIiUeQRzlNMcAPRZ0rK19sW1w5OgZGcd131HViFDfX8W7V4R41sZVNF232JekMr7RwPGIaZ9htaGsDJeJF8TaiG1Akk32LQZV8= appveyor.yml: environment: HONEYCOMB_WRITEKEY: 7f3c63a70eecc61d635917de46bea4e6 HONEYCOMB_DATASET: litmus tests use_litmus: true matrix_extras: - RUBY_VERSION: 25-x64 ACCEPTANCE: 'yes' TARGET_HOST: localhost - RUBY_VERSION: 25-x64 ACCEPTANCE: 'yes' TARGET_HOST: localhost APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017 simplecov: true Gemfile: - use_litmus: true optional: ":development": - gem: github_changelog_generator - git: https://github.com/skywinder/github-changelog-generator - ref: 20ee04ba1234e9e83eb2ffb5056e23d641c7a018 - condition: Gem::Version.new(RUBY_VERSION.dup) >= Gem::Version.new('2.2.2') -Rakefile: - requires: - - puppet-lint/tasks/puppet-lint spec/spec_helper.rb: mock_with: ":rspec" coverage_report: true .gitpod.Dockerfile: unmanaged: false .gitpod.yml: unmanaged: false .github/workflows/nightly.yml: unmanaged: false .github/workflows/pr_test.yml: unmanaged: false diff --git a/.travis.yml b/.travis.yml index 3f1e6a6..f006c47 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,146 +1,138 @@ --- os: linux dist: trusty language: ruby cache: bundler before_install: - bundle -v - rm -f Gemfile.lock - "# Update system gems if requested. This is useful to temporarily workaround troubles in the test runner" - "# See https://github.com/puppetlabs/pdk-templates/commit/705154d5c437796b821691b707156e1b056d244f for an example of how this was used" - "# Ignore exit code of SIGPIPE'd yes to not fail with shell's pipefail set" - '[ -z "$RUBYGEMS_VERSION" ] || (yes || true) | gem update --system $RUBYGEMS_VERSION' - gem --version - bundle -v script: - 'SIMPLECOV=yes bundle exec rake $CHECK' bundler_args: --without system_tests rvm: - 2.5.7 env: global: - HONEYCOMB_WRITEKEY="7f3c63a70eecc61d635917de46bea4e6",HONEYCOMB_DATASET="litmus tests" stages: - static - spec - acceptance jobs: fast_finish: true include: - - + - bundler_args: --with system_tests before_script: - "bundle exec rake 'litmus:provision_list[travis_ub_6]'" - "bundle exec rake 'litmus:install_agent[puppet6]'" - "bundle exec rake litmus:install_module" - bundler_args: env: PLATFORMS=travis_ub_6_puppet6 rvm: 2.5.7 script: ["travis_wait 45 bundle exec rake litmus:acceptance:parallel"] services: docker stage: acceptance - - + - bundler_args: --with system_tests before_script: - "bundle exec rake 'litmus:provision_list[travis_ub_5]'" - "bundle exec rake 'litmus:install_agent[puppet5]'" - "bundle exec rake litmus:install_module" - bundler_args: env: PLATFORMS=travis_ub_5_puppet5 rvm: 2.5.7 script: ["travis_wait 45 bundle exec rake litmus:acceptance:parallel"] services: docker stage: acceptance - - + - bundler_args: --with system_tests before_script: - "bundle exec rake 'litmus:provision_list[travis_deb]'" - "bundle exec rake 'litmus:install_agent[puppet5]'" - "bundle exec rake litmus:install_module" - bundler_args: env: PLATFORMS=travis_deb_puppet5 rvm: 2.5.7 script: ["travis_wait 45 bundle exec rake litmus:acceptance:parallel"] services: docker stage: acceptance - - + - bundler_args: --with system_tests before_script: - "bundle exec rake 'litmus:provision_list[travis_el7]'" - "bundle exec rake 'litmus:install_agent[puppet5]'" - "bundle exec rake litmus:install_module" - bundler_args: env: PLATFORMS=travis_el7_puppet5 rvm: 2.5.7 script: ["travis_wait 45 bundle exec rake litmus:acceptance:parallel"] services: docker stage: acceptance - - + - bundler_args: --with system_tests before_script: - "bundle exec rake 'litmus:provision_list[travis_el8]'" - "bundle exec rake 'litmus:install_agent[puppet5]'" - "bundle exec rake litmus:install_module" - bundler_args: env: PLATFORMS=travis_el8_puppet5 rvm: 2.5.7 script: ["travis_wait 45 bundle exec rake litmus:acceptance:parallel"] services: docker stage: acceptance - - + - bundler_args: --with system_tests before_script: - "bundle exec rake 'litmus:provision_list[travis_deb]'" - "bundle exec rake 'litmus:install_agent[puppet6]'" - "bundle exec rake litmus:install_module" - bundler_args: env: PLATFORMS=travis_deb_puppet6 rvm: 2.5.7 script: ["travis_wait 45 bundle exec rake litmus:acceptance:parallel"] services: docker stage: acceptance - - + - bundler_args: --with system_tests before_script: - "bundle exec rake 'litmus:provision_list[travis_el7]'" - "bundle exec rake 'litmus:install_agent[puppet6]'" - "bundle exec rake litmus:install_module" - bundler_args: env: PLATFORMS=travis_el7_puppet6 rvm: 2.5.7 script: ["travis_wait 45 bundle exec rake litmus:acceptance:parallel"] services: docker stage: acceptance - - + - bundler_args: --with system_tests before_script: - "bundle exec rake 'litmus:provision_list[travis_el8]'" - "bundle exec rake 'litmus:install_agent[puppet6]'" - "bundle exec rake litmus:install_module" - bundler_args: env: PLATFORMS=travis_el8_puppet6 rvm: 2.5.7 script: ["travis_wait 45 bundle exec rake litmus:acceptance:parallel"] services: docker stage: acceptance - env: CHECK="check:symlinks check:git_ignore check:dot_underscore check:test_file rubocop syntax lint metadata_lint" stage: static - env: PUPPET_GEM_VERSION="~> 5.0" CHECK=parallel_spec rvm: 2.4.5 stage: spec - env: PUPPET_GEM_VERSION="~> 6.0" CHECK=parallel_spec rvm: 2.5.7 stage: spec branches: only: - main - /^v\d/ - release notifications: email: false slack: secure: j5y9T97u6QlDPs4eEnDNch2IGAzbfWycVcMutP3u9Klvkgqu33xtxHgyAQOW+2A/Xw2sKQs/LzIiUeQRzlNMcAPRZ0rK19sW1w5OgZGcd131HViFDfX8W7V4R41sZVNF232JekMr7RwPGIaZ9htaGsDJeJF8TaiG1Akk32LQZV8= deploy: provider: puppetforge username: puppet password: secure: "" on: tags: true all_branches: true condition: "$DEPLOY_TO_FORGE = yes" diff --git a/Gemfile b/Gemfile index b6b25af..ae2b430 100644 --- a/Gemfile +++ b/Gemfile @@ -1,74 +1,73 @@ source ENV['GEM_SOURCE'] || 'https://rubygems.org' def location_for(place_or_version, fake_version = nil) git_url_regex = %r{\A(?(https?|git)[:@][^#]*)(#(?.*))?} file_url_regex = %r{\Afile:\/\/(?.*)} if place_or_version && (git_url = place_or_version.match(git_url_regex)) [fake_version, { git: git_url[:url], branch: git_url[:branch], require: false }].compact elsif place_or_version && (file_url = place_or_version.match(file_url_regex)) ['>= 0', { path: File.expand_path(file_url[:path]), require: false }] else [place_or_version, { require: false }] end end ruby_version_segments = Gem::Version.new(RUBY_VERSION.dup).segments minor_version = ruby_version_segments[0..1].join('.') group :development do - gem "fast_gettext", '1.1.0', require: false if Gem::Version.new(RUBY_VERSION.dup) < Gem::Version.new('2.1.0') - gem "fast_gettext", require: false if Gem::Version.new(RUBY_VERSION.dup) >= Gem::Version.new('2.1.0') - gem "json_pure", '<= 2.0.1', require: false if Gem::Version.new(RUBY_VERSION.dup) < Gem::Version.new('2.0.0') - gem "json", '= 1.8.1', require: false if Gem::Version.new(RUBY_VERSION.dup) == Gem::Version.new('2.1.9') gem "json", '= 2.0.4', require: false if Gem::Requirement.create('~> 2.4.2').satisfied_by?(Gem::Version.new(RUBY_VERSION.dup)) gem "json", '= 2.1.0', require: false if Gem::Requirement.create(['>= 2.5.0', '< 2.7.0']).satisfied_by?(Gem::Version.new(RUBY_VERSION.dup)) gem "json", '= 2.3.0', require: false if Gem::Requirement.create(['>= 2.7.0', '< 2.8.0']).satisfied_by?(Gem::Version.new(RUBY_VERSION.dup)) - gem "rb-readline", '= 0.5.5', require: false, platforms: [:mswin, :mingw, :x64_mingw] - gem "puppet-module-posix-default-r#{minor_version}", '~> 0.4', require: false, platforms: [:ruby] - gem "puppet-module-posix-dev-r#{minor_version}", '~> 0.4', require: false, platforms: [:ruby] - gem "puppet-module-win-default-r#{minor_version}", '~> 0.4', require: false, platforms: [:mswin, :mingw, :x64_mingw] - gem "puppet-module-win-dev-r#{minor_version}", '~> 0.4', require: false, platforms: [:mswin, :mingw, :x64_mingw] - gem "github_changelog_generator", require: false, git: 'https://github.com/skywinder/github-changelog-generator', ref: '20ee04ba1234e9e83eb2ffb5056e23d641c7a018' if Gem::Version.new(RUBY_VERSION.dup) >= Gem::Version.new('2.2.2') + gem "puppet-module-posix-default-r#{minor_version}", '~> 1.0', require: false, platforms: [:ruby] + gem "puppet-module-posix-dev-r#{minor_version}", '~> 1.0', require: false, platforms: [:ruby] + gem "puppet-module-win-default-r#{minor_version}", '~> 1.0', require: false, platforms: [:mswin, :mingw, :x64_mingw] + gem "puppet-module-win-dev-r#{minor_version}", '~> 1.0', require: false, platforms: [:mswin, :mingw, :x64_mingw] + gem "github_changelog_generator", require: false +end +group :system_tests do + gem "puppet-module-posix-system-r#{minor_version}", '~> 1.0', require: false, platforms: [:ruby] + gem "puppet-module-win-system-r#{minor_version}", '~> 1.0', require: false, platforms: [:mswin, :mingw, :x64_mingw] end puppet_version = ENV['PUPPET_GEM_VERSION'] facter_version = ENV['FACTER_GEM_VERSION'] hiera_version = ENV['HIERA_GEM_VERSION'] gems = {} gems['puppet'] = location_for(puppet_version) # If facter or hiera versions have been specified via the environment # variables gems['facter'] = location_for(facter_version) if facter_version gems['hiera'] = location_for(hiera_version) if hiera_version if Gem.win_platform? && puppet_version =~ %r{^(file:///|git://)} # If we're using a Puppet gem on Windows which handles its own win32-xxx gem # dependencies (>= 3.5.0), set the maximum versions (see PUP-6445). gems['win32-dir'] = ['<= 0.4.9', require: false] gems['win32-eventlog'] = ['<= 0.6.5', require: false] gems['win32-process'] = ['<= 0.7.5', require: false] gems['win32-security'] = ['<= 0.2.5', require: false] gems['win32-service'] = ['0.8.8', require: false] end gems.each do |gem_name, gem_params| gem gem_name, *gem_params end # Evaluate Gemfile.local and ~/.gemfile if they exist extra_gemfiles = [ "#{__FILE__}.local", File.join(Dir.home, '.gemfile'), ] extra_gemfiles.each do |gemfile| if File.file?(gemfile) && File.readable?(gemfile) eval(File.read(gemfile), binding) end end # vim: syntax=ruby diff --git a/Rakefile b/Rakefile index 11539b9..0a5093b 100644 --- a/Rakefile +++ b/Rakefile @@ -1,88 +1,87 @@ # frozen_string_literal: true require 'puppet_litmus/rake_tasks' if Bundler.rubygems.find_name('puppet_litmus').any? require 'puppetlabs_spec_helper/rake_tasks' require 'puppet-syntax/tasks/puppet-syntax' require 'puppet_blacksmith/rake_tasks' if Bundler.rubygems.find_name('puppet-blacksmith').any? require 'github_changelog_generator/task' if Bundler.rubygems.find_name('github_changelog_generator').any? require 'puppet-strings/tasks' if Bundler.rubygems.find_name('puppet-strings').any? -require 'puppet-lint/tasks/puppet-lint' def changelog_user return unless Rake.application.top_level_tasks.include? "changelog" returnVal = nil || JSON.load(File.read('metadata.json'))['author'] raise "unable to find the changelog_user in .sync.yml, or the author in metadata.json" if returnVal.nil? puts "GitHubChangelogGenerator user:#{returnVal}" returnVal end def changelog_project return unless Rake.application.top_level_tasks.include? "changelog" returnVal = nil returnVal ||= begin metadata_source = JSON.load(File.read('metadata.json'))['source'] metadata_source_match = metadata_source && metadata_source.match(%r{.*\/([^\/]*?)(?:\.git)?\Z}) metadata_source_match && metadata_source_match[1] end raise "unable to find the changelog_project in .sync.yml or calculate it from the source in metadata.json" if returnVal.nil? puts "GitHubChangelogGenerator project:#{returnVal}" returnVal end def changelog_future_release return unless Rake.application.top_level_tasks.include? "changelog" returnVal = "v%s" % JSON.load(File.read('metadata.json'))['version'] raise "unable to find the future_release (version) in metadata.json" if returnVal.nil? puts "GitHubChangelogGenerator future_release:#{returnVal}" returnVal end PuppetLint.configuration.send('disable_relative') if Bundler.rubygems.find_name('github_changelog_generator').any? GitHubChangelogGenerator::RakeTask.new :changelog do |config| raise "Set CHANGELOG_GITHUB_TOKEN environment variable eg 'export CHANGELOG_GITHUB_TOKEN=valid_token_here'" if Rake.application.top_level_tasks.include? "changelog" and ENV['CHANGELOG_GITHUB_TOKEN'].nil? config.user = "#{changelog_user}" config.project = "#{changelog_project}" config.future_release = "#{changelog_future_release}" config.exclude_labels = ['maintenance'] config.header = "# Change log\n\nAll notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](http://semver.org)." config.add_pr_wo_labels = true config.issues = false config.merge_prefix = "### UNCATEGORIZED PRS; LABEL THEM ON GITHUB" config.configure_sections = { "Changed" => { "prefix" => "### Changed", "labels" => ["backwards-incompatible"], }, "Added" => { "prefix" => "### Added", "labels" => ["enhancement", "feature"], }, "Fixed" => { "prefix" => "### Fixed", "labels" => ["bug", "documentation", "bugfix"], }, } end else desc 'Generate a Changelog from GitHub' task :changelog do raise < 1.15' condition: "Gem::Version.new(RUBY_VERSION.dup) >= Gem::Version.new('2.3.0')" EOM end end diff --git a/appveyor.yml b/appveyor.yml index eb3dcfb..d69b461 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -1,84 +1,84 @@ --- version: 1.1.x.{build} branches: only: - main - release skip_commits: message: /^\(?doc\)?.*/ clone_depth: 10 init: - SET - 'mkdir C:\ProgramData\PuppetLabs\code && exit 0' - 'mkdir C:\ProgramData\PuppetLabs\facter && exit 0' - 'mkdir C:\ProgramData\PuppetLabs\hiera && exit 0' - 'mkdir C:\ProgramData\PuppetLabs\puppet\var && exit 0' environment: HONEYCOMB_WRITEKEY: 7f3c63a70eecc61d635917de46bea4e6 HONEYCOMB_DATASET: litmus tests SIMPLECOV: yes matrix: - - RUBY_VERSION: 24-x64 + RUBY_VERSION: 25-x64 CHECK: syntax lint metadata_lint check:symlinks check:git_ignore check:dot_underscore check:test_file rubocop - PUPPET_GEM_VERSION: ~> 5.0 RUBY_VERSION: 24 CHECK: parallel_spec - PUPPET_GEM_VERSION: ~> 5.0 RUBY_VERSION: 24-x64 CHECK: parallel_spec - PUPPET_GEM_VERSION: ~> 6.0 RUBY_VERSION: 25 CHECK: parallel_spec - PUPPET_GEM_VERSION: ~> 6.0 RUBY_VERSION: 25-x64 CHECK: parallel_spec - RUBY_VERSION: 25-x64 ACCEPTANCE: yes TARGET_HOST: localhost - RUBY_VERSION: 25-x64 ACCEPTANCE: yes TARGET_HOST: localhost APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017 for: - matrix: only: - ACCEPTANCE: yes install: - set PATH=C:\Ruby%RUBY_VERSION%\bin;%PATH% - bundle install --jobs 4 --retry 2 - type Gemfile.lock test_script: - bundle exec puppet -V - ruby -v - gem -v - bundle -v - bundle exec rake spec_prep - bundle exec rake litmus:acceptance:localhost matrix: fast_finish: true install: - set PATH=C:\Ruby%RUBY_VERSION%\bin;%PATH% - bundle install --jobs 4 --retry 2 --without system_tests - type Gemfile.lock build: off test_script: - bundle exec puppet -V - ruby -v - gem -v - bundle -v - bundle exec rake %CHECK% notifications: - provider: Email to: - nobody@nowhere.com on_build_success: false on_build_failure: false on_build_status_changed: false diff --git a/lib/facter/package_provider.rb b/lib/facter/package_provider.rb index d993e79..02a1724 100644 --- a/lib/facter/package_provider.rb +++ b/lib/facter/package_provider.rb @@ -1,23 +1,25 @@ +# frozen_string_literal: true + # Fact: package_provider # # Purpose: Returns the default provider Puppet will choose to manage packages # on this system # # Resolution: Instantiates a dummy package resource and return the provider # # Caveats: # require 'puppet/type' require 'puppet/type/package' # These will be nil if Puppet is not available. Facter.add(:package_provider) do # Instantiates a dummy package resource and return the provider setcode do 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 + 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 81cd1fd..9f51431 100644 --- a/lib/facter/pe_version.rb +++ b/lib/facter/pe_version.rb @@ -1,70 +1,72 @@ +# frozen_string_literal: true + # Fact: is_pe, pe_version, pe_major_version, pe_minor_version, pe_patch_version # # Purpose: Return various facts about the PE state of the system # # Resolution: Uses a regex match against puppetversion to determine whether the # machine has Puppet Enterprise installed, and what version (overall, major, # minor, patch) is installed. # # Caveats: # # Fact: pe_version Facter.add('pe_version') do setcode do found_version = Facter.value('pe_build') unless found_version puppet_ver = Facter.value('puppetversion') unless puppet_ver.nil? pe_ver = puppet_ver.match(%r{Puppet Enterprise (\d+\.\d+\.\d+)}) found_version = pe_ver[1] if pe_ver end end found_version end end # Fact: is_pe Facter.add('is_pe') do setcode do if Facter.value(:pe_version).to_s.empty? false else true end end end # Fact: pe_major_version Facter.add('pe_major_version') do - confine :is_pe => true + confine is_pe: true setcode do pe_version = Facter.value(:pe_version) if pe_version pe_version.to_s.split('.')[0] end end end # Fact: pe_minor_version Facter.add('pe_minor_version') do - confine :is_pe => true + confine is_pe: true setcode do pe_version = Facter.value(:pe_version) if pe_version pe_version.to_s.split('.')[1] end end end # Fact: pe_patch_version Facter.add('pe_patch_version') do - confine :is_pe => true + confine is_pe: true setcode do pe_version = Facter.value(:pe_version) if pe_version pe_version.to_s.split('.')[2] end end end diff --git a/lib/facter/puppet_settings.rb b/lib/facter/puppet_settings.rb index 97deaad..951b2eb 100644 --- a/lib/facter/puppet_settings.rb +++ b/lib/facter/puppet_settings.rb @@ -1,44 +1,46 @@ +# frozen_string_literal: true + # These facter facts return the value of the Puppet vardir and environment path # settings for the node running puppet or puppet agent. The intent is to # enable Puppet modules to automatically have insight into a place where they # can place variable data, or for modules running on the puppet server to know # where environments are stored. # # The values should be directly usable in a File resource path attribute. # begin require 'facter/util/puppet_settings' rescue LoadError => e # puppet apply does not add module lib directories to the $LOAD_PATH (See # #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.exist?(rb_file) || raise(e) end # Facter fact returns the value of the Puppet vardir Facter.add(:puppet_vardir) do setcode do Facter::Util::PuppetSettings.with_puppet do Puppet[:vardir] end end end # Facter fact returns the value of the Puppet environment path Facter.add(:puppet_environmentpath) do setcode do Facter::Util::PuppetSettings.with_puppet do Puppet[:environmentpath] end end end # Facter fact returns the value of the Puppet server Facter.add(:puppet_server) do setcode do Facter::Util::PuppetSettings.with_puppet do Puppet[:server] end end end diff --git a/lib/facter/root_home.rb b/lib/facter/root_home.rb index 7544dd0..257a182 100644 --- a/lib/facter/root_home.rb +++ b/lib/facter/root_home.rb @@ -1,47 +1,49 @@ +# frozen_string_literal: true + # root_home.rb module Facter::Util::RootHome # @summary # A facter fact to determine the root home directory. # This varies on PE supported platforms and may be # reconfigured by the end user. class << self - # determines the root home directory - 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] - end + # determines the root home directory + 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] + end end end Facter.add(:root_home) do 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') hash = {} str.split("\n").each do |pair| key, value = pair.split(%r{:}) hash[key] = value end hash['dir'].strip end 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 && str.split("\n").each do |line| - next if line =~ %r{^#} + str&.split("\n")&.each do |line| + next if %r{^#}.match?(line) root_home = line.split(%r{:})[1] end root_home end end diff --git a/lib/facter/service_provider.rb b/lib/facter/service_provider.rb index a117921..3d4e44a 100644 --- a/lib/facter/service_provider.rb +++ b/lib/facter/service_provider.rb @@ -1,17 +1,19 @@ +# frozen_string_literal: true + # Fact: service_provider # # Purpose: Returns the default provider Puppet will choose to manage services # on this system # # Resolution: Instantiates a dummy service resource and return the provider # # Caveats: # require 'puppet/type' require 'puppet/type/service' 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 d12e92c..df2ed59 100644 --- a/lib/facter/util/puppet_settings.rb +++ b/lib/facter/util/puppet_settings.rb @@ -1,16 +1,18 @@ +# frozen_string_literal: true + # 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 2f6b0c0..f71924f 100644 --- a/lib/puppet/functions/deprecation.rb +++ b/lib/puppet/functions/deprecation.rb @@ -1,38 +1,40 @@ +# frozen_string_literal: true + # 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 # @param key # @param message # @return deprecated warnings dispatch :deprecation do param 'String', :key param 'String', :message end def deprecation(key, message) if defined? Puppet::Pops::PuppetStack.stacktrace stacktrace = Puppet::Pops::PuppetStack.stacktrace() file = stacktrace[0] line = stacktrace[1] message = "#{message} at #{file}:#{line}" end # depending on configuration setting of strict case Puppet.settings[:strict] - when :off # rubocop:disable Lint/EmptyWhen : Is required to prevent false errors + when :off # do nothing when :error raise("deprecation. #{key}. #{message}") else unless ENV['STDLIB_LOG_DEPRECATIONS'] == 'false' Puppet.deprecation_warning(message, key) end end end end diff --git a/lib/puppet/functions/fact.rb b/lib/puppet/functions/fact.rb index c963d16..c450436 100644 --- a/lib/puppet/functions/fact.rb +++ b/lib/puppet/functions/fact.rb @@ -1,63 +1,65 @@ +# frozen_string_literal: true + # @summary # Digs into the facts hash using dot-notation # # Supports the use of dot-notation for referring to structured facts. If a fact requested # does not exist, returns Undef. # # @example Example usage: # fact('osfamily') # fact('os.architecture') # # @example Array indexing: # fact('mountpoints."/dev".options.1') # # @example Fact containing a "." in the name: # fact('vmware."VRA.version"') # Puppet::Functions.create_function(:fact) do # @param fact_name # The name of the fact to check # # @return # All information retrieved on the given fact_name dispatch :fact do param 'String', :fact_name end def to_dot_syntax(array_path) array_path.map { |string| string.include?('.') ? %("#{string}") : string }.join('.') end def fact(fact_name) facts = closure_scope['facts'] # 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(%r{([^."]+)|(?:")([^"]+)(?:")}).map { |x| x.compact.first } walked_path = [] path.reduce(facts) do |d, k| return nil if d.nil? || k.nil? if d.is_a?(Array) begin result = d[Integer(k)] 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 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}'") result = nil end walked_path << k result end end end diff --git a/lib/puppet/functions/is_a.rb b/lib/puppet/functions/is_a.rb index 0302df9..275d218 100644 --- a/lib/puppet/functions/is_a.rb +++ b/lib/puppet/functions/is_a.rb @@ -1,42 +1,44 @@ +# frozen_string_literal: true + # @summary # Boolean check to determine whether a variable is of a given data type. # This is equivalent to the `=~` type checks. # # @example Example Usage: # # check a data type # foo = 3 # $bar = [1,2,3] # $baz = 'A string!' # # if $foo.is_a(Integer) { # notify { 'foo!': } # } # if $bar.is_a(Array) { # notify { 'bar!': } # } # if $baz.is_a(String) { # notify { 'baz!': } # } # # 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. # Puppet::Functions.create_function(:is_a) do # @param value # The value to be checked # # @param type # The expected type # # @return [Boolean] # Return's `true` or `false`. dispatch :is_a do param 'Any', :value param 'Type', :type end - 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. + def is_a(value, type) # rubocop:disable Naming/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 end diff --git a/lib/puppet/functions/is_absolute_path.rb b/lib/puppet/functions/is_absolute_path.rb index ea8383e..b801ecb 100644 --- a/lib/puppet/functions/is_absolute_path.rb +++ b/lib/puppet/functions/is_absolute_path.rb @@ -1,27 +1,29 @@ +# frozen_string_literal: true + # @summary # Wrapper that calls the Puppet 3.x function of the same name. Puppet::Functions.create_function(:is_absolute_path) do # @param scope # The main value that will be passed to the wrapped method # # @param args # Any additional values that are to be passed to the wrapped method # # @return [Boolea] # A boolean value returned from the called 3.x function. dispatch :deprecation_gen do 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. 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) end end diff --git a/lib/puppet/functions/is_array.rb b/lib/puppet/functions/is_array.rb index 8f17782..0a53e07 100644 --- a/lib/puppet/functions/is_array.rb +++ b/lib/puppet/functions/is_array.rb @@ -1,27 +1,29 @@ +# frozen_string_literal: true + # @summary # Wrapper that calls the Puppet 3.x function of the same name. Puppet::Functions.create_function(:is_array) do # @param scope # The main value that will be passed to the wrapped method # # @param args # Any additional values that are to be passed to the wrapped method # # @return [Boolea] # A boolean value returned from the called 3.x function. dispatch :deprecation_gen do 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. 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) end end diff --git a/lib/puppet/functions/is_bool.rb b/lib/puppet/functions/is_bool.rb index bc243f1..fa81709 100644 --- a/lib/puppet/functions/is_bool.rb +++ b/lib/puppet/functions/is_bool.rb @@ -1,27 +1,29 @@ +# frozen_string_literal: true + # @summary # Wrapper that calls the Puppet 3.x function of the same name. Puppet::Functions.create_function(:is_bool) do # @param scope # The main value that will be passed to the wrapped method # # @param args # Any additional values that are to be passed to the wrapped method # # @return [Boolea] # A boolean value returned from the called 3.x function. dispatch :deprecation_gen do 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. 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) end end diff --git a/lib/puppet/functions/is_float.rb b/lib/puppet/functions/is_float.rb index f6ea472..408970b 100644 --- a/lib/puppet/functions/is_float.rb +++ b/lib/puppet/functions/is_float.rb @@ -1,27 +1,29 @@ +# frozen_string_literal: true + # @summary # Wrapper that calls the Puppet 3.x function of the same name. Puppet::Functions.create_function(:is_float) do # @param scope # The main value that will be passed to the wrapped method # # @param args # Any additional values that are to be passed to the wrapped method # # @return [Boolea] # A boolean value returned from the called 3.x function. dispatch :deprecation_gen do 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. 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) end end diff --git a/lib/puppet/functions/is_ip_address.rb b/lib/puppet/functions/is_ip_address.rb index 1f2409d..3e1e015 100644 --- a/lib/puppet/functions/is_ip_address.rb +++ b/lib/puppet/functions/is_ip_address.rb @@ -1,27 +1,29 @@ +# frozen_string_literal: true + # @summary # Wrapper that calls the Puppet 3.x function of the same name. Puppet::Functions.create_function(:is_ip_address) do # @param scope # The main value that will be passed to the wrapped method # # @param args # Any additional values that are to be passed to the wrapped method # # @return [Boolea] # A boolean value returned from the called 3.x function. dispatch :deprecation_gen do 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. 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) end end diff --git a/lib/puppet/functions/is_ipv4_address.rb b/lib/puppet/functions/is_ipv4_address.rb index c9d5aa8..8a79a16 100644 --- a/lib/puppet/functions/is_ipv4_address.rb +++ b/lib/puppet/functions/is_ipv4_address.rb @@ -1,27 +1,29 @@ +# frozen_string_literal: true + # @summary # Wrapper that calls the Puppet 3.x function of the same name. Puppet::Functions.create_function(:is_ipv4_address) do # @param scope # The main value that will be passed to the wrapped method # # @param args # Any additional values that are to be passed to the wrapped method # # @return [Boolea] # A boolean value returned from the called 3.x function. dispatch :deprecation_gen do 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. 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) end end diff --git a/lib/puppet/functions/is_ipv6_address.rb b/lib/puppet/functions/is_ipv6_address.rb index 02cb58d..7833960 100644 --- a/lib/puppet/functions/is_ipv6_address.rb +++ b/lib/puppet/functions/is_ipv6_address.rb @@ -1,27 +1,29 @@ +# frozen_string_literal: true + # @summary # Wrapper that calls the Puppet 3.x function of the same name. Puppet::Functions.create_function(:is_ipv6_address) do # @param scope # The main value that will be passed to the wrapped method # # @param args # Any additional values that are to be passed to the wrapped method # # @return [Boolea] # A boolean value returned from the called 3.x function. dispatch :deprecation_gen do 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. 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) end end diff --git a/lib/puppet/functions/is_numeric.rb b/lib/puppet/functions/is_numeric.rb index 1dcf576..06fcacc 100644 --- a/lib/puppet/functions/is_numeric.rb +++ b/lib/puppet/functions/is_numeric.rb @@ -1,27 +1,29 @@ +# frozen_string_literal: true + # @summary # Wrapper that calls the Puppet 3.x function of the same name. Puppet::Functions.create_function(:is_numeric) do # @param scope # The main value that will be passed to the wrapped method # # @param args # Any additional values that are to be passed to the wrapped method # # @return [Boolea] # A boolean value returned from the called 3.x function. dispatch :deprecation_gen do 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. 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) end end diff --git a/lib/puppet/functions/is_string.rb b/lib/puppet/functions/is_string.rb index 1cbb146..b367961 100644 --- a/lib/puppet/functions/is_string.rb +++ b/lib/puppet/functions/is_string.rb @@ -1,27 +1,29 @@ +# frozen_string_literal: true + # @summary # Wrapper that calls the Puppet 3.x function of the same name. Puppet::Functions.create_function(:is_string) do # @param scope # The main value that will be passed to the wrapped method # # @param args # Any additional values that are to be passed to the wrapped method # # @return [Boolean] # A boolean value returned from the called 3.x function. dispatch :deprecation_gen do 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. 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) end end diff --git a/lib/puppet/functions/length.rb b/lib/puppet/functions/length.rb index 9a163de..d2e356c 100644 --- a/lib/puppet/functions/length.rb +++ b/lib/puppet/functions/length.rb @@ -1,27 +1,29 @@ +# frozen_string_literal: true + # @summary # **Deprecated:** 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. # # > **Note:** **Deprecated** from Puppet 6.0.0, this function has been replaced with a # built-in [`length`](https://puppet.com/docs/puppet/latest/function.html#length) function. # Puppet::Functions.create_function(:length) do # @param value # The value whose length is to be found # # @return [Integer] # The length of the given object dispatch :length do param 'Variant[String,Array,Hash]', :value end def length(value) if value.is_a?(String) result = value.length elsif value.is_a?(Array) || value.is_a?(Hash) result = value.size end result end end diff --git a/lib/puppet/functions/merge.rb b/lib/puppet/functions/merge.rb index dd65cbc..d94a793 100644 --- a/lib/puppet/functions/merge.rb +++ b/lib/puppet/functions/merge.rb @@ -1,110 +1,112 @@ +# frozen_string_literal: true + # @summary # Merges two or more hashes together or hashes resulting from iteration, and returns # the resulting hash. # # @example Using merge() # $hash1 = {'one' => 1, 'two', => 2} # $hash2 = {'two' => 'dos', 'three', => 'tres'} # $merged_hash = merge($hash1, $hash2) # $merged_hash = {'one' => 1, 'two' => 'dos', 'three' => 'tres'} # # When there is a duplicate key, the key in the rightmost hash will "win." # # Note that since Puppet 4.0.0 the same merge can be achieved with the + operator. # `$merged_hash = $hash1 + $hash2` # # If merge is given a single Iterable (Array, Hash, etc.) it will call a given block with # up to three parameters, and merge each resulting Hash into the accumulated result. All other types # of values returned from the block (typically undef) are skipped (not merged). # # The codeblock can take 2 or three parameters: # * with two, it gets the current hash (as built to this point), and each value (for hash the value is a [key, value] tuple) # * with three, it gets the current hash (as built to this point), the key/index of each value, and then the value # # If the iterable is empty, or no hash was returned from the given block, an empty hash is returned. In the given block, a call to `next()` # will skip that entry, and a call to `break()` will end the iteration. # # @example counting occurrences of strings in an array # ['a', 'b', 'c', 'c', 'd', 'b'].merge | $hsh, $v | { { $v => $hsh[$v].lest || { 0 } + 1 } } # results in { a => 1, b => 2, c => 2, d => 1 } # # @example skipping values for entries that are longer than 1 char # ['a', 'b', 'c', 'c', 'd', 'b', 'blah', 'blah'].merge | $hsh, $v | { if $v =~ String[1,1] { { $v => $hsh[$v].lest || { 0 } + 1 } } } # results in { a => 1, b => 2, c => 2, d => 1 } # # The iterative `merge()` has an advantage over doing the same with a general `reduce()` in that the constructed hash # does not have to be copied in each iteration and thus will perform much better with large inputs. Puppet::Functions.create_function(:merge) do # @param args # Repeated Param - The hashes that are to be merged # # @return # The merged hash dispatch :merge2hashes do repeated_param 'Variant[Hash, Undef, String[0,0]]', :args # this strange type is backwards compatible return_type 'Hash' end # @param args # Repeated Param - The hashes that are to be merged # # @param block # A block placed on the repeatable param `args` # # @return # The merged hash dispatch :merge_iterable3 do repeated_param 'Iterable', :args block_param 'Callable[3,3]', :block return_type 'Hash' end # @param args # Repeated Param - The hashes that are to be merged # # @param block # A block placed on the repeatable param `args` # # @return # The merged hash dispatch :merge_iterable2 do repeated_param 'Iterable', :args block_param 'Callable[2,2]', :block return_type 'Hash' end def merge2hashes(*hashes) accumulator = {} hashes.each { |h| accumulator.merge!(h) if h.is_a?(Hash) } accumulator end def merge_iterable2(iterable) accumulator = {} enum = Puppet::Pops::Types::Iterable.asserted_iterable(self, iterable) enum.each do |v| r = yield(accumulator, v) accumulator.merge!(r) if r.is_a?(Hash) end accumulator end def merge_iterable3(iterable) accumulator = {} enum = Puppet::Pops::Types::Iterable.asserted_iterable(self, iterable) if enum.hash_style? enum.each do |entry| r = yield(accumulator, *entry) accumulator.merge!(r) if r.is_a?(Hash) end else begin index = 0 loop do r = yield(accumulator, index, enum.next) accumulator.merge!(r) if r.is_a?(Hash) index += 1 end - rescue StopIteration # rubocop:disable Lint/HandleExceptions + rescue StopIteration end end accumulator end end diff --git a/lib/puppet/functions/os_version_gte.rb b/lib/puppet/functions/os_version_gte.rb index 7ab095e..c0e0043 100644 --- a/lib/puppet/functions/os_version_gte.rb +++ b/lib/puppet/functions/os_version_gte.rb @@ -1,25 +1,27 @@ +# frozen_string_literal: true + # @summary # Checks if the OS version is at least a certain version. # > *Note:* # Only the major version is taken into account. # # @example Example usage:# # if os_version_gte('Debian', '9') { } # if os_version_gte('Ubuntu', '18.04') { } Puppet::Functions.create_function(:os_version_gte) do # @param os operating system # @param version # # @return [Boolean] `true` or `false dispatch :os_version_gte do param 'String[1]', :os param 'String[1]', :version return_type 'Boolean' end def os_version_gte(os, version) facts = closure_scope['facts'] (facts['operatingsystem'] == os && Puppet::Util::Package.versioncmp(version, facts['operatingsystemmajrelease']) >= 0) end end diff --git a/lib/puppet/functions/seeded_rand_string.rb b/lib/puppet/functions/seeded_rand_string.rb index 63cb2f8..e9dee5c 100644 --- a/lib/puppet/functions/seeded_rand_string.rb +++ b/lib/puppet/functions/seeded_rand_string.rb @@ -1,30 +1,32 @@ +# frozen_string_literal: true + # @summary # Generates a consistent random string of specific length based on provided seed. # # @example Generate a consistently random string of length 8 with a seed: # seeded_rand_string(8, "${module_name}::redis_password") # # @example Generate a random string from a specific set of characters: # seeded_rand_string(5, '', 'abcdef') Puppet::Functions.create_function(:seeded_rand_string) do # @param length Length of string to be generated. # @param seed Seed string. # @param charset String that contains characters to use for the random string. # # @return [String] Random string. dispatch :rand_string do param 'Integer[1]', :length param 'String', :seed optional_param 'String[2]', :charset end def rand_string(length, seed, charset = nil) require 'digest/sha2' charset ||= '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' random_generator = Random.new(Digest::SHA256.hexdigest(seed).to_i(16)) Array.new(length) { charset[random_generator.rand(charset.size)] }.join end end diff --git a/lib/puppet/functions/sprintf_hash.rb b/lib/puppet/functions/sprintf_hash.rb index ddf82b5..42d2740 100644 --- a/lib/puppet/functions/sprintf_hash.rb +++ b/lib/puppet/functions/sprintf_hash.rb @@ -1,35 +1,37 @@ +# frozen_string_literal: true + # @summary # Uses sprintf with named references. # # The first parameter is format string describing how the rest of the parameters in the hash # should be formatted. See the documentation for the `Kernel::sprintf` function in Ruby for # all the details. # # In the given argument hash with parameters, all keys are converted to symbols so they work # with the `sprintf` function. # # @example Format a string and number # $output = sprintf_hash('String: %s / number converted to binary: %b', # { 'foo' => 'a string', 'number' => 5 }) # # $output = 'String: a string / number converted to binary: 101' # # Note that since Puppet 4.10.10, and 5.3.4 this functionality is supported by the # `sprintf` function in puppet core. # Puppet::Functions.create_function(:sprintf_hash) do # @param format The format to use. # @param arguments Hash with parameters. # @return The formatted string. dispatch :sprintf_hash do param 'String', :format param 'Hash', :arguments # Disabled for now. This gives issues on puppet 4.7.1. # return_type 'String' end def sprintf_hash(format, arguments) call_function('deprecation', 'sprintf_hash', 'This method is deprecated. From Puppet 4.10.10/5.3.4 please use the built-in sprintf instead') Kernel.sprintf(format, Hash[arguments.map { |(k, v)| [k.to_sym, v] }]) end end diff --git a/lib/puppet/functions/stdlib/end_with.rb b/lib/puppet/functions/stdlib/end_with.rb index fc83f70..6c64089 100644 --- a/lib/puppet/functions/stdlib/end_with.rb +++ b/lib/puppet/functions/stdlib/end_with.rb @@ -1,21 +1,23 @@ +# frozen_string_literal: true + # @summary # Returns true if str ends with one of the prefixes given. Each of the prefixes should be a String. # Puppet::Functions.create_function(:'stdlib::end_with') do # @param test_string The string to check # @param suffixes The suffixes to check # @example # 'foobar'.stdlib::end_with('bar') => true # 'foobar'.stdlib::end_with('foo') => false # 'foobar'.stdlib::end_with(['foo', 'baz']) => false # @return [Boolean] True or False dispatch :end_with do param 'String', :test_string param 'Variant[String[1],Array[String[1], 1]]', :suffixes return_type 'Boolean' end def end_with(test_string, suffixes) test_string.end_with?(*suffixes) end end diff --git a/lib/puppet/functions/stdlib/extname.rb b/lib/puppet/functions/stdlib/extname.rb index 120b46b..7de9d50 100644 --- a/lib/puppet/functions/stdlib/extname.rb +++ b/lib/puppet/functions/stdlib/extname.rb @@ -1,26 +1,28 @@ +# frozen_string_literal: true + # @summary # Returns the Extension (the Portion of Filename in Path starting from the # last Period). # # If Path is a Dotfile, or starts with a Period, then the starting Dot is not # dealt with the Start of the Extension. # # An empty String will also be returned, when the Period is the last Character # in Path. Puppet::Functions.create_function(:'stdlib::extname') do # @param filename The Filename # @return [String] The Extension starting from the last Period # @example Determining the Extension of a Filename # stdlib::extname('test.rb') => '.rb' # stdlib::extname('a/b/d/test.rb') => '.rb' # stdlib::extname('test') => '' # stdlib::extname('.profile') => '' dispatch :extname do param 'String', :filename return_type 'String' end def extname(filename) File.extname(filename) end end diff --git a/lib/puppet/functions/stdlib/ip_in_range.rb b/lib/puppet/functions/stdlib/ip_in_range.rb index 46fc445..eed5c0b 100644 --- a/lib/puppet/functions/stdlib/ip_in_range.rb +++ b/lib/puppet/functions/stdlib/ip_in_range.rb @@ -1,30 +1,32 @@ +# frozen_string_literal: true + # @summary # Returns true if the ipaddress is within the given CIDRs # # @example ip_in_range(, ) # stdlib::ip_in_range('10.10.10.53', '10.10.10.0/24') => true Puppet::Functions.create_function(:'stdlib::ip_in_range') do # @param ipaddress The IP address to check # @param range One CIDR or an array of CIDRs # defining the range(s) to check against # # @return [Boolean] True or False dispatch :ip_in_range do param 'String', :ipaddress param 'Variant[String, Array]', :range return_type 'Boolean' end require 'ipaddr' def ip_in_range(ipaddress, range) ip = IPAddr.new(ipaddress) if range.is_a? Array ranges = range.map { |r| IPAddr.new(r) } ranges.any? { |rng| rng.include?(ip) } elsif range.is_a? String ranges = IPAddr.new(range) ranges.include?(ip) end end end diff --git a/lib/puppet/functions/stdlib/start_with.rb b/lib/puppet/functions/stdlib/start_with.rb index 28f01bb..5203baf 100644 --- a/lib/puppet/functions/stdlib/start_with.rb +++ b/lib/puppet/functions/stdlib/start_with.rb @@ -1,21 +1,23 @@ +# frozen_string_literal: true + # @summary # Returns true if str starts with one of the prefixes given. Each of the prefixes should be a String. # Puppet::Functions.create_function(:'stdlib::start_with') do # @param test_string The string to check # @param prefixes The prefixes to check. # @example # 'foobar'.stdlib::start_with('foo') => true # 'foobar'.stdlib::start_with('bar') => false # 'foObar'.stdlib::start_with(['bar', 'baz']) => false # @return [Boolean] True or False dispatch :start_with do param 'String', :test_string param 'Variant[String[1],Array[String[1], 1]]', :prefixes return_type 'Boolean' end def start_with(test_string, prefixes) test_string.start_with?(*prefixes) end end diff --git a/lib/puppet/functions/to_json.rb b/lib/puppet/functions/to_json.rb index 20d39e7..7ff605d 100644 --- a/lib/puppet/functions/to_json.rb +++ b/lib/puppet/functions/to_json.rb @@ -1,23 +1,25 @@ +# frozen_string_literal: true + require 'json' # @summary # Convert a data structure and output to JSON # # @example how to output JSON # # output json to a file # file { '/tmp/my.json': # ensure => file, # content => to_json($myhash), # } # Puppet::Functions.create_function(:to_json) do # @param data # data structure which needs to be converted into JSON # @return converted data to json dispatch :to_json do param 'Any', :data end def to_json(data) data.to_json end end diff --git a/lib/puppet/functions/to_json_pretty.rb b/lib/puppet/functions/to_json_pretty.rb index 8a63f69..7d46fc2 100644 --- a/lib/puppet/functions/to_json_pretty.rb +++ b/lib/puppet/functions/to_json_pretty.rb @@ -1,80 +1,82 @@ +# frozen_string_literal: true + require 'json' # @summary # Convert data structure and output to pretty JSON # # @example **Usage** # * how to output pretty JSON to file # file { '/tmp/my.json': # ensure => file, # content => to_json_pretty($myhash), # } # # * how to output pretty JSON skipping over keys with undef values # file { '/tmp/my.json': # ensure => file, # content => to_json_pretty({ # param_one => 'value', # param_two => undef, # }, true), # } # # * how to output pretty JSON using tabs for indentation # file { '/tmp/my.json': # ensure => file, # content => to_json_pretty({ # param_one => 'value', # param_two => { # param_more => 42, # }, # }, nil, {indent => ' '}), # } Puppet::Functions.create_function(:to_json_pretty) do # @param data # data structure which needs to be converted to pretty json # @param skip_undef # value `true` or `false` # @param opts # hash-map of settings passed to JSON.pretty_generate, see # https://ruby-doc.org/stdlib-2.0.0/libdoc/json/rdoc/JSON.html#method-i-generate. # Note that `max_nesting` doesn't take the value `false`; use `-1` instead. # @return # converted data to pretty json dispatch :to_json_pretty do param 'Variant[Hash, Array]', :data optional_param 'Optional[Boolean]', :skip_undef optional_param 'Struct[{ indent => Optional[String], space => Optional[String], space_before => Optional[String], object_nl => Optional[String], array_nl => Optional[String], allow_nan => Optional[Boolean], max_nesting => Optional[Integer[-1,default]], }]', :opts end def to_json_pretty(data, skip_undef = false, opts = nil) # It's not possible to make an abstract type that can be either a boolean # false or an integer, so we use -1 as the falsey value if opts opts = Hash[opts.map { |k, v| [k.to_sym, v] }] if opts[:max_nesting] == -1 opts[:max_nesting] = false end end if skip_undef if data.is_a? Array data = data.reject { |value| value.nil? } elsif data.is_a? Hash data = data.reject { |_, value| value.nil? } end end # Call ::JSON to ensure it references the JSON library from Ruby's standard library # instead of a random JSON namespace that might be in scope due to user code. ::JSON.pretty_generate(data, opts) << "\n" end end diff --git a/lib/puppet/functions/to_yaml.rb b/lib/puppet/functions/to_yaml.rb index fe8ec50..781ea33 100644 --- a/lib/puppet/functions/to_yaml.rb +++ b/lib/puppet/functions/to_yaml.rb @@ -1,29 +1,31 @@ +# frozen_string_literal: true + require 'yaml' # @summary # Convert a data structure and output it as YAML # # @example How to output YAML # # output yaml to a file # file { '/tmp/my.yaml': # ensure => file, # content => to_yaml($myhash), # } # @example Use options control the output format # file { '/tmp/my.yaml': # ensure => file, # content => to_yaml($myhash, {indentation: 4}) # } Puppet::Functions.create_function(:to_yaml) do # @param data # @param options # # @return [String] dispatch :to_yaml do param 'Any', :data optional_param 'Hash', :options end def to_yaml(data, options = {}) data.to_yaml(options) end end diff --git a/lib/puppet/functions/type_of.rb b/lib/puppet/functions/type_of.rb index e745659..a05eeeb 100644 --- a/lib/puppet/functions/type_of.rb +++ b/lib/puppet/functions/type_of.rb @@ -1,24 +1,26 @@ +# frozen_string_literal: true + # @summary # Returns the type of the passed value. # # @example how to compare values' types # # compare the types of two values # if type_of($first_value) != type_of($second_value) { fail("first_value and second_value are different types") } # @example how to compare against an abstract type # unless type_of($first_value) <= Numeric { fail("first_value must be Numeric") } # unless type_of{$first_value) <= Collection[1] { fail("first_value must be an Array or Hash, and contain at least one element") } # # 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 # this function is provided for backwards compatibility. Puppet::Functions.create_function(:type_of) do # @return [String] # the type of the passed value # # @param value def type_of(value) Puppet::Pops::Types::TypeCalculator.infer_set(value) end end diff --git a/lib/puppet/functions/validate_absolute_path.rb b/lib/puppet/functions/validate_absolute_path.rb index ed7f070..9121cbb 100644 --- a/lib/puppet/functions/validate_absolute_path.rb +++ b/lib/puppet/functions/validate_absolute_path.rb @@ -1,28 +1,30 @@ +# frozen_string_literal: true + # @summary # Validate the string represents an absolute path in the filesystem. Puppet::Functions.create_function(:validate_absolute_path) do # @param scope # The main value that will be passed to the method # # @param args # Any additional values that are to be passed to the method # # @return [Boolean] # A boolean value returned from the called function. dispatch :deprecation_gen do 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. 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) end end diff --git a/lib/puppet/functions/validate_array.rb b/lib/puppet/functions/validate_array.rb index 217df76..4287aa8 100644 --- a/lib/puppet/functions/validate_array.rb +++ b/lib/puppet/functions/validate_array.rb @@ -1,28 +1,30 @@ +# frozen_string_literal: true + # @summary # Validate the passed value represents an array. Puppet::Functions.create_function(:validate_array) do # @param scope # The main value that will be passed to the method # # @param args # Any additional values that are to be passed to the method # # @return # A boolean value (`true` or `false`) returned from the called function. dispatch :deprecation_gen do 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. 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) end end diff --git a/lib/puppet/functions/validate_bool.rb b/lib/puppet/functions/validate_bool.rb index 85892dd..a080a41 100644 --- a/lib/puppet/functions/validate_bool.rb +++ b/lib/puppet/functions/validate_bool.rb @@ -1,28 +1,30 @@ +# frozen_string_literal: true + # @summary # Validate the passed value represents a boolean. Puppet::Functions.create_function(:validate_bool) do # @param scope # The main value that will be passed to the method # # @param args # Any additional values that are to be passed to the method # # @return [Boolean] `true` or `false` # A boolean value returned from the called function. dispatch :deprecation_gen do 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. 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) end end diff --git a/lib/puppet/functions/validate_hash.rb b/lib/puppet/functions/validate_hash.rb index 5efa25f..77370e2 100644 --- a/lib/puppet/functions/validate_hash.rb +++ b/lib/puppet/functions/validate_hash.rb @@ -1,28 +1,30 @@ +# frozen_string_literal: true + # @summary # Validate the passed value represents a hash. Puppet::Functions.create_function(:validate_hash) do # @param scope # The main value that will be passed to the method # # @param args # Any additional values that are to be passed to the method # # @return # A boolean value (`true` or `false`) returned from the called function. dispatch :deprecation_gen do 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. 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) end end diff --git a/lib/puppet/functions/validate_integer.rb b/lib/puppet/functions/validate_integer.rb index 7de789e..ae8e90f 100644 --- a/lib/puppet/functions/validate_integer.rb +++ b/lib/puppet/functions/validate_integer.rb @@ -1,28 +1,30 @@ +# frozen_string_literal: true + # @summary # Validate the passed value represents an integer. Puppet::Functions.create_function(:validate_integer) do # @param scope # The main value that will be passed to the method # # @param args # Any additional values that are to be passed to the method # # @return [Boolean] `true` or `false` # A boolean value returned from the called function. dispatch :deprecation_gen do 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. 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) end end diff --git a/lib/puppet/functions/validate_ip_address.rb b/lib/puppet/functions/validate_ip_address.rb index 233f083..7064052 100644 --- a/lib/puppet/functions/validate_ip_address.rb +++ b/lib/puppet/functions/validate_ip_address.rb @@ -1,28 +1,30 @@ +# frozen_string_literal: true + # @summary # Validate the passed value represents an ip_address. Puppet::Functions.create_function(:validate_ip_address) do # @param scope # The main value that will be passed to the method # # @param args # Any additional values that are to be passed to the method # # @return [Boolean] `true` or `false` # A boolean value returned from the called function. dispatch :deprecation_gen do 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. 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) end end diff --git a/lib/puppet/functions/validate_ipv4_address.rb b/lib/puppet/functions/validate_ipv4_address.rb index 799f608..090292b 100644 --- a/lib/puppet/functions/validate_ipv4_address.rb +++ b/lib/puppet/functions/validate_ipv4_address.rb @@ -1,28 +1,30 @@ +# frozen_string_literal: true + # @summary # Validate the passed value represents an ipv4_address. Puppet::Functions.create_function(:validate_ipv4_address) do # @param scope # The main value that will be passed to the method # # @param args # Any additional values that are to be passed to the method # # @return [Boolean] `true` or `false` # A boolean value returned from the called function. dispatch :deprecation_gen do 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. 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) end end diff --git a/lib/puppet/functions/validate_ipv6_address.rb b/lib/puppet/functions/validate_ipv6_address.rb index b514642..540842b 100644 --- a/lib/puppet/functions/validate_ipv6_address.rb +++ b/lib/puppet/functions/validate_ipv6_address.rb @@ -1,28 +1,30 @@ +# frozen_string_literal: true + # @summary # Validate the passed value represents an ipv6_address. Puppet::Functions.create_function(:validate_ipv6_address) do # @param scope # The main value that will be passed to the method # # @param args # Any additional values that are to be passed to the method # # @return [Boolean] `true` or `false` # A boolean value returned from the called function. dispatch :deprecation_gen do 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. 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) end end diff --git a/lib/puppet/functions/validate_legacy.rb b/lib/puppet/functions/validate_legacy.rb index 1e16219..44335fb 100644 --- a/lib/puppet/functions/validate_legacy.rb +++ b/lib/puppet/functions/validate_legacy.rb @@ -1,80 +1,82 @@ +# frozen_string_literal: true + # @summary # Validate a value against both the target_type (new) and the previous_validation function (old). Puppet::Functions.create_function(:validate_legacy) do # The function checks a value against both the target_type (new) and the previous_validation function (old). # @param scope # The main value that will be passed to the method # @param target_type # @param function_name # @param value # @param args # Any additional values that are to be passed to the method # @return # A boolean value (`true` or `false`) returned from the called function. dispatch :validate_legacy do param 'Any', :scope param 'Type', :target_type param 'String', :function_name param 'Any', :value repeated_param 'Any', :args end # @param scope # The main value that will be passed to the method # @param type_string # @param function_name # @param value # @param args Any additional values that are to be passed to the method # @return Legacy validation method # dispatch :validate_legacy_s do param 'Any', :scope param 'String', :type_string param 'String', :function_name param 'Any', :value 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. def call(scope, *args) manipulated_args = [scope] + args self.class.dispatcher.dispatch(self, scope, manipulated_args) end def validate_legacy_s(scope, type_string, *args) t = Puppet::Pops::Types::TypeParser.new.parse(type_string, scope) validate_legacy(scope, t, *args) end def validate_legacy(scope, target_type, function_name, value, *prev_args) if assert_type(target_type, value) if previous_validation(scope, function_name, value, *prev_args) # Silently passes else Puppet.notice("Accepting previously invalid value for target type '#{target_type}'") end else inferred_type = Puppet::Pops::Types::TypeCalculator.infer_set(value) error_msg = Puppet::Pops::Types::TypeMismatchDescriber.new.describe_mismatch("validate_legacy(#{function_name})", target_type, inferred_type) if previous_validation(scope, function_name, value, *prev_args) call_function('deprecation', 'validate_legacy', error_msg) else call_function('fail', error_msg) end end end 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. scope.send("function_#{function_name}".to_s, [value, *prev_args]) true rescue Puppet::ParseError false end def assert_type(type, value) Puppet::Pops::Types::TypeCalculator.instance?(type, value) end end diff --git a/lib/puppet/functions/validate_numeric.rb b/lib/puppet/functions/validate_numeric.rb index f98fa74..c9daa75 100644 --- a/lib/puppet/functions/validate_numeric.rb +++ b/lib/puppet/functions/validate_numeric.rb @@ -1,28 +1,30 @@ +# frozen_string_literal: true + # @summary # Validate the passed value represents a numeric value. Puppet::Functions.create_function(:validate_numeric) do # @param scope # The main value that will be passed to the method # # @param args # Any additional values that are to be passed to the method # # @return [Boolean] `true` or `false` # A boolean value returned from the called function. dispatch :deprecation_gen do 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. 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) end end diff --git a/lib/puppet/functions/validate_re.rb b/lib/puppet/functions/validate_re.rb index d1695df..eaea9b6 100644 --- a/lib/puppet/functions/validate_re.rb +++ b/lib/puppet/functions/validate_re.rb @@ -1,33 +1,35 @@ +# frozen_string_literal: true + # @summary # Perform validation of a string against one or more regular # expressions. # Puppet::Functions.create_function(:validate_re) do # @param scope # The main value that will be passed to the method # # @param args # Any additional values that are to be passed to the method # The first argument of this function should be a string to # test, and the second argument should be a stringified regular expression # (without the // delimiters) or an array of regular expressions # # @return [Boolean] # `true` or `false` returned from the called function. dispatch :deprecation_gen do 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. 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) end end diff --git a/lib/puppet/functions/validate_slength.rb b/lib/puppet/functions/validate_slength.rb index aa4143b..f34e705 100644 --- a/lib/puppet/functions/validate_slength.rb +++ b/lib/puppet/functions/validate_slength.rb @@ -1,27 +1,29 @@ +# frozen_string_literal: true + # Validate that a passed string has length less/equal with the passed value Puppet::Functions.create_function(:validate_slength) do # @param scope # The main value that will be passed to the method # # @param args # Any additional values that are to be passed to the method # # @return [Boolean] `true` or `false` # A boolean value returned from the called function. dispatch :deprecation_gen do 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. 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) end end diff --git a/lib/puppet/functions/validate_string.rb b/lib/puppet/functions/validate_string.rb index 50b1daf..a946da9 100644 --- a/lib/puppet/functions/validate_string.rb +++ b/lib/puppet/functions/validate_string.rb @@ -1,28 +1,30 @@ +# frozen_string_literal: true + # @summary # Validate that all passed values are string data structures. Puppet::Functions.create_function(:validate_string) do # @param scope # The main value that will be passed to the method # # @param args # Any additional values that are to be passed to the method # # @return [Boolean] `true` or `false` # A boolean value returned from the called function. dispatch :deprecation_gen do 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. 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) end end diff --git a/lib/puppet/parser/functions/abs.rb b/lib/puppet/parser/functions/abs.rb index 5625b98..822bc5d 100644 --- a/lib/puppet/parser/functions/abs.rb +++ b/lib/puppet/parser/functions/abs.rb @@ -1,43 +1,44 @@ +# frozen_string_literal: true + # # abs.rb # module Puppet::Parser::Functions - newfunction(:abs, :type => :rvalue, :doc => <<-DOC + newfunction(:abs, type: :rvalue, doc: <<-DOC @summary **Deprecated:** Returns the absolute value of a number For example -34.56 becomes 34.56. Takes a single integer or float value as an argument. > *Note:* **Deprected** from Puppet 6.0.0, the built-in ['abs'](https://puppet.com/docs/puppet/6.4/function.html#abs)function will be used instead. @return The absolute value of the given number if it was an Integer DOC - ) do |arguments| - + ) do |arguments| 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 =~ %r{^-?(?:\d+)(?:\.\d+){1}$} + if %r{^-?(?:\d+)(?:\.\d+){1}$}.match?(value) value = value.to_f - elsif value =~ %r{^-?\d+$} + elsif %r{^-?\d+$}.match?(value) value = value.to_i else raise(Puppet::ParseError, 'abs(): Requires float or integer to work with') end end # We have numeric value to handle ... result = value.abs return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/any2array.rb b/lib/puppet/parser/functions/any2array.rb index b45e5b5..107c11d 100644 --- a/lib/puppet/parser/functions/any2array.rb +++ b/lib/puppet/parser/functions/any2array.rb @@ -1,56 +1,57 @@ +# frozen_string_literal: true + # # any2array.rb # module Puppet::Parser::Functions - newfunction(:any2array, :type => :rvalue, :doc => <<-DOC + newfunction(:any2array, type: :rvalue, doc: <<-DOC @summary 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. > *Note:* since Puppet 5.0.0 it is possible to create new data types for almost any datatype using the type system and the built-in [`Array.new`](https://puppet.com/docs/puppet/latest/function.html#conversion-to-array-and-tuple) function is used to create a new Array.. ``` $hsh = {'key' => 42, 'another-key' => 100} notice(Array($hsh)) ``` Would notice `[['key', 42], ['another-key', 100]]` The Array data type also has a special mode to "create an array if not already an array" ``` notice(Array({'key' => 42, 'another-key' => 100}, true)) ``` Would notice `[{'key' => 42, 'another-key' => 100}]`, as the `true` flag prevents the hash from being transformed into an array. @return [Array] The new array containing the given object DOC - ) do |arguments| - + ) do |arguments| if arguments.empty? return [] end return arguments unless arguments.length == 1 return arguments[0] if arguments[0].is_a?(Array) return [] if arguments == [''] if arguments[0].is_a?(Hash) result = [] arguments[0].each do |key, value| result << key << value end return result end return arguments end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/any2bool.rb b/lib/puppet/parser/functions/any2bool.rb index c4b20d6..0215d19 100644 --- a/lib/puppet/parser/functions/any2bool.rb +++ b/lib/puppet/parser/functions/any2bool.rb @@ -1,60 +1,61 @@ +# frozen_string_literal: true + # # any2bool.rb # module Puppet::Parser::Functions - newfunction(:any2bool, :type => :rvalue, :doc => <<-DOC + newfunction(:any2bool, type: :rvalue, doc: <<-DOC @summary 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 Also see the built-in [`Boolean.new`](https://puppet.com/docs/puppet/latest/function.html#conversion-to-boolean) function. @return [Boolean] The boolean value of the object that was given DOC - ) do |arguments| - + ) do |arguments| 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] # 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? return false end if arg == :undef return false end 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]]) end if arg.is_a?(String) return function_num2bool([arguments[0]]) if valid_float return function_str2bool([arguments[0]]) end return true end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/assert_private.rb b/lib/puppet/parser/functions/assert_private.rb index 4f1a5e2..0e64bd6 100644 --- a/lib/puppet/parser/functions/assert_private.rb +++ b/lib/puppet/parser/functions/assert_private.rb @@ -1,32 +1,33 @@ +# frozen_string_literal: true + # # assert_private.rb # module Puppet::Parser::Functions - newfunction(:assert_private, :doc => <<-DOC + newfunction(:assert_private, doc: <<-DOC @summary Sets the current class or definition as private. @return set the current class or definition as private. Calling the class or definition from outside the current module will fail. DOC - ) 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] && args[0].is_a?(String) + if args[0]&.is_a?(String) message = args[0] else manifest_name = scope.source.name manifest_type = scope.source.type message = (manifest_type.to_s == 'hostclass') ? 'Class' : 'Definition' message += " #{manifest_name} is private" end raise(Puppet::ParseError, message) end end end diff --git a/lib/puppet/parser/functions/base64.rb b/lib/puppet/parser/functions/base64.rb index 45e1fdb..1fe2751 100644 --- a/lib/puppet/parser/functions/base64.rb +++ b/lib/puppet/parser/functions/base64.rb @@ -1,85 +1,87 @@ +# frozen_string_literal: true + # 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 => <<-DOC) do |args| + newfunction(:base64, type: :rvalue, doc: <<-DOC) do |args| @summary Base64 encode or decode a string based on the command and the string submitted @example Example usage Encode and decode a string $encodestring = base64('encode', 'thestring') $decodestring = base64('decode', 'dGhlc3RyaW5n') Explicitly define encode/decode method: default, strict, urlsafe $method = 'default' $encodestring = base64('encode', 'thestring', $method) $decodestring = base64('decode', 'dGhlc3RyaW5n', $method) Encode a string as if it was binary $encodestring = String(Binary('thestring', '%s')) Decode a Binary assuming it is an UTF-8 String $decodestring = String(Binary("dGhlc3RyaW5n"), "%s") > **Note:* Since Puppet 4.8.0, the Binary data type can be used to produce base 64 encoded strings. See the `new()` function for the Binary and String types for documentation. Also see `binary_file()` function for reading a file with binary (non UTF-8) content. @return [String] The encoded/decoded value DOC require 'base64' raise Puppet::ParseError, "base64(): Wrong number of arguments (#{args.length}; must be >= 2)" unless args.length >= 2 actions = ['encode', 'decode'] unless actions.include?(args[0]) 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' end method = ['default', 'strict', 'urlsafe'] chosen_method = if args.length <= 2 'default' else args[2] end 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 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 end end diff --git a/lib/puppet/parser/functions/basename.rb b/lib/puppet/parser/functions/basename.rb index e247e56..1761821 100644 --- a/lib/puppet/parser/functions/basename.rb +++ b/lib/puppet/parser/functions/basename.rb @@ -1,27 +1,28 @@ +# frozen_string_literal: true + # # basename.rb # module Puppet::Parser::Functions - newfunction(:basename, :type => :rvalue, :doc => <<-DOC + newfunction(:basename, type: :rvalue, doc: <<-DOC @summary Strips directory (and optional suffix) from a filename @return [String] The stripped filename DOC - ) do |arguments| - + ) do |arguments| 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 end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/bool2num.rb b/lib/puppet/parser/functions/bool2num.rb index bafe0bd..a55e5cc 100644 --- a/lib/puppet/parser/functions/bool2num.rb +++ b/lib/puppet/parser/functions/bool2num.rb @@ -1,43 +1,44 @@ +# frozen_string_literal: true + # # bool2num.rb # module Puppet::Parser::Functions - newfunction(:bool2num, :type => :rvalue, :doc => <<-DOC + newfunction(:bool2num, type: :rvalue, doc: <<-DOC @summary 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. > *Note:* since Puppet 5.0.0 it is possible to create new data types for almost any datatype using the type system and the built-in [`Numeric.new`](https://puppet.com/docs/puppet/latest/function.html#conversion-to-numeric), [`Integer.new`](https://puppet.com/docs/puppet/latest/function.html#conversion-to-integer), and [`Float.new`](https://puppet.com/docs/puppet/latest/function.html#conversion-to-float) function are used to convert to numeric values. ``` notice(Integer(false)) # Notices 0 notice(Float(true)) # Notices 1.0 ``` @return [Integer] The converted value as a number DOC - ) do |arguments| - + ) do |arguments| raise(Puppet::ParseError, "bool2num(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? value = function_str2bool([arguments[0]]) # We have real boolean values as well ... result = value ? 1 : 0 return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/bool2str.rb b/lib/puppet/parser/functions/bool2str.rb index f55fcd8..03d53d4 100644 --- a/lib/puppet/parser/functions/bool2str.rb +++ b/lib/puppet/parser/functions/bool2str.rb @@ -1,63 +1,64 @@ +# frozen_string_literal: true + # # bool2str.rb # module Puppet::Parser::Functions - newfunction(:bool2str, :type => :rvalue, :doc => <<-DOC + newfunction(:bool2str, type: :rvalue, doc: <<-DOC @summary 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 converted from a boolean to a string containing 'true' or 'false'. @return The converted value to string of the given Boolean **Examples of usage** ``` bool2str(true) => 'true' bool2str(true, 'yes', 'no') => 'yes' bool2str(false, 't', 'f') => 'f' ``` Requires a single boolean as an input. > *Note:* since Puppet 5.0.0 it is possible to create new data types for almost any datatype using the type system and the built-in [`String.new`](https://puppet.com/docs/puppet/latest/function.html#boolean-to-string) function is used to convert to String with many different format options. ``` notice(String(false)) # Notices 'false' notice(String(true)) # Notices 'true' notice(String(false, '%y')) # Notices 'yes' notice(String(true, '%y')) # Notices 'no' ``` DOC - ) do |arguments| - + ) do |arguments| unless arguments.size == 1 || arguments.size == 3 raise(Puppet::ParseError, "bool2str(): Wrong number of arguments given (#{arguments.size} for 3)") end value = arguments[0] true_string = arguments[1] || 'true' false_string = arguments[2] || 'false' klass = value.class # We can have either true or false, and nothing else unless [FalseClass, TrueClass].include?(klass) raise(Puppet::ParseError, 'bool2str(): Requires a boolean to work with') end 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 end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/camelcase.rb b/lib/puppet/parser/functions/camelcase.rb index ad1068b..4e6330c 100644 --- a/lib/puppet/parser/functions/camelcase.rb +++ b/lib/puppet/parser/functions/camelcase.rb @@ -1,40 +1,41 @@ +# frozen_string_literal: true + # # 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 => <<-DOC + newfunction(:camelcase, type: :rvalue, doc: <<-DOC @summary **Deprecated** Converts the case of a string or all strings in an array to camel case. > *Note:* **Deprecated** from Puppet 6.0.0, this function has been replaced with a built-in [`camelcase`](https://puppet.com/docs/puppet/latest/function.html#camelcase) function. @return [String] The converted String, if it was a String that was given @return [Array[String]] The converted Array, if it was a Array that was given DOC - ) do |arguments| - + ) do |arguments| raise(Puppet::ParseError, "camelcase(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? value = arguments[0] klass = value.class unless [Array, String].include?(klass) raise(Puppet::ParseError, 'camelcase(): Requires either array or string to work with') 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 end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/capitalize.rb b/lib/puppet/parser/functions/capitalize.rb index ffc4d13..fef4493 100644 --- a/lib/puppet/parser/functions/capitalize.rb +++ b/lib/puppet/parser/functions/capitalize.rb @@ -1,39 +1,40 @@ +# frozen_string_literal: true + # # 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 => <<-DOC + newfunction(:capitalize, type: :rvalue, doc: <<-DOC @summary **Deprecated** Capitalizes the first letter of a string or array of strings. Requires either a single string or an array as an input. > *Note:* **Deprecated** from Puppet 6.0.0, yhis function has been replaced with a built-in [`capitalize`](https://puppet.com/docs/puppet/latest/function.html#capitalize) function. @return [String] The converted String, if it was a String that was given @return [Array[String]] The converted Array, if it was a Array that was given DOC - ) do |arguments| - + ) do |arguments| raise(Puppet::ParseError, "capitalize(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? value = arguments[0] unless value.is_a?(Array) || value.is_a?(String) raise(Puppet::ParseError, 'capitalize(): Requires either array or string to work with') 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 end diff --git a/lib/puppet/parser/functions/ceiling.rb b/lib/puppet/parser/functions/ceiling.rb index ea50e88..b801235 100644 --- a/lib/puppet/parser/functions/ceiling.rb +++ b/lib/puppet/parser/functions/ceiling.rb @@ -1,32 +1,33 @@ +# frozen_string_literal: true + # # ceiling.rb # module Puppet::Parser::Functions - newfunction(:ceiling, :type => :rvalue, :doc => <<-DOC + newfunction(:ceiling, type: :rvalue, doc: <<-DOC @summary **Deprecated** Returns the smallest integer greater or equal to the argument. Takes a single numeric value as an argument. > *Note:* **Deprecated** from Puppet 6.0.0, this function has been replaced with a built-in [`ceiling`](https://puppet.com/docs/puppet/latest/function.html#ceiling) function. @return [Integer] The rounded value DOC - ) 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 raise(Puppet::ParseError, "ceiling(): Wrong argument type given (#{arguments[0]} for Numeric)") end raise(Puppet::ParseError, "ceiling(): Wrong argument type given (#{arg.class} for Numeric)") if arg.is_a?(Numeric) == false arg.ceil end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/chomp.rb b/lib/puppet/parser/functions/chomp.rb index c917d58..84aeaf1 100644 --- a/lib/puppet/parser/functions/chomp.rb +++ b/lib/puppet/parser/functions/chomp.rb @@ -1,40 +1,41 @@ +# frozen_string_literal: true + # # chomp.rb # module Puppet::Parser::Functions - newfunction(:chomp, :type => :rvalue, :doc => <<-DOC + newfunction(:chomp, type: :rvalue, doc: <<-DOC @summary **Deprecated** 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. > *Note:* **Deprecated** from Puppet 6.0.0, this function has been replaced with a built-in [`chomp`](https://puppet.com/docs/puppet/latest/function.html#chomp) function. @return [String] The converted String, if it was a String that was given @return [Array[String]] The converted Array, if it was a Array that was given DOC - ) do |arguments| - + ) do |arguments| raise(Puppet::ParseError, "chomp(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? value = arguments[0] unless value.is_a?(Array) || value.is_a?(String) raise(Puppet::ParseError, 'chomp(): Requires either array or string to work with') 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 end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/chop.rb b/lib/puppet/parser/functions/chop.rb index 69b5f3f..2e4b054 100644 --- a/lib/puppet/parser/functions/chop.rb +++ b/lib/puppet/parser/functions/chop.rb @@ -1,40 +1,41 @@ +# frozen_string_literal: true + # # chop.rb # module Puppet::Parser::Functions - newfunction(:chop, :type => :rvalue, :doc => <<-DOC + newfunction(:chop, type: :rvalue, doc: <<-DOC @summary **Deprecated** 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. > *Note:* **Deprecated** from Puppet 6.0.0, this function has been replaced with a built-in [`chop`](https://puppet.com/docs/puppet/latest/function.html#chop) function. @return [String] The given String, sans the last character. DOC - ) do |arguments| - + ) do |arguments| raise(Puppet::ParseError, "chop(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? value = arguments[0] unless value.is_a?(Array) || value.is_a?(String) raise(Puppet::ParseError, 'chop(): Requires either an array or string to work with') 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 end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/clamp.rb b/lib/puppet/parser/functions/clamp.rb index 1b6e2d2..c056884 100644 --- a/lib/puppet/parser/functions/clamp.rb +++ b/lib/puppet/parser/functions/clamp.rb @@ -1,45 +1,46 @@ +# frozen_string_literal: true + # # clamp.rb # module Puppet::Parser::Functions - newfunction(:clamp, :type => :rvalue, :arity => -2, :doc => <<-DOC + newfunction(:clamp, type: :rvalue, arity: -2, doc: <<-DOC @summary Keeps value within the range [Min, X, Max] by sort based on integer value (parameter order doesn't matter). Strings are converted and compared numerically. Arrays of values are flattened into a list for further handling. @example Example usage clamp('24', [575, 187])` returns 187. clamp(16, 88, 661)` returns 88. clamp([4, 3, '99'])` returns 4. > *Note:* From Puppet 6.0.0 this can be done with only core Puppet like this: `[$minval, $maxval, $value_to_clamp].sort[1]` @return [Array[Integer]] The sorted Array DOC - ) do |args| - + ) do |args| args.flatten! raise(Puppet::ParseError, 'clamp(): Wrong number of arguments, need three to clamp') if args.size != 3 # check values out args.each do |value| case [value.class] when [String] - raise(Puppet::ParseError, "clamp(): Required explicit numeric (#{value}:String)") unless value =~ %r{^\d+$} + raise(Puppet::ParseError, "clamp(): Required explicit numeric (#{value}:String)") unless %r{^\d+$}.match?(value) 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] end end diff --git a/lib/puppet/parser/functions/concat.rb b/lib/puppet/parser/functions/concat.rb index d3c2e24..2ee1c2a 100644 --- a/lib/puppet/parser/functions/concat.rb +++ b/lib/puppet/parser/functions/concat.rb @@ -1,47 +1,48 @@ +# frozen_string_literal: true + # # concat.rb # module Puppet::Parser::Functions - newfunction(:concat, :type => :rvalue, :doc => <<-DOC + newfunction(:concat, type: :rvalue, doc: <<-DOC @summary Appends the contents of multiple arrays into array 1. @example Example usage concat(['1','2','3'],'4') returns ['1','2','3','4'] concat(['1','2','3'],'4',['5','6','7']) returns ['1','2','3','4','5','6','7'] > *Note:* Since Puppet 4.0, you can use the `+`` operator for concatenation of arrays and merge of hashes, and the `<<`` operator for appending: `['1','2','3'] + ['4','5','6'] + ['7','8','9']` returns `['1','2','3','4','5','6','7','8','9']` `[1, 2, 3] << 4` returns `[1, 2, 3, 4]` `[1, 2, 3] << [4, 5]` returns `[1, 2, 3, [4, 5]]` @return [Array] The single concatenated array DOC - ) do |arguments| - + ) 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 a = arguments[0] # Check that the first parameter is an array unless a.is_a?(Array) raise(Puppet::ParseError, 'concat(): Requires array to work with') end result = a arguments.shift arguments.each do |x| result += (x.is_a?(Array) ? x : [x]) end return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/convert_base.rb b/lib/puppet/parser/functions/convert_base.rb index 3e4c89f..d655419 100644 --- a/lib/puppet/parser/functions/convert_base.rb +++ b/lib/puppet/parser/functions/convert_base.rb @@ -1,51 +1,53 @@ +# frozen_string_literal: true + # # convert_base.rb # module Puppet::Parser::Functions - newfunction(:convert_base, :type => :rvalue, :arity => 2, :doc => <<-'DOC') do |args| + newfunction(:convert_base, type: :rvalue, arity: 2, doc: <<-'DOC') do |args| @summary Converts a given integer or base 10 string representing an integer to a specified base, as a string. @return converted value as a string @example Example usage convert_base(5, 2)` results in: `'101'` convert_base('254', '16')` results in: `'fe'` > *Note:* Since Puppet 4.5.0 this can be done with the built-in [`String.new`](https://puppet.com/docs/puppet/latest/function.html#integer-to-string) function and its many formatting options: `$binary_repr = String(5, '%b')` return `"101"` `$hex_repr = String(254, "%x")` return `"fe"` `$hex_repr = String(254, "%#x")` return `"0xfe"` @return [String] The converted value as a String DOC 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] =~ %r{^[0-9]+$} + raise Puppet::ParseError, 'convert_base(): First argument must be an integer or a string corresponding to an integer in base 10' unless %r{^[0-9]+$}.match?(args[0]) 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] =~ %r{^[0-9]+$} + raise Puppet::ParseError, 'convert_base(): First argument must be an integer or a string corresponding to an integer in base 10' unless %r{^[0-9]+$}.match?(args[1]) end number_to_convert = args[0] new_base = args[1] 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 && new_base <= 36 return number_to_convert.to_s(new_base) end end diff --git a/lib/puppet/parser/functions/count.rb b/lib/puppet/parser/functions/count.rb index c302aa1..b2bd89a 100644 --- a/lib/puppet/parser/functions/count.rb +++ b/lib/puppet/parser/functions/count.rb @@ -1,41 +1,42 @@ +# frozen_string_literal: true + # # count.rb # module Puppet::Parser::Functions - newfunction(:count, :type => :rvalue, :arity => -2, :doc => <<-DOC + newfunction(:count, type: :rvalue, arity: -2, doc: <<-DOC @summary Counts the number of elements in array. Takes an array as first argument and an optional second argument. Counts the number of elements in array that is equal to the second argument. If called with only an array, it counts the number of elements that are not nil/undef/empty-string. > *Note:* equality is tested with a Ruby method and it is therefore subject to what Ruby considers to be equal. For strings this means that equality is case sensitive. In Puppet core, counting can be done in general by using a combination of the core functions filter() (since Puppet 4.0.0) and length() (since Puppet 5.5.0, before that in stdlib). Example below shows counting values that are not undef. ```notice([42, "hello", undef].filter |$x| { $x =~ NotUndef }.length)``` Would notice the value 2. @return [Integer] The amount of elements counted within the array DOC - ) do |args| - + ) do |args| if args.size > 2 raise(ArgumentError, "count(): Wrong number of arguments given #{args.size} for 1 or 2.") end collection, item = args if item collection.count item else 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 bf62576..bd796ec 100644 --- a/lib/puppet/parser/functions/deep_merge.rb +++ b/lib/puppet/parser/functions/deep_merge.rb @@ -1,51 +1,53 @@ +# frozen_string_literal: true + # # deep_merge.rb # module Puppet::Parser::Functions - newfunction(:deep_merge, :type => :rvalue, :doc => <<-'DOC') do |args| + newfunction(:deep_merge, type: :rvalue, doc: <<-'DOC') do |args| @summary Recursively merges two or more hashes together and returns the resulting hash. @example Example usage $hash1 = {'one' => 1, 'two' => 2, 'three' => { 'four' => 4 } } $hash2 = {'two' => 'dos', 'three' => { 'five' => 5 } } $merged_hash = deep_merge($hash1, $hash2) The resulting hash is equivalent to: $merged_hash = { 'one' => 1, 'two' => 'dos', 'three' => { 'four' => 4, 'five' => 5 } } When there is a duplicate key that is a hash, they are recursively merged. When there is a duplicate key that is not a hash, the key in the rightmost hash will "win." @return [Hash] The merged hash DOC if args.length < 2 raise Puppet::ParseError, "deep_merge(): wrong number of arguments (#{args.length}; must be at least 2)" end 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 new_value end end end result = {} args.each do |arg| 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" end result = deep_merge.call(result, arg) end 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 daac567..74fc67a 100644 --- a/lib/puppet/parser/functions/defined_with_params.rb +++ b/lib/puppet/parser/functions/defined_with_params.rb @@ -1,79 +1,81 @@ +# frozen_string_literal: true + # Test whether a given class or definition is defined require 'puppet/parser/functions' Puppet::Parser::Functions.newfunction(:defined_with_params, - :type => :rvalue, - :doc => <<-DOC + type: :rvalue, + doc: <<-DOC, @summary 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. ``` user { 'dan': ensure => present, } if ! defined_with_params(User[dan], {'ensure' => 'present' }) { user { 'dan': ensure => present, } } ``` @return [Boolean] returns `true` or `false` DOC ) do |vals| reference, params = vals raise(ArgumentError, 'Must specify a reference') unless reference if !params || params == '' params = {} end ret = false if Puppet::Util::Package.versioncmp(Puppet.version, '4.6.0') >= 0 # Workaround for PE-20308 if reference.is_a?(String) type_name, title = Puppet::Resource.type_and_title(reference, nil) type = Puppet::Pops::Evaluator::Runtime3ResourceSupport.find_resource_type_or_class(find_global_scope, type_name.downcase) elsif reference.is_a?(Puppet::Resource) type = reference.type title = reference.title else raise(ArgumentError, "Reference is not understood: '#{reference.class}'") end # end workaround else type = reference.to_s title = nil end resources = if title.empty? catalog.resources.select { |r| r.type == type } else [findresource(type, title)] end resources.compact.each do |res| # If you call this from within a defined type, it will find itself next if res.to_s == resource.to_s matches = params.map do |key, value| # eql? avoids bugs caused by monkeypatching in puppet res_is_undef = res[key].eql?(:undef) || res[key].nil? value_is_undef = value.eql?(:undef) || value.nil? found_match = (res_is_undef && value_is_undef) || (res[key] == value) Puppet.debug("Matching resource is #{res}") if found_match found_match end ret = params.empty? || !matches.include?(false) break if ret end Puppet.debug("Resource #{reference} was not determined to be defined") unless ret ret end diff --git a/lib/puppet/parser/functions/delete.rb b/lib/puppet/parser/functions/delete.rb index bf614f7..e66b3c4 100644 --- a/lib/puppet/parser/functions/delete.rb +++ b/lib/puppet/parser/functions/delete.rb @@ -1,67 +1,68 @@ +# frozen_string_literal: true + # # delete.rb # module Puppet::Parser::Functions - newfunction(:delete, :type => :rvalue, :doc => <<-DOC + newfunction(:delete, type: :rvalue, doc: <<-DOC @summary Deletes all instances of a given element from an array, substring from a string, or key from a hash. @example Example usage 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','c']) Would return: {'a'=>1} delete('abracadabra', 'bra') Would return: 'acada' ['a', 'b', 'c', 'b'] - 'b' Would return: ['a', 'c'] {'a'=>1,'b'=>2,'c'=>3} - ['b','c']) Would return: {'a' => '1'} 'abracadabra'.regsubst(/bra/, '', 'G') Would return: 'acada' > *Note:* From Puppet 4.0.0 the minus (-) operator deletes values from arrays and keys from a hash `{'a'=>1,'b'=>2,'c'=>3} - ['b','c'])` > A global delete from a string can be performed with the [`regsubst`](https://puppet.com/docs/puppet/latest/function.html#regsubst) function: `'abracadabra'.regsubst(/bra/, '', 'G')` In general, the built-in [`filter`](https://puppet.com/docs/puppet/latest/function.html#filter) function can filter out entries from arrays and hashes based on keys and/or values. @return [String] The filtered String, if one was given. @return [Hash] The filtered Hash, if one was given. @return [Array] The filtered Array, if one was given. DOC - ) 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}.") end end collection end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/delete_at.rb b/lib/puppet/parser/functions/delete_at.rb index 992d7d8..12cba08 100644 --- a/lib/puppet/parser/functions/delete_at.rb +++ b/lib/puppet/parser/functions/delete_at.rb @@ -1,61 +1,63 @@ +# frozen_string_literal: true + # # delete_at.rb # module Puppet::Parser::Functions - newfunction(:delete_at, :type => :rvalue, :doc => <<-DOC) do |arguments| + newfunction(:delete_at, type: :rvalue, doc: <<-DOC) do |arguments| @summary Deletes a determined indexed value from an array. For example ```delete_at(['a','b','c'], 1)``` Would return: `['a','c']` > *Note:* Since Puppet 4 this can be done in general with the built-in [`filter`](https://puppet.com/docs/puppet/latest/function.html#filter) function: ```['a', 'b', 'c'].filter |$pos, $val | { $pos != 1 }``` Or if a delete is wanted from the beginning or end of the array, by using the slice operator [ ]: ``` $array[0, -1] # the same as all the values $array[2, -1] # all but the first 2 elements $array[0, -3] # all but the last 2 elements $array[1, -2] # all but the first and last element ``` @return [Array] The given array, now missing the target value DOC raise(Puppet::ParseError, "delete_at(): Wrong number of arguments given (#{arguments.size} for 2)") if arguments.size < 2 array = arguments[0] unless array.is_a?(Array) raise(Puppet::ParseError, 'delete_at(): Requires array to work with') end index = arguments[1] if index.is_a?(String) && !index.match(%r{^\d+$}) raise(Puppet::ParseError, 'delete_at(): You must provide non-negative numeric index') end result = array.clone # Numbers in Puppet are often string-encoded which is troublesome ... index = index.to_i if index > result.size - 1 # First element is at index 0 is it not? raise(Puppet::ParseError, 'delete_at(): Given index exceeds size of array given') end result.delete_at(index) # We ignore the element that got deleted ... return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/delete_regex.rb b/lib/puppet/parser/functions/delete_regex.rb index 3645191..0f14177 100644 --- a/lib/puppet/parser/functions/delete_regex.rb +++ b/lib/puppet/parser/functions/delete_regex.rb @@ -1,52 +1,53 @@ +# frozen_string_literal: true + # # 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 => <<-DOC + newfunction(:delete_regex, type: :rvalue, doc: <<-DOC @summary 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. @example Example usage 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'=>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} > *Note:* Since Puppet 4 this can be done in general with the built-in [`filter`](https://puppet.com/docs/puppet/latest/function.html#filter) function: ["aaa", "aba", "aca"].filter |$val| { $val !~ /b/ } Would return: ['aaa', 'aca'] @return [Array] The given array now missing all targeted values. DOC - ) 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}.") end end collection end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/delete_undef_values.rb b/lib/puppet/parser/functions/delete_undef_values.rb index b00f5e4..e537e9a 100644 --- a/lib/puppet/parser/functions/delete_undef_values.rb +++ b/lib/puppet/parser/functions/delete_undef_values.rb @@ -1,42 +1,43 @@ +# frozen_string_literal: true + # # delete_undef_values.rb # module Puppet::Parser::Functions - newfunction(:delete_undef_values, :type => :rvalue, :doc => <<-DOC + newfunction(:delete_undef_values, type: :rvalue, doc: <<-DOC @summary Returns a copy of input hash or array with all undefs deleted. @example Example usage $hash = delete_undef_values({a=>'A', b=>'', c=>undef, d => false}) Would return: {a => 'A', b => '', d => false} While: $array = delete_undef_values(['A','',undef,false]) Would return: ['A','',false] > *Note:* Since Puppet 4.0.0 the equivalent can be performed with the built-in [`filter`](https://puppet.com/docs/puppet/latest/function.html#filter) function: $array.filter |$val| { $val =~ NotUndef } $hash.filter |$key, $val| { $val =~ NotUndef } @return [Array] The given array now issing of undefined values. DOC - ) do |args| - + ) do |args| raise(Puppet::ParseError, "delete_undef_values(): Wrong number of arguments given (#{args.size})") if args.empty? 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 { |_, val| val.equal?(:undef) || val.nil? } elsif result.is_a?(Array) result.delete :undef result.delete nil end result end end diff --git a/lib/puppet/parser/functions/delete_values.rb b/lib/puppet/parser/functions/delete_values.rb index f162522..3aa8be7 100644 --- a/lib/puppet/parser/functions/delete_values.rb +++ b/lib/puppet/parser/functions/delete_values.rb @@ -1,33 +1,34 @@ +# frozen_string_literal: true + # # delete_values.rb # module Puppet::Parser::Functions - newfunction(:delete_values, :type => :rvalue, :doc => <<-DOC + newfunction(:delete_values, type: :rvalue, doc: <<-DOC @summary Deletes all instances of a given value from a hash. @example Example usage delete_values({'a'=>'A','b'=>'B','c'=>'C','B'=>'D'}, 'B') Would return: {'a'=>'A','c'=>'C','B'=>'D'} > *Note:* Since Puppet 4.0.0 the equivalent can be performed with the built-in [`filter`](https://puppet.com/docs/puppet/latest/function.html#filter) function: $array.filter |$val| { $val != 'B' } $hash.filter |$key, $val| { $val != 'B' } @return [Hash] The given hash now missing all instances of the targeted value DOC - ) 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 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 } end end diff --git a/lib/puppet/parser/functions/deprecation.rb b/lib/puppet/parser/functions/deprecation.rb index 2a39cc3..1633723 100644 --- a/lib/puppet/parser/functions/deprecation.rb +++ b/lib/puppet/parser/functions/deprecation.rb @@ -1,26 +1,27 @@ +# frozen_string_literal: true + # # deprecation.rb # module Puppet::Parser::Functions - newfunction(:deprecation, :doc => <<-DOC + newfunction(:deprecation, doc: <<-DOC @summary 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.). @return [String] return deprecation warnings DOC - ) 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' warning("deprecation. #{key}. #{message}") end end end diff --git a/lib/puppet/parser/functions/difference.rb b/lib/puppet/parser/functions/difference.rb index 49e8673..3c44610 100644 --- a/lib/puppet/parser/functions/difference.rb +++ b/lib/puppet/parser/functions/difference.rb @@ -1,44 +1,45 @@ +# frozen_string_literal: true + # # difference.rb # module Puppet::Parser::Functions - newfunction(:difference, :type => :rvalue, :doc => <<-DOC + newfunction(:difference, type: :rvalue, doc: <<-DOC @summary 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. @example Example usage difference(["a","b","c"],["b","c","d"]) Would return: `["a"]` > *Note:* Since Puppet 4 the minus (-) operator in the Puppet language does the same thing: ['a', 'b', 'c'] - ['b', 'c', 'd'] Would return: `['a']` @return [Array] The difference between the two given arrays DOC - ) 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 first = arguments[0] second = arguments[1] unless first.is_a?(Array) && second.is_a?(Array) raise(Puppet::ParseError, 'difference(): Requires 2 arrays') end result = first - second return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/dig.rb b/lib/puppet/parser/functions/dig.rb index b6addb4..81b58e1 100644 --- a/lib/puppet/parser/functions/dig.rb +++ b/lib/puppet/parser/functions/dig.rb @@ -1,57 +1,59 @@ +# frozen_string_literal: true + # # dig.rb # module Puppet::Parser::Functions - newfunction(:dig, :type => :rvalue, :doc => <<-DOC + newfunction(:dig, type: :rvalue, doc: <<-DOC @summary **DEPRECATED** Retrieves a value within multiple layers of hashes and arrays via an array of keys containing a path. @return The function goes through the structure by each path component and tries to return the value at the end of the path. In addition to the required path argument, the function accepts the default argument. It is returned if the path is not correct, if no value was found, or if any other error has occurred. ```ruby $data = { 'a' => { 'b' => [ 'b1', 'b2', 'b3', ] } } $value = dig($data, ['a', 'b', 2]) # $value = 'b3' # with all possible options $value = dig($data, ['a', 'b', 2], 'not_found') # $value = 'b3' # using the default value $value = dig($data, ['a', 'b', 'c', 'd'], 'not_found') # $value = 'not_found' ``` 1. `$data` The data structure we are working with. 2. `['a', 'b', 2]` The path array. 3. `not_found` The default value. It is returned if nothing is found. > **Note:* **Deprecated** This function has been replaced with a built-in [`dig`](https://puppet.com/docs/puppet/latest/function.html#dig) function as of Puppet 4.5.0. Use [`dig44()`](#dig44) for backwards compatibility or use the new version. DOC - ) do |arguments| + ) 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) end end diff --git a/lib/puppet/parser/functions/dig44.rb b/lib/puppet/parser/functions/dig44.rb index ff1d9df..7b58c22 100644 --- a/lib/puppet/parser/functions/dig44.rb +++ b/lib/puppet/parser/functions/dig44.rb @@ -1,70 +1,72 @@ +# frozen_string_literal: true + # # dig44.rb # module Puppet::Parser::Functions newfunction( :dig44, - :type => :rvalue, - :arity => -2, - :doc => <<-DOC + type: :rvalue, + arity: -2, + doc: <<-DOC, @summary **DEPRECATED**: 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 = dig44($data, ['a', 'b', 2]) # $value = 'b3' # with all possible options $value = dig44($data, ['a', 'b', 2], 'not_found') # $value = 'b3' # using the default value $value = dig44($data, ['a', 'b', 'c', 'd'], 'not_found') # $value = 'not_found' ``` > **Note:* **Deprecated** This function has been replaced with a built-in [`dig`](https://puppet.com/docs/puppet/latest/function.html#dig) function as of Puppet 4.5.0. @return [String] 'not_found' will be returned if nothing is found @return [Any] the value that was searched for DOC ) do |arguments| # Two arguments are required raise(Puppet::ParseError, "dig44(): Wrong number of arguments given (#{arguments.size} for at least 2)") if arguments.size < 2 data, path, default = *arguments 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| break unless structure.is_a?(Hash) || structure.is_a?(Array) if structure.is_a? Array begin key = Integer key rescue break end end break if structure[key].nil? || structure[key] == :undef structure[key] end value.nil? ? default : value end end diff --git a/lib/puppet/parser/functions/dirname.rb b/lib/puppet/parser/functions/dirname.rb index ae579e2..4a07a29 100644 --- a/lib/puppet/parser/functions/dirname.rb +++ b/lib/puppet/parser/functions/dirname.rb @@ -1,31 +1,32 @@ +# frozen_string_literal: true + # # dirname.rb # module Puppet::Parser::Functions - newfunction(:dirname, :type => :rvalue, :doc => <<-DOC + newfunction(:dirname, type: :rvalue, doc: <<-DOC @summary Returns the dirname of a path. @return [String] the given path's dirname DOC - ) do |arguments| - + ) do |arguments| if arguments.empty? raise(Puppet::ParseError, 'dirname(): No arguments given') end if arguments.size > 1 raise(Puppet::ParseError, "dirname(): Too many arguments given (#{arguments.size})") end unless arguments[0].is_a?(String) raise(Puppet::ParseError, 'dirname(): Requires string as argument') end # undef is converted to an empty string '' if arguments[0].empty? raise(Puppet::ParseError, 'dirname(): Requires a non-empty string as argument') end return File.dirname(arguments[0]) end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/dos2unix.rb b/lib/puppet/parser/functions/dos2unix.rb index e741aa8..0e2b2b6 100644 --- a/lib/puppet/parser/functions/dos2unix.rb +++ b/lib/puppet/parser/functions/dos2unix.rb @@ -1,19 +1,20 @@ +# frozen_string_literal: true + # Custom Puppet function to convert dos to unix format module Puppet::Parser::Functions - newfunction(:dos2unix, :type => :rvalue, :arity => 1, :doc => <<-DOC + newfunction(:dos2unix, type: :rvalue, arity: 1, doc: <<-DOC @summary Returns the Unix version of the given string. Takes a single string argument. @return The retrieved version DOC - ) do |arguments| - + ) do |arguments| unless arguments[0].is_a?(String) raise(Puppet::ParseError, 'dos2unix(): Requires string as argument') end 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 a0717ff..32e338c 100644 --- a/lib/puppet/parser/functions/downcase.rb +++ b/lib/puppet/parser/functions/downcase.rb @@ -1,40 +1,41 @@ +# frozen_string_literal: true + # # 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 => <<-DOC + newfunction(:downcase, type: :rvalue, doc: <<-DOC @summary **Deprecated:** Converts the case of a string or all strings in an array to lower case. > *Note:* **Deprecated** from Puppet 6.0.0, this function has been replaced with a built-in [`downcase`](https://puppet.com/docs/puppet/latest/function.html#downcase) function. > This function is an implementation of a Ruby class and might not be UTF8 compatible. To ensure compatibility, use this function with Ruby 2.4.0 or greater. @return [String] The converted String, if it was a String that was given @return [Array[String]] The converted Array, if it was a Array that was given DOC - ) do |arguments| - + ) do |arguments| raise(Puppet::ParseError, "downcase(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? value = arguments[0] unless value.is_a?(Array) || value.is_a?(String) raise(Puppet::ParseError, 'downcase(): Requires either array or string to work with') 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 end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/empty.rb b/lib/puppet/parser/functions/empty.rb index 907ecb1..ee1dabc 100644 --- a/lib/puppet/parser/functions/empty.rb +++ b/lib/puppet/parser/functions/empty.rb @@ -1,31 +1,32 @@ +# frozen_string_literal: true + # # empty.rb # module Puppet::Parser::Functions - newfunction(:empty, :type => :rvalue, :doc => <<-DOC + newfunction(:empty, type: :rvalue, doc: <<-DOC @summary **Deprecated:** Returns true if the variable is empty. @return Returns `true` if the argument is an array or hash that contains no elements, or an empty string. Returns `false` when the argument is a numerical value. > *Note*: **Deprecated** from Puppet 5.5.0, the built-in [`empty`](https://puppet.com/docs/puppet/6.4/function.html#empty) function will be used instead. DOC - ) do |arguments| - + ) 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 return false if value.is_a?(Numeric) result = value.empty? return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/enclose_ipv6.rb b/lib/puppet/parser/functions/enclose_ipv6.rb index b55f76b..cfa174b 100644 --- a/lib/puppet/parser/functions/enclose_ipv6.rb +++ b/lib/puppet/parser/functions/enclose_ipv6.rb @@ -1,46 +1,47 @@ +# frozen_string_literal: true + # # enclose_ipv6.rb # module Puppet::Parser::Functions - newfunction(:enclose_ipv6, :type => :rvalue, :doc => <<-DOC + newfunction(:enclose_ipv6, type: :rvalue, doc: <<-DOC @summary Takes an array of ip addresses and encloses the ipv6 addresses with square brackets. @return encloses the ipv6 addresses with square brackets. DOC - ) do |arguments| - + ) do |arguments| require 'ipaddr' rescuable_exceptions = [ArgumentError] if defined?(IPAddr::InvalidAddressError) rescuable_exceptions << IPAddr::InvalidAddressError end 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) || arguments[0].is_a?(Array) raise(Puppet::ParseError, "enclose_ipv6(): Wrong argument type given #{arguments[0].class} expected String or Array") end input = [arguments[0]].flatten.compact result = [] input.each do |val| unless val == '*' begin ip = IPAddr.new(val) rescue *rescuable_exceptions raise(Puppet::ParseError, "enclose_ipv6(): Wrong argument given #{val} is not an ip address.") end val = "[#{ip}]" if ip.ipv6? end result << val end return result.uniq end end diff --git a/lib/puppet/parser/functions/ensure_packages.rb b/lib/puppet/parser/functions/ensure_packages.rb index f255c03..3cd2b20 100644 --- a/lib/puppet/parser/functions/ensure_packages.rb +++ b/lib/puppet/parser/functions/ensure_packages.rb @@ -1,53 +1,54 @@ +# frozen_string_literal: true + # # ensure_packages.rb # module Puppet::Parser::Functions - newfunction(:ensure_packages, :type => :statement, :doc => <<-DOC + newfunction(:ensure_packages, type: :statement, doc: <<-DOC @summary 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. @return install the passed packages DOC - ) do |arguments| - + ) do |arguments| 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] defaults = { 'ensure' => 'present' }.merge(arguments[1]) if defaults['ensure'] == 'installed' defaults['ensure'] = 'present' end else defaults = { 'ensure' => 'present' } end Puppet::Parser::Functions.function(:ensure_resources) function_ensure_resources(['package', arguments[0].dup, defaults]) else packages = Array(arguments[0]) if arguments[1] defaults = { 'ensure' => 'present' }.merge(arguments[1]) if defaults['ensure'] == 'installed' defaults['ensure'] = 'present' end else defaults = { 'ensure' => 'present' } end Puppet::Parser::Functions.function(:ensure_resource) packages.each do |package_name| raise(Puppet::ParseError, 'ensure_packages(): Empty String provided for package name') if package_name.empty? function_ensure_resource(['package', package_name, defaults]) end end end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/ensure_resource.rb b/lib/puppet/parser/functions/ensure_resource.rb index e4fa771..e606360 100644 --- a/lib/puppet/parser/functions/ensure_resource.rb +++ b/lib/puppet/parser/functions/ensure_resource.rb @@ -1,52 +1,54 @@ +# frozen_string_literal: true + # Test whether a given class or definition is defined require 'puppet/parser/functions' Puppet::Parser::Functions.newfunction(:ensure_resource, - :type => :statement, - :doc => <<-DOC + type: :statement, + doc: <<-DOC, @summary Takes a resource type, title, and a list of attributes that describe a resource. user { 'dan': ensure => present, } @return created or recreated the passed resource with the passed type and attributes @example Example usage Creates the resource if it does not already exist: 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. 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'}) DOC ) do |vals| type, title, params = vals raise(ArgumentError, 'Must specify a type') unless type raise(ArgumentError, 'Must specify a title') unless title params ||= {} items = [title].flatten items.each do |item| Puppet::Parser::Functions.function(:defined_with_params) if function_defined_with_params(["#{type}[#{item}]", params]) Puppet.debug("Resource #{type}[#{item}] with params #{params} not created because it already exists") else Puppet.debug("Create new resource #{type}[#{item}] with params #{params}") Puppet::Parser::Functions.function(:create_resources) function_create_resources([type.capitalize, { item => params }]) end end end diff --git a/lib/puppet/parser/functions/ensure_resources.rb b/lib/puppet/parser/functions/ensure_resources.rb index c7032ca..ed82b23 100644 --- a/lib/puppet/parser/functions/ensure_resources.rb +++ b/lib/puppet/parser/functions/ensure_resources.rb @@ -1,56 +1,58 @@ +# frozen_string_literal: true + require 'puppet/parser/functions' Puppet::Parser::Functions.newfunction(:ensure_resources, - :type => :statement, - :doc => <<-DOC + type: :statement, + doc: <<-DOC, @summary Takes a resource type, title (only hash), and a list of attributes that describe a resource. @return created resources with the passed type and attributes @example Example usage 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. ensure_resources('user', {'dan' => { gid => 'mygroup', uid => '600' }, 'alex' => { gid => 'mygroup' }}, {'ensure' => 'present'}) From Hiera Backend: userlist: dan: gid: 'mygroup' uid: '600' alex: gid: 'mygroup' Call: ensure_resources('user', hiera_hash('userlist'), {'ensure' => 'present'}) DOC ) do |vals| type, title, params = vals raise(ArgumentError, 'Must specify a type') unless type raise(ArgumentError, 'Must specify a title') unless title params ||= {} 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 7344201..a544d33 100644 --- a/lib/puppet/parser/functions/flatten.rb +++ b/lib/puppet/parser/functions/flatten.rb @@ -1,36 +1,37 @@ +# frozen_string_literal: true + # # flatten.rb # module Puppet::Parser::Functions - newfunction(:flatten, :type => :rvalue, :doc => <<-DOC + newfunction(:flatten, type: :rvalue, doc: <<-DOC @summary This function flattens any deeply nested arrays and returns a single flat array as a result. @return convert nested arrays into a single flat array @example Example usage flatten(['a', ['b', ['c']]])` returns: `['a','b','c'] > **Note:** **Deprecated** from Puppet 5.5.0, this function has been replaced with a built-in [`flatten`](https://puppet.com/docs/puppet/latest/function.html#flatten) function. DOC - ) do |arguments| - + ) do |arguments| raise(Puppet::ParseError, "flatten(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size != 1 array = arguments[0] unless array.is_a?(Array) raise(Puppet::ParseError, 'flatten(): Requires array to work with') end result = array.flatten return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/floor.rb b/lib/puppet/parser/functions/floor.rb index 3a6f3c8..1d59963 100644 --- a/lib/puppet/parser/functions/floor.rb +++ b/lib/puppet/parser/functions/floor.rb @@ -1,32 +1,33 @@ +# frozen_string_literal: true + # # floor.rb # module Puppet::Parser::Functions - newfunction(:floor, :type => :rvalue, :doc => <<-DOC + newfunction(:floor, type: :rvalue, doc: <<-DOC @summary Returns the largest integer less or equal to the argument. @return the largest integer less or equal to the argument. Takes a single numeric value as an argument. > **Note:** **Deprecated** from Puppet 6.0.0, this function has been replaced with a built-in [`floor`](https://puppet.com/docs/puppet/latest/function.html#floor) function. DOC - ) 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 raise(Puppet::ParseError, "floor(): Wrong argument type given (#{arguments[0]} for Numeric)") end raise(Puppet::ParseError, "floor(): Wrong argument type given (#{arg.class} for Numeric)") if arg.is_a?(Numeric) == false arg.floor end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/fqdn_rand_string.rb b/lib/puppet/parser/functions/fqdn_rand_string.rb index 9bfba73..e9636c2 100644 --- a/lib/puppet/parser/functions/fqdn_rand_string.rb +++ b/lib/puppet/parser/functions/fqdn_rand_string.rb @@ -1,43 +1,45 @@ +# frozen_string_literal: true + Puppet::Parser::Functions.newfunction( :fqdn_rand_string, - :arity => -2, - :type => :rvalue, - :doc => <<-DOC + arity: -2, + type: :rvalue, + doc: <<-DOC, @summary Generates a random alphanumeric string. Combining the `$fqdn` fact and an optional seed for repeatable randomness. Optionally, you can specify a character set for the function (defaults to alphanumeric). Arguments * An integer, specifying the length of the resulting string. * Optionally, a string specifying the character set. * Optionally, a string specifying the seed for repeatable randomness. @return [String] @example Example Usage: fqdn_rand_string(10) fqdn_rand_string(10, 'ABCDEF!@$%^') fqdn_rand_string(10, '', 'custom seed') DOC ) 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') 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? 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] + rand_string += charset[function_fqdn_rand([charset.size, (args + [current.to_s]).join(':')]).to_i] end rand_string end diff --git a/lib/puppet/parser/functions/fqdn_rotate.rb b/lib/puppet/parser/functions/fqdn_rotate.rb index c86ea68..603c57c 100644 --- a/lib/puppet/parser/functions/fqdn_rotate.rb +++ b/lib/puppet/parser/functions/fqdn_rotate.rb @@ -1,63 +1,64 @@ +# frozen_string_literal: true + # # fqdn_rotate.rb # Puppet::Parser::Functions.newfunction( :fqdn_rotate, - :type => :rvalue, - :doc => <<-DOC + type: :rvalue, + doc: <<-DOC, @summary Rotates an array or string a random number of times, combining the `$fqdn` fact and an optional seed for repeatable randomness. @return rotated array or string @example Example Usage: fqdn_rotate(['a', 'b', 'c', 'd']) fqdn_rotate('abcd') fqdn_rotate([1, 2, 3], 'custom seed') DOC ) do |args| - raise(Puppet::ParseError, "fqdn_rotate(): Wrong number of arguments given (#{args.size} for 1)") if args.empty? 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 result = value.clone string = value.is_a?(String) ? true : false # 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 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 old_seed = srand(seed) offset = rand(elements) srand(old_seed) end offset.times do result.push result.shift end result = string ? result.join : 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 e325fe7..b3141c8 100644 --- a/lib/puppet/parser/functions/fqdn_uuid.rb +++ b/lib/puppet/parser/functions/fqdn_uuid.rb @@ -1,68 +1,70 @@ +# frozen_string_literal: true + require 'digest/sha1' # # fqdn_uuid.rb # module Puppet::Parser::Functions - newfunction(:fqdn_uuid, :type => :rvalue, :doc => <<-DOC) do |args| + newfunction(:fqdn_uuid, type: :rvalue, doc: <<-DOC) do |args| @summary Returns a [RFC 4122](https://tools.ietf.org/html/rfc4122) valid version 5 UUID based on an FQDN string under the DNS namespace @return Returns a [RFC 4122](https://tools.ietf.org/html/rfc4122) valid version 5 UUID @example Example Usage: fqdn_uuid('puppetlabs.com') # Returns '9c70320f-6815-5fc5-ab0f-debe68bf764c' fqdn_uuid('google.com') # Returns '64ee70a4-8cc1-5d25-abf2-dea6c79a09c8' DOC 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 # This is the UUID version 5 type DNS name space which is as follows: # # 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 sha1 = Digest::SHA1.new sha1.update(uuid_name_space_dns) sha1.update(fqdn) # first 16 bytes.. bytes = sha1.digest[0, 16].bytes.to_a # version 5 adjustments bytes[6] &= 0x0f bytes[6] |= 0x50 # variant is DCE 1.1 bytes[8] &= 0x3f bytes[8] |= 0x80 bytes = [4, 2, 2, 2, 6].map do |i| bytes.slice!(0, i).pack('C*').unpack('H*') end bytes.join('-') end end diff --git a/lib/puppet/parser/functions/get_module_path.rb b/lib/puppet/parser/functions/get_module_path.rb index ac787c6..3595d53 100644 --- a/lib/puppet/parser/functions/get_module_path.rb +++ b/lib/puppet/parser/functions/get_module_path.rb @@ -1,29 +1,31 @@ +# frozen_string_literal: true + # # get_module_path.rb # module Puppet::Parser::Functions - newfunction(:get_module_path, :type => :rvalue, :doc => <<-DOC + newfunction(:get_module_path, type: :rvalue, doc: <<-DOC @summary Returns the absolute path of the specified module for the current environment. @return Returns the absolute path of the specified module for the current environment. @example Example Usage: $module_path = get_module_path('stdlib') > *Note:* that since Puppet 5.4.0 the built-in [`module_directory`](https://puppet.com/docs/puppet/latest/function.html#module_directory) function in Puppet does the same thing and will return the path to the first found module if given multiple values or an array. DOC - ) do |args| + ) 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 59ef769..18b7b51 100644 --- a/lib/puppet/parser/functions/getparam.rb +++ b/lib/puppet/parser/functions/getparam.rb @@ -1,59 +1,61 @@ +# frozen_string_literal: true + # Test whether a given class or definition is defined require 'puppet/parser/functions' Puppet::Parser::Functions.newfunction(:getparam, - :type => :rvalue, - :doc => <<-'DOC' + type: :rvalue, + doc: <<-'DOC', @summary Returns the value of a resource's parameter. @return value of a resource's parameter. Takes a resource reference and name of the parameter and returns value of resource's parameter. Note that user defined resource types are evaluated lazily. @example Example Usage: # define a resource type with a parameter define example_resource($param) { } # declare an instance of that type example_resource { "example_resource_instance": param => "'the value we are getting in this example''" } # Because of order of evaluation, a second definition is needed # that will be evaluated after the first resource has been declared # define example_get_param { # This will notice the value of the parameter notice(getparam(Example_resource["example_resource_instance"], "param")) } # Declare an instance of the second resource type - this will call notice example_get_param { 'show_notify': } Would notice: 'the value we are getting in this example' > **Note** that since Puppet 4.0.0 it is possible to get a parameter value by using its data type and the [ ] operator. The example below is equivalent to a call to getparam(): ```Example_resource['example_resource_instance']['param']`` DOC ) do |vals| reference, param = vals raise(ArgumentError, 'Must specify a reference') unless reference - raise(ArgumentError, 'Must specify name of a parameter') unless param && param.instance_of?(String) + raise(ArgumentError, 'Must specify name of a parameter') unless param&.instance_of?(String) return '' if param.empty? resource = findresource(reference.to_s) if resource return resource[param] unless resource[param].nil? end return '' end diff --git a/lib/puppet/parser/functions/getvar.rb b/lib/puppet/parser/functions/getvar.rb index 41d3c4f..4ecd832 100644 --- a/lib/puppet/parser/functions/getvar.rb +++ b/lib/puppet/parser/functions/getvar.rb @@ -1,40 +1,42 @@ +# frozen_string_literal: true + # # getvar.rb # module Puppet::Parser::Functions - newfunction(:getvar, :type => :rvalue, :doc => <<-'DOC') do |args| + newfunction(:getvar, type: :rvalue, doc: <<-'DOC') do |args| @summary Lookup a variable in a given namespace. @return undef - if variable does not exist @example Example usage $foo = getvar('site::data::foo') # Equivalent to $foo = $site::data::foo @example Where namespace is stored in a string $datalocation = 'site::data' $bar = getvar("${datalocation}::bar") # Equivalent to $bar = $site::data::bar > **Note:** from Puppet 6.0.0, the compatible function with the same name in Puppet core will be used instead of this function. The new function also has support for digging into a structured value. See the built-in [`getvar`](https://puppet.com/docs/puppet/latest/function.html#getvar) function DOC unless args.length == 1 raise Puppet::ParseError, "getvar(): wrong number of arguments (#{args.length}; must be 1)" end begin result = nil catch(:undefined_variable) do result = lookupvar((args[0]).to_s) end # avoid relying on inconsistent behaviour around ruby return values from catch result - rescue Puppet::ParseError # rubocop:disable Lint/HandleExceptions : Eat the exception if strict_variables = true is set + rescue Puppet::ParseError end end end diff --git a/lib/puppet/parser/functions/glob.rb b/lib/puppet/parser/functions/glob.rb index 5475b74..be4e0d2 100644 --- a/lib/puppet/parser/functions/glob.rb +++ b/lib/puppet/parser/functions/glob.rb @@ -1,31 +1,32 @@ +# frozen_string_literal: true + # # glob.rb # module Puppet::Parser::Functions - newfunction(:glob, :type => :rvalue, :doc => <<-DOC + newfunction(:glob, type: :rvalue, doc: <<-DOC @summary Uses same patterns as Dir#glob. @return Returns an Array of file entries of a directory or an Array of directories. @example Example Usage: $confs = glob(['/etc/**/*.conf', '/opt/**/*.conf']) DOC - ) do |arguments| - + ) do |arguments| unless arguments.size == 1 raise(Puppet::ParseError, 'glob(): Wrong number of arguments given ' \ "(#{arguments.size} for 1)") end pattern = arguments[0] 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 end diff --git a/lib/puppet/parser/functions/grep.rb b/lib/puppet/parser/functions/grep.rb index 2d27483..6ef3ee4 100644 --- a/lib/puppet/parser/functions/grep.rb +++ b/lib/puppet/parser/functions/grep.rb @@ -1,33 +1,34 @@ +# frozen_string_literal: true + # # grep.rb # module Puppet::Parser::Functions - newfunction(:grep, :type => :rvalue, :doc => <<-DOC + newfunction(:grep, type: :rvalue, doc: <<-DOC @summary This function searches through an array and returns any elements that match the provided regular expression. @return array of elements that match the provided regular expression. @example Example Usage: grep(['aaa','bbb','ccc','aaaddd'], 'aaa') # Returns ['aaa','aaaddd'] > **Note:** that since Puppet 4.0.0, the built-in [`filter`](https://puppet.com/docs/puppet/latest/function.html#filter) function does the "same" - as any logic can be used to filter, as opposed to just regular expressions: ```['aaa', 'bbb', 'ccc', 'aaaddd']. filter |$x| { $x =~ 'aaa' }``` DOC - ) do |arguments| - + ) do |arguments| if arguments.size != 2 raise(Puppet::ParseError, "grep(): Wrong number of arguments given #{arguments.size} for 2") end a = arguments[0] pattern = Regexp.new(arguments[1]) a.grep(pattern) end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/has_interface_with.rb b/lib/puppet/parser/functions/has_interface_with.rb index fb9af42..0404217 100644 --- a/lib/puppet/parser/functions/has_interface_with.rb +++ b/lib/puppet/parser/functions/has_interface_with.rb @@ -1,71 +1,72 @@ +# frozen_string_literal: true + # # has_interface_with # module Puppet::Parser::Functions - newfunction(:has_interface_with, :type => :rvalue, :doc => <<-DOC + newfunction(:has_interface_with, type: :rvalue, doc: <<-DOC @summary Returns boolean based on kind and value. @return boolean values `true` or `false` Valid kinds are `macaddress`, `netmask`, `ipaddress` and `network`. @example **Usage** has_interface_with("macaddress", "x:x:x:x:x:x") # Returns `false` has_interface_with("ipaddress", "127.0.0.1") # Returns `true` @example If no "kind" is given, then the presence of the interface is checked: has_interface_with("lo") # Returns `true` DOC - ) do |args| - + ) do |args| 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? interfaces = interfaces.split(',') if args.size == 1 return interfaces.member?(args[0]) end kind, value = args # Bug with 3.7.1 - 3.7.3 when using future parser throws :undefined_variable # https://tickets.puppetlabs.com/browse/PUP-3597 factval = nil begin catch :undefined_variable do factval = lookupvar(kind) end - rescue Puppet::ParseError # rubocop:disable Lint/HandleExceptions : Eat the exception if strict_variables = true is set + rescue Puppet::ParseError end if factval == value return true end result = false interfaces.each do |iface| iface.downcase! factval = nil begin # Bug with 3.7.1 - 3.7.3 when using future parser throws :undefined_variable # https://tickets.puppetlabs.com/browse/PUP-3597 catch :undefined_variable do factval = lookupvar("#{kind}_#{iface}") end - rescue Puppet::ParseError # rubocop:disable Lint/HandleExceptions : Eat the exception if strict_variables = true is set + rescue Puppet::ParseError end if value == factval result = true break end end result end end diff --git a/lib/puppet/parser/functions/has_ip_address.rb b/lib/puppet/parser/functions/has_ip_address.rb index 4004681..0cea4a7 100644 --- a/lib/puppet/parser/functions/has_ip_address.rb +++ b/lib/puppet/parser/functions/has_ip_address.rb @@ -1,26 +1,27 @@ +# frozen_string_literal: true + # # has_ip_address # module Puppet::Parser::Functions - newfunction(:has_ip_address, :type => :rvalue, :doc => <<-DOC + newfunction(:has_ip_address, type: :rvalue, doc: <<-DOC @summary Returns true if the client has the requested IP address on some interface. @return [Boolean] `true` or `false` This function iterates through the 'interfaces' fact and checks the 'ipaddress_IFACE' facts, performing a simple string comparison. DOC - ) do |args| - + ) do |args| raise(Puppet::ParseError, "has_ip_address(): Wrong number of arguments given (#{args.size} for 1)") if args.size != 1 Puppet::Parser::Functions.autoloader.load(:has_interface_with) \ unless Puppet::Parser::Functions.autoloader.loaded?(:has_interface_with) function_has_interface_with(['ipaddress', args[0]]) end end # vim:sts=2 sw=2 diff --git a/lib/puppet/parser/functions/has_ip_network.rb b/lib/puppet/parser/functions/has_ip_network.rb index b4a3bad..7406ed5 100644 --- a/lib/puppet/parser/functions/has_ip_network.rb +++ b/lib/puppet/parser/functions/has_ip_network.rb @@ -1,26 +1,27 @@ +# frozen_string_literal: true + # # has_ip_network # module Puppet::Parser::Functions - newfunction(:has_ip_network, :type => :rvalue, :doc => <<-DOC + newfunction(:has_ip_network, type: :rvalue, doc: <<-DOC @summary Returns true if the client has an IP address within the requested network. @return Boolean value, `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. DOC - ) do |args| - + ) do |args| raise(Puppet::ParseError, "has_ip_network(): Wrong number of arguments given (#{args.size} for 1)") if args.size != 1 Puppet::Parser::Functions.autoloader.load(:has_interface_with) \ unless Puppet::Parser::Functions.autoloader.loaded?(:has_interface_with) function_has_interface_with(['network', args[0]]) end end # vim:sts=2 sw=2 diff --git a/lib/puppet/parser/functions/has_key.rb b/lib/puppet/parser/functions/has_key.rb index 50dde53..334b849 100644 --- a/lib/puppet/parser/functions/has_key.rb +++ b/lib/puppet/parser/functions/has_key.rb @@ -1,39 +1,41 @@ +# frozen_string_literal: true + # # has_key.rb # module Puppet::Parser::Functions - newfunction(:has_key, :type => :rvalue, :doc => <<-'DOC') do |args| + newfunction(:has_key, type: :rvalue, doc: <<-'DOC') do |args| @summary **Deprecated:** Determine if a hash has a certain key value. @return Boolean value @example Example Usage: $my_hash = {'key_one' => 'value_one'} if has_key($my_hash, 'key_two') { notice('we will not reach here') } if has_key($my_hash, 'key_one') { notice('this will be printed') } > **Note:** **Deprecated** since Puppet 4.0.0, this can now be achieved in the Puppet language with the following equivalent expression: $my_hash = {'key_one' => 'value_one'} if 'key_one' in $my_hash { notice('this will be printed') } DOC unless args.length == 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].key?(args[1]) end end diff --git a/lib/puppet/parser/functions/hash.rb b/lib/puppet/parser/functions/hash.rb index 484cb59..029089e 100644 --- a/lib/puppet/parser/functions/hash.rb +++ b/lib/puppet/parser/functions/hash.rb @@ -1,47 +1,48 @@ +# frozen_string_literal: true + # # hash.rb # module Puppet::Parser::Functions - newfunction(:hash, :type => :rvalue, :doc => <<-DOC + newfunction(:hash, type: :rvalue, doc: <<-DOC @summary **Deprecated:** This function converts an array into a hash. @return the converted array as a hash @example Example Usage: hash(['a',1,'b',2,'c',3]) # Returns: {'a'=>1,'b'=>2,'c'=>3} > **Note:** This function has been replaced with the built-in ability to create a new value of almost any data type - see the built-in [`Hash.new`](https://puppet.com/docs/puppet/latest/function.html#conversion-to-hash-and-struct) function in Puppet. This example shows the equivalent expression in the Puppet language: ``` Hash(['a',1,'b',2,'c',3]) Hash([['a',1],['b',2],['c',3]]) ``` DOC - ) do |arguments| - + ) do |arguments| raise(Puppet::ParseError, "hash(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? array = arguments[0] unless array.is_a?(Array) raise(Puppet::ParseError, 'hash(): Requires array to work with') end result = {} begin # This is to make it compatible with older version of Ruby ... array = array.flatten result = Hash[*array] rescue StandardError raise(Puppet::ParseError, 'hash(): Unable to compute hash from array given') end return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/intersection.rb b/lib/puppet/parser/functions/intersection.rb index 6d9d104..ead7580 100644 --- a/lib/puppet/parser/functions/intersection.rb +++ b/lib/puppet/parser/functions/intersection.rb @@ -1,34 +1,35 @@ +# frozen_string_literal: true + # # intersection.rb # module Puppet::Parser::Functions - newfunction(:intersection, :type => :rvalue, :doc => <<-DOC + newfunction(:intersection, type: :rvalue, doc: <<-DOC @summary This function returns an array of the intersection of two. @return an array of the intersection of two. @example Example Usage: 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) DOC - ) 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 first = arguments[0] second = arguments[1] unless first.is_a?(Array) && second.is_a?(Array) raise(Puppet::ParseError, "intersection(): Requires 2 arrays, got #{first.class} and #{second.class}") end result = first & second return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/is_absolute_path.rb b/lib/puppet/parser/functions/is_absolute_path.rb index f309913..c464afa 100644 --- a/lib/puppet/parser/functions/is_absolute_path.rb +++ b/lib/puppet/parser/functions/is_absolute_path.rb @@ -1,59 +1,61 @@ +# frozen_string_literal: true + # # is_absolute_path.rb # module Puppet::Parser::Functions - newfunction(:is_absolute_path, :type => :rvalue, :arity => 1, :doc => <<-'DOC') do |args| + newfunction(:is_absolute_path, type: :rvalue, arity: 1, doc: <<-'DOC') do |args| @summary **Deprecated:** Returns boolean true if the string represents an absolute path in the filesystem. This function works for windows and unix style paths. @example The following values will return true: $my_path = 'C:/Program Files (x86)/Puppet Labs/Puppet' is_absolute_path($my_path) $my_path2 = '/var/lib/puppet' is_absolute_path($my_path2) $my_path3 = ['C:/Program Files (x86)/Puppet Labs/Puppet'] is_absolute_path($my_path3) $my_path4 = ['/var/lib/puppet'] is_absolute_path($my_path4) @example The following values will return false: is_absolute_path(true) is_absolute_path('../var/lib/puppet') is_absolute_path('var/lib/puppet') $undefined = undef is_absolute_path($undefined) @return [Boolean] Returns `true` or `false` > **Note:* **Deprecated** Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy). DOC 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/main/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?) 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 # defaults to the local platform if none is specified. # Escape once for the string literal, and once for the regex. 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]) # rubocop:disable Style/DoubleNegation : No alternative known end value end end diff --git a/lib/puppet/parser/functions/is_array.rb b/lib/puppet/parser/functions/is_array.rb index 1df57b2..e4e7b81 100644 --- a/lib/puppet/parser/functions/is_array.rb +++ b/lib/puppet/parser/functions/is_array.rb @@ -1,28 +1,29 @@ +# frozen_string_literal: true + # # is_array.rb # module Puppet::Parser::Functions - newfunction(:is_array, :type => :rvalue, :doc => <<-DOC + newfunction(:is_array, type: :rvalue, doc: <<-DOC @summary **Deprecated:** Returns true if the variable passed to this function is an array. @return [Boolean] Returns `true` or `false` > **Note:* **Deprecated** Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy). DOC - ) 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.']) raise(Puppet::ParseError, "is_array(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? type = arguments[0] result = type.is_a?(Array) return result end end diff --git a/lib/puppet/parser/functions/is_bool.rb b/lib/puppet/parser/functions/is_bool.rb index cf5cb32..96cb217 100644 --- a/lib/puppet/parser/functions/is_bool.rb +++ b/lib/puppet/parser/functions/is_bool.rb @@ -1,28 +1,29 @@ +# frozen_string_literal: true + # # is_bool.rb # module Puppet::Parser::Functions - newfunction(:is_bool, :type => :rvalue, :doc => <<-DOC + newfunction(:is_bool, type: :rvalue, doc: <<-DOC @summary **Deprecated:** Returns true if the variable passed to this function is a boolean. @return [Boolean] Returns `true` or `false` > **Note:* **Deprecated** Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy). DOC - ) 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.']) raise(Puppet::ParseError, "is_bool(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size != 1 type = arguments[0] result = type.is_a?(TrueClass) || type.is_a?(FalseClass) return result end end diff --git a/lib/puppet/parser/functions/is_domain_name.rb b/lib/puppet/parser/functions/is_domain_name.rb index 390a868..32b9481 100644 --- a/lib/puppet/parser/functions/is_domain_name.rb +++ b/lib/puppet/parser/functions/is_domain_name.rb @@ -1,59 +1,60 @@ +# frozen_string_literal: true + # # is_domain_name.rb # module Puppet::Parser::Functions - newfunction(:is_domain_name, :type => :rvalue, :doc => <<-DOC + newfunction(:is_domain_name, type: :rvalue, doc: <<-DOC @summary **Deprecated:** Returns true if the string passed to this function is a syntactically correct domain name. @return [Boolean] Returns `true` or `false` > **Note:* **Deprecated** Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy). DOC - ) do |arguments| - + ) do |arguments| if arguments.size != 1 raise(Puppet::ParseError, "is_domain_name(): Wrong number of arguments given #{arguments.size} for 1") end # Only allow string types return false unless arguments[0].is_a?(String) domain = arguments[0].dup # Limits (rfc1035, 3.1) domain_max_length = 255 label_min_length = 1 label_max_length = 63 # Allow ".", it is the top level domain return true if domain == '.' # Remove the final dot, if present. domain.chomp!('.') # Check the whole domain return false if domain.empty? return false if domain.length > domain_max_length # The top level domain must be alphabetic if there are multiple labels. # See rfc1123, 2.1 return false if domain.include?('.') && !%r{\.[A-Za-z]+$}.match(domain) # Check each label in the domain labels = domain.split('.') vlabels = labels.each do |label| break if label.length < label_min_length break if label.length > label_max_length break if label[-1..-1] == '-' break if label[0..0] == '-' - break unless %r{^[a-z\d-]+$}i =~ label + break unless %r{^[a-z\d-]+$}i.match?(label) end return vlabels == labels end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/is_email_address.rb b/lib/puppet/parser/functions/is_email_address.rb index 1c41b86..5a9594c 100644 --- a/lib/puppet/parser/functions/is_email_address.rb +++ b/lib/puppet/parser/functions/is_email_address.rb @@ -1,26 +1,28 @@ +# frozen_string_literal: true + # # is_email_address.rb # module Puppet::Parser::Functions - newfunction(:is_email_address, :type => :rvalue, :doc => <<-DOC + newfunction(:is_email_address, type: :rvalue, doc: <<-DOC @summary **Deprecated:** Returns true if the string passed to this function is a valid email address. @return [Boolean] Returns `true` or `false` > **Note:* **Deprecated** Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy). DOC - ) do |arguments| + ) do |arguments| if arguments.size != 1 raise(Puppet::ParseError, "is_email_address(): Wrong number of arguments given #{arguments.size} for 1") end # 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 # rubocop:disable Style/NumericPredicate : Changing to '.zero?' breaks the code + return (arguments[0] =~ valid_email_regex) == 0 end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/is_float.rb b/lib/puppet/parser/functions/is_float.rb index 583793d..c44746b 100644 --- a/lib/puppet/parser/functions/is_float.rb +++ b/lib/puppet/parser/functions/is_float.rb @@ -1,34 +1,35 @@ +# frozen_string_literal: true + # # is_float.rb # module Puppet::Parser::Functions - newfunction(:is_float, :type => :rvalue, :doc => <<-DOC + newfunction(:is_float, type: :rvalue, doc: <<-DOC @summary **Deprecated:** Returns true if the variable passed to this function is a float. @return [Boolean] Returns `true` or `false` > **Note:* **Deprecated** Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy). DOC - ) 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.']) 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) || value.is_a?(String) return false if value != value.to_f.to_s && !value.is_a?(Float) return true end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/is_function_available.rb b/lib/puppet/parser/functions/is_function_available.rb index e931225..d6f666f 100644 --- a/lib/puppet/parser/functions/is_function_available.rb +++ b/lib/puppet/parser/functions/is_function_available.rb @@ -1,31 +1,32 @@ +# frozen_string_literal: true + # # is_function_available.rb # module Puppet::Parser::Functions - newfunction(:is_function_available, :type => :rvalue, :doc => <<-DOC + newfunction(:is_function_available, type: :rvalue, doc: <<-DOC @summary **Deprecated:** Determines whether the Puppet runtime has access to a function by that name. This function accepts a string as an argument. @return [Boolean] Returns `true` or `false` > **Note:* **Deprecated** Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy). DOC - ) do |arguments| - + ) do |arguments| if arguments.size != 1 raise(Puppet::ParseError, "is_function_available?(): Wrong number of arguments given #{arguments.size} for 1") end # Only allow String types return false unless arguments[0].is_a?(String) function = Puppet::Parser::Functions.function(arguments[0].to_sym) function.is_a?(String) && !function.empty? end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/is_hash.rb b/lib/puppet/parser/functions/is_hash.rb index f85b9ee..812ff88 100644 --- a/lib/puppet/parser/functions/is_hash.rb +++ b/lib/puppet/parser/functions/is_hash.rb @@ -1,27 +1,28 @@ +# frozen_string_literal: true + # # is_hash.rb # module Puppet::Parser::Functions - newfunction(:is_hash, :type => :rvalue, :doc => <<-DOC + newfunction(:is_hash, type: :rvalue, doc: <<-DOC @summary **Deprecated:** Returns true if the variable passed to this function is a hash. @return [Boolean] Returns `true` or `false` > **Note:* **Deprecated** Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy). DOC - ) do |arguments| - + ) do |arguments| raise(Puppet::ParseError, "is_hash(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size != 1 type = arguments[0] result = type.is_a?(Hash) return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/is_integer.rb b/lib/puppet/parser/functions/is_integer.rb index a86b5cd..cdb5771 100644 --- a/lib/puppet/parser/functions/is_integer.rb +++ b/lib/puppet/parser/functions/is_integer.rb @@ -1,51 +1,52 @@ +# frozen_string_literal: true + # # is_integer.rb # module Puppet::Parser::Functions - newfunction(:is_integer, :type => :rvalue, :doc => <<-DOC + newfunction(:is_integer, type: :rvalue, doc: <<-DOC @summary **Deprecated:** 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. @return [Boolean] Returns `true` or `false` > **Note:* **Deprecated** Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy). DOC - ) 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.']) if arguments.size != 1 raise(Puppet::ParseError, "is_integer(): Wrong number of arguments given #{arguments.size} for 1") end value = arguments[0] # Regex is taken from the lexer of puppet # puppet/pops/parser/lexer.rb but modified to match also # negative values and disallow numbers prefixed with multiple # 0's # # TODO these parameter should be a constant but I'm not sure # if there is no risk to declare it inside of the module # Puppet::Parser::Functions # Integer numbers like # -1234568981273 # 47291 numeric = %r{^-?(?:(?:[1-9]\d*)|0)$} return true if value.is_a?(Integer) || (value.is_a?(String) && value.match(numeric)) return false end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/is_ip_address.rb b/lib/puppet/parser/functions/is_ip_address.rb index 61f84a1..506244f 100644 --- a/lib/puppet/parser/functions/is_ip_address.rb +++ b/lib/puppet/parser/functions/is_ip_address.rb @@ -1,37 +1,38 @@ +# frozen_string_literal: true + # # is_ip_address.rb # module Puppet::Parser::Functions - newfunction(:is_ip_address, :type => :rvalue, :doc => <<-DOC + newfunction(:is_ip_address, type: :rvalue, doc: <<-DOC @summary **Deprecated:** Returns true if the string passed to this function is a valid IP address. @return [Boolean] Returns `true` or `false` > **Note:* **Deprecated** Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy). DOC - ) 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.']) if arguments.size != 1 raise(Puppet::ParseError, "is_ip_address(): Wrong number of arguments given #{arguments.size} for 1") end begin ip = IPAddr.new(arguments[0]) rescue ArgumentError return false end return true if ip.ipv4? || ip.ipv6? return false end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/is_ipv4_address.rb b/lib/puppet/parser/functions/is_ipv4_address.rb index 5064f48..4610805 100644 --- a/lib/puppet/parser/functions/is_ipv4_address.rb +++ b/lib/puppet/parser/functions/is_ipv4_address.rb @@ -1,36 +1,37 @@ +# frozen_string_literal: true + # # is_ipv4_address.rb # module Puppet::Parser::Functions - newfunction(:is_ipv4_address, :type => :rvalue, :doc => <<-DOC + newfunction(:is_ipv4_address, type: :rvalue, doc: <<-DOC @summary **Deprecated:** Returns true if the string passed to this function is a valid IPv4 address. @return [Boolean] Returns `true` or `false` > **Note:* **Deprecated** Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy). DOC - ) 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.']) if arguments.size != 1 raise(Puppet::ParseError, "is_ipv4_address(): Wrong number of arguments given #{arguments.size} for 1") end begin ip = IPAddr.new(arguments[0]) rescue ArgumentError return false end return ip.ipv4? end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/is_ipv6_address.rb b/lib/puppet/parser/functions/is_ipv6_address.rb index a4de14f..abb79df 100644 --- a/lib/puppet/parser/functions/is_ipv6_address.rb +++ b/lib/puppet/parser/functions/is_ipv6_address.rb @@ -1,36 +1,37 @@ +# frozen_string_literal: true + # # is_ipv6_address.rb # module Puppet::Parser::Functions - newfunction(:is_ipv6_address, :type => :rvalue, :doc => <<-DOC + newfunction(:is_ipv6_address, type: :rvalue, doc: <<-DOC @summary **Deprecated:** Returns true if the string passed to this function is a valid IPv6 address. @return [Boolean] Returns `true` or `false` > **Note:* **Deprecated** Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy). DOC - ) 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.']) require 'ipaddr' if arguments.size != 1 raise(Puppet::ParseError, "is_ipv6_address(): Wrong number of arguments given #{arguments.size} for 1") end begin ip = IPAddr.new(arguments[0]) rescue ArgumentError return false end return ip.ipv6? end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/is_mac_address.rb b/lib/puppet/parser/functions/is_mac_address.rb index ef1fc20..67a269c 100644 --- a/lib/puppet/parser/functions/is_mac_address.rb +++ b/lib/puppet/parser/functions/is_mac_address.rb @@ -1,29 +1,30 @@ +# frozen_string_literal: true + # # is_mac_address.rb # module Puppet::Parser::Functions - newfunction(:is_mac_address, :type => :rvalue, :doc => <<-DOC + newfunction(:is_mac_address, type: :rvalue, doc: <<-DOC @summary **Deprecated:** Returns true if the string passed to this function is a valid mac address. @return [Boolean] Returns `true` or `false` > **Note:* **Deprecated** Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy). DOC - ) do |arguments| - + ) do |arguments| if arguments.size != 1 raise(Puppet::ParseError, "is_mac_address(): Wrong number of arguments given #{arguments.size} for 1") end mac = arguments[0] - return true if %r{^[a-f0-9]{1,2}(:[a-f0-9]{1,2}){5}$}i =~ mac - return true if %r{^[a-f0-9]{1,2}(:[a-f0-9]{1,2}){19}$}i =~ mac + return true if %r{^[a-f0-9]{1,2}(:[a-f0-9]{1,2}){5}$}i.match?(mac) + return true if %r{^[a-f0-9]{1,2}(:[a-f0-9]{1,2}){19}$}i.match?(mac) return false end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/is_numeric.rb b/lib/puppet/parser/functions/is_numeric.rb index 8b42119..a949557 100644 --- a/lib/puppet/parser/functions/is_numeric.rb +++ b/lib/puppet/parser/functions/is_numeric.rb @@ -1,75 +1,76 @@ +# frozen_string_literal: true + # # is_numeric.rb # module Puppet::Parser::Functions - newfunction(:is_numeric, :type => :rvalue, :doc => <<-DOC + newfunction(:is_numeric, type: :rvalue, doc: <<-DOC @summary **Deprecated:** Returns true if the given value is numeric. 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 string representation may start with a '-' (minus). If a decimal '.' is used, it must be followed by at least one digit. @return [Boolean] Returns `true` or `false` > **Note:* **Deprecated** Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy). DOC - ) 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.']) if arguments.size != 1 raise(Puppet::ParseError, "is_numeric(): Wrong number of arguments given #{arguments.size} for 1") end value = arguments[0] # Regex is taken from the lexer of puppet # puppet/pops/parser/lexer.rb but modified to match also # negative values and disallow invalid octal numbers or # numbers prefixed with multiple 0's (except in hex numbers) # # TODO these parameters should be constants but I'm not sure # if there is no risk to declare them inside of the module # Puppet::Parser::Functions # TODO: decide if this should be used # HEX numbers like # 0xaa230F # 0X1234009C # 0x0012 # -12FcD # numeric_hex = %r{^-?0[xX][0-9A-Fa-f]+$} # TODO: decide if this should be used # OCTAL numbers like # 01234567 # -045372 # numeric_oct = %r{^-?0[1-7][0-7]*$} # Integer/Float numbers like # -0.1234568981273 # 47291 # 42.12345e-12 numeric = %r{^-?(?:(?:[1-9]\d*)|0)(?:\.\d+)?(?:[eE]-?\d+)?$} 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 end end end diff --git a/lib/puppet/parser/functions/is_string.rb b/lib/puppet/parser/functions/is_string.rb index 7410d32..5b4627a 100644 --- a/lib/puppet/parser/functions/is_string.rb +++ b/lib/puppet/parser/functions/is_string.rb @@ -1,35 +1,36 @@ +# frozen_string_literal: true + # # is_string.rb # module Puppet::Parser::Functions - newfunction(:is_string, :type => :rvalue, :doc => <<-DOC + newfunction(:is_string, type: :rvalue, doc: <<-DOC @summary **Deprecated:** Returns true if the variable passed to this function is a string. @return [Boolean] Returns `true` or `false` > **Note:* **Deprecated** Will be removed in a future version of stdlib. See [`validate_legacy`](#validate_legacy). DOC - ) 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.']) 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 && (type == type.to_f.to_s || type == type.to_i.to_s) return false end return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/join.rb b/lib/puppet/parser/functions/join.rb index 266ad65..f1e4bc1 100644 --- a/lib/puppet/parser/functions/join.rb +++ b/lib/puppet/parser/functions/join.rb @@ -1,43 +1,44 @@ +# frozen_string_literal: true + # # join.rb # module Puppet::Parser::Functions - newfunction(:join, :type => :rvalue, :doc => <<-DOC + newfunction(:join, type: :rvalue, doc: <<-DOC @summary **Deprecated:** This function joins an array into a string using a separator. @example Example Usage: join(['a','b','c'], ",") # Results in: "a,b,c" @return [String] The String containing each of the array values > **Note:** **Deprecated** from Puppet 5.4.0 this function has been replaced with a built-in [`join`](https://puppet.com/docs/puppet/latest/function.html#join) function. DOC - ) 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.empty? array = arguments[0] unless array.is_a?(Array) raise(Puppet::ParseError, 'join(): Requires array to work with') end suffix = arguments[1] if arguments[1] if suffix unless suffix.is_a?(String) raise(Puppet::ParseError, 'join(): Requires string to work with') end end result = suffix ? array.join(suffix) : array.join return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/join_keys_to_values.rb b/lib/puppet/parser/functions/join_keys_to_values.rb index 73d4a1f..3e709cb 100644 --- a/lib/puppet/parser/functions/join_keys_to_values.rb +++ b/lib/puppet/parser/functions/join_keys_to_values.rb @@ -1,58 +1,59 @@ +# frozen_string_literal: true + # # join_keys_to_values.rb # module Puppet::Parser::Functions - newfunction(:join_keys_to_values, :type => :rvalue, :doc => <<-DOC + newfunction(:join_keys_to_values, type: :rvalue, doc: <<-DOC @summary 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. @example Example Usage: join_keys_to_values({'a'=>1,'b'=>2}, " is ") # Results in: ["a is 1","b is 2"] join_keys_to_values({'a'=>1,'b'=>[2,3]}, " is ") # Results in: ["a is 1","b is 2","b is 3"] @return [Hash] The joined hash > **Note:** Since Puppet 5.0.0 - for more detailed control over the formatting (including indentations and line breaks, delimiters around arrays and hash entries, between key/values in hash entries, and individual formatting of values in the array) - see the `new` function for `String` and its formatting options for `Array` and `Hash`. DOC - ) do |arguments| - + ) do |arguments| # Validate the number of arguments. if arguments.size != 2 raise(Puppet::ParseError, "join_keys_to_values(): Takes exactly two arguments, but #{arguments.size} given.") end # Validate the first argument. hash = arguments[0] 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] 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 { |k, v| if v.is_a?(Array) v.map { |va| String(k) + separator + String(va) } elsif String(v) == 'undef' String(k) else String(k) + separator + String(v) end }.flatten end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/keys.rb b/lib/puppet/parser/functions/keys.rb index 80d080c..10a8547 100644 --- a/lib/puppet/parser/functions/keys.rb +++ b/lib/puppet/parser/functions/keys.rb @@ -1,31 +1,32 @@ +# frozen_string_literal: true + # # keys.rb # module Puppet::Parser::Functions - newfunction(:keys, :type => :rvalue, :doc => <<-DOC + newfunction(:keys, type: :rvalue, doc: <<-DOC @summary **Deprecated:** Returns the keys of a hash as an array. @return [Array] An array containing each of the hashes key values. > **Note:** **Deprecated** from Puppet 5.5.0, the built-in [`keys`](https://puppet.com/docs/puppet/latest/function.html#keys) function will be used instead of this function. DOC - ) do |arguments| - + ) do |arguments| raise(Puppet::ParseError, "keys(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? hash = arguments[0] unless hash.is_a?(Hash) raise(Puppet::ParseError, 'keys(): Requires hash to work with') end result = hash.keys return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/load_module_metadata.rb b/lib/puppet/parser/functions/load_module_metadata.rb index 79d98cd..b1fd196 100644 --- a/lib/puppet/parser/functions/load_module_metadata.rb +++ b/lib/puppet/parser/functions/load_module_metadata.rb @@ -1,33 +1,35 @@ +# frozen_string_literal: true + # # load_module_metadata.rb # module Puppet::Parser::Functions - newfunction(:load_module_metadata, :type => :rvalue, :doc => <<-DOC + newfunction(:load_module_metadata, type: :rvalue, doc: <<-DOC @summary This function loads the metadata of a given module. @example Example USage: $metadata = load_module_metadata('archive') notify { $metadata['author']: } @return The modules metadata DOC - ) do |args| + ) 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) # rubocop:disable Lint/DeprecatedClassMethods : Changing to .exist? breaks the code if metadata_exists metadata = PSON.load(File.read(metadata_json)) else metadata = {} raise(Puppet::ParseError, "load_module_metadata(): No metadata.json file for module #{mod}") unless allow_empty_metadata end return metadata end end diff --git a/lib/puppet/parser/functions/loadjson.rb b/lib/puppet/parser/functions/loadjson.rb index 3c60878..ef1fd87 100644 --- a/lib/puppet/parser/functions/loadjson.rb +++ b/lib/puppet/parser/functions/loadjson.rb @@ -1,62 +1,64 @@ +# frozen_string_literal: true + # # loadjson.rb # module Puppet::Parser::Functions - newfunction(:loadjson, :type => :rvalue, :arity => -2, :doc => <<-'DOC') do |args| + newfunction(:loadjson, type: :rvalue, arity: -2, doc: <<-'DOC') do |args| @summary Load a JSON file containing an array, string, or hash, and return the data in the corresponding native data type. The first parameter can be a file path or a URL. The second parameter is the default value. It will be returned if the file was not found or could not be parsed. @return [Array|String|Hash] The data stored in the JSON file, the type depending on the type of data that was stored. @example Example Usage: $myhash = loadjson('/etc/puppet/data/myhash.json') $myhash = loadjson('https://example.local/my_hash.json') $myhash = loadjson('https://username:password@example.local/my_hash.json') $myhash = loadjson('no-file.json', {'default' => 'value'}) DOC raise ArgumentError, 'Wrong number of arguments. 1 or 2 arguments should be provided.' unless args.length >= 1 require 'open-uri' begin if args[0].start_with?('http://', 'https://') username = '' password = '' if (match = args[0].match(%r{(http\://|https\://)(.*):(.*)@(.*)})) # If URL is in the format of https://username:password@example.local/my_hash.yaml protocol, username, password, path = match.captures url = "#{protocol}#{path}" elsif (match = args[0].match(%r{(http\:\/\/|https\:\/\/)(.*)@(.*)})) # If URL is in the format of https://username@example.local/my_hash.yaml protocol, username, path = match.captures url = "#{protocol}#{path}" else url = args[0] end begin - contents = OpenURI.open_uri(url, :http_basic_authentication => [username, password]) + contents = OpenURI.open_uri(url, http_basic_authentication: [username, password]) rescue OpenURI::HTTPError => err res = err.io warning("Can't load '#{url}' HTTP Error Code: '#{res.status[0]}'") args[1] end PSON.load(contents) || args[1] elsif File.exists?(args[0]) # rubocop:disable Lint/DeprecatedClassMethods : Changing to .exist? breaks the code content = File.read(args[0]) PSON.load(content) || args[1] else warning("Can't load '#{args[0]}' File does not exist!") args[1] end rescue StandardError => e raise e unless args[1] args[1] end end end diff --git a/lib/puppet/parser/functions/loadyaml.rb b/lib/puppet/parser/functions/loadyaml.rb index f84f530..70f8e5f 100644 --- a/lib/puppet/parser/functions/loadyaml.rb +++ b/lib/puppet/parser/functions/loadyaml.rb @@ -1,61 +1,63 @@ +# frozen_string_literal: true + # # loadyaml.rb # module Puppet::Parser::Functions - newfunction(:loadyaml, :type => :rvalue, :arity => -2, :doc => <<-'DOC') do |args| + newfunction(:loadyaml, type: :rvalue, arity: -2, doc: <<-'DOC') do |args| @summary Load a YAML file containing an array, string, or hash, and return the data in the corresponding native data type. The first parameter can be a file path or a URL. The second parameter is the default value. It will be returned if the file was not found or could not be parsed. @return [Array|String|Hash] The data stored in the YAML file, the type depending on the type of data that was stored. @example Example Usage: $myhash = loadyaml('/etc/puppet/data/myhash.yaml') $myhash = loadyaml('https://example.local/my_hash.yaml') $myhash = loadyaml('https://username:password@example.local/my_hash.yaml') $myhash = loadyaml('no-file.yaml', {'default' => 'value'}) DOC raise ArgumentError, 'Wrong number of arguments. 1 or 2 arguments should be provided.' unless args.length >= 1 require 'yaml' require 'open-uri' begin if args[0].start_with?('http://', 'https://') username = '' password = '' if (match = args[0].match(%r{(http\://|https\://)(.*):(.*)@(.*)})) # If URL is in the format of https://username:password@example.local/my_hash.yaml protocol, username, password, path = match.captures url = "#{protocol}#{path}" elsif (match = args[0].match(%r{(http\:\/\/|https\:\/\/)(.*)@(.*)})) # If URL is in the format of https://username@example.local/my_hash.yaml protocol, username, path = match.captures url = "#{protocol}#{path}" else url = args[0] end begin - contents = OpenURI.open_uri(url, :http_basic_authentication => [username, password]) + contents = OpenURI.open_uri(url, http_basic_authentication: [username, password]) rescue OpenURI::HTTPError => err res = err.io warning("Can't load '#{url}' HTTP Error Code: '#{res.status[0]}'") args[1] end YAML.safe_load(contents) || args[1] elsif File.exists?(args[0]) # rubocop:disable Lint/DeprecatedClassMethods : Changing to .exist? breaks the code YAML.load_file(args[0]) || args[1] else warning("Can't load '#{args[0]}' File does not exist!") args[1] end rescue StandardError => e raise e unless args[1] args[1] end end end diff --git a/lib/puppet/parser/functions/lstrip.rb b/lib/puppet/parser/functions/lstrip.rb index 2fd31a2..16e0006 100644 --- a/lib/puppet/parser/functions/lstrip.rb +++ b/lib/puppet/parser/functions/lstrip.rb @@ -1,36 +1,37 @@ +# frozen_string_literal: true + # # lstrip.rb # module Puppet::Parser::Functions - newfunction(:lstrip, :type => :rvalue, :doc => <<-DOC + newfunction(:lstrip, type: :rvalue, doc: <<-DOC @summary **Deprecated:** Strips leading spaces to the left of a string. @return [String] The stripped string > **Note:** **Deprecated** from Puppet 6.0.0, this function has been replaced with a built-in [`max`](https://puppet.com/docs/puppet/latest/function.html#max) function. DOC - ) do |arguments| - + ) do |arguments| raise(Puppet::ParseError, "lstrip(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? value = arguments[0] unless value.is_a?(Array) || value.is_a?(String) raise(Puppet::ParseError, 'lstrip(): Requires either array or string to work with') 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 end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/max.rb b/lib/puppet/parser/functions/max.rb index 00a183a..173dc0e 100644 --- a/lib/puppet/parser/functions/max.rb +++ b/lib/puppet/parser/functions/max.rb @@ -1,31 +1,32 @@ +# frozen_string_literal: true + # # max.rb # module Puppet::Parser::Functions - newfunction(:max, :type => :rvalue, :doc => <<-DOC + newfunction(:max, type: :rvalue, doc: <<-DOC @summary **Deprecated:** Returns the highest value of all arguments. Requires at least one argument. @return The highest value among those passed in > **Note:** **Deprecated** from Puppet 6.0.0, this function has been replaced with a built-in [`lstrip`](https://puppet.com/docs/puppet/latest/function.html#lstrip) function. DOC - ) do |args| - + ) do |args| 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 =~ %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 end end end end diff --git a/lib/puppet/parser/functions/member.rb b/lib/puppet/parser/functions/member.rb index 7efcb1f..2795488 100644 --- a/lib/puppet/parser/functions/member.rb +++ b/lib/puppet/parser/functions/member.rb @@ -1,65 +1,66 @@ +# frozen_string_literal: true + # TODO(Krzysztof Wilczynski): We need to add support for regular expression ... # TODO(Krzysztof Wilczynski): Support for strings and hashes too ... # # member.rb # module Puppet::Parser::Functions - newfunction(:member, :type => :rvalue, :doc => <<-DOC + newfunction(:member, type: :rvalue, doc: <<-DOC @summary This function determines if a variable is a member of an array. The variable can be a string, fixnum, or array. > **Note**: This function does not support nested arrays. If the first argument contains nested arrays, it will not recurse through them. @example **Usage** member(['a','b'], 'b') # Returns: true member(['a', 'b', 'c'], ['a', 'b']) # Returns: true member(['a','b'], 'c') # Returns: false member(['a', 'b', 'c'], ['d', 'b']) # Returns: false > *Note:* Since Puppet 4.0.0 the same can be performed in the Puppet language. For single values the operator `in` can be used: `'a' in ['a', 'b'] # true` For arrays by using operator `-` to compute a diff: `['d', 'b'] - ['a', 'b', 'c'] == [] # false because 'd' is not subtracted` `['a', 'b'] - ['a', 'b', 'c'] == [] # true because both 'a' and 'b' are subtracted` @return Returns whether the given value was a member of the array > **Note** that since Puppet 5.2.0, the general form to test the content of an array or hash is to use the built-in [`any`](https://puppet.com/docs/puppet/latest/function.html#any) and [`all`](https://puppet.com/docs/puppet/latest/function.html#all) functions. DOC - ) do |arguments| - + ) do |arguments| raise(Puppet::ParseError, "member(): Wrong number of arguments given (#{arguments.size} for 2)") if arguments.size < 2 array = arguments[0] unless array.is_a?(Array) raise(Puppet::ParseError, 'member(): Requires array to work with') end 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 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? result = (item - array).empty? return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/merge.rb b/lib/puppet/parser/functions/merge.rb index 9a0e8c1..522e484 100644 --- a/lib/puppet/parser/functions/merge.rb +++ b/lib/puppet/parser/functions/merge.rb @@ -1,40 +1,42 @@ +# frozen_string_literal: true + # # merge.rb # module Puppet::Parser::Functions - newfunction(:merge, :type => :rvalue, :doc => <<-'DOC') do |args| + newfunction(:merge, type: :rvalue, doc: <<-'DOC') do |args| @summary Merges two or more hashes together and returns the resulting hash. @example **Usage** $hash1 = {'one' => 1, 'two', => 2} $hash2 = {'two' => 'dos', 'three', => 'tres'} $merged_hash = merge($hash1, $hash2) # $merged_hash = {'one' => 1, 'two' => 'dos', 'three' => 'tres'} When there is a duplicate key, the key in the rightmost hash will "win." @return [Hash] The merged hash Note that since Puppet 4.0.0 the same merge can be achieved with the + operator. `$merged_hash = $hash1 + $hash2` DOC if args.length < 2 raise Puppet::ParseError, "merge(): wrong number of arguments (#{args.length}; must be at least 2)" end # The hash we accumulate into accumulator = {} # Merge into the accumulator hash args.each do |arg| 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 accumulator.merge!(arg) end # Return the fully merged hash accumulator end end diff --git a/lib/puppet/parser/functions/min.rb b/lib/puppet/parser/functions/min.rb index c211a9e..1734222 100644 --- a/lib/puppet/parser/functions/min.rb +++ b/lib/puppet/parser/functions/min.rb @@ -1,31 +1,32 @@ +# frozen_string_literal: true + # # min.rb # module Puppet::Parser::Functions - newfunction(:min, :type => :rvalue, :doc => <<-DOC + newfunction(:min, type: :rvalue, doc: <<-DOC @summary **Deprecated:** Returns the lowest value of all arguments. Requires at least one argument. @return The lowest value among the given arguments > **Note:** **Deprecated** from Puppet 6.0.0, this function has been replaced with a built-in [`min`](https://puppet.com/docs/puppet/latest/function.html#min) function. DOC - ) do |args| - + ) do |args| 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 =~ %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 end end end end diff --git a/lib/puppet/parser/functions/num2bool.rb b/lib/puppet/parser/functions/num2bool.rb index 6e530db..c74ba01 100644 --- a/lib/puppet/parser/functions/num2bool.rb +++ b/lib/puppet/parser/functions/num2bool.rb @@ -1,48 +1,49 @@ +# frozen_string_literal: true + # # num2bool.rb # module Puppet::Parser::Functions - newfunction(:num2bool, :type => :rvalue, :doc => <<-DOC + newfunction(:num2bool, type: :rvalue, doc: <<-DOC @summary This function converts a number or a string representation of a number into a true boolean. > *Note:* that since Puppet 5.0.0 the same can be achieved with the Puppet Type System. See the new() function in Puppet for the many available type conversions. @return [Boolean] Boolean(0) # false for any zero or negative number Boolean(1) # true for any positive number DOC - ) 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 # rubocop:disable Lint/EmptyWhen : Required for the module to work + when Numeric # Yay, it's a number when String begin number = Float(number) rescue ArgumentError => ex raise(Puppet::ParseError, "num2bool(): '#{number}' does not look like a number: #{ex.message}") end else begin number = number.to_s rescue NoMethodError => ex raise(Puppet::ParseError, "num2bool(): Unable to parse argument: #{ex.message}") end end # Truncate Floats number = number.to_i # Return true for any positive number and false otherwise return number > 0 end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/parsejson.rb b/lib/puppet/parser/functions/parsejson.rb index 76b392f..bb1992e 100644 --- a/lib/puppet/parser/functions/parsejson.rb +++ b/lib/puppet/parser/functions/parsejson.rb @@ -1,29 +1,31 @@ +# frozen_string_literal: true + # # parsejson.rb # module Puppet::Parser::Functions - newfunction(:parsejson, :type => :rvalue, :doc => <<-DOC + newfunction(:parsejson, type: :rvalue, doc: <<-DOC @summary This function accepts JSON as a string and converts it into the correct Puppet structure. @return convert JSON into Puppet structure > *Note:* The optional second argument can be used to pass a default value that will be returned if the parsing of YAML string have failed. DOC - ) 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] rescue StandardError => e raise e unless arguments[1] arguments[1] end end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/parseyaml.rb b/lib/puppet/parser/functions/parseyaml.rb index 5d081e6..f80c293 100644 --- a/lib/puppet/parser/functions/parseyaml.rb +++ b/lib/puppet/parser/functions/parseyaml.rb @@ -1,33 +1,35 @@ +# frozen_string_literal: true + # # parseyaml.rb # module Puppet::Parser::Functions - newfunction(:parseyaml, :type => :rvalue, :doc => <<-DOC + newfunction(:parseyaml, type: :rvalue, doc: <<-DOC @summary This function accepts YAML as a string and converts it into the correct Puppet structure. @return converted YAML into Puppet structure > *Note:* The optional second argument can be used to pass a default value that will be returned if the parsing of YAML string have failed. DOC - ) 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] # 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 # rubocop:disable Lint/ShadowedException : See above raise e unless arguments[1] arguments[1] end end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/pick.rb b/lib/puppet/parser/functions/pick.rb index e31dc95..34450c5 100644 --- a/lib/puppet/parser/functions/pick.rb +++ b/lib/puppet/parser/functions/pick.rb @@ -1,32 +1,34 @@ +# frozen_string_literal: true + # # pick.rb # module Puppet::Parser::Functions - newfunction(:pick, :type => :rvalue, :doc => <<-EOS + newfunction(:pick, type: :rvalue, doc: <<-EOS @summary 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. @return the first value in a list of values that is not undefined or an empty string. 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')``` > *Note:* 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| + ) 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 d94bb52..0915df1 100644 --- a/lib/puppet/parser/functions/pick_default.rb +++ b/lib/puppet/parser/functions/pick_default.rb @@ -1,40 +1,42 @@ +# frozen_string_literal: true + # # pick_default.rb # module Puppet::Parser::Functions - newfunction(:pick_default, :type => :rvalue, :doc => <<-DOC + newfunction(:pick_default, type: :rvalue, doc: <<-DOC @summary This function will return the first value in a list of values that is not undefined or an empty string. @return 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 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: $real_jenkins_version = pick_default($::jenkins_version, '1.449') > *Note:* 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. 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. DOC - ) do |args| + ) 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 b5e9641..04ed267 100644 --- a/lib/puppet/parser/functions/prefix.rb +++ b/lib/puppet/parser/functions/prefix.rb @@ -1,56 +1,57 @@ +# frozen_string_literal: true + # # prefix.rb # module Puppet::Parser::Functions - newfunction(:prefix, :type => :rvalue, :doc => <<-DOC + newfunction(:prefix, type: :rvalue, doc: <<-DOC @summary This function applies a prefix to all elements in an array or a hash. @example **Usage** prefix(['a','b','c'], 'p') Will return: ['pa','pb','pc'] > *Note:* since Puppet 4.0.0 the general way to modify values is in array is by using the map function in Puppet. This example does the same as the example above: ['a', 'b', 'c'].map |$x| { "p${x}" } @return [Hash] or [Array] The passed values now contains the passed prefix DOC - ) 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.empty? enumerable = arguments[0] 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 prefix = arguments[1] if arguments[1] if prefix unless prefix.is_a?(String) raise Puppet::ParseError, "prefix(): expected second argument to be a String, got #{prefix.inspect}" 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 end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/private.rb b/lib/puppet/parser/functions/private.rb index 11a9451..037d2b2 100644 --- a/lib/puppet/parser/functions/private.rb +++ b/lib/puppet/parser/functions/private.rb @@ -1,20 +1,22 @@ +# frozen_string_literal: true + # # private.rb # module Puppet::Parser::Functions - newfunction(:private, :doc => <<-'DOC' + newfunction(:private, doc: <<-'DOC' @summary **Deprecated:** Sets the current class or definition as private. Calling the class or definition from outside the current module will fail. @return Sets the current class or definition as private DOC - ) 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 Metrics/LineLength : Cannot shorten this line + ) 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 Layout/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.empty?)]) end end diff --git a/lib/puppet/parser/functions/pry.rb b/lib/puppet/parser/functions/pry.rb index 4191951..8fb7d20 100644 --- a/lib/puppet/parser/functions/pry.rb +++ b/lib/puppet/parser/functions/pry.rb @@ -1,35 +1,37 @@ +# frozen_string_literal: true + # # pry.rb # module Puppet::Parser::Functions - newfunction(:pry, :type => :statement, :doc => <<-DOC + newfunction(:pry, type: :statement, doc: <<-DOC @summary 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. @return debugging information @example **Usage** `pry()` DOC - ) do |arguments| + ) do |arguments| begin require 'pry' rescue LoadError raise(Puppet::Error, "pry(): Requires the 'pry' rubygem to use, but it was not found") end # ## Run `catalog` to see the contents currently compiling catalog ## Run `cd catalog` and `ls` to see catalog methods and instance variables ## Run `@resource_table` to see the current catalog resource table # if $stdout.isatty binding.pry # rubocop:disable Lint/Debugger else Puppet.warning 'pry(): cowardly refusing to start the debugger on a daemonized server' end end end diff --git a/lib/puppet/parser/functions/pw_hash.rb b/lib/puppet/parser/functions/pw_hash.rb index 9b8e0d8..3351c9f 100644 --- a/lib/puppet/parser/functions/pw_hash.rb +++ b/lib/puppet/parser/functions/pw_hash.rb @@ -1,70 +1,73 @@ +# frozen_string_literal: true + # 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( :pw_hash, - :type => :rvalue, - :arity => 3, - :doc => <<-DOC + type: :rvalue, + arity: 3, + doc: <<-DOC, @summary 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 undef or an empty string, this function returns undef. The second argument to this function is which type of hash to use. It will be converted into the appropriate crypt(3) hash specifier. Valid hash types are: |Hash type |Specifier| |---------------------|---------| |MD5 |1 | |SHA-256 |5 | |SHA-512 (recommended)|6 | The third argument to this function is the salt to use. @return [Hash] Provides a hash usable on most POSIX systems. > *Note:*: this uses the Puppet Server's implementation of crypt(3). If your environment contains several different operating systems, ensure that they are compatible before using this function. DOC ) 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) || 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} + raise ArgumentError, 'pw_hash(): characters in salt must be in the set [a-zA-Z0-9./]' unless %r{\A[a-zA-Z0-9./]+\z}.match?(args[2]) 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.' + # dup the string to get rid of frozen status for testing + if ('test'.dup).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 1df7327..5410943 100644 --- a/lib/puppet/parser/functions/range.rb +++ b/lib/puppet/parser/functions/range.rb @@ -1,95 +1,96 @@ +# frozen_string_literal: true + # # range.rb # # TODO(Krzysztof Wilczynski): We probably need to approach numeric values differently ... module Puppet::Parser::Functions - newfunction(:range, :type => :rvalue, :doc => <<-DOC + newfunction(:range, type: :rvalue, doc: <<-DOC @summary When given range in the form of (start, stop) it will extrapolate a range as an array. @return the range is extrapolated as an array @example **Usage** range("0", "9") Will return: [0,1,2,3,4,5,6,7,8,9] range("00", "09") Will return: [0,1,2,3,4,5,6,7,8,9] (Zero padded strings are converted to integers automatically) range("a", "c") Will return: ["a","b","c"] range("host01", "host10") Will return: ["host01", "host02", ..., "host09", "host10"] range("0", "9", "2") Will return: [0,2,4,6,8] NB Be explicit in including trailing zeros. Otherwise the underlying ruby function will fail. > *Note:* Passing a third argument will cause the generated range to step by that interval, e.g. The Puppet Language support Integer and Float ranges by using the type system. Those are suitable for iterating a given number of times. @see the step() function in Puppet for skipping values. Integer[0, 9].each |$x| { notice($x) } # notices 0, 1, 2, ... 9 DOC - ) do |arguments| - + ) do |arguments| raise(Puppet::ParseError, 'range(): Wrong number of arguments given (0 for 1)') if arguments.empty? if arguments.size > 1 start = arguments[0] stop = arguments[1] step = arguments[2].nil? ? 1 : arguments[2].to_i.abs raise(ArgumentError, 'range(): 3rd arg (step size) must be a non zero integer (e.g. 1 or -1)') if step.zero? type = '..' # Use the simplest type of Range available in Ruby else # arguments.size == 1 value = arguments[0] m = value.match(%r{^(\w+)(\.\.\.?|\-)(\w+)$}) if m start = m[1] stop = m[3] type = m[2] step = 1 - elsif value =~ %r{^.+$} + elsif %r{^.+$}.match?(value) raise(Puppet::ParseError, "range(): Unable to compute range from the value: #{value}") else raise(Puppet::ParseError, "range(): Unknown range format: #{value}") end end # If we were given an integer, ensure we work with one - if start.to_s =~ %r{^\d+$} + if %r{^\d+$}.match?(start.to_s) start = start.to_i stop = stop.to_i else start = start.to_s stop = stop.to_s end range = case type when %r{^(..|-)$} then (start..stop) when '...' then (start...stop) # Exclusive of last element end result = range.step(step).first(1_000_000).to_a return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/regexpescape.rb b/lib/puppet/parser/functions/regexpescape.rb index 43b729e..c5dcf8c 100644 --- a/lib/puppet/parser/functions/regexpescape.rb +++ b/lib/puppet/parser/functions/regexpescape.rb @@ -1,32 +1,34 @@ +# frozen_string_literal: true + # # regexpescape.rb # module Puppet::Parser::Functions - newfunction(:regexpescape, :type => :rvalue, :doc => <<-DOC + newfunction(:regexpescape, type: :rvalue, doc: <<-DOC @summary Regexp escape a string or array of strings. Requires either a single string or an array as an input. @return [String] A string of characters with metacharacters converted to their escaped form. DOC - ) do |arguments| # rubocop:disable Layout/ClosingParenthesisIndentation + ) do |arguments| raise(Puppet::ParseError, "regexpescape(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? value = arguments[0] unless value.is_a?(Array) || value.is_a?(String) raise(Puppet::ParseError, 'regexpescape(): Requires either array or string to work with') end result = if value.is_a?(Array) # Numbers in Puppet are often string-encoded which is troublesome ... value.map { |i| i.is_a?(String) ? Regexp.escape(i) : i } else Regexp.escape(value) end return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/reject.rb b/lib/puppet/parser/functions/reject.rb index 6342db6..490249c 100644 --- a/lib/puppet/parser/functions/reject.rb +++ b/lib/puppet/parser/functions/reject.rb @@ -1,36 +1,38 @@ +# frozen_string_literal: true + # # reject.rb # module Puppet::Parser::Functions - newfunction(:reject, :type => :rvalue, :doc => <<-DOC) do |args| + newfunction(:reject, type: :rvalue, doc: <<-DOC) do |args| @summary This function searches through an array and rejects all elements that match the provided regular expression. @return an array containing all the elements which doesn'' match the provided regular expression @example **Usage** reject(['aaa','bbb','ccc','aaaddd'], 'aaa') Would return: ['bbb','ccc'] > *Note:* Since Puppet 4.0.0 the same is in general done with the filter function. Here is the equivalence of the reject() function: ['aaa','bbb','ccc','aaaddd'].filter |$x| { $x !~ /aaa/ } DOC if args.size != 2 raise Puppet::ParseError, "reject(): Wrong number of arguments given #{args.size} for 2" end ary = args[0] pattern = Regexp.new(args[1]) ary.reject { |e| e =~ pattern } end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/reverse.rb b/lib/puppet/parser/functions/reverse.rb index 8b97a97..38250bb 100644 --- a/lib/puppet/parser/functions/reverse.rb +++ b/lib/puppet/parser/functions/reverse.rb @@ -1,30 +1,31 @@ +# frozen_string_literal: true + # # reverse.rb # module Puppet::Parser::Functions - newfunction(:reverse, :type => :rvalue, :doc => <<-DOC + newfunction(:reverse, type: :rvalue, doc: <<-DOC @summary Reverses the order of a string or array. @return reversed string or array > *Note:* that the same can be done with the reverse_each() function in Puppet. DOC - ) do |arguments| - + ) do |arguments| raise(Puppet::ParseError, "reverse(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? value = arguments[0] unless value.is_a?(Array) || value.is_a?(String) raise(Puppet::ParseError, 'reverse(): Requires either array or string to work with') end result = value.reverse return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/round.rb b/lib/puppet/parser/functions/round.rb index 12067ba..bb1013a 100644 --- a/lib/puppet/parser/functions/round.rb +++ b/lib/puppet/parser/functions/round.rb @@ -1,34 +1,35 @@ +# frozen_string_literal: true + # # round.rb # module Puppet::Parser::Functions - newfunction(:round, :type => :rvalue, :doc => <<-DOC + newfunction(:round, type: :rvalue, doc: <<-DOC @summary Rounds a number to the nearest integer @return the rounded value as integer @example ```round(2.9)``` returns ```3``` ```round(2.4)``` returns ```2``` > *Note:* from Puppet 6.0.0, the compatible function with the same name in Puppet core will be used instead of this function. DOC - ) 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 value = args[0] if value >= 0 Integer(value + 0.5) else Integer(value - 0.5) end end end diff --git a/lib/puppet/parser/functions/rstrip.rb b/lib/puppet/parser/functions/rstrip.rb index fc809c8..d07ef63 100644 --- a/lib/puppet/parser/functions/rstrip.rb +++ b/lib/puppet/parser/functions/rstrip.rb @@ -1,35 +1,36 @@ +# frozen_string_literal: true + # # rstrip.rb # module Puppet::Parser::Functions - newfunction(:rstrip, :type => :rvalue, :doc => <<-DOC + newfunction(:rstrip, type: :rvalue, doc: <<-DOC @summary Strips leading spaces to the right of the string. @return the string with leading spaces removed > *Note:* from Puppet 6.0.0, the compatible function with the same name in Puppet core will be used instead of this function. DOC - ) do |arguments| - + ) do |arguments| raise(Puppet::ParseError, "rstrip(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? value = arguments[0] unless value.is_a?(Array) || value.is_a?(String) raise(Puppet::ParseError, 'rstrip(): Requires either array or string to work with') end result = if value.is_a?(Array) value.map { |i| i.is_a?(String) ? i.rstrip : i } else value.rstrip end return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/seeded_rand.rb b/lib/puppet/parser/functions/seeded_rand.rb index 848e092..eb495e8 100644 --- a/lib/puppet/parser/functions/seeded_rand.rb +++ b/lib/puppet/parser/functions/seeded_rand.rb @@ -1,32 +1,34 @@ +# frozen_string_literal: true + # # seeded_rand.rb # Puppet::Parser::Functions.newfunction( :seeded_rand, - :arity => 2, - :type => :rvalue, - :doc => <<-DOC + arity: 2, + type: :rvalue, + doc: <<-DOC, @summary Generates a random whole number greater than or equal to 0 and less than MAX, using the value of SEED for repeatable randomness. @return random number greater than or equal to 0 and less than MAX @example **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`. DOC ) do |args| require 'digest/md5' 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_int(seed, max) end diff --git a/lib/puppet/parser/functions/shell_escape.rb b/lib/puppet/parser/functions/shell_escape.rb index 0cf07e5..113feee 100644 --- a/lib/puppet/parser/functions/shell_escape.rb +++ b/lib/puppet/parser/functions/shell_escape.rb @@ -1,31 +1,32 @@ +# frozen_string_literal: true + require 'shellwords' # # shell_escape.rb # module Puppet::Parser::Functions - newfunction(:shell_escape, :type => :rvalue, :doc => <<-DOC + newfunction(:shell_escape, type: :rvalue, doc: <<-DOC @summary Escapes a string so that it can be safely used in a Bourne shell command line. @return A string of characters with metacharacters converted to their escaped form. >* 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. DOC - ) do |arguments| - + ) do |arguments| raise(Puppet::ParseError, "shell_escape(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size != 1 # explicit conversion to string is required for ruby 1.9 string = arguments[0].to_s result = Shellwords.shellescape(string) return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/shell_join.rb b/lib/puppet/parser/functions/shell_join.rb index e498f55..12d1652 100644 --- a/lib/puppet/parser/functions/shell_join.rb +++ b/lib/puppet/parser/functions/shell_join.rb @@ -1,32 +1,32 @@ +# frozen_string_literal: true require 'shellwords' # # shell_join.rb # module Puppet::Parser::Functions - newfunction(:shell_join, :type => :rvalue, :doc => <<-DOC + newfunction(:shell_join, type: :rvalue, doc: <<-DOC @summary 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 @return a command line string DOC - ) 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) # explicit conversion to string is required for ruby 1.9 array = array.map { |item| item.to_s } result = Shellwords.shelljoin(array) return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/shell_split.rb b/lib/puppet/parser/functions/shell_split.rb index 7c9f123..1fa3c8e 100644 --- a/lib/puppet/parser/functions/shell_split.rb +++ b/lib/puppet/parser/functions/shell_split.rb @@ -1,27 +1,28 @@ +# frozen_string_literal: true + require 'shellwords' # # shell_split.rb # module Puppet::Parser::Functions - newfunction(:shell_split, :type => :rvalue, :doc => <<-DOC + newfunction(:shell_split, type: :rvalue, doc: <<-DOC @summary Splits a string into an array of tokens in the same way the Bourne shell does. @return array of tokens This function behaves the same as ruby's Shellwords.shellsplit() function DOC - ) do |arguments| - + ) do |arguments| raise(Puppet::ParseError, "shell_split(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size != 1 string = arguments[0].to_s result = Shellwords.shellsplit(string) return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/shuffle.rb b/lib/puppet/parser/functions/shuffle.rb index 3e10739..c79ec2e 100644 --- a/lib/puppet/parser/functions/shuffle.rb +++ b/lib/puppet/parser/functions/shuffle.rb @@ -1,46 +1,47 @@ +# frozen_string_literal: true + # # shuffle.rb # module Puppet::Parser::Functions - newfunction(:shuffle, :type => :rvalue, :doc => <<-DOC + newfunction(:shuffle, type: :rvalue, doc: <<-DOC @summary Randomizes the order of a string or array elements. @return randomized string or array DOC - ) do |arguments| - + ) do |arguments| raise(Puppet::ParseError, "shuffle(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? value = arguments[0] unless value.is_a?(Array) || value.is_a?(String) raise(Puppet::ParseError, 'shuffle(): Requires either array or string to work with') end result = value.clone string = value.is_a?(String) ? true : false # Check whether it makes sense to shuffle ... return result if result.size <= 1 # We turn any string value into an array to be able to shuffle ... result = string ? result.split('') : result elements = result.size # Simple implementation of Fisher–Yates in-place shuffle ... elements.times do |i| j = rand(elements - i) + i result[j], result[i] = result[i], result[j] end result = string ? result.join : result return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/size.rb b/lib/puppet/parser/functions/size.rb index 39b856c..9942bb1 100644 --- a/lib/puppet/parser/functions/size.rb +++ b/lib/puppet/parser/functions/size.rb @@ -1,51 +1,52 @@ +# frozen_string_literal: true + # # size.rb # module Puppet::Parser::Functions - newfunction(:size, :type => :rvalue, :doc => <<-DOC + newfunction(:size, type: :rvalue, doc: <<-DOC @summary Returns the number of elements in a string, an array or a hash @return the number of elements in a string, an array or a hash > *Note:* that since Puppet 5.4.0, the length() function in Puppet is preferred over this. For versions of Puppet < 5.4.0 use the stdlib length() function. DOC - ) do |arguments| - + ) do |arguments| raise(Puppet::ParseError, "size(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? item = arguments[0] function_deprecation([:size, 'This method is going to be deprecated, please use the stdlib length function.']) if item.is_a?(String) begin # # Check whether your item is a numeric value or not ... # This will take care about positive and/or negative numbers # for both integer and floating-point values ... # # Please note that Puppet has no notion of hexadecimal # nor octal numbers for its DSL at this point in time ... # Float(item) raise(Puppet::ParseError, 'size(): Requires either string, array or hash to work with') rescue ArgumentError result = item.size end elsif item.is_a?(Array) || item.is_a?(Hash) result = item.size else raise(Puppet::ParseError, 'size(): Unknown type given') end return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/sort.rb b/lib/puppet/parser/functions/sort.rb index a6e0509..29c9f60 100644 --- a/lib/puppet/parser/functions/sort.rb +++ b/lib/puppet/parser/functions/sort.rb @@ -1,31 +1,32 @@ +# frozen_string_literal: true + # # 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 => <<-DOC + newfunction(:sort, type: :rvalue, doc: <<-DOC @summary Sorts strings and arrays lexically. @return sorted string or array Note that from Puppet 6.0.0 the same function in Puppet will be used instead of this. DOC - ) do |arguments| - + ) do |arguments| 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) value.sort elsif value.is_a?(String) value.split('').sort.join('') end end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/squeeze.rb b/lib/puppet/parser/functions/squeeze.rb index 548c933..9fdc3a8 100644 --- a/lib/puppet/parser/functions/squeeze.rb +++ b/lib/puppet/parser/functions/squeeze.rb @@ -1,35 +1,36 @@ +# frozen_string_literal: true + # # squeeze.rb # module Puppet::Parser::Functions - newfunction(:squeeze, :type => :rvalue, :doc => <<-DOC + newfunction(:squeeze, type: :rvalue, doc: <<-DOC @summary Returns a new string where runs of the same character that occur in this set are replaced by a single character. @return a new string where runs of the same character that occur in this set are replaced by a single character. DOC - ) do |arguments| - + ) do |arguments| 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) if squeezeval item.map { |i| i.squeeze(squeezeval) } else item.map { |i| i.squeeze } end elsif squeezeval item.squeeze(squeezeval) else item.squeeze end end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/str2bool.rb b/lib/puppet/parser/functions/str2bool.rb index 165cf5d..6723060 100644 --- a/lib/puppet/parser/functions/str2bool.rb +++ b/lib/puppet/parser/functions/str2bool.rb @@ -1,49 +1,50 @@ +# frozen_string_literal: true + # # str2bool.rb # module Puppet::Parser::Functions - newfunction(:str2bool, :type => :rvalue, :doc => <<-DOC + newfunction(:str2bool, type: :rvalue, doc: <<-DOC @summary This converts a string to a boolean. @return This attempt to convert to boolean 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'. > *Note:* that since Puppet 5.0.0 the Boolean data type can convert strings to a Boolean value. See the function new() in Puppet for details what the Boolean data type supports. DOC - ) do |arguments| - + ) do |arguments| 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 # rubocop:disable Style/DoubleNegation : No viable alternative return string end unless string.is_a?(String) raise(Puppet::ParseError, 'str2bool(): Requires string to work with') end # 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 %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 end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/str2saltedpbkdf2.rb b/lib/puppet/parser/functions/str2saltedpbkdf2.rb index 1f0a193..f3cd811 100644 --- a/lib/puppet/parser/functions/str2saltedpbkdf2.rb +++ b/lib/puppet/parser/functions/str2saltedpbkdf2.rb @@ -1,68 +1,70 @@ +# frozen_string_literal: true + # str2saltedpbkdf2.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(:str2saltedpbkdf2, :type => :rvalue, :doc => <<-DOC + newfunction(:str2saltedpbkdf2, type: :rvalue, doc: <<-DOC @summary Convert a string into a salted SHA512 PBKDF2 password hash like requred for OS X / macOS 10.8+ Convert a string into a salted SHA512 PBKDF2 password hash like requred for OS X / macOS 10.8+. Note, however, that Apple changes what's required periodically and this may not work for the latest version of macOS. If that is the case you should get a helpful error message when Puppet tries to set the pasword using the parameters you provide to the user resource. @example Plain text password and salt $pw_info = str2saltedpbkdf2('Pa55w0rd', 'Using s0m3 s@lt', 50000) user { 'jdoe': ensure => present, iterations => $pw_info['interations'], password => $pw_info['password_hex'], salt => $pw_info['salt_hex'], } @example Sensitive password and salt $pw = Sensitive.new('Pa55w0rd') $salt = Sensitive.new('Using s0m3 s@lt') $pw_info = Sensitive.new(str2saltedpbkdf2($pw, $salt, 50000)) user { 'jdoe': ensure => present, iterations => unwrap($pw_info)['interations'], password => unwrap($pw_info)['password_hex'], salt => unwrap($pw_info)['salt_hex'], } @return [Hash] Provides a hash containing the hex version of the password, the hex version of the salt, and iterations. DOC - ) do |args| + ) do |args| require 'openssl' raise ArgumentError, "str2saltedpbkdf2(): 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, 'str2saltedpbkdf2(): first argument must be a string' unless args[0].is_a?(String) raise ArgumentError, 'str2saltedpbkdf2(): second argument must be a string' unless args[1].is_a?(String) raise ArgumentError, 'str2saltedpbkdf2(): second argument must be at least 8 bytes long' unless args[1].bytesize >= 8 raise ArgumentError, 'str2saltedpbkdf2(): third argument must be an integer' unless args[2].is_a?(Integer) raise ArgumentError, 'str2saltedpbkdf2(): third argument must be between 40,000 and 70,000' unless args[2] > 40_000 && args[2] < 70_000 password = args[0] salt = args[1] iterations = args[2] keylen = 128 digest = OpenSSL::Digest::SHA512.new hash = OpenSSL::PKCS5.pbkdf2_hmac(password, salt, iterations, keylen, digest) { 'password_hex' => hash.unpack('H*').first, 'salt_hex' => salt.unpack('H*').first, 'iterations' => iterations, } end end diff --git a/lib/puppet/parser/functions/str2saltedsha512.rb b/lib/puppet/parser/functions/str2saltedsha512.rb index 8b1c2c9..a1a278b 100644 --- a/lib/puppet/parser/functions/str2saltedsha512.rb +++ b/lib/puppet/parser/functions/str2saltedsha512.rb @@ -1,36 +1,38 @@ +# frozen_string_literal: true + # # 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 => <<-DOC + newfunction(:str2saltedsha512, type: :rvalue, doc: <<-DOC @summary This converts a string to a salted-SHA512 password hash (which is used for OS X versions >= 10.7). @return converted string as a hex version of a salted-SHA512 password hash 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. DOC - ) 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 password = arguments[0] unless password.is_a?(String) raise(Puppet::ParseError, "str2saltedsha512(): Requires a String argument, you passed: #{password.class}") end seedint = rand(2**31 - 1) seedstring = Array(seedint).pack('L') saltedpass = Digest::SHA512.digest(seedstring + password) (seedstring + saltedpass).unpack('H*')[0] end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/strip.rb b/lib/puppet/parser/functions/strip.rb index 067af00..6f11736 100644 --- a/lib/puppet/parser/functions/strip.rb +++ b/lib/puppet/parser/functions/strip.rb @@ -1,41 +1,42 @@ +# frozen_string_literal: true + # # strip.rb # module Puppet::Parser::Functions - newfunction(:strip, :type => :rvalue, :doc => <<-DOC + newfunction(:strip, type: :rvalue, doc: <<-DOC @summary This function removes leading and trailing whitespace from a string or from every string inside an array. @return String or Array converted @example **Usage** strip(" aaa ") Would result in: "aaa" > *Note:*: from Puppet 6.0.0, the compatible function with the same name in Puppet core will be used instead of this function. DOC - ) do |arguments| - + ) do |arguments| raise(Puppet::ParseError, "strip(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? value = arguments[0] unless value.is_a?(Array) || value.is_a?(String) raise(Puppet::ParseError, 'strip(): Requires either array or string to work with') end result = if value.is_a?(Array) value.map { |i| i.is_a?(String) ? i.strip : i } else value.strip end return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/suffix.rb b/lib/puppet/parser/functions/suffix.rb index 643d722..5c519ba 100644 --- a/lib/puppet/parser/functions/suffix.rb +++ b/lib/puppet/parser/functions/suffix.rb @@ -1,60 +1,61 @@ +# frozen_string_literal: true + # # suffix.rb # module Puppet::Parser::Functions - newfunction(:suffix, :type => :rvalue, :doc => <<-DOC + newfunction(:suffix, type: :rvalue, doc: <<-DOC @summary This function applies a suffix to all elements in an array, or to the keys in a hash. @return Array or Hash with updated elements containing the passed suffix @example **Usage** suffix(['a','b','c'], 'p') Will return: ['ap','bp','cp'] > *Note:* that since Puppet 4.0.0 the general way to modify values is in array is by using the map function in Puppet. This example does the same as the example above: ```['a', 'b', 'c'].map |$x| { "${x}p" }``` DOC - ) 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.empty? enumerable = arguments[0] 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 suffix = arguments[1] if arguments[1] if suffix unless suffix.is_a? String raise Puppet::ParseError, "suffix(): expected second argument to be a String, got #{suffix.inspect}" 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 end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/swapcase.rb b/lib/puppet/parser/functions/swapcase.rb index dd17330..cddd289 100644 --- a/lib/puppet/parser/functions/swapcase.rb +++ b/lib/puppet/parser/functions/swapcase.rb @@ -1,39 +1,40 @@ +# frozen_string_literal: true + # # 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 => <<-DOC + newfunction(:swapcase, type: :rvalue, doc: <<-DOC @summary This function will swap the existing case of a string. @return string with uppercase alphabetic characters converted to lowercase and lowercase characters converted to uppercase @example **Usage** swapcase("aBcD") Would result in: "AbCd" DOC - ) do |arguments| - + ) do |arguments| raise(Puppet::ParseError, "swapcase(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? value = arguments[0] unless value.is_a?(Array) || value.is_a?(String) raise(Puppet::ParseError, 'swapcase(): Requires either array or string to work with') 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 end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/time.rb b/lib/puppet/parser/functions/time.rb index d123cf6..e154643 100644 --- a/lib/puppet/parser/functions/time.rb +++ b/lib/puppet/parser/functions/time.rb @@ -1,58 +1,59 @@ +# frozen_string_literal: true + # # time.rb # module Puppet::Parser::Functions - newfunction(:time, :type => :rvalue, :doc => <<-DOC + newfunction(:time, type: :rvalue, doc: <<-DOC @summary This function will return the current time since epoch as an integer. @return the current time since epoch as an integer. @example **Usage** time() Will return something like: 1311972653 > *Note:* that since Puppet 4.8.0 the Puppet language has the data types Timestamp (a point in time) and Timespan (a duration). The following example is equivalent to calling time() without any arguments: ```Timestamp()``` DOC - ) do |arguments| - + ) do |arguments| # The Time Zone argument is optional ... time_zone = arguments[0] if arguments[0] 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 && !time_zone.empty? original_zone = ENV['TZ'] local_time = time.clone local_time = local_time.utc ENV['TZ'] = time_zone result = local_time.localtime.strftime('%s') ENV['TZ'] = original_zone else result = time.localtime.strftime('%s') end # Calling Time#to_i on a receiver changes it. Trust me I am the Doctor. result = result.to_i return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/to_bytes.rb b/lib/puppet/parser/functions/to_bytes.rb index b7de587..b1beb5f 100644 --- a/lib/puppet/parser/functions/to_bytes.rb +++ b/lib/puppet/parser/functions/to_bytes.rb @@ -1,38 +1,39 @@ +# frozen_string_literal: true + # # to_bytes.rb # module Puppet::Parser::Functions - newfunction(:to_bytes, :type => :rvalue, :doc => <<-DOC + newfunction(:to_bytes, type: :rvalue, doc: <<-DOC @summary Converts the argument into bytes, for example 4 kB becomes 4096. @return converted value into bytes 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. DOC - ) do |arguments| - + ) do |arguments| raise(Puppet::ParseError, "to_bytes(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size != 1 arg = arguments[0] return arg if arg.is_a? Numeric 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 else raise Puppet::ParseError, "to_bytes(): Unknown prefix #{prefix}" end end end diff --git a/lib/puppet/parser/functions/try_get_value.rb b/lib/puppet/parser/functions/try_get_value.rb index 26c0b2d..8df9530 100644 --- a/lib/puppet/parser/functions/try_get_value.rb +++ b/lib/puppet/parser/functions/try_get_value.rb @@ -1,60 +1,62 @@ +# frozen_string_literal: true + # # try_get_value.rb # module Puppet::Parser::Functions newfunction( :try_get_value, - :type => :rvalue, - :arity => -2, - :doc => <<-DOC + type: :rvalue, + arity: -2, + doc: <<-DOC, @summary **DEPRECATED:** this function is deprecated, please use dig() instead. @return 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. DOC ) do |args| warning('try_get_value() DEPRECATED: this function is deprecated, please use dig() instead.') data = args[0] path = args[1] || '' default = args[2] if !(data.is_a?(Hash) || data.is_a?(Array)) || path == '' return default || data end separator = args[3] || '/' 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 6b01408..57dd3e1 100644 --- a/lib/puppet/parser/functions/type.rb +++ b/lib/puppet/parser/functions/type.rb @@ -1,29 +1,30 @@ +# frozen_string_literal: true + # # type.rb # module Puppet::Parser::Functions - newfunction(:type, :type => :rvalue, :doc => <<-DOC + newfunction(:type, type: :rvalue, doc: <<-DOC @summary **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. @return the type when passed a value. Type can be one of: * string * array * hash * float * integer * boolean DOC - ) 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.") # rubocop:disable Metrics/LineLength : Cannot reduce line length + ) 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.") # rubocop:disable Layout/LineLength : Cannot reduce line length unless Puppet::Parser::Functions.autoloader.loaded?(:type3x) Puppet::Parser::Functions.autoloader.load(:type3x) end function_type3x(args) end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/type3x.rb b/lib/puppet/parser/functions/type3x.rb index e8d90d8..49903b9 100644 --- a/lib/puppet/parser/functions/type3x.rb +++ b/lib/puppet/parser/functions/type3x.rb @@ -1,50 +1,52 @@ +# frozen_string_literal: true + # # type3x.rb # module Puppet::Parser::Functions - newfunction(:type3x, :type => :rvalue, :doc => <<-DOC + newfunction(:type3x, type: :rvalue, doc: <<-DOC @summary **DEPRECATED:** This function will be removed when Puppet 3 support is dropped; please migrate to the new parser's typing system. @return the type when passed a value. Type can be one of: * string * array * hash * float * integer * boolean DOC - ) do |args| + ) do |args| raise(Puppet::ParseError, "type3x(): Wrong number of arguments given (#{args.size} for 1)") unless args.size == 1 value = args[0] klass = value.class unless [TrueClass, FalseClass, Array, Bignum, Fixnum, Float, Hash, String].include?(klass) # rubocop:disable Lint/UnifiedInteger raise(Puppet::ParseError, 'type3x(): Unknown type') end klass = klass.to_s # Ugly ... # We note that Integer is the parent to Bignum and Fixnum ... result = case klass 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 return result.downcase end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/union.rb b/lib/puppet/parser/functions/union.rb index ac521e5..353e51e 100644 --- a/lib/puppet/parser/functions/union.rb +++ b/lib/puppet/parser/functions/union.rb @@ -1,29 +1,30 @@ +# frozen_string_literal: true + # # union.rb # module Puppet::Parser::Functions - newfunction(:union, :type => :rvalue, :doc => <<-DOC + newfunction(:union, type: :rvalue, doc: <<-DOC @summary This function returns a union of two or more arrays. @return a unionized array of two or more arrays @example **Usage** union(["a","b","c"],["b","c","d"]) Would return: ["a","b","c","d"] DOC - ) 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 arguments.each do |argument| raise(Puppet::ParseError, 'union(): Every parameter must be an array') unless argument.is_a?(Array) end arguments.reduce(:|) end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/unique.rb b/lib/puppet/parser/functions/unique.rb index c9eaa08..7efdaa3 100644 --- a/lib/puppet/parser/functions/unique.rb +++ b/lib/puppet/parser/functions/unique.rb @@ -1,50 +1,51 @@ +# frozen_string_literal: true + # # unique.rb # module Puppet::Parser::Functions - newfunction(:unique, :type => :rvalue, :doc => <<-DOC + newfunction(:unique, type: :rvalue, doc: <<-DOC @summary This function will remove duplicates from strings and arrays. @return String or array with duplicates removed @example **Usage** unique("aabbcc") Will return: abc You can also use this with arrays: unique(["a","a","b","b","c","c"]) This returns: ["a","b","c"] DOC - ) 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.empty? value = arguments[0] unless value.is_a?(Array) || value.is_a?(String) raise(Puppet::ParseError, 'unique(): Requires either array or string to work with') end result = value.clone string = value.is_a?(String) ? true : false # We turn any string value into an array to be able to shuffle ... result = string ? result.split('') : result result = result.uniq # Remove duplicates ... result = string ? result.join : result return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/unix2dos.rb b/lib/puppet/parser/functions/unix2dos.rb index 91b2596..95d9dfc 100644 --- a/lib/puppet/parser/functions/unix2dos.rb +++ b/lib/puppet/parser/functions/unix2dos.rb @@ -1,20 +1,21 @@ +# frozen_string_literal: true + # Custom Puppet function to convert unix to dos format module Puppet::Parser::Functions - newfunction(:unix2dos, :type => :rvalue, :arity => 1, :doc => <<-DOC + newfunction(:unix2dos, type: :rvalue, arity: 1, doc: <<-DOC @summary Returns the DOS version of the given string. @return the DOS version of the given string. Takes a single string argument. DOC - ) do |arguments| - + ) do |arguments| unless arguments[0].is_a?(String) raise(Puppet::ParseError, 'unix2dos(): Requires string as argument') end 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 de07970..a7685d1 100644 --- a/lib/puppet/parser/functions/upcase.rb +++ b/lib/puppet/parser/functions/upcase.rb @@ -1,47 +1,48 @@ +# frozen_string_literal: true + # # 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 => <<-DOC + newfunction(:upcase, type: :rvalue, doc: <<-DOC @summary Converts a string or an array of strings to uppercase. @return converted string ot array of strings to uppercase @example **Usage** upcase("abcd") Will return ABCD > *Note:* from Puppet 6.0.0, the compatible function with the same name in Puppet core will be used instead of this function. DOC - ) do |arguments| - + ) do |arguments| raise(Puppet::ParseError, "upcase(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.size != 1 value = arguments[0] unless value.is_a?(Array) || value.is_a?(Hash) || value.respond_to?(:upcase) raise(Puppet::ParseError, 'upcase(): Requires an array, hash or object that responds to upcase in order to work') end if value.is_a?(Array) # Numbers in Puppet are often string-encoded which is troublesome ... result = value.map { |i| function_upcase([i]) } elsif value.is_a?(Hash) result = {} value.each_pair do |k, v| result[function_upcase([k])] = function_upcase([v]) end else result = value.upcase end return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/uriescape.rb b/lib/puppet/parser/functions/uriescape.rb index 4078b86..b7de4c1 100644 --- a/lib/puppet/parser/functions/uriescape.rb +++ b/lib/puppet/parser/functions/uriescape.rb @@ -1,37 +1,38 @@ +# frozen_string_literal: true + 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. # module Puppet::Parser::Functions - newfunction(:uriescape, :type => :rvalue, :doc => <<-DOC + newfunction(:uriescape, type: :rvalue, doc: <<-DOC @summary Urlencodes a string or array of strings. Requires either a single string or an array as an input. @return [String] a string that contains the converted value DOC - ) do |arguments| - + ) do |arguments| raise(Puppet::ParseError, "uriescape(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? value = arguments[0] unless value.is_a?(Array) || value.is_a?(String) raise(Puppet::ParseError, 'uriescape(): Requires either array or string to work with') 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 end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/validate_absolute_path.rb b/lib/puppet/parser/functions/validate_absolute_path.rb index 7d79445..e0ea72b 100644 --- a/lib/puppet/parser/functions/validate_absolute_path.rb +++ b/lib/puppet/parser/functions/validate_absolute_path.rb @@ -1,59 +1,61 @@ +# frozen_string_literal: true + # # validate_absolute_path.rb # module Puppet::Parser::Functions - newfunction(:validate_absolute_path, :doc => <<-DOC) do |args| + newfunction(:validate_absolute_path, doc: <<-DOC) do |args| @summary Validate the string represents an absolute path in the filesystem. This function works for windows and unix style paths. @return passes when the string is an absolute path or raise an error when it is not and fails compilation @example **Usage** The following values will pass: $my_path = 'C:/Program Files (x86)/Puppet Labs/Puppet' validate_absolute_path($my_path) $my_path2 = '/var/lib/puppet' validate_absolute_path($my_path2) $my_path3 = ['C:/Program Files (x86)/Puppet Labs/Puppet','C:/Program Files/Puppet Labs/Puppet'] validate_absolute_path($my_path3) $my_path4 = ['/var/lib/puppet','/usr/share/puppet'] validate_absolute_path($my_path4) The following values will fail, causing compilation to abort: validate_absolute_path(true) validate_absolute_path('../var/lib/puppet') validate_absolute_path('var/lib/puppet') validate_absolute_path([ 'var/lib/puppet', '/var/foo' ]) validate_absolute_path([ '/var/lib/puppet', 'var/foo' ]) $undefined = undef validate_absolute_path($undefined) DOC require 'puppet/util' if args.empty? raise Puppet::ParseError, "validate_absolute_path(): wrong number of arguments (#{args.length}; must be > 0)" end args.each do |arg| # put arg to candidate var to be able to replace it 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) 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." end end end end end diff --git a/lib/puppet/parser/functions/validate_array.rb b/lib/puppet/parser/functions/validate_array.rb index d24f75e..15cbc44 100644 --- a/lib/puppet/parser/functions/validate_array.rb +++ b/lib/puppet/parser/functions/validate_array.rb @@ -1,40 +1,42 @@ +# frozen_string_literal: true + # # validate_array.rb # module Puppet::Parser::Functions - newfunction(:validate_array, :doc => <<-DOC) do |args| + newfunction(:validate_array, doc: <<-DOC) do |args| @summary Validate that all passed values are array data structures. Abort catalog compilation if any value fails this check. @return validate array @example **Usage** The following values will pass: $my_array = [ 'one', 'two' ] validate_array($my_array) The following values will fail, causing compilation to abort: validate_array(true) validate_array('some_string') $undefined = undef validate_array($undefined) DOC 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.']) 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}" end end end end diff --git a/lib/puppet/parser/functions/validate_augeas.rb b/lib/puppet/parser/functions/validate_augeas.rb index 26e51e8..55f932f 100644 --- a/lib/puppet/parser/functions/validate_augeas.rb +++ b/lib/puppet/parser/functions/validate_augeas.rb @@ -1,94 +1,96 @@ +# frozen_string_literal: true + require 'tempfile' # # validate_augaes.rb # module Puppet::Parser::Functions - newfunction(:validate_augeas, :doc => <<-DOC + newfunction(:validate_augeas, doc: <<-DOC @summary 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. If Augeas fails to parse the string with the lens, the compilation will abort with a parse error. A third argument can be specified, listing paths which should not be found in the file. The `$file` variable points to the location of the temporary file being tested in the Augeas tree. @return validate string using an Augeas lens @example **Usage** If you want to make sure your passwd content never contains a user `foo`, you could write: validate_augeas($passwdcontent, 'Passwd.lns', ['$file/foo']) If you wanted to ensure that no users used the '/bin/barsh' shell, you could use: validate_augeas($passwdcontent, 'Passwd.lns', ['$file/*[shell="/bin/barsh"]'] If a fourth argument is specified, this will be the error message raised and seen by the user. A helpful error message can be returned like this: validate_augeas($sudoerscontent, 'Sudoers.lns', [], 'Failed to validate sudoers content with Augeas') DOC - ) do |args| + ) do |args| 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.' end 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) begin content = args[0] # Test content in a temporary file tmpfile = Tempfile.new('validate_augeas') begin tmpfile.write(content) ensure tmpfile.close end # 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 end # Launch unit tests tests = args[2] || [] aug.defvar('file', "/files#{tmpfile.path}") tests.each do |t| msg += " testing path #{t}" raise Puppet::ParseError, msg unless aug.match(t).empty? end ensure aug.close tmpfile.unlink end end end diff --git a/lib/puppet/parser/functions/validate_bool.rb b/lib/puppet/parser/functions/validate_bool.rb index d6f07af..125d262 100644 --- a/lib/puppet/parser/functions/validate_bool.rb +++ b/lib/puppet/parser/functions/validate_bool.rb @@ -1,39 +1,41 @@ +# frozen_string_literal: true + # # validate_bool.rb # module Puppet::Parser::Functions - newfunction(:validate_bool, :doc => <<-DOC + newfunction(:validate_bool, doc: <<-DOC @summary Validate that all passed values are either true or false. Abort catalog compilation if any value fails this check. @return validate boolean @example **Usage** The following values will pass: $iamtrue = true validate_bool(true) validate_bool(true, true, false, $iamtrue) The following values will fail, causing compilation to abort: $some_array = [ true ] validate_bool("false") validate_bool("true") validate_bool($some_array) DOC - ) do |args| + ) do |args| 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}" end end end end diff --git a/lib/puppet/parser/functions/validate_cmd.rb b/lib/puppet/parser/functions/validate_cmd.rb index 592d0ee..16b4ab9 100644 --- a/lib/puppet/parser/functions/validate_cmd.rb +++ b/lib/puppet/parser/functions/validate_cmd.rb @@ -1,71 +1,73 @@ +# frozen_string_literal: true + require 'puppet/util/execution' require 'tempfile' # # validate_cmd.rb # module Puppet::Parser::Functions - newfunction(:validate_cmd, :doc => <<-DOC + newfunction(:validate_cmd, doc: <<-DOC @summary 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 taking a % as a placeholder for the file path (will default to the end). If the command, launched against a tempfile containing the passed string, returns a non-null value, compilation will abort with a parse error. If a third argument is specified, this will be the error message raised and seen by the user. @return validate of a string with an external command A helpful error message can be returned like this: @example **Usage** Defaults to end of path validate_cmd($sudoerscontent, '/usr/sbin/visudo -c -f', 'Visudo failed to validate sudoers content') % as file location validate_cmd($haproxycontent, '/usr/sbin/haproxy -f % -c', 'Haproxy failed to validate config content') DOC - ) do |args| + ) do |args| 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}" content = args[0] checkscript = args[1] # Test content in a temporary file tmpfile = Tempfile.new('validate_cmd') begin tmpfile.write(content) tmpfile.close - check_with_correct_location = if checkscript =~ %r{\s%(\s|$)} + check_with_correct_location = if %r{\s%(\s|$)}.match?(checkscript) 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) else Puppet::Util.execute(check_with_correct_location) end rescue Puppet::ExecutionFailure => detail msg += "\n#{detail}" raise Puppet::ParseError, msg rescue StandardError => detail msg += "\n#{detail.class.name} #{detail}" raise Puppet::ParseError, msg ensure tmpfile.unlink end end end diff --git a/lib/puppet/parser/functions/validate_domain_name.rb b/lib/puppet/parser/functions/validate_domain_name.rb index f3dc1d5..0ed576f 100644 --- a/lib/puppet/parser/functions/validate_domain_name.rb +++ b/lib/puppet/parser/functions/validate_domain_name.rb @@ -1,47 +1,48 @@ +# frozen_string_literal: true + # # validate_domain_name.rb # module Puppet::Parser::Functions - newfunction(:validate_domain_name, :doc => <<-DOC + newfunction(:validate_domain_name, doc: <<-DOC @summary Validate that all values passed are syntactically correct domain names. Fail compilation if any value fails this check. @return passes when the given values are syntactically correct domain names or raise an error when they are not and fails compilation @example **Usage** The following values will pass: $my_domain_name = 'server.domain.tld' validate_domain_name($my_domain_name) validate_domain_name('domain.tld', 'puppet.com', $my_domain_name) The following values will fail, causing compilation to abort: validate_domain_name(1) validate_domain_name(true) validate_domain_name('invalid domain') validate_domain_name('-foo.example.com') validate_domain_name('www.example.2com') DOC - ) do |args| - + ) do |args| rescuable_exceptions = [ArgumentError] if args.empty? raise Puppet::ParseError, "validate_domain_name(): wrong number of arguments (#{args.length}; must be > 0)" end args.each do |arg| raise Puppet::ParseError, "#{arg.inspect} is not a string." unless arg.is_a?(String) begin raise Puppet::ParseError, "#{arg.inspect} is not a syntactically correct domain name" unless function_is_domain_name([arg]) rescue *rescuable_exceptions raise Puppet::ParseError, "#{arg.inspect} is not a syntactically correct domain name" end end end end diff --git a/lib/puppet/parser/functions/validate_email_address.rb b/lib/puppet/parser/functions/validate_email_address.rb index 5ad983a..ae847b5 100644 --- a/lib/puppet/parser/functions/validate_email_address.rb +++ b/lib/puppet/parser/functions/validate_email_address.rb @@ -1,43 +1,45 @@ +# frozen_string_literal: true + # # validate_email_address.rb # module Puppet::Parser::Functions - newfunction(:validate_email_address, :doc => <<-DOC + newfunction(:validate_email_address, doc: <<-DOC @summary Validate that all values passed are valid email addresses. Fail compilation if any value fails this check. @return Fail compilation if any value fails this check. @example **Usage** The following values will pass: $my_email = "waldo@gmail.com" validate_email_address($my_email) validate_email_address("bob@gmail.com", "alice@gmail.com", $my_email) The following values will fail, causing compilation to abort: $some_array = [ 'bad_email@/d/efdf.com' ] validate_email_address($some_array) DOC - ) do |args| + ) do |args| rescuable_exceptions = [ArgumentError] if args.empty? raise Puppet::ParseError, "validate_email_address(): wrong number of arguments (#{args.length}; must be > 0)" end args.each do |arg| raise Puppet::ParseError, "#{arg.inspect} is not a string." unless arg.is_a?(String) begin raise Puppet::ParseError, "#{arg.inspect} is not a valid email address" unless function_is_email_address([arg]) rescue *rescuable_exceptions raise Puppet::ParseError, "#{arg.inspect} is not a valid email address" end end end end diff --git a/lib/puppet/parser/functions/validate_hash.rb b/lib/puppet/parser/functions/validate_hash.rb index c3b0dfd..c34f1e4 100644 --- a/lib/puppet/parser/functions/validate_hash.rb +++ b/lib/puppet/parser/functions/validate_hash.rb @@ -1,42 +1,43 @@ +# frozen_string_literal: true + # # validate_hash.rb # module Puppet::Parser::Functions - newfunction(:validate_hash, :doc => <<-DOC + newfunction(:validate_hash, doc: <<-DOC @summary Validate that all passed values are hash data structures. Abort catalog compilation if any value fails this check. @return validate hash @example **Usage** The following values will pass: $my_hash = { 'one' => 'two' } validate_hash($my_hash) The following values will fail, causing compilation to abort: validate_hash(true) validate_hash('some_string') $undefined = undef validate_hash($undefined) DOC - ) do |args| - + ) do |args| 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.']) 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}" end end end end diff --git a/lib/puppet/parser/functions/validate_integer.rb b/lib/puppet/parser/functions/validate_integer.rb index 6a56d5c..4ec05b0 100644 --- a/lib/puppet/parser/functions/validate_integer.rb +++ b/lib/puppet/parser/functions/validate_integer.rb @@ -1,141 +1,143 @@ +# frozen_string_literal: true + # # validate_interger.rb # module Puppet::Parser::Functions - newfunction(:validate_integer, :doc => <<-DOC + newfunction(:validate_integer, doc: <<-DOC @summary 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. The third argument is optional and passes a minimum. (All elements of) the first argument has to be greater or equal to this min. If, and only if, a minimum is given, the second argument may be an empty string or undef, which will be handled to just check if (all elements of) the first argument are greater or equal to the given minimum. It will fail if the first argument is not an integer or array of integers, and if arg 2 and arg 3 are not convertable to an integer. @return Validate that the first argument is an integer (or an array of integers). Fail compilation if any of the checks fail. @example **Usage** The following values will pass: validate_integer(1) validate_integer(1, 2) validate_integer(1, 1) validate_integer(1, 2, 0) validate_integer(2, 2, 2) validate_integer(2, '', 0) validate_integer(2, undef, 0) $foo = undef validate_integer(2, $foo, 0) validate_integer([1,2,3,4,5], 6) validate_integer([1,2,3,4,5], 6, 0) Plus all of the above, but any combination of values passed as strings ('1' or "1"). Plus all of the above, but with (correct) combinations of negative integer values. The following values will not: validate_integer(true) validate_integer(false) validate_integer(7.0) validate_integer({ 1 => 2 }) $foo = undef validate_integer($foo) validate_integer($foobaridontexist) validate_integer(1, 0) validate_integer(1, true) validate_integer(1, '') validate_integer(1, undef) validate_integer(1, , 0) validate_integer(1, 2, 3) validate_integer(1, 3, 2) validate_integer(1, 3, true) Plus all of the above, but any combination of values passed as strings ('false' or "false"). Plus all of the above, but with incorrect combinations of negative integer values. Plus all of the above, but with non-integer items in arrays or maximum / minimum argument. DOC - ) do |args| + ) do |args| 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.empty? && args.length < 4 input, max, min = *args # check maximum parameter 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 && max == '' max = nil else begin max = Integer(max) rescue TypeError, ArgumentError raise Puppet::ParseError, "validate_integer(): Expected second argument to be unset or an Integer, got #{max}:#{max.class}" end end else max = nil end # check minimum parameter if args.length > 2 begin min = Integer(min.to_s) rescue TypeError, ArgumentError raise Puppet::ParseError, "validate_integer(): Expected third argument to be unset or an Integer, got #{min}:#{min.class}" end else min = nil end # ensure that 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 = ->(num) do # check input < 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 && num < min raise Puppet::ParseError, "validate_integer(): Expected #{input.inspect} to be greater or equal to #{min}, got #{input.inspect}." end end # if this is an array, handle it. case input when Array # check every element of the array input.each_with_index do |arg, pos| begin raise TypeError if arg.is_a?(Hash) arg = Integer(arg.to_s) validator.call(arg) rescue TypeError, ArgumentError raise Puppet::ParseError, "validate_integer(): Expected element at array position #{pos} to be an Integer, got #{arg.class}" end end # for the sake of compatibility with ruby 1.8, we need extra handling of hashes when Hash raise Puppet::ParseError, "validate_integer(): Expected first argument to be an Integer or Array, got #{input.class}" # check the input. this will also fail any stuff other than pure, shiny integers else begin input = Integer(input.to_s) validator.call(input) rescue TypeError, ArgumentError raise Puppet::ParseError, "validate_integer(): Expected first argument to be an Integer or Array, got #{input.class}" end end end end diff --git a/lib/puppet/parser/functions/validate_ip_address.rb b/lib/puppet/parser/functions/validate_ip_address.rb index 3fd582b..32400e2 100644 --- a/lib/puppet/parser/functions/validate_ip_address.rb +++ b/lib/puppet/parser/functions/validate_ip_address.rb @@ -1,61 +1,62 @@ +# frozen_string_literal: true + # # validate_ip_address.rb # module Puppet::Parser::Functions - newfunction(:validate_ip_address, :doc => <<-DOC + newfunction(:validate_ip_address, doc: <<-DOC @summary Validate that all values passed are valid IP addresses, regardless they are IPv4 or IPv6 Fail compilation if any value fails this check. @return passes when the given values are valid IP addresses or raise an error when they are not and fails compilation @example **Usage** The following values will pass: $my_ip = "1.2.3.4" validate_ip_address($my_ip) validate_ip_address("8.8.8.8", "172.16.0.1", $my_ip) $my_ip = "3ffe:505:2" validate_ip_address(1) validate_ip_address($my_ip) validate_ip_address("fe80::baf6:b1ff:fe19:7507", $my_ip) The following values will fail, causing compilation to abort: $some_array = [ 1, true, false, "garbage string", "3ffe:505:2" ] validate_ip_address($some_array) DOC - ) do |args| - + ) do |args| 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.']) if defined?(IPAddr::InvalidAddressError) rescuable_exceptions << IPAddr::InvalidAddressError end if args.empty? raise Puppet::ParseError, "validate_ip_address(): wrong number of arguments (#{args.length}; must be > 0)" end args.each do |arg| unless arg.is_a?(String) raise Puppet::ParseError, "#{arg.inspect} is not a string." end begin 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 1f3223f..9e86690 100644 --- a/lib/puppet/parser/functions/validate_ipv4_address.rb +++ b/lib/puppet/parser/functions/validate_ipv4_address.rb @@ -1,55 +1,56 @@ +# frozen_string_literal: true + # # validate_ipv4_address.rb # module Puppet::Parser::Functions - newfunction(:validate_ipv4_address, :doc => <<-DOC + newfunction(:validate_ipv4_address, doc: <<-DOC @summary Validate that all values passed are valid IPv4 addresses. Fail compilation if any value fails this check. @return passes when the given values are valid IPv4 addresses or raise an error when they are not and fails compilation @example **Usage** The following values will pass: $my_ip = "1.2.3.4" validate_ipv4_address($my_ip) validate_ipv4_address("8.8.8.8", "172.16.0.1", $my_ip) The following values will fail, causing compilation to abort: $some_array = [ 1, true, false, "garbage string", "3ffe:505:2" ] validate_ipv4_address($some_array) DOC - ) 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.']) require 'ipaddr' rescuable_exceptions = [ArgumentError] if defined?(IPAddr::InvalidAddressError) rescuable_exceptions << IPAddr::InvalidAddressError end if args.empty? raise Puppet::ParseError, "validate_ipv4_address(): wrong number of arguments (#{args.length}; must be > 0)" end args.each do |arg| unless arg.is_a?(String) raise Puppet::ParseError, "#{arg.inspect} is not a string." end begin unless IPAddr.new(arg).ipv4? raise Puppet::ParseError, "#{arg.inspect} is not a valid IPv4 address." end rescue *rescuable_exceptions 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 b1f33fe..3596e69 100644 --- a/lib/puppet/parser/functions/validate_ipv6_address.rb +++ b/lib/puppet/parser/functions/validate_ipv6_address.rb @@ -1,57 +1,58 @@ +# frozen_string_literal: true + # # validate_ipv7_address.rb # module Puppet::Parser::Functions - newfunction(:validate_ipv6_address, :doc => <<-DOC + newfunction(:validate_ipv6_address, doc: <<-DOC @summary Validate that all values passed are valid IPv6 addresses. Fail compilation if any value fails this check. @return passes when the given values are valid IPv6 addresses or raise an error when they are not and fails compilation @example **Usage** The following values will pass: $my_ip = "3ffe:505:2" validate_ipv6_address(1) validate_ipv6_address($my_ip) validate_bool("fe80::baf6:b1ff:fe19:7507", $my_ip) The following values will fail, causing compilation to abort: $some_array = [ true, false, "garbage string", "1.2.3.4" ] validate_ipv6_address($some_array) DOC - ) 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.']) require 'ipaddr' rescuable_exceptions = [ArgumentError] if defined?(IPAddr::InvalidAddressError) rescuable_exceptions << IPAddr::InvalidAddressError end if args.empty? raise Puppet::ParseError, "validate_ipv6_address(): wrong number of arguments (#{args.length}; must be > 0)" end args.each do |arg| unless arg.is_a?(String) raise Puppet::ParseError, "#{arg.inspect} is not a string." end begin unless IPAddr.new(arg).ipv6? raise Puppet::ParseError, "#{arg.inspect} is not a valid IPv6 address." end rescue *rescuable_exceptions 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 6ccdb0e..1bbc667 100644 --- a/lib/puppet/parser/functions/validate_numeric.rb +++ b/lib/puppet/parser/functions/validate_numeric.rb @@ -1,101 +1,103 @@ +# frozen_string_literal: true + # # validate_numeric.rb # module Puppet::Parser::Functions - newfunction(:validate_numeric, :doc => <<-DOC + newfunction(:validate_numeric, doc: <<-DOC @summary 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. The third argument is optional and passes a minimum. (All elements of) the first argument has to be greater or equal to this min. If, and only if, a minimum is given, the second argument may be an empty string or undef, which will be handled to just check if (all elements of) the first argument are greater or equal to the given minimum. It will fail if the first argument is not a numeric (Integer or Float) or array of numerics, and if arg 2 and arg 3 are not convertable to a numeric. @return Validate that the first argument is a numeric value (or an array of numeric values). Fail compilation if any of the checks fail. For passing and failing usage, see `validate_integer()`. It is all the same for validate_numeric, yet now floating point values are allowed, too. DOC - ) do |args| + ) do |args| 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.empty? && args.length < 4 input, max, min = *args # check maximum parameter 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 && max == '' max = nil else begin max = Float(max) rescue TypeError, ArgumentError raise Puppet::ParseError, "validate_numeric(): Expected second argument to be unset or a Numeric, got #{max}:#{max.class}" end end else max = nil end # check minimum parameter if args.length > 2 begin min = Float(min.to_s) rescue TypeError, ArgumentError raise Puppet::ParseError, "validate_numeric(): Expected third argument to be unset or a Numeric, got #{min}:#{min.class}" end else min = nil end # ensure that 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 = ->(num) do # check input < 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 && num < min raise Puppet::ParseError, "validate_numeric(): Expected #{input.inspect} to be greater or equal to #{min}, got #{input.inspect}." end end # if this is an array, handle it. case input when Array # check every element of the array input.each_with_index do |arg, pos| begin raise TypeError if arg.is_a?(Hash) arg = Float(arg.to_s) validator.call(arg) rescue TypeError, ArgumentError raise Puppet::ParseError, "validate_numeric(): Expected element at array position #{pos} to be a Numeric, got #{arg.class}" end end # for the sake of compatibility with ruby 1.8, we need extra handling of hashes when Hash raise Puppet::ParseError, "validate_integer(): Expected first argument to be a Numeric or Array, got #{input.class}" # check the input. this will also fail any stuff other than pure, shiny integers else begin input = Float(input.to_s) validator.call(input) rescue TypeError, ArgumentError raise Puppet::ParseError, "validate_numeric(): Expected first argument to be a Numeric or Array, got #{input.class}" end end end end diff --git a/lib/puppet/parser/functions/validate_re.rb b/lib/puppet/parser/functions/validate_re.rb index 14ad7ab..f116280 100644 --- a/lib/puppet/parser/functions/validate_re.rb +++ b/lib/puppet/parser/functions/validate_re.rb @@ -1,58 +1,60 @@ +# frozen_string_literal: true + # # validate.rb # module Puppet::Parser::Functions - newfunction(:validate_re, :doc => <<-DOC + newfunction(:validate_re, doc: <<-DOC @summary 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 (without the // delimiters) or an array of regular expressions. If none of the regular expressions match the string passed in, compilation will abort with a parse error. If a third argument is specified, this will be the error message raised and seen by the user. @return validation of a string against one or more regular expressions. @example **Usage** The following strings will validate against the regular expressions: validate_re('one', '^one$') validate_re('one', [ '^one', '^two' ]) The following strings will fail to validate, causing compilation to abort: validate_re('one', [ '^two', '^three' ]) A helpful error message can be returned like this: validate_re($::puppetversion, '^2.7', 'The $puppetversion fact value does not match 2.7') > *Note:* Compilation will also abort, if the first argument is not a String. Always use quotes to force stringification: validate_re("${::operatingsystemmajrelease}", '^[57]$') DOC - ) do |args| + ) do |args| 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) || (args.length > 3) raise Puppet::ParseError, "validate_re(): wrong number of arguments (#{args.length}; must be 2 or 3)" end raise Puppet::ParseError, "validate_re(): input needs to be a String, not a #{args[0].class}" unless args[0].is_a? String msg = args[2] || "validate_re(): #{args[0].inspect} does not match #{args[1].inspect}" # We're using a flattened array here because we can't call String#any? in # Ruby 1.9 like we can in Ruby 1.8 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 c28650f..c7d5bb6 100644 --- a/lib/puppet/parser/functions/validate_slength.rb +++ b/lib/puppet/parser/functions/validate_slength.rb @@ -1,73 +1,75 @@ +# frozen_string_literal: true + # # validate_slength.rb # module Puppet::Parser::Functions - newfunction(:validate_slength, :doc => <<-DOC + newfunction(:validate_slength, doc: <<-DOC @summary 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 argument is not a string or array of strings, and if arg 2 and arg 3 are not convertable to a number. @return validate that the first argument is a string (or an array of strings), and less/equal to than the length of the second argument. Fail compilation if any of the checks fail. @example **Usage** The following values will pass: validate_slength("discombobulate",17) validate_slength(["discombobulate","moo"],17) validate_slength(["discombobulate","moo"],17,3) The following valueis will not: validate_slength("discombobulate",1) validate_slength(["discombobulate","thermometer"],5) validate_slength(["discombobulate","moo"],17,10) DOC - ) do |args| + ) do |args| 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 || args.length == 3 input, max_length, min_length = *args begin max_length = Integer(max_length) raise ArgumentError if max_length <= 0 rescue ArgumentError, TypeError raise Puppet::ParseError, "validate_slength(): Expected second argument to be a positive Numeric, got #{max_length}:#{max_length.class}" end if min_length begin min_length = Integer(min_length) raise ArgumentError if min_length < 0 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 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 case input when String validator.call(input) when Array input.each_with_index do |arg, pos| 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}" end end end diff --git a/lib/puppet/parser/functions/validate_string.rb b/lib/puppet/parser/functions/validate_string.rb index f6c52a7..6dd9634 100644 --- a/lib/puppet/parser/functions/validate_string.rb +++ b/lib/puppet/parser/functions/validate_string.rb @@ -1,47 +1,49 @@ +# frozen_string_literal: true + # # validate_String.rb # module Puppet::Parser::Functions - newfunction(:validate_string, :doc => <<-DOC + newfunction(:validate_string, doc: <<-DOC @summary Validate that all passed values are string data structures @return Validate that all passed values are string data structures. Failed compilation if any value fails this check. @example **Usage** The following values will pass: $my_string = "one two" validate_string($my_string, 'three') The following values will fail, causing compilation to abort: validate_string(true) validate_string([ 'some', 'array' ]) > *Note:* Validate_string(undef) will not fail in this version of the functions API (incl. current and future parser). Instead, use: ``` if $var == undef { fail('...') } ``` DOC - ) do |args| + ) do |args| 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.']) 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}" 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 93388e0..a62ba37 100644 --- a/lib/puppet/parser/functions/validate_x509_rsa_key_pair.rb +++ b/lib/puppet/parser/functions/validate_x509_rsa_key_pair.rb @@ -1,50 +1,51 @@ +# frozen_string_literal: true + # # validate_x509_rsa_key_pair.rb # module Puppet::Parser::Functions - newfunction(:validate_x509_rsa_key_pair, :doc => <<-DOC + newfunction(:validate_x509_rsa_key_pair, doc: <<-DOC @summary 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. @return Fail compilation if any value fails this check. ```validate_x509_rsa_key_pair($cert, $key)``` DOC - ) do |args| - + ) do |args| require 'openssl' NUM_ARGS = 2 unless defined? NUM_ARGS unless args.length == NUM_ARGS raise Puppet::ParseError, "validate_x509_rsa_key_pair(): wrong number of arguments (#{args.length}; must be #{NUM_ARGS})" end args.each do |arg| unless arg.is_a?(String) raise Puppet::ParseError, "#{arg.inspect} is not a string." end end begin cert = OpenSSL::X509::Certificate.new(args[0]) rescue OpenSSL::X509::CertificateError => e raise Puppet::ParseError, "Not a valid x509 certificate: #{e}" end begin key = OpenSSL::PKey::RSA.new(args[1]) rescue OpenSSL::PKey::RSAError => e raise Puppet::ParseError, "Not a valid RSA key: #{e}" end unless cert.verify(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 434ce6c..a47fe52 100644 --- a/lib/puppet/parser/functions/values.rb +++ b/lib/puppet/parser/functions/values.rb @@ -1,43 +1,44 @@ +# frozen_string_literal: true + # # values.rb # module Puppet::Parser::Functions - newfunction(:values, :type => :rvalue, :doc => <<-DOC + newfunction(:values, type: :rvalue, doc: <<-DOC @summary When given a hash this function will return the values of that hash. @return array of values @example **Usage** $hash = { 'a' => 1, 'b' => 2, 'c' => 3, } values($hash) This example would return: ```[1,2,3]``` > *Note:* From Puppet 5.5.0, the compatible function with the same name in Puppet core will be used instead of this function. DOC - ) do |arguments| - + ) do |arguments| raise(Puppet::ParseError, "values(): Wrong number of arguments given (#{arguments.size} for 1)") if arguments.empty? hash = arguments[0] unless hash.is_a?(Hash) raise(Puppet::ParseError, 'values(): Requires hash to work with') end result = hash.values return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/values_at.rb b/lib/puppet/parser/functions/values_at.rb index 3371042..29301b8 100644 --- a/lib/puppet/parser/functions/values_at.rb +++ b/lib/puppet/parser/functions/values_at.rb @@ -1,99 +1,100 @@ +# frozen_string_literal: true + # # values_at.rb # module Puppet::Parser::Functions - newfunction(:values_at, :type => :rvalue, :doc => <<-DOC + newfunction(:values_at, type: :rvalue, doc: <<-DOC @summary 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: * A single numeric index * A range in the form of 'start-stop' (eg. 4-9) * An array combining the above @return an array of values identified by location @example **Usage** values_at(['a','b','c'], 2) Would return ['c'] values_at(['a','b','c'], ["0-1"]) Would return ['a','b'] values_at(['a','b','c','d','e'], [0, "2-3"]) Would return ['a','c','d'] > *Note:* Since Puppet 4.0.0 it is possible to slice an array with index and count directly in the language. A negative value is taken to be "from the end" of the array: `['a', 'b', 'c', 'd'][1, 2]` results in `['b', 'c']` `['a', 'b', 'c', 'd'][2, -1]` results in `['c', 'd']` `['a', 'b', 'c', 'd'][1, -2]` results in `['b', 'c']` DOC - ) do |arguments| - + ) do |arguments| raise(Puppet::ParseError, "values_at(): Wrong number of arguments given (#{arguments.size} for 2)") if arguments.size < 2 array = arguments.shift unless array.is_a?(Array) raise(Puppet::ParseError, 'values_at(): Requires array to work with') end indices = [arguments.shift].flatten # Get them all ... Pokemon ... if !indices || indices.empty? raise(Puppet::ParseError, 'values_at(): You must provide at least one positive index to collect') end indices_list = [] indices.each do |i| i = i.to_s m = i.match(%r{^(\d+)(\.\.\.?|\-)(\d+)$}) if m start = m[1].to_i stop = m[3].to_i type = m[2] 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 %r{^(\.\.|\-)$} then (start..stop) when %r{^(\.\.\.)$} then (start...stop) # Exclusive of last element ... end 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 ... - unless i =~ %r{^\d+$} + unless %r{^\d+$}.match?(i) raise(Puppet::ParseError, 'values_at(): Unknown format of given index') end # In Puppet numbers are often string-encoded ... i = i.to_i if i > array.size - 1 # Same story. First element is at index 0 ... raise(Puppet::ParseError, 'values_at(): Given index exceeds array size') end indices_list << i end end # We remove nil values as they make no sense in Puppet DSL ... result = indices_list.map { |i| array[i] }.compact return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/parser/functions/zip.rb b/lib/puppet/parser/functions/zip.rb index 120d097..1006183 100644 --- a/lib/puppet/parser/functions/zip.rb +++ b/lib/puppet/parser/functions/zip.rb @@ -1,37 +1,38 @@ +# frozen_string_literal: true + # # zip.rb # module Puppet::Parser::Functions - newfunction(:zip, :type => :rvalue, :doc => <<-DOC + newfunction(:zip, type: :rvalue, doc: <<-DOC @summary Takes one element from first array and merges corresponding elements from second array. @return This generates a sequence of n-element arrays, where n is one more than the count of arguments. @example zip(['1','2','3'],['4','5','6']) Would result in: ["1", "4"], ["2", "5"], ["3", "6"] DOC - ) 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 a = arguments[0] b = arguments[1] unless a.is_a?(Array) && b.is_a?(Array) raise(Puppet::ParseError, 'zip(): Requires array to work with') end flatten = function_str2bool([arguments[2]]) if arguments[2] result = a.zip(b) result = flatten ? result.flatten : result return result end end # vim: set ts=2 sw=2 et : diff --git a/lib/puppet/provider/file_line/ruby.rb b/lib/puppet/provider/file_line/ruby.rb index f85ae85..41e0531 100644 --- a/lib/puppet/provider/file_line/ruby.rb +++ b/lib/puppet/provider/file_line/ruby.rb @@ -1,180 +1,182 @@ +# frozen_string_literal: true + Puppet::Type.type(:file_line).provide(:ruby) do desc <<-DOC @summary This type allows puppet to manage small config files. The implementation matches the full line, including whitespace at the beginning and end. If the line is not contained in the given file, Puppet will append the line to the end of the file to ensure the desired state. Multiple resources may be declared to manage multiple lines in the same file. DOC def exists? found = false lines_count = 0 lines.each do |line| found = line.chomp == resource[:line] if found lines_count += 1 end end 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? resource[:replace].to_s == 'false' else true end elsif match_count.zero? if lines_count.zero? false else true end elsif lines_count.zero? resource[:match_for_absence].to_s == 'true' else true end end def create 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 def destroy if resource[:match_for_absence].to_s == 'true' && resource[:match] handle_destroy_with_match else handle_destroy_line end end private def lines # If this type is ever used with very large files, we should # write this in a different way, using a temp # file; for now assuming that this type is only used on # small-ish config files that can fit into memory without # too much trouble. - @lines ||= File.readlines(resource[:path], :encoding => resource[:encoding]) + @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 resource[:after] ? Regexp.new(resource[:after]) : nil end def new_match_regex resource[:match] ? Regexp.new(resource[:match]) : nil end def count_matches(regex) - lines.select { |line| + lines.count do |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 - }.size + end end 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]}'" end File.open(resource[:path], 'w') do |fh| lines.each do |line| fh.puts(match_regex.match(line) ? resource[:line] : line) 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.zero? fh.puts(resource[:line]) end end end def handle_create_with_after after_regex = new_after_regex after_count = count_matches(after_regex) if after_count > 1 && resource[:multiple].to_s != 'true' 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| lines.each do |line| fh.puts(line) if after_regex.match(line) fh.puts(resource[:line]) end end if after_count.zero? fh.puts(resource[:line]) end end end 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]}'" end local_lines = lines 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('')) end end def handle_append_line local_lines = lines File.open(resource[:path], 'w') do |fh| local_lines.each do |line| fh.puts(line) end fh.puts(resource[:line]) end end end diff --git a/lib/puppet/type/anchor.rb b/lib/puppet/type/anchor.rb index 7458a4b..8bd35d7 100644 --- a/lib/puppet/type/anchor.rb +++ b/lib/puppet/type/anchor.rb @@ -1,50 +1,52 @@ +# frozen_string_literal: true + Puppet::Type.newtype(:anchor) do desc <<-DOC @summary A simple resource type intended to be used as an anchor in a composite class. In Puppet 2.6, when a class declares another class, the resources in the interior class are not contained by the exterior class. This interacts badly with the pattern of composing complex modules from smaller classes, as it makes it impossible for end users to specify order relationships between the exterior class and other modules. The anchor type lets you work around this. By sandwiching any interior classes between two no-op resources that _are_ contained by the exterior class, you can ensure that all resources in the module are contained. ``` class ntp { # These classes will have the correct order relationship with each # other. However, without anchors, they won't have any order # relationship to Class['ntp']. class { 'ntp::package': } -> class { 'ntp::config': } -> class { 'ntp::service': } # These two resources "anchor" the composed classes within the ntp # class. anchor { 'ntp::begin': } -> Class['ntp::package'] Class['ntp::service'] -> anchor { 'ntp::end': } } ``` This allows the end user of the ntp module to establish require and before relationships with Class['ntp']: ``` class { 'ntp': } -> class { 'mcollective': } class { 'mcollective': } -> class { 'ntp': } ``` DOC newparam :name do desc 'The name of the anchor resource.' end def refresh # We don't do anything with them, but we need this to # show that we are "refresh aware" and not break the # chain of propagation. end end diff --git a/lib/puppet/type/file_line.rb b/lib/puppet/type/file_line.rb index ead6b10..00a6512 100644 --- a/lib/puppet/type/file_line.rb +++ b/lib/puppet/type/file_line.rb @@ -1,203 +1,205 @@ +# frozen_string_literal: true + Puppet::Type.newtype(:file_line) do desc <<-DOC @summary Ensures that a given line is contained within a file. The implementation matches the full line, including whitespace at the beginning and end. If the line is not contained in the given file, Puppet will append the line to the end of the file to ensure the desired state. Multiple resources may be declared to manage multiple lines in the same file. * Ensure Example ``` file_line { 'sudo_rule': path => '/etc/sudoers', line => '%sudo ALL=(ALL) ALL', } file_line { 'sudo_rule_nopw': path => '/etc/sudoers', line => '%sudonopw ALL=(ALL) NOPASSWD: ALL', } ``` In this example, Puppet will ensure both of the specified lines are contained in the file /etc/sudoers. * Match Example ``` file_line { 'bashrc_proxy': ensure => present, path => '/etc/bashrc', line => 'export HTTP_PROXY=http://squid.puppetlabs.vm:3128', match => '^export\ HTTP_PROXY\=', } ``` In this code example match will look for a line beginning with export followed by HTTP_PROXY and replace it with the value in line. * Examples With `ensure => absent`: This type has two behaviors when `ensure => absent` is set. One possibility is to set `match => ...` and `match_for_absence => true`, as in the following example: ``` file_line { 'bashrc_proxy': ensure => absent, path => '/etc/bashrc', match => '^export\ HTTP_PROXY\=', match_for_absence => true, } ``` In this code example match will look for a line beginning with export followed by HTTP_PROXY and delete it. If multiple lines match, an error will be raised unless the `multiple => true` parameter is set. Note that the `line => ...` parameter would be accepted BUT IGNORED in the above example. The second way of using `ensure => absent` is to specify a `line => ...`, and no match: ``` file_line { 'bashrc_proxy': ensure => absent, path => '/etc/bashrc', line => 'export HTTP_PROXY=http://squid.puppetlabs.vm:3128', } ``` > *Note:* When ensuring lines are absent this way, the default behavior this time is to always remove all lines matching, and this behavior can't be disabled. * Encoding example: ``` file_line { "XScreenSaver": ensure => present, path => '/root/XScreenSaver', line => "*lock: 10:00:00", match => '^*lock:', encoding => "iso-8859-1", } ``` Files with special characters that are not valid UTF-8 will give the error message "invalid byte sequence in UTF-8". In this case, determine the correct file encoding and specify the correct encoding using the encoding attribute, the value of which needs to be a valid Ruby character encoding. **Autorequires:** If Puppet is managing the file that will contain the line being managed, the file_line resource will autorequire that file. DOC ensurable do desc 'Manage the state of this type.' defaultvalues defaultto :present end - newparam(:name, :namevar => true) do + newparam(:name, namevar: true) do desc 'An arbitrary name used as the identity of the resource.' end newparam(: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 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. 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. 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) This is also takes a regex.' end # The line property never changes; the type only ever performs a create() or # destroy(). line is a property in order to allow it to correctly handle # Sensitive type values. Because it is a property which will never change, # it should never be considered out of sync. newproperty(:line) do desc 'The line to be appended to the file or used to replace matches found by the match attribute.' def retrieve @resource[:line] end end newparam(:path) do desc 'The file Puppet will ensure contains the line specified by the line parameter.' validate do |value| unless Puppet::Util.absolute_path?(value) raise Puppet::Error, "File paths must be fully qualified, not '#{value}'" end end end newparam(:replace) do desc 'If true, replace line that matches. If false, do not write line if a match is found' newvalues(true, false) defaultto true end newparam(:replace_all_matches_not_matching_line) do desc 'Configures the behavior of replacing all lines in a file which match the `match` parameter regular expression, regardless of whether the specified line is already present in the file.' newvalues(true, false) defaultto false end newparam(:encoding) do desc 'For files that are not UTF-8 encoded, specify encoding such as iso-8859-1' defaultto 'UTF-8' end newparam(:append_on_no_match) do desc 'If true, append line if match is not found. If false, do not append line if a match is not found' newvalues(true, false) defaultto true end # Autorequire the file resource if it's being managed autorequire(:file) do self[:path] end validate do 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' && 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') && (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') end end end diff --git a/metadata.json b/metadata.json index d28f5de..5f2566e 100644 --- a/metadata.json +++ b/metadata.json @@ -1,112 +1,112 @@ { "name": "puppetlabs-stdlib", "version": "6.6.0", "author": "puppetlabs", "summary": "Standard library of resources for Puppet modules.", "license": "Apache-2.0", "source": "https://github.com/puppetlabs/puppetlabs-stdlib", "project_page": "https://github.com/puppetlabs/puppetlabs-stdlib", "issues_url": "https://tickets.puppetlabs.com/browse/MODULES", "dependencies": [ ], "operatingsystem_support": [ { "operatingsystem": "RedHat", "operatingsystemrelease": [ "5", "6", "7", "8" ] }, { "operatingsystem": "CentOS", "operatingsystemrelease": [ "5", "6", "7", "8" ] }, { "operatingsystem": "OracleLinux", "operatingsystemrelease": [ "5", "6", "7" ] }, { "operatingsystem": "Scientific", "operatingsystemrelease": [ "6", "7" ] }, { "operatingsystem": "SLES", "operatingsystemrelease": [ "11", "12", "15" ] }, { "operatingsystem": "Debian", "operatingsystemrelease": [ "8", "9", "10" ] }, { "operatingsystem": "Ubuntu", "operatingsystemrelease": [ "14.04", "16.04", "18.04", "20.04" ] }, { "operatingsystem": "Solaris", "operatingsystemrelease": [ "10", "11" ] }, { "operatingsystem": "Windows", "operatingsystemrelease": [ "2008", "2008 R2", "2012", "2012 R2", "2016", "2019", "7", "8.1", "10" ] }, { "operatingsystem": "AIX", "operatingsystemrelease": [ "5.3", "6.1", "7.1" ] } ], "requirements": [ { "name": "puppet", "version_requirement": ">= 5.5.10 < 8.0.0" } ], "description": "Standard Library for Puppet Modules", "pdk-version": "1.18.1", "template-url": "https://github.com/puppetlabs/pdk-templates#main", - "template-ref": "heads/main-0-g5afcd3d" + "template-ref": "heads/main-0-g4543421" } diff --git a/spec/acceptance/anchor_spec.rb b/spec/acceptance/anchor_spec.rb index fda1674..9136b66 100644 --- a/spec/acceptance/anchor_spec.rb +++ b/spec/acceptance/anchor_spec.rb @@ -1,26 +1,28 @@ +# frozen_string_literal: true + require 'spec_helper_acceptance' describe 'anchor type' do let(:pp) do <<-MANIFEST class anchored { anchor { 'anchored::begin': } ~> anchor { 'anchored::end': } } class anchorrefresh { notify { 'first': } ~> class { 'anchored': } ~> anchor { 'final': } } include anchorrefresh MANIFEST end it 'applies manifest, anchors resources in correct order' do apply_manifest(pp) do |r| expect(r.stdout).to match(%r{Anchor\[final\]: Triggered 'refresh'}) end end end diff --git a/spec/acceptance/file_line_spec.rb b/spec/acceptance/file_line_spec.rb index d8068de..a322ab1 100644 --- a/spec/acceptance/file_line_spec.rb +++ b/spec/acceptance/file_line_spec.rb @@ -1,98 +1,100 @@ +# frozen_string_literal: true + require 'spec_helper_acceptance' describe 'file_line type' do let(:test_file) { (os[:family] == 'windows') ? 'C:\test\file_line_test.txt' : '/tmp/test/testfile_line_test.txt' } before(:all) do apply_manifest(<<-MANIFEST) case($facts['os']['family']) { windows: { file { 'C:\\test': ensure => directory } } default: { file { '/tmp/test': ensure => directory } } } MANIFEST end before(:each) do pp_test_file = <<-MANIFEST file { '#{test_file}': ensure => present, content => 'a wild test file has appeared!', } MANIFEST apply_manifest(pp_test_file) end context 'ensure line' do let(:pp) do <<-MANIFEST file_line { 'test_ensure': path => '#{test_file}', line => 'test file uses attack!', } MANIFEST end it 'applies manifest, adds line' do idempotent_apply(pp) expect(file(test_file)).to be_file expect(file(test_file).content).to match(%r{test file uses attack!}) end end context 'matches and replaces line' do let(:pp) do <<-MANIFEST file_line { 'test_match': path => '#{test_file}', line => 'a tame test file has appeared!', match => '^a wild', } MANIFEST end it 'applies manifest, replaces line' do idempotent_apply(pp) expect(file(test_file)).to be_file expect(file(test_file).content).to match(%r{a tame test file has appeared!}) end end context 'remove line' do context 'using match' do let(:pp) do <<-MANIFEST file_line { 'test_absent_match': ensure => absent, path => '#{test_file}', match => '^a wild', match_for_absence => true, } MANIFEST end it 'applies manifest, removes line' do idempotent_apply(pp) expect(file(test_file)).to be_file expect(file(test_file).content).to be_empty end end context 'using line' do let(:pp) do <<-MANIFEST file_line { 'test_absent_line': ensure => absent, path => '#{test_file}', line => 'a wild test file has appeared!', } MANIFEST end it 'applies manifest, removes line' do idempotent_apply(pp) expect(file(test_file)).to be_file expect(file(test_file).content).to be_empty end end end end diff --git a/spec/functions/abs_spec.rb b/spec/functions/abs_spec.rb index 24dfa2f..0044864 100644 --- a/spec/functions/abs_spec.rb +++ b/spec/functions/abs_spec.rb @@ -1,14 +1,16 @@ +# frozen_string_literal: true + require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 describe 'abs' do it { is_expected.not_to eq(nil) } 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) } end end diff --git a/spec/functions/any2array_spec.rb b/spec/functions/any2array_spec.rb index a795672..7ddf67b 100644 --- a/spec/functions/any2array_spec.rb +++ b/spec/functions/any2array_spec.rb @@ -1,21 +1,23 @@ +# frozen_string_literal: true + require 'spec_helper' 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([]).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('‰').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('€', '万', 'Ö', '♥', '割').and_return(['€', '万', 'Ö', '♥', '割']) } end diff --git a/spec/functions/any2bool_spec.rb b/spec/functions/any2bool_spec.rb index 4de9d21..ff06a68 100644 --- a/spec/functions/any2bool_spec.rb +++ b/spec/functions/any2bool_spec.rb @@ -1,41 +1,43 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'any2bool' do it { is_expected.not_to eq(nil) } 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) } 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| 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| 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| 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| 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 ee7db0b..cb1e896 100644 --- a/spec/functions/assert_private_spec.rb +++ b/spec/functions/assert_private_spec.rb @@ -1,38 +1,40 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'assert_private' do context 'when called from inside module' do it 'does not fail' do expect(scope).to receive(:lookupvar).with('module_name').and_return('foo') expect(scope).to receive(:lookupvar).with('caller_module_name').and_return('foo') is_expected.to run.with_params end end context 'when called from private class' do it 'fails with a class error message' do expect(scope).to receive(:lookupvar).with('module_name').and_return('foo') expect(scope).to receive(:lookupvar).with('caller_module_name').and_return('bar') expect(scope.source).to receive(:name).and_return('foo::baz') expect(scope.source).to receive(:type).and_return('hostclass') is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{Class foo::baz is private}) end it 'fails with an explicit failure message' do 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 'fails with a class error message' do expect(scope).to receive(:lookupvar).with('module_name').and_return('foo') expect(scope).to receive(:lookupvar).with('caller_module_name').and_return('bar') expect(scope.source).to receive(:name).and_return('foo::baz') expect(scope.source).to receive(:type).and_return('definition') 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 dafab36..3a10811 100644 --- a/spec/functions/base64_spec.rb +++ b/spec/functions/base64_spec.rb @@ -1,60 +1,62 @@ +# frozen_string_literal: true + require 'spec_helper' 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, %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 a2a12a1..3f52060 100644 --- a/spec/functions/basename_spec.rb +++ b/spec/functions/basename_spec.rb @@ -1,19 +1,21 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'basename' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{No arguments given}) } it { is_expected.to run.with_params('one', 'two', 'three').and_raise_error(Puppet::ParseError, %r{Too many arguments given}) } it { is_expected.to run.with_params([]).and_raise_error(Puppet::ParseError, %r{Requires string as first argument}) } it { is_expected.to run.with_params('/path/to/a/file.ext', []).and_raise_error(Puppet::ParseError, %r{Requires string as second argument}) } it { is_expected.to run.with_params('/path/to/a/file.ext').and_return('file.ext') } it { is_expected.to run.with_params('relative_path/to/a/file.ext').and_return('file.ext') } it { is_expected.to run.with_params('/path/to/a/file.ext', '.ext').and_return('file') } it { is_expected.to run.with_params('relative_path/to/a/file.ext', '.ext').and_return('file') } it { is_expected.to run.with_params('scheme:///path/to/a/file.ext').and_return('file.ext') } context 'with UTF8 and double byte characters' do it { is_expected.to run.with_params('scheme:///√ạĺűē/竹.ext').and_return('竹.ext') } it { is_expected.to run.with_params('ҝẽγ:/√ạĺűē/竹.ㄘ', '.ㄘ').and_return('竹') } end end diff --git a/spec/functions/bool2num_spec.rb b/spec/functions/bool2num_spec.rb index 7402f3a..63a664b 100644 --- a/spec/functions/bool2num_spec.rb +++ b/spec/functions/bool2num_spec.rb @@ -1,18 +1,20 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'bool2num' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError) } [true, 'true', 't', '1', 'y', 'yes', AlsoString.new('true')].each do |truthy| it { is_expected.to run.with_params(truthy).and_return(1) } end [false, 'false', 'f', '0', 'n', 'no', AlsoString.new('false')].each do |falsey| it { is_expected.to run.with_params(falsey).and_return(0) } end [[], 10, 'invalid', 1.0].each do |falsey| it { is_expected.to run.with_params(falsey).and_raise_error(Puppet::ParseError) } end end diff --git a/spec/functions/bool2str_spec.rb b/spec/functions/bool2str_spec.rb index 8d8f9b5..013d551 100644 --- a/spec/functions/bool2str_spec.rb +++ b/spec/functions/bool2str_spec.rb @@ -1,16 +1,18 @@ +# frozen_string_literal: true + require 'spec_helper' 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(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') } end diff --git a/spec/functions/camelcase_spec.rb b/spec/functions/camelcase_spec.rb index e0e4003..aa78fcb 100644 --- a/spec/functions/camelcase_spec.rb +++ b/spec/functions/camelcase_spec.rb @@ -1,17 +1,19 @@ +# frozen_string_literal: true + require 'spec_helper' -describe 'camelcase', :if => Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do +describe 'camelcase', if: Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 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(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([]).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']) } end diff --git a/spec/functions/capitalize_spec.rb b/spec/functions/capitalize_spec.rb index dd5fc35..f67c8be 100644 --- a/spec/functions/capitalize_spec.rb +++ b/spec/functions/capitalize_spec.rb @@ -1,15 +1,17 @@ +# frozen_string_literal: true + require 'spec_helper' -describe 'capitalize', :if => Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do +describe 'capitalize', if: Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 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(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(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']) } end diff --git a/spec/functions/ceiling_spec.rb b/spec/functions/ceiling_spec.rb index 7f9a045..5e5f34c 100644 --- a/spec/functions/ceiling_spec.rb +++ b/spec/functions/ceiling_spec.rb @@ -1,13 +1,15 @@ +# frozen_string_literal: true + require 'spec_helper' -describe 'ceiling', :if => Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do +describe 'ceiling', if: Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{Wrong number of arguments}) } it { is_expected.to run.with_params('foo').and_raise_error(Puppet::ParseError, %r{Wrong argument type given}) } it { is_expected.to run.with_params([]).and_raise_error(Puppet::ParseError, %r{Wrong argument type given}) } 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) } it { is_expected.to run.with_params('33.1').and_return(34) } end diff --git a/spec/functions/chomp_spec.rb b/spec/functions/chomp_spec.rb index 2137c61..68b7cd3 100644 --- a/spec/functions/chomp_spec.rb +++ b/spec/functions/chomp_spec.rb @@ -1,27 +1,29 @@ +# frozen_string_literal: true + require 'spec_helper' -describe 'chomp', :if => Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do +describe 'chomp', if: Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{Wrong number of arguments given}) } it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{Requires either array or string}) } it { 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\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(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([1, 2, 3]).and_return([1, 2, 3]) } context 'with UTF8 and double byte characters' do it { is_expected.to run.with_params("ůťƒ8\n\n").and_return("ůťƒ8\n") } it { is_expected.to run.with_params("ネット\n\n").and_return("ネット\n") } end end diff --git a/spec/functions/chop_spec.rb b/spec/functions/chop_spec.rb index be90981..2cbccd1 100644 --- a/spec/functions/chop_spec.rb +++ b/spec/functions/chop_spec.rb @@ -1,27 +1,29 @@ +# frozen_string_literal: true + require 'spec_helper' -describe 'chop', :if => Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do +describe 'chop', if: Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{Wrong number of arguments}) } it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{Requires either an array or string}) } it { 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\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(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([1, 2, 3]).and_return([1, 2, 3]) } context 'with UTF8 and double byte characters' do it { is_expected.to run.with_params("ůťƒ8\n\n").and_return("ůťƒ8\n") } it { is_expected.to run.with_params("ネット\n\n").and_return("ネット\n") } end end diff --git a/spec/functions/clamp_spec.rb b/spec/functions/clamp_spec.rb index 6380b29..37b4935 100644 --- a/spec/functions/clamp_spec.rb +++ b/spec/functions/clamp_spec.rb @@ -1,17 +1,19 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'clamp' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(ArgumentError, %r{Wrong number of arguments}) } it { is_expected.to run.with_params([]).and_raise_error(Puppet::ParseError, %r{Wrong number of arguments}) } 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) } it { is_expected.to run.with_params([3, 873], 73).and_return(73) } it { is_expected.to run.with_params([4], 8, 75).and_return(8) } it { is_expected.to run.with_params([6], [31], 9911).and_return(31) } end diff --git a/spec/functions/concat_spec.rb b/spec/functions/concat_spec.rb index 9290d40..d0893e9 100644 --- a/spec/functions/concat_spec.rb +++ b/spec/functions/concat_spec.rb @@ -1,28 +1,30 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'concat' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{Wrong number of arguments}) } it { is_expected.to run.with_params([1]).and_raise_error(Puppet::ParseError, %r{Wrong number of arguments}) } it { is_expected.to run.with_params(1, [2]).and_raise_error(Puppet::ParseError, %r{Requires array}) } 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']) } context '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 arguments = [['1', '2', '3'], ['4', '5', '6']] originals = [arguments[0].dup, arguments[1].dup] it 'leaves the original array intact' do _result = subject.execute(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 d1a6cef..a2de736 100644 --- a/spec/functions/convert_base_spec.rb +++ b/spec/functions/convert_base_spec.rb @@ -1,24 +1,26 @@ +# frozen_string_literal: true + require 'spec_helper' 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, %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 '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 '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(5, 2).and_return('101') } end diff --git a/spec/functions/count_spec.rb b/spec/functions/count_spec.rb index 54e1491..564974a 100644 --- a/spec/functions/count_spec.rb +++ b/spec/functions/count_spec.rb @@ -1,23 +1,25 @@ +# frozen_string_literal: true + require 'spec_helper' 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 { 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(['ổņ℮', 'ŧщộ', '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 489bca5..bd40d67 100644 --- a/spec/functions/deep_merge_spec.rb +++ b/spec/functions/deep_merge_spec.rb @@ -1,58 +1,60 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'deep_merge' do 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') } describe 'when arguments have key collisions' 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') end 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' => { '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' } }) } end arguments = { 'key1' => 'value1' }, { 'key2' => 'value2' } originals = [arguments[0].dup, arguments[1].dup] it 'does not change the original hashes' do subject.execute(arguments[0], arguments[1]) arguments.each_with_index do |argument, index| expect(argument).to eq(originals[index]) end end context 'with UTF8 and double byte characters' do 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 36a627d..e372cd3 100644 --- a/spec/functions/defined_with_params_spec.rb +++ b/spec/functions/defined_with_params_spec.rb @@ -1,129 +1,131 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'defined_with_params' do describe 'when no resource is specified' do 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) } context 'with UTF8 and double byte characters' do it { is_expected.to run.with_params('User[ĵĭмოү]', {}).and_return(false) } it { is_expected.to run.with_params('User[ポーラ]', {}).and_return(false) } end end describe 'when compared against a resource with attributes' do 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) } end describe 'when passing undef values' do let :pre_condition do 'file { "/tmp/a": ensure => present }' end let(:is_puppet_6_or_greater) { Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') >= 0 } let(:undef_value) { is_puppet_6_or_greater ? nil : :undef } # even if :undef would work on 6.0.1, :undef should not be used 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_value).and_return(true) } end describe 'when the reference is a' do let :pre_condition do 'user { "dan": }' end context 'with reference' do it { is_expected.to run.with_params(Puppet::Resource.new('User[dan]'), {}).and_return(true) } end if Puppet::Util::Package.versioncmp(Puppet.version, '4.6.0') >= 0 context 'with array' do it 'fails' do expect { subject.execute(['User[dan]'], {}) }.to raise_error(ArgumentError, %r{not understood: 'Array'}) end end end end describe 'when passed a defined type' do let :pre_condition do <<-PRECOND define test::deftype( Optional $port = undef ) { } test::deftype { "foo": } test::deftype { "baz": port => 100 } test::deftype { "adv": port => 200 } test::deftype { "adv2": port => 200 } # Unsure how to stub this out below properly if defined_with_params(Test::Deftype, { 'port' => 200 }) { notify { 'Duplicate found somewhere': } } if defined_with_params(Test::Deftype, { 'port' => 'nope' }) { notify { 'Should not find me': } } PRECOND 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) } it { is_expected.to run.with_params(Puppet::Resource.new('Test::Deftype[bar]'), {}).and_return(false) expect(catalogue.resource('Notify[Duplicate found somewhere]')).not_to be_nil expect(catalogue.resource('Notify[Should not find me]')).to be_nil } end describe 'when called from within a defined type looking for a defined type of the same type' do let :pre_condition do <<-PRECOND define test::deftype( Optional $port = undef ) { if defined_with_params(Test::Deftype, { 'port' => $port }) { fail('Ruh Roh Shaggy') } } test::deftype { 'foo': } test::deftype { 'bar': port => 200 } PRECOND end # Testing to make sure that the internal logic handles this case via the pre_condition it { is_expected.to run.with_params('NoOp[noop]', {}).and_return(false) } end describe 'when passed a class' do let :pre_condition do 'class test () { } class { "test": }' end it { is_expected.to run.with_params('Class[test]', {}).and_return(true) } it { is_expected.to run.with_params('Class["bar"]', {}).and_return(false) } it { is_expected.to run.with_params('Class[bar]', {}).and_return(false) } it { is_expected.to run.with_params(Puppet::Resource.new('class', 'test'), {}).and_return(true) } it { is_expected.to run.with_params(Puppet::Resource.new('Class["bar"]'), {}).and_return(false) } it { is_expected.to run.with_params(Puppet::Resource.new('Class[bar]'), {}).and_return(false) } end end diff --git a/spec/functions/delete_at_spec.rb b/spec/functions/delete_at_spec.rb index 89359b1..7bc7140 100644 --- a/spec/functions/delete_at_spec.rb +++ b/spec/functions/delete_at_spec.rb @@ -1,29 +1,31 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'delete_at' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{Wrong number of arguments}) } it { is_expected.to run.with_params('one', 1).and_raise_error(Puppet::ParseError, %r{Requires array}) } it { is_expected.to run.with_params(1, 1).and_raise_error(Puppet::ParseError, %r{Requires array}) } it { is_expected.to run.with_params(['one'], 'two').and_raise_error(Puppet::ParseError, %r{You must provide non-negative numeric}) } it { pending('Current implementation ignores parameters after the first two.') is_expected.to run.with_params(['one'], 0, 1).and_raise_error(Puppet::ParseError) } describe 'argument validation' do it { is_expected.to run.with_params([0, 1, 2], 3).and_raise_error(Puppet::ParseError, %r{Given index exceeds size of array}) } end 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 'leaves the original array intact' do argument = [1, 2, 3] original = argument.dup _result = subject.execute(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 8e16b0b..ab9516f 100644 --- a/spec/functions/delete_regex_spec.rb +++ b/spec/functions/delete_regex_spec.rb @@ -1,55 +1,57 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'delete_regex' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{Wrong number of arguments}) } it { is_expected.to run.with_params([]).and_raise_error(Puppet::ParseError, %r{Wrong number of arguments}) } it { is_expected.to run.with_params([], 'two') } it { is_expected.to run.with_params({}, 'two') } it { is_expected.to run.with_params([], 'two', 'three').and_raise_error(Puppet::ParseError, %r{Wrong number of arguments}) } it { is_expected.to run.with_params(1, 'two').and_raise_error(TypeError, %r{First argument must be an Array, Hash, or String}) } describe 'deleting from an array' do 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(['abracadabra'], 'abr').and_return(['abracadabra']) } it { is_expected.to run.with_params(['abracadabra'], '^.*jimbob.*$').and_return(['abracadabra']) } 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({ 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3' }, ['key1', 'key2']) \ .and_return('key3' => 'value3') } end it 'leaves the original array intact' do argument1 = ['one', 'two', 'three'] original1 = argument1.dup subject.execute(argument1, 'two') expect(argument1).to eq(original1) end it 'leaves the original hash intact' do argument1 = { 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3' } original1 = argument1.dup subject.execute(argument1, 'key2') expect(argument1).to eq(original1) end end diff --git a/spec/functions/delete_spec.rb b/spec/functions/delete_spec.rb index df5ee7a..5fe7825 100644 --- a/spec/functions/delete_spec.rb +++ b/spec/functions/delete_spec.rb @@ -1,79 +1,81 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'delete' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{Wrong number of arguments}) } it { is_expected.to run.with_params([]).and_raise_error(Puppet::ParseError, %r{Wrong number of arguments}) } it { is_expected.to run.with_params([], 'two') } it { is_expected.to run.with_params([], 'two', 'three').and_raise_error(Puppet::ParseError, %r{Wrong number of arguments}) } it { is_expected.to run.with_params(1, 'two').and_raise_error(TypeError, %r{First argument must be an Array, String, or Hash}) } describe 'deleting from an array' do 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(['ŧңŗё℮']) } end describe 'deleting from a string' do it { is_expected.to run.with_params('', '').and_return('') } it { is_expected.to run.with_params('bar', '').and_return('bar') } it { is_expected.to run.with_params('', 'bar').and_return('') } it { is_expected.to run.with_params('bar', 'bar').and_return('') } 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('barfoobar', ['barbar', 'foo']).and_return('barbar') } it { is_expected.to run.with_params('barfoobar', ['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({ 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3' }, ['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') } end it 'leaves the original array intact' do argument1 = ['one', 'two', 'three'] original1 = argument1.dup _result = subject.execute(argument1, 'two') expect(argument1).to eq(original1) end it 'leaves the original string intact' do argument1 = 'onetwothree' original1 = argument1.dup _result = subject.execute(argument1, 'two') expect(argument1).to eq(original1) end it 'leaves the original hash intact' do argument1 = { 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3' } original1 = argument1.dup _result = subject.execute(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 1294579..068217f 100644 --- a/spec/functions/delete_undef_values_spec.rb +++ b/spec/functions/delete_undef_values_spec.rb @@ -1,61 +1,63 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'delete_undef_values' do let(:is_puppet_6) { Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') == 0 } it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{Wrong number of arguments}) } it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{expected an array or hash}) } it { is_expected.to run.with_params('one').and_raise_error(Puppet::ParseError, %r{expected an array or hash}) } it { is_expected.to run.with_params('one', 'two').and_raise_error(Puppet::ParseError, %r{expected an array or hash}) } describe 'when deleting from an array' do # Behavior is different in Puppet 6.0.0, and fixed in PUP-9180 in Puppet 6.0.1 [:undef, '', nil].each do |undef_value| describe "when undef is represented by #{undef_value.inspect}" 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 == :undef && is_puppet_6 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(['ớņέ', 'ŧשּׁō', 'ŧħґëə']) } end it 'leaves the original argument intact' do argument = ['one', undef_value, 'two'] original = argument.dup _result = subject.execute(argument, 2) expect(argument).to eq(original) end end it { is_expected.to run.with_params(['undef']).and_return(['undef']) } end describe 'when deleting from a hash' do [:undef, '', nil].each do |undef_value| describe "when undef is represented by #{undef_value.inspect}" 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 == :undef && is_puppet_6 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') } end it 'leaves the original argument intact' do argument = { 'key1' => 'value1', 'key2' => undef_value } original = argument.dup _result = subject.execute(argument, 2) expect(argument).to eq(original) end end 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 3ee3af1..4a48893 100644 --- a/spec/functions/delete_values_spec.rb +++ b/spec/functions/delete_values_spec.rb @@ -1,45 +1,47 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'delete_values' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{Wrong number of arguments}) } it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{Wrong number of arguments}) } it { is_expected.to run.with_params('one').and_raise_error(Puppet::ParseError, %r{Wrong number of arguments}) } it { is_expected.to run.with_params('one', 'two', 'three').and_raise_error(Puppet::ParseError, %r{Wrong number of arguments}) } describe 'when the first argument is not a hash' do it { is_expected.to run.with_params(1, 'two').and_raise_error(TypeError, %r{First argument must be a Hash}) } it { is_expected.to run.with_params('one', 'two').and_raise_error(TypeError, %r{First argument must be a Hash}) } it { is_expected.to run.with_params([], 'two').and_raise_error(TypeError, %r{First argument must be a Hash}) } end 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({ 'ҝếỵ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' => 'value to delete', 'key3' => 'value to delete' }, 'value to delete') \ .and_return('key1' => 'value1') } end it 'leaves the original argument intact' do argument = { 'key1' => 'value1', 'key2' => 'value2' } original = argument.dup _result = subject.execute(argument, 'value2') expect(argument).to eq(original) end end diff --git a/spec/functions/deprecation_spec.rb b/spec/functions/deprecation_spec.rb index 50203c9..d03b5e2 100644 --- a/spec/functions/deprecation_spec.rb +++ b/spec/functions/deprecation_spec.rb @@ -1,73 +1,75 @@ +# frozen_string_literal: true + require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'deprecation' do 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 'displays a single warning' do if Puppet::Util::Package.versioncmp(Puppet.version, '5.0.0') >= 0 && Puppet::Util::Package.versioncmp(Puppet.version, '5.5.7') < 0 expect(Puppet).to receive(:deprecation_warning).with('heelo at :', 'key') expect(Puppet).to receive(:deprecation_warning).with("Modifying 'autosign' as a setting is deprecated.") else expect(Puppet).to receive(:warning).with(include('heelo')).once end is_expected.to run.with_params('key', 'heelo') end it 'displays a single warning, despite multiple calls' do if Puppet::Util::Package.versioncmp(Puppet.version, '5.0.0') >= 0 && Puppet::Util::Package.versioncmp(Puppet.version, '5.5.7') < 0 expect(Puppet).to receive(:deprecation_warning).with('heelo at :', 'key').twice expect(Puppet).to receive(:deprecation_warning).with("Modifying 'autosign' as a setting is deprecated.") else expect(Puppet).to receive(:warning).with(include('heelo')).once end (0..1).each do |_i| is_expected.to run.with_params('key', 'heelo') end end it 'fails twice with message, with multiple calls. when strict= :error' do Puppet.settings[:strict] = :error expect(Puppet).to receive(:warning).with(include('heelo')).never (0..1).each do |_i| is_expected.to run.with_params('key', 'heelo').and_raise_error(RuntimeError, %r{deprecation. key. heelo}) end end it 'displays nothing, despite multiple calls. strict= :off' do Puppet.settings[:strict] = :off expect(Puppet).to receive(:warning).with(include('heelo')).never (0..1).each do |_i| is_expected.to run.with_params('key', 'heelo') end end 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(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end 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, %r{wrong number of arguments}i) } it 'displays a single warning' do expect(scope).to receive(:warning).with(include('heelo')) is_expected.to run.with_params('key', 'heelo') end end end diff --git a/spec/functions/difference_spec.rb b/spec/functions/difference_spec.rb index b30437e..292023c 100644 --- a/spec/functions/difference_spec.rb +++ b/spec/functions/difference_spec.rb @@ -1,22 +1,24 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'difference' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{Wrong number of arguments}) } it { is_expected.to run.with_params('one').and_raise_error(Puppet::ParseError, %r{Wrong number of arguments}) } it { is_expected.to run.with_params('one', 'two').and_raise_error(Puppet::ParseError, %r{Requires 2 arrays}) } it { is_expected.to run.with_params('one', []).and_raise_error(Puppet::ParseError, %r{Requires 2 arrays}) } it { is_expected.to run.with_params({}, {}).and_raise_error(Puppet::ParseError, %r{Requires 2 arrays}) } it { is_expected.to run.with_params([], []).and_return([]) } it { is_expected.to run.with_params([], ['one']).and_return([]) } 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 'does not confuse types' do is_expected.to run.with_params(['1', '2', '3'], [1, 2]).and_return(['1', '2', '3']) end end diff --git a/spec/functions/dig44_spec.rb b/spec/functions/dig44_spec.rb index e7c6d81..576935f 100644 --- a/spec/functions/dig44_spec.rb +++ b/spec/functions/dig44_spec.rb @@ -1,132 +1,134 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'dig44' do let(:undef_value) do (Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0) ? :undef : nil end let(:data) do { 'a' => { 'g' => '2', 'e' => [ 'f0', 'f1', { 'x' => { 'y' => 'z', }, }, 'f3', ], }, 'b' => true, 'c' => false, 'd' => '1', 'e' => undef_value, 'f' => nil, } end let(:utf8_data) do { 'ẵ' => { 'в' => [ '©', 'ĝ', 'に', ], }, } end context 'with single values' do it 'exists' do is_expected.not_to be_nil end it 'requires two arguments' do is_expected.to run.with_params.and_raise_error(ArgumentError, %r{Wrong number of arguments}) end it 'fails if the data is not a structure' do is_expected.to run.with_params('test', []).and_raise_error(Puppet::Error, %r{first argument must be a hash or an array}) end it 'fails if the path is not an array' do is_expected.to run.with_params({}, '').and_raise_error(Puppet::Error, %r{second argument must be an array}) end it 'returns the value if the value is string' do is_expected.to run.with_params(data, ['d'], 'default').and_return('1') end it 'returns true if the value is true' do is_expected.to run.with_params(data, ['b'], 'default').and_return(true) end it 'returns false if the value is false' do is_expected.to run.with_params(data, ['c'], 'default').and_return(false) end it 'returns the default if the value is nil' do is_expected.to run.with_params(data, ['f'], 'default').and_return('default') end 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 '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 'with structured values' 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 '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 '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 'supports an array index (string) in the path' do is_expected.to run.with_params(data, ['a', 'e', '1'], 'default').and_return('f1') end 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 '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 '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 '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 end context 'with internationalization (i18N) values' do it 'is able to return a unicode character' do is_expected.to run.with_params(utf8_data, ['ẵ', 'в', 0]).and_return('©') end it 'is able to return a utf8 character' do is_expected.to run.with_params(utf8_data, ['ẵ', 'в', 1]).and_return('ĝ') end it 'is able to return a double byte character' do is_expected.to run.with_params(utf8_data, ['ẵ', 'в', 2]).and_return('に') end end end diff --git a/spec/functions/dig_spec.rb b/spec/functions/dig_spec.rb index ac2b6e4..a11ab7e 100644 --- a/spec/functions/dig_spec.rb +++ b/spec/functions/dig_spec.rb @@ -1,12 +1,14 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'dig' do it 'exists' do expect(Puppet::Parser::Functions.function('dig')).to eq('function_dig') end it 'gives a deprecation warning when called' do expect(scope).to receive(: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 cda15c8..a801f1c 100644 --- a/spec/functions/dirname_spec.rb +++ b/spec/functions/dirname_spec.rb @@ -1,20 +1,22 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'dirname' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{No arguments given}) } it { is_expected.to run.with_params('one', 'two').and_raise_error(Puppet::ParseError, %r{Too many arguments given}) } it { is_expected.to run.with_params([]).and_raise_error(Puppet::ParseError, %r{Requires string as argument}) } it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, %r{Requires string as argument}) } it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{Requires string as argument}) } it { is_expected.to run.with_params('').and_raise_error(Puppet::ParseError, %r{Requires a non-empty string as argument}) } it { is_expected.to run.with_params(:undef).and_raise_error(Puppet::ParseError, %r{string as argument}) } it { is_expected.to run.with_params(nil).and_raise_error(Puppet::ParseError, %r{string as argument}) } it { is_expected.to run.with_params('/path/to/a/file.ext').and_return('/path/to/a') } it { is_expected.to run.with_params('relative_path/to/a/file.ext').and_return('relative_path/to/a') } context 'with UTF8 and double byte characters' do it { is_expected.to run.with_params('scheme:///√ạĺűē/竹.ext').and_return('scheme:///√ạĺűē') } it { is_expected.to run.with_params('ҝẽγ:/√ạĺűē/竹.ㄘ').and_return('ҝẽγ:/√ạĺűē') } end end diff --git a/spec/functions/dos2unix_spec.rb b/spec/functions/dos2unix_spec.rb index 4b04f5b..d86d93b 100644 --- a/spec/functions/dos2unix_spec.rb +++ b/spec/functions/dos2unix_spec.rb @@ -1,47 +1,49 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'dos2unix' do context 'when checking parameter validity' do it { is_expected.not_to eq(nil) } it do 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, %r{Wrong number of arguments}) end it do is_expected.to run.with_params([]).and_raise_error(Puppet::ParseError, %r{Requires string as argument}) end it do is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, %r{Requires string as argument}) end it do is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{Requires string as argument}) end end context 'when converting from dos to unix format' do sample_text = "Hello\r\nWorld\r\n" desired_output = "Hello\nWorld\n" it 'outputs unix format' do is_expected.to run.with_params(sample_text).and_return(desired_output) end end context 'with internationalization (i18N) values' do sample_text_utf8 = "Ħ℮ļłǿ\r\nשׁөŕłđ\r\n" desired_output_utf8 = "Ħ℮ļłǿ\nשׁөŕłđ\n" sample_text_doublebyte = "こんにちは\r\n世界\r\n" desired_output_doublebyte = "こんにちは\n世界\n" it 'outputs uft8 string' do is_expected.to run.with_params(sample_text_utf8).and_return(desired_output_utf8) end 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 181e282..07c6374 100644 --- a/spec/functions/downcase_spec.rb +++ b/spec/functions/downcase_spec.rb @@ -1,15 +1,17 @@ +# frozen_string_literal: true + require 'spec_helper' -describe 'downcase', :if => Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do +describe 'downcase', if: Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{Wrong number of arguments}) } it { is_expected.to run.with_params(100).and_raise_error(Puppet::ParseError, %r{Requires either array or string}) } 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([]).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']) } end diff --git a/spec/functions/empty_spec.rb b/spec/functions/empty_spec.rb index 695c8a5..5b0ba29 100644 --- a/spec/functions/empty_spec.rb +++ b/spec/functions/empty_spec.rb @@ -1,23 +1,25 @@ +# frozen_string_literal: true + require 'spec_helper' -describe 'empty', :if => Puppet::Util::Package.versioncmp(Puppet.version, '5.5.0') < 0 do +describe 'empty', if: Puppet::Util::Package.versioncmp(Puppet.version, '5.5.0') < 0 do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{Wrong number of arguments}) } it { 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(false).and_raise_error(Puppet::ParseError, %r{Requires either array, hash, string or integer}) } it { is_expected.to run.with_params(0).and_return(false) } it { is_expected.to run.with_params('').and_return(true) } it { is_expected.to run.with_params('one').and_return(false) } it { is_expected.to run.with_params(AlsoString.new('')).and_return(true) } it { is_expected.to run.with_params(AlsoString.new('one')).and_return(false) } it { is_expected.to run.with_params([]).and_return(true) } 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) } end diff --git a/spec/functions/end_with_spec.rb b/spec/functions/end_with_spec.rb index 5c1e8a9..19c4ed6 100644 --- a/spec/functions/end_with_spec.rb +++ b/spec/functions/end_with_spec.rb @@ -1,13 +1,15 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'stdlib::end_with' do it { is_expected.to run.with_params('', 'bar').and_return(false) } it { is_expected.to run.with_params('foobar', 'bar').and_return(true) } it { is_expected.to run.with_params('foobar', 'foo').and_return(false) } it { is_expected.to run.with_params('foobar', ['foo', 'baz']).and_return(false) } it do is_expected.to run.with_params('foobar', '').and_raise_error( ArgumentError, %r{'stdlib::end_with' parameter 'suffixes' expects a value of type String\[1\] or Array\[String\[1\], 1\]} ) end end diff --git a/spec/functions/ensure_packages_spec.rb b/spec/functions/ensure_packages_spec.rb index 6d1a841..1f6b85d 100644 --- a/spec/functions/ensure_packages_spec.rb +++ b/spec/functions/ensure_packages_spec.rb @@ -1,72 +1,74 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'ensure_packages' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError) } it { 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) } it { is_expected.to run.with_params('packagename') } it { is_expected.to run.with_params(['packagename1', 'packagename2']) } context 'when given a catalog with "package { puppet: ensure => absent }"' do let(:pre_condition) { 'package { puppet: ensure => absent }' } describe 'after running ensure_package("facter")' do before(:each) { subject.execute('facter') } # this lambda is required due to strangeness within rspec-puppet's expectation handling 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(:each) { subject.execute('facter', 'provider' => 'gem') } # this lambda is required due to strangeness within rspec-puppet's expectation handling 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 context 'when given an empty packages array' do 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, %r{Empty String provided}) } end end context 'when given hash of packages' do before(:each) do subject.execute({ 'foo' => { 'provider' => 'rpm' }, 'bar' => { 'provider' => 'gem' } }, 'ensure' => 'present') subject.execute('パッケージ' => { 'ensure' => 'absent' }) subject.execute('ρǻ¢κầģẻ' => { 'ensure' => 'absent' }) end # this lambda is required due to strangeness within rspec-puppet's expectation handling 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 'with UTF8 and double byte characters' do it { expect(-> { catalogue }).to contain_package('パッケージ').with('ensure' => 'absent') } it { expect(-> { catalogue }).to contain_package('ρǻ¢κầģẻ').with('ensure' => 'absent') } end end context 'when given a catalog with "package { puppet: ensure => present }"' do let(:pre_condition) { 'package { puppet: ensure => present }' } describe 'after running ensure_package("puppet", { "ensure" => "installed" })' do before(:each) { subject.execute('puppet', 'ensure' => 'installed') } # this lambda is required due to strangeness within rspec-puppet's expectation handling 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 9bbfacc..b7266f7 100644 --- a/spec/functions/ensure_resource_spec.rb +++ b/spec/functions/ensure_resource_spec.rb @@ -1,149 +1,151 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'ensure_resource' do it { is_expected.not_to eq(nil) } 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 it { is_expected.to run.with_params('type', 'title', {}, 'extras').and_raise_error(Puppet::ParseError) } end it { pending('should not accept numbers as arguments') is_expected.to run.with_params(1, 2, 3).and_raise_error(Puppet::ParseError) } context 'when given an empty catalog' do describe 'after running ensure_resource("user", "username1", {})' do before(:each) { subject.execute('User', 'username1', {}) } # this lambda is required due to strangeness within rspec-puppet's expectation handling it { expect(-> { catalogue }).to contain_user('username1').without_ensure } end describe 'after running ensure_resource("user", "username1", { gid => undef })' do before(:each) { subject.execute('User', 'username1', 'gid' => undef_value) } # this lambda is required due to strangeness within rspec-puppet's expectation handling 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(:each) { subject.execute('User', 'username1', 'ensure' => 'present', 'gid' => undef_value) } # this lambda is required due to strangeness within rspec-puppet's expectation handling 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 let(:pre_condition) { 'define test::deftype { }' } before(:each) { subject.execute('test::deftype', 'foo', {}) } # this lambda is required due to strangeness within rspec-puppet's expectation handling it { expect(-> { catalogue }).to contain_test__deftype('foo').without_ensure } end end context 'when given a catalog with UTF8 chars' do describe 'after running ensure_resource("user", "Şắოрŀễ Ţëם", {})' do before(:each) { subject.execute('User', 'Şắოрŀễ Ţëם', {}) } # this lambda is required due to strangeness within rspec-puppet's expectation handling it { expect(-> { catalogue }).to contain_user('Şắოрŀễ Ţëם').without_ensure } end describe 'after running ensure_resource("user", "Şắოрŀễ Ţëם", { gid => undef })' do before(:each) { subject.execute('User', 'Şắოрŀễ Ţëם', 'gid' => undef_value) } # this lambda is required due to strangeness within rspec-puppet's expectation handling 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(:each) { subject.execute('User', 'Şắოрŀễ Ţëם', 'ensure' => 'present', 'gid' => undef_value) } # this lambda is required due to strangeness within rspec-puppet's expectation handling it { expect(-> { catalogue }).to contain_user('Şắოрŀễ Ţëם').with_ensure('present') } it { expect(-> { catalogue }).to contain_user('Şắოрŀễ Ţëם').without_gid } end end context 'when given a catalog with "user { username1: ensure => present }"' do let(:pre_condition) { 'user { username1: ensure => present }' } describe 'after running ensure_resource("user", "username1", {})' do before(:each) { subject.execute('User', 'username1', {}) } # this lambda is required due to strangeness within rspec-puppet's expectation handling it { expect(-> { catalogue }).to contain_user('username1').with_ensure('present') } end describe 'after running ensure_resource("user", "username2", {})' do before(:each) { subject.execute('User', 'username2', {}) } # this lambda is required due to strangeness within rspec-puppet's expectation handling 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(:each) { subject.execute('User', 'username1', 'gid' => undef_value) } # this lambda is required due to strangeness within rspec-puppet's expectation handling it { expect(-> { catalogue }).to contain_user('username1').with_ensure('present') } end describe 'after running ensure_resource("user", ["username1", "username2"], {})' do before(:each) { subject.execute('User', ['username1', 'username2'], {}) } # this lambda is required due to strangeness within rspec-puppet's expectation handling 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(:each) { subject.execute('User', ['username2', 'username3'], params) } # this lambda is required due to strangeness within rspec-puppet's expectation handling 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, %r{User\[username1\] is already declared}) } end end context 'when given a catalog with "test::deftype { foo: }"' do let(:pre_condition) { 'define test::deftype { } test::deftype { "foo": }' } describe 'after running ensure_resource("test::deftype", "foo", {})' do before(:each) { subject.execute('test::deftype', 'foo', {}) } # this lambda is required due to strangeness within rspec-puppet's expectation handling it { expect(-> { catalogue }).to contain_test__deftype('foo').without_ensure } end end if Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 def undef_value :undef end else def undef_value nil end end end diff --git a/spec/functions/ensure_resources_spec.rb b/spec/functions/ensure_resources_spec.rb index 10a27bf..55dac3d 100644 --- a/spec/functions/ensure_resources_spec.rb +++ b/spec/functions/ensure_resources_spec.rb @@ -1,27 +1,29 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'ensure_resources' do it { is_expected.not_to eq(nil) } 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(:each) do subject.execute('user', { 'dan' => { 'gid' => 'mygroup', 'uid' => '600' }, 'alex' => { 'gid' => 'mygroup', 'uid' => '700' } }, 'ensure' => 'present') end # this lambda is required due to strangeness within rspec-puppet's expectation handling 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(:each) { subject.execute('user', { 'dan' => { 'gid' => 'mygroup', 'uid' => '600' } }, 'ensure' => 'present') } # this lambda is required due to strangeness within rspec-puppet's expectation handling 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/extname_spec.rb b/spec/functions/extname_spec.rb index 0a8d3ca..4808e11 100644 --- a/spec/functions/extname_spec.rb +++ b/spec/functions/extname_spec.rb @@ -1,16 +1,18 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'stdlib::extname' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(ArgumentError, %r{'stdlib::extname' expects 1 argument, got none}) } it { is_expected.to run.with_params('one', 'two').and_raise_error(ArgumentError, %r{'stdlib::extname' expects 1 argument, got 2}) } it { is_expected.to run.with_params([]).and_raise_error(ArgumentError, %r{'stdlib::extname' parameter 'filename' expects a String value, got Array}) } it { is_expected.to run.with_params('test.rb').and_return('.rb') } it { is_expected.to run.with_params('a/b/d/test.rb').and_return('.rb') } it { is_expected.to run.with_params('test').and_return('') } it { is_expected.to run.with_params('.profile').and_return('') } context 'with UTF8 and double byte characters' do it { is_expected.to run.with_params('file_√ạĺűē/竹.rb').and_return('.rb') } end end diff --git a/spec/functions/flatten_spec.rb b/spec/functions/flatten_spec.rb index 0b08f35..365535b 100644 --- a/spec/functions/flatten_spec.rb +++ b/spec/functions/flatten_spec.rb @@ -1,16 +1,18 @@ +# frozen_string_literal: true + require 'spec_helper' -describe 'flatten', :if => Puppet::Util::Package.versioncmp(Puppet.version, '5.5.0') < 0 do +describe 'flatten', if: Puppet::Util::Package.versioncmp(Puppet.version, '5.5.0') < 0 do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{Wrong number of arguments}) } it { is_expected.to run.with_params([], []).and_raise_error(Puppet::ParseError, %r{Wrong number of arguments}) } it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{Requires array}) } it { is_expected.to run.with_params('one').and_raise_error(Puppet::ParseError, %r{Requires array}) } 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(['ã', 'β', 'ĉ', 'đ', 'ẽ', 'ƒ', 'ġ']) } end diff --git a/spec/functions/floor_spec.rb b/spec/functions/floor_spec.rb index e87a601..fe45142 100644 --- a/spec/functions/floor_spec.rb +++ b/spec/functions/floor_spec.rb @@ -1,13 +1,15 @@ +# frozen_string_literal: true + require 'spec_helper' -describe 'floor', :if => Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do +describe 'floor', if: Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{Wrong number of arguments}) } it { is_expected.to run.with_params('foo').and_raise_error(Puppet::ParseError, %r{Wrong argument type}) } it { is_expected.to run.with_params([]).and_raise_error(Puppet::ParseError, %r{Wrong argument type}) } 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(33) } it { is_expected.to run.with_params(-33.1).and_return(-34) } end diff --git a/spec/functions/fqdn_rand_string_spec.rb b/spec/functions/fqdn_rand_string_spec.rb index d5d3fbf..1102b87 100644 --- a/spec/functions/fqdn_rand_string_spec.rb +++ b/spec/functions/fqdn_rand_string_spec.rb @@ -1,67 +1,69 @@ +# frozen_string_literal: true + require 'spec_helper' 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, %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, 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(%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']) + 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']) + 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 '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') + 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 def fqdn_rand_string(max, args = {}) host = args[:host] || '127.0.0.1' charset = args[:charset] extra = args[:extra_identifier] || [] # workaround not being able to use let(:facts) because some tests need # multiple different hostnames in one context allow(scope).to receive(:lookupvar).with('::fqdn', {}).and_return(host) function_args = [max] if args.key?(:charset) || !extra.empty? function_args << charset end function_args += extra scope.function_fqdn_rand_string(function_args) end end diff --git a/spec/functions/fqdn_rotate_spec.rb b/spec/functions/fqdn_rotate_spec.rb index 7cd9f1d..8c68c37 100644 --- a/spec/functions/fqdn_rotate_spec.rb +++ b/spec/functions/fqdn_rotate_spec.rb @@ -1,74 +1,76 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'fqdn_rotate' do it { is_expected.not_to eq(nil) } 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('ã') } it { is_expected.to run.with_params([]).and_return([]) } it { is_expected.to run.with_params(['a']).and_return(['a']) } it 'rotates a string and the result should be the same size' do expect(fqdn_rotate('asdf').size).to eq(4) end 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') + 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']) + 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']) + 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 'rotates a string to give different values on different hosts' do - val1 = fqdn_rotate('abcdefg', :host => 'one') - val2 = fqdn_rotate('abcdefg', :host => 'two') + val1 = fqdn_rotate('abcdefg', host: 'one') + val2 = fqdn_rotate('abcdefg', host: 'two') expect(val1).not_to eq(val2) end it 'accepts objects which extend String' do result = fqdn_rotate(AlsoString.new('asdf')) expect(result).to eq('dfas') end it 'uses the Puppet::Util.deterministic_rand function' do skip 'Puppet::Util#deterministic_rand not available' unless Puppet::Util.respond_to?(:deterministic_rand) expect(Puppet::Util).to receive(:deterministic_rand).with(44_489_829_212_339_698_569_024_999_901_561_968_770, 4) fqdn_rotate('asdf') end 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 def fqdn_rotate(value, args = {}) host = args[:host] || '127.0.0.1' extra = args[:extra_identifier] || [] # workaround not being able to use let(:facts) because some tests need # multiple different hostnames in one context allow(scope).to receive(:lookupvar).with('::fqdn').and_return(host) function_args = [value] + extra scope.function_fqdn_rotate(function_args) end end diff --git a/spec/functions/fqdn_uuid_spec.rb b/spec/functions/fqdn_uuid_spec.rb index 60df2e4..a15751f 100644 --- a/spec/functions/fqdn_uuid_spec.rb +++ b/spec/functions/fqdn_uuid_spec.rb @@ -1,16 +1,18 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'fqdn_uuid' do context 'with invalid parameters' do it { is_expected.to run.with_params.and_raise_error(ArgumentError, %r{No arguments given}) } it { is_expected.to run.with_params('puppetlabs.com', 'google.com').and_raise_error(ArgumentError, %r{Too many arguments given}) } it { is_expected.to run.with_params({}).and_raise_error(TypeError, %r{no implicit conversion of Hash}) } it { is_expected.to run.with_params(0).and_raise_error(TypeError, %r{no implicit conversion of Integer}) } end context 'with 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') } it { is_expected.to run.with_params('0').and_return('6af613b6-569c-5c22-9c37-2ed93f31d3af') } end end diff --git a/spec/functions/get_module_path_spec.rb b/spec/functions/get_module_path_spec.rb index dd31c67..1d6d3be 100644 --- a/spec/functions/get_module_path_spec.rb +++ b/spec/functions/get_module_path_spec.rb @@ -1,57 +1,59 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'get_module_path' do it { is_expected.not_to eq(nil) } 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 class StubModule attr_reader :path def initialize(path) @path = path end 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') } before(:each) do Puppet[:modulepath] = modulepath end context 'when in the default environment' do before(:each) do allow(Puppet::Module).to receive(:find).with('foo', 'rp_env').and_return(path_of_module_foo) end it 'runs against foo' do is_expected.to run.with_params('foo').and_return(path_of_module_foo.path) end it 'when the modulepath is a list' do Puppet[:modulepath] = modulepath + 'tmp/something_else' is_expected.to run.with_params('foo').and_return(path_of_module_foo.path) end end context 'when in a non-default default environment' do let(:environment) { 'test' } before(:each) do allow(Puppet::Module).to receive(:find).with('foo', 'test').and_return(path_of_module_foo) end it 'runs against foo' do is_expected.to run.with_params('foo').and_return(path_of_module_foo.path) end it 'when the modulepath is a list' do Puppet[:modulepath] = modulepath + 'tmp/something_else' is_expected.to run.with_params('foo').and_return(path_of_module_foo.path) end end end end diff --git a/spec/functions/getparam_spec.rb b/spec/functions/getparam_spec.rb index 3a3cc27..d79493b 100644 --- a/spec/functions/getparam_spec.rb +++ b/spec/functions/getparam_spec.rb @@ -1,34 +1,36 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'getparam' do it { is_expected.not_to eq(nil) } 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": }' } it { is_expected.to run.with_params('User[one]', 'ensure').and_return('') } it { is_expected.to run.with_params('User[two]', 'ensure').and_return('') } it { is_expected.to run.with_params('User[one]', 'shell').and_return('') } end describe 'when compared against a user resource with params' do let(:pre_condition) { 'user { "one": ensure => present, shell => "/bin/sh", managehome => false, }' } it { is_expected.to run.with_params('User[one]', 'ensure').and_return('present') } it { is_expected.to run.with_params('User[two]', 'ensure').and_return('') } it { is_expected.to run.with_params('User[one]', 'shell').and_return('/bin/sh') } it { is_expected.to run.with_params('User[one]', 'managehome').and_return(false) } end describe 'when compared against a user resource with UTF8 and double byte params' do let(:pre_condition) { 'user { ["三", "ƒốưř"]: ensure => present }' } 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 6c37baa..94af518 100644 --- a/spec/functions/getvar_spec.rb +++ b/spec/functions/getvar_spec.rb @@ -1,45 +1,47 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'getvar' do it { is_expected.not_to eq(nil) } - describe 'before Puppet 6.0.0', :if => Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do + describe 'before Puppet 6.0.0', if: Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do 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) } end - describe 'from Puppet 6.0.0', :if => Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') >= 0 do + describe 'from Puppet 6.0.0', if: Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') >= 0 do it { is_expected.to run.with_params.and_raise_error(ArgumentError, %r{expects between 1 and 2 arguments, got none}i) } it { is_expected.to run.with_params('one', 'two').and_return('two') } it { is_expected.to run.with_params('one', 'two', 'three').and_raise_error(ArgumentError, %r{expects between 1 and 2 arguments, got 3}i) } end it { is_expected.to run.with_params('::foo').and_return(nil) } context 'with given variables in namespaces' do let(:pre_condition) do <<-PUPPETCODE class site::data { $foo = 'baz' } include site::data PUPPETCODE 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') } it { is_expected.to run.with_params('::site::data::bar').and_return(nil) } end context 'with given variables in namespaces' do let(:pre_condition) do <<-PUPPETCODE class site::info { $lock = 'ŧҺîš íš ắ śţřĭŋĝ' } class site::new { $item = '万Ü€‰' } include site::info include site::new PUPPETCODE 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 209aca6..141ee77 100644 --- a/spec/functions/glob_spec.rb +++ b/spec/functions/glob_spec.rb @@ -1,11 +1,13 @@ +# frozen_string_literal: true + require 'spec_helper' 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(1).and_raise_error(Puppet::ParseError) } 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(['/etc/xyzxyzxyz', '/etcxyzxyzxyz']).and_return([]) } end diff --git a/spec/functions/grep_spec.rb b/spec/functions/grep_spec.rb index 587e51b..b428d2d 100644 --- a/spec/functions/grep_spec.rb +++ b/spec/functions/grep_spec.rb @@ -1,20 +1,22 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'grep' do it { is_expected.not_to eq(nil) } 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, %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, %r{first argument not an array}) } 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(['ţשּׂỡ', 'ţһŗəè']) } end diff --git a/spec/functions/has_interface_with_spec.rb b/spec/functions/has_interface_with_spec.rb index 273ecb2..d55f58e 100644 --- a/spec/functions/has_interface_with_spec.rb +++ b/spec/functions/has_interface_with_spec.rb @@ -1,39 +1,41 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'has_interface_with' do it { is_expected.not_to eq(nil) } 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 'when on Mac OS X Systems' do - let(:facts) { { :interfaces => 'lo0,gif0,stf0,en1,p2p0,fw0,en0,vmnet1,vmnet8,utun0' } } + 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 'when 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 it { is_expected.to run.with_params('lo').and_return(true) } it { is_expected.to run.with_params('lo0').and_return(false) } it { is_expected.to run.with_params('ipaddress', '127.0.0.1').and_return(true) } it { is_expected.to run.with_params('ipaddress', '10.0.0.1').and_return(true) } it { is_expected.to run.with_params('ipaddress', '8.8.8.8').and_return(false) } it { is_expected.to run.with_params('muppet', 'kermit').and_return(true) } it { is_expected.to run.with_params('muppet', 'mspiggy').and_return(true) } it { is_expected.to run.with_params('muppet', 'bigbird').and_return(false) } end end diff --git a/spec/functions/has_ip_address_spec.rb b/spec/functions/has_ip_address_spec.rb index 8fbde61..a30a5a5 100644 --- a/spec/functions/has_ip_address_spec.rb +++ b/spec/functions/has_ip_address_spec.rb @@ -1,23 +1,25 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'has_ip_address' do it { is_expected.not_to eq(nil) } 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 'when 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 it { is_expected.to run.with_params('127.0.0.1').and_return(true) } it { is_expected.to run.with_params('10.0.0.1').and_return(true) } it { is_expected.to run.with_params('8.8.8.8').and_return(false) } it { is_expected.to run.with_params('invalid').and_return(false) } end end diff --git a/spec/functions/has_ip_network_spec.rb b/spec/functions/has_ip_network_spec.rb index b9dbde9..3366757 100644 --- a/spec/functions/has_ip_network_spec.rb +++ b/spec/functions/has_ip_network_spec.rb @@ -1,22 +1,24 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'has_ip_network' do it { is_expected.not_to eq(nil) } 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 'when 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 it { is_expected.to run.with_params('127.0.0.0').and_return(true) } it { is_expected.to run.with_params('10.0.0.0').and_return(true) } it { is_expected.to run.with_params('8.8.8.0').and_return(false) } it { is_expected.to run.with_params('invalid').and_return(false) } end end diff --git a/spec/functions/has_key_spec.rb b/spec/functions/has_key_spec.rb index 6abebba..8823561 100644 --- a/spec/functions/has_key_spec.rb +++ b/spec/functions/has_key_spec.rb @@ -1,20 +1,22 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'has_key' do it { is_expected.not_to eq(nil) } 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) } context '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) } end end diff --git a/spec/functions/hash_spec.rb b/spec/functions/hash_spec.rb index 2f78da4..1d678f9 100644 --- a/spec/functions/hash_spec.rb +++ b/spec/functions/hash_spec.rb @@ -1,15 +1,17 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'hash' do it { is_expected.not_to eq(nil) } 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, %r{wrong number of arguments}i) } 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') } end diff --git a/spec/functions/intersection_spec.rb b/spec/functions/intersection_spec.rb index 0ea871f..2be738f 100644 --- a/spec/functions/intersection_spec.rb +++ b/spec/functions/intersection_spec.rb @@ -1,22 +1,24 @@ +# frozen_string_literal: true + require 'spec_helper' 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('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) } it { is_expected.to run.with_params('one', []).and_raise_error(Puppet::ParseError) } it { is_expected.to run.with_params([], '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_return([]) } 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 'does not confuse types' do is_expected.to run.with_params(['1', '2', '3'], [1, 2]).and_return([]) end end diff --git a/spec/functions/ip_in_range_spec.rb b/spec/functions/ip_in_range_spec.rb index 01d800c..78130de 100644 --- a/spec/functions/ip_in_range_spec.rb +++ b/spec/functions/ip_in_range_spec.rb @@ -1,17 +1,19 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'stdlib::ip_in_range' do describe 'signature validation' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(ArgumentError, %r{'stdlib::ip_in_range' expects 2 arguments, got none}) } it { is_expected.to run.with_params('one', 'two', '3').and_raise_error(ArgumentError, %r{'stdlib::ip_in_range' expects 2 arguments, got 3}) } it { is_expected.to run.with_params([], []).and_raise_error(ArgumentError, %r{'stdlib::ip_in_range' parameter 'ipaddress' expects a String value, got Array}) } it { is_expected.to run.with_params('1.1.1.1', 7).and_raise_error(ArgumentError, %r{'stdlib::ip_in_range' parameter 'range' expects a value of type String or Array, got Integer}) } end describe 'basic validation inputs' do it { is_expected.to run.with_params('192.168.100.12', '192.168.100.0/24').and_return(true) } it { is_expected.to run.with_params('192.168.100.12', ['10.10.10.10/24', '192.168.100.0/24']).and_return(true) } it { is_expected.to run.with_params('10.10.10.10', '192.168.100.0/24').and_return(false) } end end diff --git a/spec/functions/is_a_spec.rb b/spec/functions/is_a_spec.rb index a5fe590..fd510b2 100644 --- a/spec/functions/is_a_spec.rb +++ b/spec/functions/is_a_spec.rb @@ -1,32 +1,34 @@ +# frozen_string_literal: true + require 'spec_helper' 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) } end end end 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 'succeeds when comparing a string and a string' do is_expected.to run.with_params('hello world', String).and_return(true) end it 'fails when comparing an integer and a string' do is_expected.to run.with_params(5, String).and_return(false) end it 'suceeds when comparing an UTF8 and double byte characters' do 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 a24c2c7..6356160 100644 --- a/spec/functions/is_array_spec.rb +++ b/spec/functions/is_array_spec.rb @@ -1,35 +1,37 @@ +# frozen_string_literal: true + 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, %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, %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) } it { is_expected.to run.with_params([1]).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(false) } it { is_expected.to run.with_params('one').and_return(false) } it { is_expected.to run.with_params(1).and_return(false) } it { is_expected.to run.with_params({}).and_return(false) } context 'with deprecation warning' 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 'displays a single deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' expect(scope).to receive(:warning).with(include('This method is deprecated')) is_expected.to run.with_params(['1.2.3.4']).and_return(true) end it 'displays no warning for deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'false' expect(scope).to receive(:warning).with(include('This method is deprecated')).never is_expected.to run.with_params(['1.2.3.4']).and_return(true) end end end diff --git a/spec/functions/is_bool_spec.rb b/spec/functions/is_bool_spec.rb index 2a8112e..7c5edda 100644 --- a/spec/functions/is_bool_spec.rb +++ b/spec/functions/is_bool_spec.rb @@ -1,31 +1,33 @@ +# frozen_string_literal: true + 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, %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) } it { is_expected.to run.with_params([{}]).and_return(false) } it { is_expected.to run.with_params([[]]).and_return(false) } it { is_expected.to run.with_params([true]).and_return(false) } it { is_expected.to run.with_params('true').and_return(false) } it { is_expected.to run.with_params('false').and_return(false) } context 'with deprecation warning' 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 'displays a single deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' expect(scope).to receive(:warning).with(include('This method is deprecated')) is_expected.to run.with_params(true).and_return(true) end it 'displays no warning for deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'false' expect(scope).to receive(:warning).with(include('This method is deprecated')).never is_expected.to run.with_params(false).and_return(true) end end end diff --git a/spec/functions/is_domain_name_spec.rb b/spec/functions/is_domain_name_spec.rb index 16caa8a..a022140 100644 --- a/spec/functions/is_domain_name_spec.rb +++ b/spec/functions/is_domain_name_spec.rb @@ -1,49 +1,51 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'is_domain_name' do it { is_expected.not_to eq(nil) } 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) } 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('com').and_return(true) } it { is_expected.to run.with_params('com.').and_return(true) } it { is_expected.to run.with_params('x.com').and_return(true) } it { is_expected.to run.with_params('x.com.').and_return(true) } it { is_expected.to run.with_params('foo.example.com').and_return(true) } it { is_expected.to run.with_params('foo.example.com.').and_return(true) } it { is_expected.to run.with_params('2foo.example.com').and_return(true) } it { is_expected.to run.with_params('2foo.example.com.').and_return(true) } it { is_expected.to run.with_params('www.2foo.example.com').and_return(true) } it { is_expected.to run.with_params('www.2foo.example.com.').and_return(true) } it { is_expected.to run.with_params(true).and_return(false) } describe 'inputs with spaces' do it { is_expected.to run.with_params('invalid domain').and_return(false) } end describe 'inputs with hyphens' do it { is_expected.to run.with_params('foo-bar.example.com').and_return(true) } it { is_expected.to run.with_params('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('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) } end # Values obtained from Facter values will be frozen strings # in newer versions of Facter: - it { is_expected.to run.with_params('www.example.com'.freeze).and_return(true) } + it { is_expected.to run.with_params('www.example.com').and_return(true) } describe 'top level domain must be alphabetic if there are multiple labels' do it { is_expected.to run.with_params('2com').and_return(true) } it { is_expected.to run.with_params('www.example.2com').and_return(false) } end describe 'IP addresses are not domain names' do it { is_expected.to run.with_params('192.168.1.1').and_return(false) } end end diff --git a/spec/functions/is_email_address_spec.rb b/spec/functions/is_email_address_spec.rb index 6c291e6..c2aeaf3 100644 --- a/spec/functions/is_email_address_spec.rb +++ b/spec/functions/is_email_address_spec.rb @@ -1,14 +1,16 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'is_email_address' do it { is_expected.not_to eq(nil) } 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) } it { is_expected.to run.with_params('1.2.3@domain').and_return(false) } it { is_expected.to run.with_params('1.2.3.4.5@').and_return(false) } it { is_expected.to run.with_params({}).and_return(false) } it { is_expected.to run.with_params([]).and_return(false) } end diff --git a/spec/functions/is_float_spec.rb b/spec/functions/is_float_spec.rb index a231446..e80dc4c 100644 --- a/spec/functions/is_float_spec.rb +++ b/spec/functions/is_float_spec.rb @@ -1,36 +1,38 @@ +# frozen_string_literal: true + 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, %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) } it { is_expected.to run.with_params('0.1').and_return(true) } it { is_expected.to run.with_params('1.0').and_return(true) } it { is_expected.to run.with_params('1').and_return(false) } it { is_expected.to run.with_params('one').and_return(false) } it { is_expected.to run.with_params('one 1.0').and_return(false) } it { is_expected.to run.with_params('1.0 one').and_return(false) } it { is_expected.to run.with_params(0.1).and_return(true) } it { is_expected.to run.with_params(1.0).and_return(true) } 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) } context 'with deprecation warning' 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 'displays a single deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' expect(scope).to receive(:warning).with(include('This method is deprecated')) is_expected.to run.with_params(2.2).and_return(true) end it 'displays no warning for deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'false' expect(scope).to receive(:warning).with(include('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 4de7f9e..3b39654 100644 --- a/spec/functions/is_function_available_spec.rb +++ b/spec/functions/is_function_available_spec.rb @@ -1,12 +1,14 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'is_function_available' do it { is_expected.not_to eq(nil) } 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) } it { is_expected.to run.with_params([]).and_return(false) } it { is_expected.to run.with_params({}).and_return(false) } it { is_expected.to run.with_params(1).and_return(false) } end diff --git a/spec/functions/is_hash_spec.rb b/spec/functions/is_hash_spec.rb index e154be3..126535d 100644 --- a/spec/functions/is_hash_spec.rb +++ b/spec/functions/is_hash_spec.rb @@ -1,12 +1,14 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'is_hash' do it { is_expected.not_to eq(nil) } 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) } it { is_expected.to run.with_params(1).and_return(false) } it { is_expected.to run.with_params([{ 'aaa' => 'bbb' }]).and_return(false) } end diff --git a/spec/functions/is_integer_spec.rb b/spec/functions/is_integer_spec.rb index 7e93005..1de12c9 100644 --- a/spec/functions/is_integer_spec.rb +++ b/spec/functions/is_integer_spec.rb @@ -1,46 +1,48 @@ +# frozen_string_literal: true + 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, %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("123\nfoo").and_return(true) } it { is_expected.to run.with_params("foo\n123").and_return(true) } 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) } 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(true).and_return(false) } it { is_expected.to run.with_params(false).and_return(false) } it { is_expected.to run.with_params('0001234').and_return(false) } it { is_expected.to run.with_params("foo\nbar").and_return(false) } context 'with deprecation warning' 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 'displays a single deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' expect(scope).to receive(:warning).with(include('This method is deprecated')) is_expected.to run.with_params(50).and_return(true) end it 'displays no warning for deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'false' expect(scope).to receive(:warning).with(include('This method is deprecated')).never is_expected.to run.with_params(50).and_return(true) end end end diff --git a/spec/functions/is_ip_address_spec.rb b/spec/functions/is_ip_address_spec.rb index 86f3cf8..208d645 100644 --- a/spec/functions/is_ip_address_spec.rb +++ b/spec/functions/is_ip_address_spec.rb @@ -1,24 +1,26 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'is_ip_address' do it { is_expected.not_to eq(nil) } 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) } it { is_expected.to run.with_params('1.2.3').and_return(false) } it { is_expected.to run.with_params('1.2.3.4.5').and_return(false) } it { is_expected.to run.with_params('fe00::1').and_return(true) } it { is_expected.to run.with_params('fe80:0000:cd12:d123:e2f8:47ff:fe09:dd74').and_return(true) } it { is_expected.to run.with_params('FE80:0000:CD12:D123:E2F8:47FF:FE09:DD74').and_return(true) } it { is_expected.to run.with_params('fe80:0000:cd12:d123:e2f8:47ff:fe09:zzzz').and_return(false) } it { is_expected.to run.with_params('fe80:0000:cd12:d123:e2f8:47ff:fe09').and_return(false) } it { is_expected.to run.with_params('fe80:0000:cd12:d123:e2f8:47ff:fe09:dd74:dd74').and_return(false) } it { is_expected.to run.with_params('').and_return(false) } it { is_expected.to run.with_params('one').and_return(false) } 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) } it { is_expected.to run.with_params('thisstring').and_return(false) } end diff --git a/spec/functions/is_ipv4_address_spec.rb b/spec/functions/is_ipv4_address_spec.rb index fddd351..4298683 100644 --- a/spec/functions/is_ipv4_address_spec.rb +++ b/spec/functions/is_ipv4_address_spec.rb @@ -1,31 +1,33 @@ +# frozen_string_literal: true + 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, %r{wrong number of arguments}i) } SharedData::IPV4_PATTERNS.each do |value| it { is_expected.to run.with_params(value).and_return(true) } end SharedData::IPV4_NEGATIVE_PATTERNS.each do |value| it { is_expected.to run.with_params(value).and_return(false) } end - context 'Checking for deprecation warning', :if => Puppet.version.to_f < 4.0 do + context 'Checking for deprecation warning', if: Puppet.version.to_f < 4.0 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 'displays a single deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' expect(scope).to receive(:warning).with(include('This method is deprecated')) is_expected.to run.with_params(SharedData::IPV4_PATTERNS.first).and_return(true) end it 'displays no warning for deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'false' expect(scope).to receive(:warning).with(include('This method is deprecated')).never is_expected.to run.with_params(SharedData::IPV4_PATTERNS.first).and_return(true) end end end diff --git a/spec/functions/is_ipv6_address_spec.rb b/spec/functions/is_ipv6_address_spec.rb index c8bad51..3917133 100644 --- a/spec/functions/is_ipv6_address_spec.rb +++ b/spec/functions/is_ipv6_address_spec.rb @@ -1,30 +1,32 @@ +# frozen_string_literal: true + 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, %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) } it { is_expected.to run.with_params('1.2.3.4.5').and_return(false) } it { is_expected.to run.with_params('').and_return(false) } it { is_expected.to run.with_params('one').and_return(false) } it { is_expected.to run.with_params('2001:0db8:85a3:0000:0000:8a2e:0370:7334:ggg').and_return(false) } - context 'Checking for deprecation warning', :if => Puppet.version.to_f < 4.0 do + context 'Checking for deprecation warning', if: Puppet.version.to_f < 4.0 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 'displays a single deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' expect(scope).to receive(:warning).with(include('This method is deprecated')) is_expected.to run.with_params('2001:0db8:85a3:0000:0000:8a2e:0370:7334').and_return(true) end it 'displays no warning for deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'false' expect(scope).to receive(:warning).with(include('This method is deprecated')).never is_expected.to run.with_params('2001:0db8:85a3:0000:0000:8a2e:0370:7334').and_return(true) end end end diff --git a/spec/functions/is_mac_address_spec.rb b/spec/functions/is_mac_address_spec.rb index 2f6602b..3312bb3 100644 --- a/spec/functions/is_mac_address_spec.rb +++ b/spec/functions/is_mac_address_spec.rb @@ -1,31 +1,33 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'is_mac_address' do it { is_expected.not_to eq(nil) } 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('80:00:02:09:fe:80:00:00:00:00:00:00:00:24:65:ff:ff:91:a3:12').and_return(true) } it { is_expected.to run.with_params('00:00:00:00:00:0g').and_return(false) } it { is_expected.to run.with_params('').and_return(false) } it { is_expected.to run.with_params('one').and_return(false) } context 'with UTF8 and double byte characters' do it { is_expected.to run.with_params('ƒốưř').and_return(false) } it { is_expected.to run.with_params('三+').and_return(false) } end it { pending 'should properly typecheck its arguments' is_expected.to run.with_params(1).and_return(false) } it { pending 'should properly typecheck its arguments' is_expected.to run.with_params({}).and_return(false) } it { 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 6125ecd..9c9d9db 100644 --- a/spec/functions/is_numeric_spec.rb +++ b/spec/functions/is_numeric_spec.rb @@ -1,47 +1,49 @@ +# frozen_string_literal: true + 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, %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('-342.2315e-12').and_return(true) } it { is_expected.to run.with_params('one').and_return(false) } it { is_expected.to run.with_params([]).and_return(false) } 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(true).and_return(false) } it { is_expected.to run.with_params(false).and_return(false) } it { is_expected.to run.with_params('0001234').and_return(false) } it { is_expected.to run.with_params(' - 1234').and_return(false) } it { is_expected.to run.with_params(['aaa.com', 'bbb', 'ccc']).and_return(false) } context 'with deprecation warning' 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 'displays a single deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' expect(scope).to receive(:warning).with(include('This method is deprecated')) is_expected.to run.with_params(7).and_return(true) end it 'displays no warning for deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'false' expect(scope).to receive(:warning).with(include('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 946305f..9a22150 100644 --- a/spec/functions/is_string_spec.rb +++ b/spec/functions/is_string_spec.rb @@ -1,47 +1,49 @@ +# frozen_string_literal: true + 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, %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, %r{wrong number of arguments}i) } it { is_expected.to run.with_params(3).and_return(false) } it { is_expected.to run.with_params('3').and_return(false) } it { is_expected.to run.with_params(-3).and_return(false) } it { is_expected.to run.with_params('-3').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(:undef).and_return(false) } it { is_expected.to run.with_params([]).and_return(false) } 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(true).and_return(false) } it { is_expected.to run.with_params(false).and_return(false) } it { is_expected.to run.with_params('one').and_return(true) } it { is_expected.to run.with_params('0001234').and_return(true) } it { is_expected.to run.with_params('aaa' => 'www.com').and_return(false) } context 'with deprecation warning' 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 'displays a single deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' expect(scope).to receive(:warning).with(include('This method is deprecated')) is_expected.to run.with_params('sponge').and_return(true) end it 'displays no warning for deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'false' expect(scope).to receive(:warning).with(include('This method is deprecated')).never is_expected.to run.with_params('bob').and_return(true) end end end diff --git a/spec/functions/join_keys_to_values_spec.rb b/spec/functions/join_keys_to_values_spec.rb index 97674ef..5d9942e 100644 --- a/spec/functions/join_keys_to_values_spec.rb +++ b/spec/functions/join_keys_to_values_spec.rb @@ -1,34 +1,36 @@ +# frozen_string_literal: true + require 'spec_helper' 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, %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 '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(['ҝẽγ万√ạĺűē']) } end if Puppet::Util::Package.versioncmp(Puppet.version, '5.5.7') == 0 it { is_expected.to run.with_params({ 'key' => '' }, ':').and_return(['key:']) } else it { is_expected.to run.with_params({ 'key' => nil }, ':').and_return(['key:']) } end it 'runs join_keys_to_values(, ":") and return the proper array' do is_expected.to run.with_params({ 'key1' => 'value1', 'key2' => 'value2' }, ':').and_return(['key1:value1', 'key2:value2']) end it 'runs join_keys_to_values(, " ") and return the proper array' do expected_result = ['key1 value1', 'key2 value2', 'key2 value3'] is_expected.to run.with_params({ 'key1' => 'value1', 'key2' => ['value2', 'value3'] }, ' ').and_return(expected_result) end end diff --git a/spec/functions/join_spec.rb b/spec/functions/join_spec.rb index 264ebc9..2175248 100644 --- a/spec/functions/join_spec.rb +++ b/spec/functions/join_spec.rb @@ -1,20 +1,22 @@ +# frozen_string_literal: true + require 'spec_helper' -describe 'join', :if => Puppet::Util::Package.versioncmp(Puppet.version, '5.5.0') < 0 do +describe 'join', if: Puppet::Util::Package.versioncmp(Puppet.version, '5.5.0') < 0 do it { is_expected.not_to eq(nil) } 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, %r{wrong number of arguments}i) } 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('ōŋể:ŧשợ:ţђŕẽё') } end diff --git a/spec/functions/keys_spec.rb b/spec/functions/keys_spec.rb index 2b538a0..befc834 100644 --- a/spec/functions/keys_spec.rb +++ b/spec/functions/keys_spec.rb @@ -1,24 +1,26 @@ +# frozen_string_literal: true + require 'spec_helper' -describe 'keys', :if => Puppet::Util::Package.versioncmp(Puppet.version, '5.5.0') < 0 do +describe 'keys', if: Puppet::Util::Package.versioncmp(Puppet.version, '5.5.0') < 0 do it { is_expected.not_to eq(nil) } 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, %r{wrong number of arguments}i) } 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 'returns the array of keys' do result = subject.call([{ 'key1' => 'value1', 'key2' => 'value2' }]) expect(result).to match_array(['key1', 'key2']) end it 'runs with UTF8 and double byte characters' do result = subject.call([{ 'ҝểү' => '√ẳŀμệ', 'キー' => '値' }]) expect(result).to match_array(['ҝểү', 'キー']) end end diff --git a/spec/functions/length_spec.rb b/spec/functions/length_spec.rb index 72ebb62..183a31c 100644 --- a/spec/functions/length_spec.rb +++ b/spec/functions/length_spec.rb @@ -1,31 +1,33 @@ +# frozen_string_literal: true + require 'spec_helper' -describe 'length', :if => Puppet::Util::Package.versioncmp(Puppet.version, '5.5.0') < 0 do +describe 'length', if: Puppet::Util::Package.versioncmp(Puppet.version, '5.5.0') < 0 do it { is_expected.not_to eq(nil) } 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({}).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('').and_return(0) } it { is_expected.to run.with_params('a').and_return(1) } it { is_expected.to run.with_params('abc').and_return(3) } it { is_expected.to run.with_params('abcd').and_return(4) } it { is_expected.to run.with_params('万').and_return(1) } it { is_expected.to run.with_params('āβćđ').and_return(4) } context 'when using a class extending String' do it { is_expected.to run.with_params(AlsoString.new('asdfghjkl')).and_return(9) } end end diff --git a/spec/functions/load_module_metadata_spec.rb b/spec/functions/load_module_metadata_spec.rb index 45eaa7e..caca5e7 100644 --- a/spec/functions/load_module_metadata_spec.rb +++ b/spec/functions/load_module_metadata_spec.rb @@ -1,51 +1,53 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'load_module_metadata' do it { is_expected.not_to eq(nil) } 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 before :each do # In Puppet 7, there are two prior calls to File.read prior to the responses we want to mock allow(File).to receive(:read).with(anything, anything).and_call_original - 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}, encoding: 'utf-8').and_return('{"name": "puppetlabs-stdlib"}') allow(File).to receive(:read).with(%r{\/(stdlib|test)\/metadata.json}).and_return('{"name": "puppetlabs-stdlib"}') # Additional modules used by litmus which are identified while running these dues to being in fixtures - allow(File).to receive(:read).with(%r{\/(provision|puppet_agent|facts)\/metadata.json}, :encoding => 'utf-8') + allow(File).to receive(:read).with(%r{\/(provision|puppet_agent|facts)\/metadata.json}, encoding: 'utf-8') end context 'when calling with valid utf8 and double byte character arguments' do before :each do - allow(File).to receive(:read).with(%r{\/(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(%r{\/(stdlib|test)\/metadata.json}).and_return('{"ĭďèʼnţĩƒіểя": "ċơņťęאּť ỡƒ ţħíš - この文字"}') end let(:prefix) { 'C:' if Puppet::Util::Platform.windows? } 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"}') result = subject.execute('science') expect(result['name']).to eq('spencer-science') end 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.execute('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 48d79fb..c45123c 100644 --- a/spec/functions/loadjson_spec.rb +++ b/spec/functions/loadjson_spec.rb @@ -1,146 +1,148 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'loadjson' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(ArgumentError, %r{wrong number of arguments}i) } describe 'when calling with valid arguments' do before :each do # In Puppet 7, there are two prior calls to File.read prior to the responses we want to mock allow(File).to receive(:read).with(anything, anything).and_call_original - 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}, encoding: 'utf-8').and_return('{"name": "puppetlabs-stdlib"}') allow(File).to receive(:read).with(%r{\/(stdlib|test)\/metadata.json}).and_return('{"name": "puppetlabs-stdlib"}') # Additional modules used by litmus which are identified while running these dues to being in fixtures - allow(File).to receive(:read).with(%r{\/(provision|puppet_agent|facts)\/metadata.json}, :encoding => 'utf-8') + allow(File).to receive(:read).with(%r{\/(provision|puppet_agent|facts)\/metadata.json}, encoding: 'utf-8') end context 'when a non-existing file is specified' do let(:filename) do if Puppet::Util::Platform.windows? 'C:/tmp/doesnotexist' else '/tmp/doesnotexist' end end before(:each) do allow(File).to receive(:exists?).with(filename).and_return(false).once allow(PSON).to receive(:load).never 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) do if Puppet::Util::Platform.windows? 'C:/tmp/doesexist' else '/tmp/doesexist' end end let(:data) { { 'key' => 'value', 'ķęŷ' => 'νậŀųề', 'キー' => '値' } } let(:json) { '{"key":"value", {"ķęŷ":"νậŀųề" }, {"キー":"値" }' } 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) do if Puppet::Util::Platform.windows? 'C:/tmp/doesexist' else '/tmp/doesexist' end end let(:json) { '{"key":"value"}' } 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!' end it { is_expected.to run.with_params(filename, 'default' => 'value').and_return('default' => 'value') } end context 'when an existing URL is specified' do let(:filename) do 'https://example.local/myhash.json' end - let(:basic_auth) { { :http_basic_authentication => ['', ''] } } + let(:basic_auth) { { http_basic_authentication: ['', ''] } } let(:data) { { 'key' => 'value', 'ķęŷ' => 'νậŀųề', 'キー' => '値' } } let(:json) { '{"key":"value", {"ķęŷ":"νậŀųề" }, {"キー":"値" }' } it { expect(OpenURI).to receive(:open_uri).with(filename, basic_auth).and_return(json) expect(PSON).to receive(:load).with(json).and_return(data).once is_expected.to run.with_params(filename).and_return(data) } end context 'when an existing URL (with username and password) is specified' do let(:filename) do 'https://user1:pass1@example.local/myhash.json' end let(:url_no_auth) { 'https://example.local/myhash.json' } - let(:basic_auth) { { :http_basic_authentication => ['user1', 'pass1'] } } + let(:basic_auth) { { http_basic_authentication: ['user1', 'pass1'] } } let(:data) { { 'key' => 'value', 'ķęŷ' => 'νậŀųề', 'キー' => '値' } } let(:json) { '{"key":"value", {"ķęŷ":"νậŀųề" }, {"キー":"値" }' } it { expect(OpenURI).to receive(:open_uri).with(url_no_auth, basic_auth).and_return(json) expect(PSON).to receive(:load).with(json).and_return(data).once is_expected.to run.with_params(filename).and_return(data) } end context 'when an existing URL (with username) is specified' do let(:filename) do 'https://user1@example.local/myhash.json' end let(:url_no_auth) { 'https://example.local/myhash.json' } - let(:basic_auth) { { :http_basic_authentication => ['user1', ''] } } + let(:basic_auth) { { http_basic_authentication: ['user1', ''] } } let(:data) { { 'key' => 'value', 'ķęŷ' => 'νậŀųề', 'キー' => '値' } } let(:json) { '{"key":"value", {"ķęŷ":"νậŀųề" }, {"キー":"値" }' } it { expect(OpenURI).to receive(:open_uri).with(url_no_auth, basic_auth).and_return(json) expect(PSON).to receive(:load).with(json).and_return(data).once is_expected.to run.with_params(filename).and_return(data) } end context 'when the URL output could not be parsed, with default specified' do let(:filename) do 'https://example.local/myhash.json' end - let(:basic_auth) { { :http_basic_authentication => ['', ''] } } + let(:basic_auth) { { http_basic_authentication: ['', ''] } } let(:json) { ',;{"key":"value"}' } it { expect(OpenURI).to receive(:open_uri).with(filename, basic_auth).and_return(json) expect(PSON).to receive(:load).with(json).once.and_raise StandardError, 'Something terrible have happened!' is_expected.to run.with_params(filename, 'default' => 'value').and_return('default' => 'value') } end context 'when the URL does not exist, with default specified' do let(:filename) do 'https://example.local/myhash.json' end - let(:basic_auth) { { :http_basic_authentication => ['', ''] } } + let(:basic_auth) { { http_basic_authentication: ['', ''] } } it { expect(OpenURI).to receive(:open_uri).with(filename, basic_auth).and_raise OpenURI::HTTPError, '404 File not Found' 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 d71fd32..4de82ec 100644 --- a/spec/functions/loadyaml_spec.rb +++ b/spec/functions/loadyaml_spec.rb @@ -1,101 +1,103 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'loadyaml' do it { is_expected.not_to eq(nil) } 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' } it "'default' => 'value'" do expect(File).to receive(:exists?).with(filename).and_return(false).once expect(YAML).to receive(:load_file).never is_expected.to run.with_params(filename, 'default' => 'value').and_return('default' => 'value') end end context 'when an existing file is specified' do let(:filename) { '/tmp/doesexist' } let(:data) { { 'key' => 'value', 'ķęŷ' => 'νậŀųề', 'キー' => '値' } } it "returns 'key' => 'value', 'ķęŷ' => 'νậŀųề', 'キー' => '値'" do expect(File).to receive(:exists?).with(filename).and_return(true).once expect(YAML).to receive(:load_file).with(filename).and_return(data).once is_expected.to run.with_params(filename).and_return(data) end end context 'when the file could not be parsed' do let(:filename) { '/tmp/doesexist' } it 'filename /tmp/doesexist' do expect(File).to receive(:exists?).with(filename).and_return(true).once allow(YAML).to receive(:load_file).with(filename).once.and_raise(StandardError, 'Something terrible have happened!') is_expected.to run.with_params(filename, 'default' => 'value').and_return('default' => 'value') end end context 'when an existing URL is specified' do let(:filename) { 'https://example.local/myhash.yaml' } - let(:basic_auth) { { :http_basic_authentication => ['', ''] } } + let(:basic_auth) { { http_basic_authentication: ['', ''] } } let(:yaml) { 'Dummy YAML' } let(:data) { { 'key' => 'value', 'ķęŷ' => 'νậŀųề', 'キー' => '値' } } it { expect(OpenURI).to receive(:open_uri).with(filename, basic_auth).and_return(yaml) expect(YAML).to receive(:safe_load).with(yaml).and_return(data).once is_expected.to run.with_params(filename).and_return(data) } end context 'when an existing URL (with username and password) is specified' do let(:filename) { 'https://user1:pass1@example.local/myhash.yaml' } let(:url_no_auth) { 'https://example.local/myhash.yaml' } - let(:basic_auth) { { :http_basic_authentication => ['user1', 'pass1'] } } + let(:basic_auth) { { http_basic_authentication: ['user1', 'pass1'] } } let(:yaml) { 'Dummy YAML' } let(:data) { { 'key' => 'value', 'ķęŷ' => 'νậŀųề', 'キー' => '値' } } it { expect(OpenURI).to receive(:open_uri).with(url_no_auth, basic_auth).and_return(yaml) expect(YAML).to receive(:safe_load).with(yaml).and_return(data).once is_expected.to run.with_params(filename).and_return(data) } end context 'when an existing URL (with username) is specified' do let(:filename) { 'https://user1@example.local/myhash.yaml' } let(:url_no_auth) { 'https://example.local/myhash.yaml' } - let(:basic_auth) { { :http_basic_authentication => ['user1', ''] } } + let(:basic_auth) { { http_basic_authentication: ['user1', ''] } } let(:yaml) { 'Dummy YAML' } let(:data) { { 'key' => 'value', 'ķęŷ' => 'νậŀųề', 'キー' => '値' } } it { expect(OpenURI).to receive(:open_uri).with(url_no_auth, basic_auth).and_return(yaml) expect(YAML).to receive(:safe_load).with(yaml).and_return(data).once is_expected.to run.with_params(filename).and_return(data) } end context 'when an existing URL could not be parsed, with default specified' do let(:filename) { 'https://example.local/myhash.yaml' } - let(:basic_auth) { { :http_basic_authentication => ['', ''] } } + let(:basic_auth) { { http_basic_authentication: ['', ''] } } let(:yaml) { 'Dummy YAML' } it { expect(OpenURI).to receive(:open_uri).with(filename, basic_auth).and_return(yaml) expect(YAML).to receive(:safe_load).with(yaml).and_raise StandardError, 'Cannot parse data' is_expected.to run.with_params(filename, 'default' => 'value').and_return('default' => 'value') } end context 'when a URL does not exist, with default specified' do let(:filename) { 'https://example.local/myhash.yaml' } - let(:basic_auth) { { :http_basic_authentication => ['', ''] } } + let(:basic_auth) { { http_basic_authentication: ['', ''] } } let(:yaml) { 'Dummy YAML' } it { expect(OpenURI).to receive(:open_uri).with(filename, basic_auth).and_raise OpenURI::HTTPError, '404 File not Found' 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 ab2f6f0..ee82223 100644 --- a/spec/functions/lstrip_spec.rb +++ b/spec/functions/lstrip_spec.rb @@ -1,35 +1,37 @@ +# frozen_string_literal: true + require 'spec_helper' -describe 'lstrip', :if => Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do +describe 'lstrip', if: Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do it { is_expected.not_to eq(nil) } 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, %r{wrong number of arguments}i) } 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('') } it { is_expected.to run.with_params("\t").and_return('') } it { is_expected.to run.with_params("\t ").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').and_return('one') } it { is_expected.to run.with_params("\tone").and_return('one') } it { is_expected.to run.with_params("\t 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 ').and_return('one ') } it { is_expected.to run.with_params(' ǿňè ').and_return('ǿňè ') } it { is_expected.to run.with_params("\tone ").and_return('one ') } it { is_expected.to run.with_params("\t one ").and_return('one ') } it { is_expected.to run.with_params("one \t").and_return("one \t") } it { is_expected.to run.with_params(" one \t").and_return("one \t") } it { is_expected.to run.with_params(" one \t").and_return("one \t") } it { is_expected.to run.with_params("\tone \t").and_return("one \t") } it { is_expected.to run.with_params("\t one \t").and_return("one \t") } it { is_expected.to run.with_params(' o n e ').and_return('o n e ') } it { is_expected.to run.with_params(AlsoString.new(' one ')).and_return('one ') } end diff --git a/spec/functions/max_spec.rb b/spec/functions/max_spec.rb index 88879d1..b3868d7 100644 --- a/spec/functions/max_spec.rb +++ b/spec/functions/max_spec.rb @@ -1,21 +1,23 @@ +# frozen_string_literal: true + require 'spec_helper' -describe 'max', :if => Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do +describe 'max', if: Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do it { is_expected.not_to eq(nil) } 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) } it { is_expected.to run.with_params(3, 2, 1).and_return(3) } it { is_expected.to run.with_params('one').and_return('one') } it { is_expected.to run.with_params('one', 'two').and_return('two') } it { is_expected.to run.with_params('one', 'two', 'three').and_return('two') } it { is_expected.to run.with_params('three', 'two', 'one').and_return('two') } describe 'implementation artifacts' do it { is_expected.to run.with_params(1, 'one').and_return('one') } it { is_expected.to run.with_params('1', 'one').and_return('one') } it { is_expected.to run.with_params('1.3e1', '1.4e0').and_return('1.4e0') } it { is_expected.to run.with_params(1.3e1, 1.4e0).and_return(1.3e1) } end end diff --git a/spec/functions/member_spec.rb b/spec/functions/member_spec.rb index 861f6e5..f4a5bc2 100644 --- a/spec/functions/member_spec.rb +++ b/spec/functions/member_spec.rb @@ -1,25 +1,27 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'member' do it { is_expected.not_to eq(nil) } 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, %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) } 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([], 'one').and_return(false) } 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([1, 2, 3, 4], [4, 2]).and_return(true) } it { is_expected.to run.with_params([1, 'a', 'b', 4], [4, 'b']).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) } end diff --git a/spec/functions/merge_spec.rb b/spec/functions/merge_spec.rb index 7bffaab..da3e2e7 100644 --- a/spec/functions/merge_spec.rb +++ b/spec/functions/merge_spec.rb @@ -1,80 +1,82 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'merge' do it { is_expected.not_to eq(nil) } it { is_expected.to run \ .with_params({}, 'two') \ .and_raise_error( ArgumentError, \ Regexp.new(Regexp.escape("rejected: parameter 'args' expects a value of type Undef, Hash, or String[0, 0], got String")), ) } it { is_expected.to run \ .with_params({}, 1) \ .and_raise_error(ArgumentError, %r{parameter 'args' expects a value of type Undef, Hash, or String, got Integer}) } it { is_expected.to run \ .with_params({ 'one' => 1, 'three' => { 'four' => 4 } }, 'two' => 'dos', 'three' => { 'five' => 5 }) \ .and_return('one' => 1, 'three' => { 'five' => 5 }, 'two' => 'dos') } 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({}) } 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({ 'key1' => 'value1' }, { 'key2' => 'value2' }, 'key3' => 'value3') \ .and_return('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3') } describe 'should accept iterable and merge produced hashes' do it { is_expected.to run \ .with_params([1, 2, 3]) \ .with_lambda { |_hsh, val| { val => val } } \ .and_return(1 => 1, 2 => 2, 3 => 3) } it { is_expected.to run \ .with_params([1, 2, 3]) \ .with_lambda { |_hsh, val| { val => val } unless val == 2 } \ .and_return(1 => 1, 3 => 3) } it { is_expected.to run \ .with_params([1, 2, 3]) \ # rubocop:disable Style/Semicolon .with_lambda { |_hsh, val| raise StopIteration if val == 3; { val => val } } \ .and_return(1 => 1, 2 => 2) } it { is_expected.to run \ .with_params(['a', 'b', 'b', 'c', 'b']) \ .with_lambda { |hsh, val| { val => (hsh[val] || 0) + 1 } } \ .and_return('a' => 1, 'b' => 3, 'c' => 1) } it { is_expected.to run \ .with_params(['a', 'b', 'c']) \ .with_lambda { |_hsh, idx, val| { idx => val } } \ .and_return(0 => 'a', 1 => 'b', 2 => 'c') } it { is_expected.to run \ .with_params('a' => 'A', 'b' => 'B', 'c' => 'C') \ .with_lambda { |_hsh, key, val| { key => "#{key}#{val}" } } \ .and_return('a' => 'aA', 'b' => 'bB', 'c' => 'cC') } end end diff --git a/spec/functions/min_spec.rb b/spec/functions/min_spec.rb index 34efb67..4b73012 100644 --- a/spec/functions/min_spec.rb +++ b/spec/functions/min_spec.rb @@ -1,23 +1,25 @@ +# frozen_string_literal: true + require 'spec_helper' -describe 'min', :if => Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do +describe 'min', if: Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do it { is_expected.not_to eq(nil) } 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) } it { is_expected.to run.with_params(3, 2, 1).and_return(1) } it { is_expected.to run.with_params(12, 8).and_return(8) } it { is_expected.to run.with_params('one').and_return('one') } it { is_expected.to run.with_params('one', 'two').and_return('one') } it { is_expected.to run.with_params('one', 'two', 'three').and_return('one') } it { is_expected.to run.with_params('three', 'two', 'one').and_return('one') } it { is_expected.to run.with_params('the', 'public', 'art', 'galleries').and_return('art') } describe 'implementation artifacts' do it { is_expected.to run.with_params(1, 'one').and_return(1) } it { is_expected.to run.with_params('1', 'one').and_return('1') } it { is_expected.to run.with_params('1.3e1', '1.4e0').and_return('1.3e1') } it { is_expected.to run.with_params(1.3e1, 1.4e0).and_return(1.4e0) } end end diff --git a/spec/functions/num2bool_spec.rb b/spec/functions/num2bool_spec.rb index 786fd97..bedfb64 100644 --- a/spec/functions/num2bool_spec.rb +++ b/spec/functions/num2bool_spec.rb @@ -1,23 +1,25 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'num2bool' do it { is_expected.not_to eq(nil) } 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) } it { is_expected.to run.with_params('1.5').and_return(true) } it { is_expected.to run.with_params(-1).and_return(false) } it { is_expected.to run.with_params('-1').and_return(false) } it { is_expected.to run.with_params(-1.5).and_return(false) } it { is_expected.to run.with_params('-1.5').and_return(false) } 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, %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, %r{does not look like a number}) } it { is_expected.to run.with_params(['-50', '1']).and_return(false) } end diff --git a/spec/functions/os_version_gte_spec.rb b/spec/functions/os_version_gte_spec.rb index 98ccc44..5de5838 100644 --- a/spec/functions/os_version_gte_spec.rb +++ b/spec/functions/os_version_gte_spec.rb @@ -1,45 +1,47 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'os_version_gte' do context 'on Debian 9' do let(:facts) do { - :operatingsystem => 'Debian', - :operatingsystemmajrelease => '9', + operatingsystem: 'Debian', + operatingsystemmajrelease: '9', } end it { is_expected.to run.with_params('Debian', '9').and_return(true) } it { is_expected.to run.with_params('Debian', '8').and_return(false) } it { is_expected.to run.with_params('Debian', '8.0').and_return(false) } it { is_expected.to run.with_params('Ubuntu', '16.04').and_return(false) } it { is_expected.to run.with_params('Fedora', '29').and_return(false) } end context 'on Ubuntu 16.04' do let(:facts) do { - :operatingsystem => 'Ubuntu', - :operatingsystemmajrelease => '16.04', + operatingsystem: 'Ubuntu', + operatingsystemmajrelease: '16.04', } end it { is_expected.to run.with_params('Debian', '9').and_return(false) } it { is_expected.to run.with_params('Ubuntu', '16').and_return(false) } it { is_expected.to run.with_params('Ubuntu', '16.04').and_return(true) } it { is_expected.to run.with_params('Ubuntu', '18.04').and_return(true) } it { is_expected.to run.with_params('Fedora', '29').and_return(false) } end context 'with invalid params' do let(:facts) do { - :operatingsystem => 'Ubuntu', - :operatingsystemmajrelease => '16.04', + operatingsystem: 'Ubuntu', + operatingsystemmajrelease: '16.04', } end it { is_expected.to run.with_params('123', 'abc').and_return(false) } it { is_expected.to run.with_params([], 123).and_raise_error(ArgumentError) } end end diff --git a/spec/functions/parsehocon_spec.rb b/spec/functions/parsehocon_spec.rb index 4eae3ab..623a7da 100644 --- a/spec/functions/parsehocon_spec.rb +++ b/spec/functions/parsehocon_spec.rb @@ -1,8 +1,10 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'parsehocon' do it { is_expected.to run.with_params('').and_return({}) } it { is_expected.to run.with_params('valid hocon: string').and_return('valid hocon' => 'string') } it { is_expected.to run.with_params('invalid').and_raise_error(Hocon::ConfigError::ConfigParseError) } it { is_expected.to run.with_params('invalid', 'default').and_return('default') } end diff --git a/spec/functions/parsejson_spec.rb b/spec/functions/parsejson_spec.rb index d038584..bc8c2f7 100644 --- a/spec/functions/parsejson_spec.rb +++ b/spec/functions/parsejson_spec.rb @@ -1,66 +1,68 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'parsejson' do it 'exists' do is_expected.not_to eq(nil) end 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 '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 'is able to parse JSON data with an Array' do is_expected.to run.with_params('["a","b","c"]') .and_return(['a', 'b', 'c']) end it 'is able to parse empty JSON values' do actual_array = ['[]', '{}'] expected = [[], {}] actual_array.each_with_index do |actual, index| is_expected.to run.with_params(actual).and_return(expected[index]) end end 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 'is able to parse JSON data with a UTF8 and double byte characters' do is_expected.to run.with_params('{"×":"これ","ý":"記号","です":{"©":["Á","ß"]}}') .and_return('×' => 'これ', 'ý' => '記号', 'です' => { '©' => ['Á', 'ß'] }) end 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 'raises an error with invalid JSON and no default' do is_expected.to run.with_params('') .and_raise_error(PSON::ParserError) end 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 + it "returns 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') end end end end diff --git a/spec/functions/parseyaml_spec.rb b/spec/functions/parseyaml_spec.rb index 62e18a3..f4ce419 100644 --- a/spec/functions/parseyaml_spec.rb +++ b/spec/functions/parseyaml_spec.rb @@ -1,74 +1,76 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'parseyaml' do it 'exists' do is_expected.not_to eq(nil) end 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 '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 '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 '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(['a', 'b', 'c']) end 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 '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' => '×', 'これ' => '記号', 'です' => { '©' => ['Á', 'ß'] }) end 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 it 'raises an error with invalid YAML and no default' do is_expected.to run.with_params('["one"') .and_raise_error(Psych::SyntaxError) end context 'with incorrect YAML data' do 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 + it "returns 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') end end context 'when running on modern rubies' do ['---', '...', '*8', ''].each do |value| - it "should return the default value for an incorrect #{value.inspect} string parameter" do + it "returns the default value for an incorrect #{value.inspect} string parameter" do 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 29d7896..6e32c40 100644 --- a/spec/functions/pick_default_spec.rb +++ b/spec/functions/pick_default_spec.rb @@ -1,40 +1,42 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'pick_default' do it { is_expected.not_to eq(nil) } 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('ớņệ') } it { is_expected.to run.with_params('', 'two').and_return('two') } it { is_expected.to run.with_params(:undef, 'two').and_return('two') } 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| 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('ớņệ') } it { is_expected.to run.with_params([], value).and_return([]) } it { is_expected.to run.with_params({}, value).and_return({}) } it { is_expected.to run.with_params(value, value).and_return(mapped_value(value)) } it { is_expected.to run.with_params(:undef, value).and_return(mapped_value(value)) } it { is_expected.to run.with_params(:undefined, value).and_return(mapped_value(value)) } it { is_expected.to run.with_params(nil, value).and_return(mapped_value(value)) } end end if Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 || Puppet::Util::Package.versioncmp(Puppet.version, '5.5.7') == 0 def mapped_value(v) v end else def mapped_value(v) # Puppet 6.0.0 will always map arguments the same way as the Puppet Language # even if function is called from Ruby via call_function # The 3x function API expects nil and :undef to be represented as empty string (v.nil? || v == :undef) ? '' : v end end end diff --git a/spec/functions/pick_spec.rb b/spec/functions/pick_spec.rb index d8c6fbf..741e0b7 100644 --- a/spec/functions/pick_spec.rb +++ b/spec/functions/pick_spec.rb @@ -1,17 +1,19 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'pick' do it { is_expected.not_to eq(nil) } 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') } it { is_expected.to run.with_params(:undefined, 'two').and_return('two') } it { is_expected.to run.with_params(nil, 'two').and_return('two') } context '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 ţẽם') } end end diff --git a/spec/functions/prefix_spec.rb b/spec/functions/prefix_spec.rb index 1b771d9..7353857 100644 --- a/spec/functions/prefix_spec.rb +++ b/spec/functions/prefix_spec.rb @@ -1,29 +1,31 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'prefix' do it { is_expected.not_to eq(nil) } 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, %r{wrong number of arguments}i) } 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([], '').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({}).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({}, '').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({ 'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3' }, 'pre') \ .and_return('prekey1' => 'value1', 'prekey2' => 'value2', 'prekey3' => 'value3') } end diff --git a/spec/functions/private_spec.rb b/spec/functions/private_spec.rb index cfd78c4..e0f2667 100644 --- a/spec/functions/private_spec.rb +++ b/spec/functions/private_spec.rb @@ -1,52 +1,54 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'private' do it 'issues a warning' do - expect(scope).to receive(: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 + expect(scope).to receive(: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 Layout/LineLength : unable to cut line to required length begin subject.execute - rescue # rubocop:disable Lint/HandleExceptions + rescue # ignore this end end context 'when called from inside module' do it 'does not fail' do expect(scope).to receive(:lookupvar).with('module_name').and_return('foo') expect(scope).to receive(:lookupvar).with('caller_module_name').and_return('foo') expect { subject.execute }.not_to raise_error end end context 'with an explicit failure message' do it 'prints the failure message on error' do expect(scope).to receive(:lookupvar).with('module_name').and_return('foo') expect(scope).to receive(:lookupvar).with('caller_module_name').and_return('bar') expect { subject.execute('failure message!') }.to raise_error(Puppet::ParseError, %r{failure message!}) end end context 'when called from private class' do it 'fails with a class error message' do expect(scope).to receive(:lookupvar).with('module_name').and_return('foo') expect(scope).to receive(:lookupvar).with('caller_module_name').and_return('bar') expect(scope.source).to receive(:name).and_return('foo::baz') expect(scope.source).to receive(:type).and_return('hostclass') expect { subject.execute }.to raise_error(Puppet::ParseError, %r{Class foo::baz is private}) end end context 'when called from private definition' do it 'fails with a class error message' do expect(scope).to receive(:lookupvar).with('module_name').and_return('foo') expect(scope).to receive(:lookupvar).with('caller_module_name').and_return('bar') expect(scope.source).to receive(:name).and_return('foo::baz') expect(scope.source).to receive(:type).and_return('definition') expect { subject.execute }.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 31010d6..ac7d097 100644 --- a/spec/functions/pw_hash_spec.rb +++ b/spec/functions/pw_hash_spec.rb @@ -1,79 +1,81 @@ +# frozen_string_literal: true + 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, %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, %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, %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 it { is_expected.to run.with_params('', 'sha-256', 'salt').and_return(nil) } it { is_expected.to run.with_params(nil, 'sha-256', 'salt').and_return(nil) } end context 'when the second argument is not a string' do 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, %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, %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, %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, %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') } # 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, %r{system does not support enhanced salts}) } end 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.') } end 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('password', 'md5', Puppet::Pops::Types::PSensitiveType::Sensitive.new('salt')).and_return('$1$salt$qJH7.N4xYta3aEG/dfqo/0') } end end end end diff --git a/spec/functions/range_spec.rb b/spec/functions/range_spec.rb index 7b9e6d4..f6d9a2f 100644 --- a/spec/functions/range_spec.rb +++ b/spec/functions/range_spec.rb @@ -1,157 +1,159 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'range' do it { is_expected.not_to eq(nil) } - describe 'signature validation in puppet3', :unless => RSpec.configuration.puppet_future do + 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, %r{wrong number of arguments}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 + 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', '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('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']) } end context 'with integers as bounds' do it { is_expected.to run.with_params(4, 1).and_return([]) } it { is_expected.to run.with_params(1, 1).and_return([1]) } it { is_expected.to run.with_params(1, 2).and_return([1, 2]) } it { is_expected.to run.with_params(1, 4).and_return([1, 2, 3, 4]) } it { is_expected.to run.with_params(1, 4, 1).and_return([1, 2, 3, 4]) } it { is_expected.to run.with_params(1, 4, '1').and_return([1, 2, 3, 4]) } it { is_expected.to run.with_params(1, 4, 2).and_return([1, 3]) } it { is_expected.to run.with_params(1, 4, -2).and_return([1, 3]) } it { is_expected.to run.with_params(1, 4, 3).and_return([1, 4]) } it { is_expected.to run.with_params(1, 4, 4).and_return([1]) } end context 'with integers as strings as bounds' do it { is_expected.to run.with_params('4', '1').and_return([]) } it { is_expected.to run.with_params('1', '1').and_return([1]) } it { is_expected.to run.with_params('1', '2').and_return([1, 2]) } it { is_expected.to run.with_params('1', '4').and_return([1, 2, 3, 4]) } it { is_expected.to run.with_params('1', '4', 1).and_return([1, 2, 3, 4]) } it { is_expected.to run.with_params('1', '4', '1').and_return([1, 2, 3, 4]) } it { is_expected.to run.with_params('1', '4', 2).and_return([1, 3]) } it { is_expected.to run.with_params('1', '4', -2).and_return([1, 3]) } it { is_expected.to run.with_params('1', '4', 3).and_return([1, 4]) } it { is_expected.to run.with_params('1', '4', 4).and_return([1]) } 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('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']) } 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']) } end context 'with dash-range syntax' do it { is_expected.to run.with_params('4-1').and_return([]) } it { is_expected.to run.with_params('1-1').and_return([1]) } it { is_expected.to run.with_params('1-2').and_return([1, 2]) } it { is_expected.to run.with_params('1-4').and_return([1, 2, 3, 4]) } end context 'with two-dot-range syntax' do it { is_expected.to run.with_params('4..1').and_return([]) } it { is_expected.to run.with_params('1..1').and_return([1]) } it { is_expected.to run.with_params('1..2').and_return([1, 2]) } it { is_expected.to run.with_params('1..4').and_return([1, 2, 3, 4]) } end context 'with three-dot-range syntax' do it { is_expected.to run.with_params('4...1').and_return([]) } it { is_expected.to run.with_params('1...1').and_return([]) } it { is_expected.to run.with_params('1...2').and_return([1]) } it { is_expected.to run.with_params('1...3').and_return([1, 2]) } it { is_expected.to run.with_params('1...5').and_return([1, 2, 3, 4]) } end 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') # rubocop:disable Metrics/LineLength : unable to cut line to required length + 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 Layout/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') # rubocop:disable Metrics/LineLength : unable to cut line to required length + 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 Layout/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') # rubocop:disable Metrics/LineLength : unable to cut line to required length + 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 Layout/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 b60cb99..b8d66cf 100644 --- a/spec/functions/regexpescape_spec.rb +++ b/spec/functions/regexpescape_spec.rb @@ -1,41 +1,43 @@ +# frozen_string_literal: true + require 'spec_helper' 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, %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, %r{wrong number of arguments}i) } 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 'calls ruby\'s Regexp.escape function' do expect(Regexp).to receive(:escape).with('regexp_string').and_return('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 'calls ruby\'s Regexp.escape function' do regexp_string = AlsoString.new('regexp_string') expect(Regexp).to receive(:escape).with(regexp_string).and_return('escaped_regexp_string').once 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']) } context 'with UTF8 and double byte characters' do it { is_expected.to run.with_params(['ŏʼnε*']).and_return(['ŏʼnε\*']) } it { is_expected.to run.with_params(['インターネット*']).and_return(['インターネット\*']) } end end end diff --git a/spec/functions/reject_spec.rb b/spec/functions/reject_spec.rb index b7f6d2e..efc3b69 100644 --- a/spec/functions/reject_spec.rb +++ b/spec/functions/reject_spec.rb @@ -1,20 +1,22 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'reject' do it { is_expected.not_to eq(nil) } 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, %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, %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ệ']) } end diff --git a/spec/functions/reverse_spec.rb b/spec/functions/reverse_spec.rb index 93a4e2a..cad7086 100644 --- a/spec/functions/reverse_spec.rb +++ b/spec/functions/reverse_spec.rb @@ -1,33 +1,35 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'reverse' do it { is_expected.not_to eq(nil) } 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, %r{wrong number of arguments}i) } 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('').and_return('') } it { is_expected.to run.with_params('a').and_return('a') } it { is_expected.to run.with_params('abc').and_return('cba') } it { is_expected.to run.with_params('abcd').and_return('dcba') } it { is_expected.to run.with_params('āβćđ').and_return('đćβā') } context 'when using a class extending String' do it 'calls its reverse method' do value = AlsoString.new('asdfghjkl') expect_any_instance_of(AlsoString).to receive(:reverse).and_return('foo') # rubocop:disable RSpec/AnyInstance expect(subject).to run.with_params(value).and_return('foo') end end end diff --git a/spec/functions/round_spec.rb b/spec/functions/round_spec.rb index fa8ebd5..7b3baf1 100644 --- a/spec/functions/round_spec.rb +++ b/spec/functions/round_spec.rb @@ -1,14 +1,16 @@ +# frozen_string_literal: true + require 'spec_helper' -describe 'round', :if => Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do +describe 'round', if: Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params(34.3).and_return(34) } it { is_expected.to run.with_params(-34.3).and_return(-34) } it { is_expected.to run.with_params(34.5).and_return(35) } 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(3, 4).and_raise_error Puppet::ParseError } end diff --git a/spec/functions/rstrip_spec.rb b/spec/functions/rstrip_spec.rb index 60776d8..251fb66 100644 --- a/spec/functions/rstrip_spec.rb +++ b/spec/functions/rstrip_spec.rb @@ -1,35 +1,37 @@ +# frozen_string_literal: true + require 'spec_helper' -describe 'rstrip', :if => Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do +describe 'rstrip', if: Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do it { is_expected.not_to eq(nil) } 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, %r{wrong number of arguments}i) } 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('') } it { is_expected.to run.with_params("\t").and_return('') } it { is_expected.to run.with_params("\t ").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').and_return(' one') } it { is_expected.to run.with_params("\tone").and_return("\tone") } it { is_expected.to run.with_params("\t one").and_return("\t 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 ').and_return(' one') } it { is_expected.to run.with_params(' ǿňè ').and_return(' ǿňè') } it { is_expected.to run.with_params("\tone ").and_return("\tone") } it { is_expected.to run.with_params("\t one ").and_return("\t one") } it { is_expected.to run.with_params("one\t").and_return('one') } it { is_expected.to run.with_params(" one\t").and_return(' one') } it { is_expected.to run.with_params(" one\t").and_return(' one') } it { is_expected.to run.with_params("\tone\t").and_return("\tone") } it { is_expected.to run.with_params("\t one\t").and_return("\t one") } it { is_expected.to run.with_params(' o n e ').and_return(' o n e') } it { is_expected.to run.with_params(AlsoString.new(' one ')).and_return(' one') } end diff --git a/spec/functions/seeded_rand_spec.rb b/spec/functions/seeded_rand_spec.rb index 0bd8d6d..9ee3b86 100644 --- a/spec/functions/seeded_rand_spec.rb +++ b/spec/functions/seeded_rand_spec.rb @@ -1,58 +1,60 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'seeded_rand' do it { is_expected.not_to eq(nil) } 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 } # 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 first_random = seeded_rand(1000, 'seed1') second_different_random = seeded_rand(1000, 'seed2') expect(first_random).not_to eql(second_different_random) end 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') + val1 = seeded_rand(1000, 'foo', host: 'first.host.com') + val2 = seeded_rand(1000, 'foo', host: 'second.host.com') expect(val1).to eql(val2) end def seeded_rand(max, seed, args = {}) host = args[:host] || '127.0.0.1' # workaround not being able to use let(:facts) because some tests need # multiple different hostnames in one context allow(scope).to receive(:lookupvar).with('::fqdn', {}).and_return(host) scope.function_seeded_rand([max, seed]) end context 'with UTF8 and double byte characters' do it { is_expected.to run.with_params(1000, 'ǿňè') } it { is_expected.to run.with_params(1000, '文字列') } end end diff --git a/spec/functions/seeded_rand_string_spec.rb b/spec/functions/seeded_rand_string_spec.rb index 9083feb..66a5a16 100644 --- a/spec/functions/seeded_rand_string_spec.rb +++ b/spec/functions/seeded_rand_string_spec.rb @@ -1,34 +1,36 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'seeded_rand_string' do it { is_expected.not_to be(nil) } # Test for erroneous params it { is_expected.to run.with_params.and_raise_error(ArgumentError, %r{expects between.+got none}i) } it { is_expected.to run.with_params(1).and_raise_error(ArgumentError, %r{expects between.+got 1}i) } it { is_expected.to run.with_params('1', 'hello').and_raise_error(ArgumentError, %r{parameter 'length' expects an Integer value}i) } it { is_expected.to run.with_params(1, 1).and_raise_error(ArgumentError, %r{parameter 'seed' expects a String value}i) } it { is_expected.to run.with_params(1, 'hello', 1).and_raise_error(ArgumentError, %r{parameter 'charset' expects a.+String}i) } # Test regular run it { is_expected.to run.with_params(100, 'hello') } # Test custom charsets it { is_expected.to run.with_params(100, 'hello', 'abcd').and_return(%r{[a-d]{100}}) } it { is_expected.to run.with_params(100, 'hello', 'abcdefgh').and_return(%r{[a-h]{100}}) } it { is_expected.to run.with_params(100, 'hello', 'ab,|').and_return(%r{[ab,|]{100}}) } # Test behavior it 'generates the same string with the same seed' do rand_str_one = call_function(:seeded_rand_string, 300, 'my_seed') rand_str_two = call_function(:seeded_rand_string, 300, 'my_seed') expect(rand_str_one).to eq(rand_str_two) end it 'generates different strings if seeded differently' do rand_str_one = call_function(:seeded_rand_string, 300, 'my_seed_one') rand_str_two = call_function(:seeded_rand_string, 300, 'my_seed_two') expect(rand_str_one).not_to eq(rand_str_two) end end diff --git a/spec/functions/shell_escape_spec.rb b/spec/functions/shell_escape_spec.rb index 1e86d7c..4b17237 100644 --- a/spec/functions/shell_escape_spec.rb +++ b/spec/functions/shell_escape_spec.rb @@ -1,29 +1,31 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'shell_escape' do it { is_expected.not_to eq(nil) } describe 'signature validation' do 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 it { is_expected.to run.with_params(10).and_return('10') } it { is_expected.to run.with_params(false).and_return('false') } end 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('\~\`\!@\#\$\%\^\&\*\(\)_-\=\[\]\\\\\{\}\|\;\\\':\",./\<\>\?') } end context '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\\ \\ \\ŧ\\ĕ\\χ\\ť') } end end diff --git a/spec/functions/shell_join_spec.rb b/spec/functions/shell_join_spec.rb index 8c4ba1e..f29bf53 100644 --- a/spec/functions/shell_join_spec.rb +++ b/spec/functions/shell_join_spec.rb @@ -1,30 +1,32 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'shell_join' do it { is_expected.not_to eq(nil) } describe 'signature validation' do 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(['foo', 'bar baz']).and_return('foo bar\ baz') } it { is_expected.to run.with_params(['~`!@#$', '%^&*()_-=', '[]\{}|;\':"', ',./<>?']) .and_return('\~\`\!@\#\$ \%\^\&\*\(\)_-\= \[\]\\\\\{\}\|\;\\\':\" ,./\<\>\?') } context '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('\\ス\\ペ\\ー \\ス\\を\\含\\む\\テ \\ \\キ\\ス\\ト') } end end describe 'stringification' do it { is_expected.to run.with_params([10, false, 'foo']).and_return('10 false foo') } end end diff --git a/spec/functions/shell_split_spec.rb b/spec/functions/shell_split_spec.rb index 4a72cab..82d41f1 100644 --- a/spec/functions/shell_split_spec.rb +++ b/spec/functions/shell_split_spec.rb @@ -1,33 +1,35 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'shell_split' do it { is_expected.not_to eq(nil) } describe 'signature validation' do 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 it { is_expected.to run.with_params(10).and_return(['10']) } it { is_expected.to run.with_params(false).and_return(['false']) } end 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(['~`!@#$', '%^&*()_+-=', '[]\{}|;\':"', ',./<>?']) } context '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(['スペー', 'スを含むテ', ' キスト']) } end end end diff --git a/spec/functions/shuffle_spec.rb b/spec/functions/shuffle_spec.rb index a3b68a8..0e4b1e5 100644 --- a/spec/functions/shuffle_spec.rb +++ b/spec/functions/shuffle_spec.rb @@ -1,38 +1,40 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'shuffle' do it { is_expected.not_to eq(nil) } 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, %r{wrong number of arguments}i) } 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 before(:each) { srand(2) } 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('').and_return('') } it { is_expected.to run.with_params('a').and_return('a') } it { is_expected.to run.with_params('abc').and_return('bac') } it { is_expected.to run.with_params('abcd').and_return('dcba') } context '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('字本日語文列の') } end context 'when using a class extending String' do it { is_expected.to run.with_params(AlsoString.new('asdfghjkl')).and_return('lkhdsfajg') } end end end diff --git a/spec/functions/size_spec.rb b/spec/functions/size_spec.rb index 69fdff2..386f912 100644 --- a/spec/functions/size_spec.rb +++ b/spec/functions/size_spec.rb @@ -1,38 +1,40 @@ +# frozen_string_literal: true + require 'spec_helper' -describe 'size', :if => Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do +describe 'size', if: Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do it { is_expected.not_to eq(nil) } 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, %r{wrong number of arguments}i) } 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({}).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('').and_return(0) } it { is_expected.to run.with_params('a').and_return(1) } it { is_expected.to run.with_params('abc').and_return(3) } it { is_expected.to run.with_params('abcd').and_return(4) } it { is_expected.to run.with_params('万').and_return(1) } it { is_expected.to run.with_params('āβćđ').and_return(4) } - context 'when using a class extending String', :unless => Puppet::Util::Package.versioncmp(Puppet.version, '5.5.7') == 0 do + context 'when using a class extending String', unless: Puppet::Util::Package.versioncmp(Puppet.version, '5.5.7') == 0 do it 'calls its size method' do value = AlsoString.new('asdfghjkl') expect(value).to receive(:size).and_return('foo') expect(subject).to run.with_params(value).and_return('foo') end end end diff --git a/spec/functions/sort_spec.rb b/spec/functions/sort_spec.rb index 0e6e8e6..3387e75 100644 --- a/spec/functions/sort_spec.rb +++ b/spec/functions/sort_spec.rb @@ -1,37 +1,39 @@ +# frozen_string_literal: true + require 'spec_helper' -describe 'sort', :if => Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do +describe 'sort', if: Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do describe 'signature validation' do it { is_expected.not_to eq(nil) } 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']) } end context 'when called with a string' 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('cbda').and_return('abcd') } end context 'when called with a number' do it { is_expected.to run.with_params('9478').and_return('4789') } end end diff --git a/spec/functions/sprintf_hash_spec.rb b/spec/functions/sprintf_hash_spec.rb index 4bead46..4e72d3d 100644 --- a/spec/functions/sprintf_hash_spec.rb +++ b/spec/functions/sprintf_hash_spec.rb @@ -1,33 +1,35 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'sprintf_hash' do it 'exists' do is_expected.not_to eq(nil) end context 'with param count' do it 'fails with no arguments' do is_expected.to run.with_params.and_raise_error(ArgumentError, %r{expects 2 arguments}i) end it 'fails with 1 argument' do is_expected.to run.with_params('').and_raise_error(ArgumentError, %r{expects 2 arguments}i) end it 'fails with too many arguments' do is_expected.to run.with_params('', '', '').and_raise_error(ArgumentError, %r{expects 2 arguments}i) end end context 'with param type' do it 'fails with wrong format type' do is_expected.to run.with_params(false, {}).and_raise_error(ArgumentError, %r{parameter 'format' expects a String value}i) end it 'fails with wrong arguments type' do is_expected.to run.with_params('', false).and_raise_error(ArgumentError, %r{parameter 'arguments' expects a Hash value}i) end end it 'prints formats with name placeholders' do 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 ee144b3..2818461 100644 --- a/spec/functions/squeeze_spec.rb +++ b/spec/functions/squeeze_spec.rb @@ -1,50 +1,52 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'squeeze' do it { is_expected.not_to eq(nil) } 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) } context 'when squeezing a single string' 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('aaaaaaaaa').and_return('a') } it { is_expected.to run.with_params('aaaaaaaaa', 'a').and_return('a') } it { is_expected.to run.with_params('aaaaaaaaabbbbbbbbbbcccccccccc', 'b-c').and_return('aaaaaaaaabc') } end context '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 context 'when squeezing values in an array' do it { is_expected.to run \ .with_params(['', 'a', 'aaaaaaaaa', 'aaaaaaaaabbbbbbbbbbcccccccccc']) \ .and_return(['', 'a', 'a', 'abc']) } it { is_expected.to run \ .with_params(['', 'a', 'aaaaaaaaa', 'aaaaaaaaabbbbbbbbbbcccccccccc'], 'a') \ .and_return(['', 'a', 'a', 'abbbbbbbbbbcccccccccc']) } it { is_expected.to run \ .with_params(['', 'a', 'aaaaaaaaa', 'aaaaaaaaabbbbbbbbbbcccccccccc'], 'b-c') \ .and_return(['', 'a', 'aaaaaaaaa', 'aaaaaaaaabc']) } end context 'when using a class extending String' do it 'calls its squeeze method' do value = AlsoString.new('aaaaaaaaa') expect_any_instance_of(AlsoString).to receive(:squeeze).and_return('foo') # rubocop:disable RSpec/AnyInstance expect(subject).to run.with_params(value).and_return('foo') end end end diff --git a/spec/functions/startswith_spec.rb b/spec/functions/startswith_spec.rb index a259192..a3478bb 100644 --- a/spec/functions/startswith_spec.rb +++ b/spec/functions/startswith_spec.rb @@ -1,11 +1,13 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'stdlib::start_with' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(ArgumentError, %r{expects 2 arguments, got none}i) } it { is_expected.to run.with_params('').and_raise_error(ArgumentError, %r{expects 2 arguments, got 1}) } it { is_expected.to run.with_params('', 'foo').and_return(false) } it { is_expected.to run.with_params('foobar', 'foo').and_return(true) } it { is_expected.to run.with_params('foObar', ['bar', 'baz']).and_return(false) } end diff --git a/spec/functions/stdlib_ensure_spec.rb b/spec/functions/stdlib_ensure_spec.rb index ebdcb9c..8a110b8 100644 --- a/spec/functions/stdlib_ensure_spec.rb +++ b/spec/functions/stdlib_ensure_spec.rb @@ -1,18 +1,20 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'stdlib::ensure' do context 'work with service resource' do it { is_expected.to run.with_params('present', 'service').and_return('running') } it { is_expected.to run.with_params(true, 'service').and_return('running') } it { is_expected.to run.with_params('absent', 'service').and_return('stopped') } it { is_expected.to run.with_params(false, 'service').and_return('stopped') } end ['directory', 'link', 'mounted', 'file'].each do |resource| context "work with #{resource} resource" do it { is_expected.to run.with_params('present', resource).and_return(resource) } it { is_expected.to run.with_params(true, resource).and_return(resource) } it { is_expected.to run.with_params('absent', resource).and_return('absent') } it { is_expected.to run.with_params(false, resource).and_return('absent') } end end end diff --git a/spec/functions/str2bool_spec.rb b/spec/functions/str2bool_spec.rb index fe43c4c..070955c 100644 --- a/spec/functions/str2bool_spec.rb +++ b/spec/functions/str2bool_spec.rb @@ -1,23 +1,25 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'str2bool' do it { is_expected.not_to eq(nil) } 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, %r{wrong number of arguments}i) } 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| 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| it { is_expected.to run.with_params(value).and_return(false) } end end end diff --git a/spec/functions/str2saltedpbkdf2_spec.rb b/spec/functions/str2saltedpbkdf2_spec.rb index 48dcdc4..c46df7a 100644 --- a/spec/functions/str2saltedpbkdf2_spec.rb +++ b/spec/functions/str2saltedpbkdf2_spec.rb @@ -1,23 +1,25 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'str2saltedpbkdf2' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(ArgumentError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params('Pa55w0rd', 2).and_raise_error(ArgumentError, %r{wrong number of arguments}i) } it { is_expected.to run.with_params(1, 'Using s0m3 s@lt', 50_000).and_raise_error(ArgumentError, %r{first argument must be a string}) } it { is_expected.to run.with_params('Pa55w0rd', 1, 50_000).and_raise_error(ArgumentError, %r{second argument must be a string}) } it { is_expected.to run.with_params('Pa55w0rd', 'U', 50_000).and_raise_error(ArgumentError, %r{second argument must be at least 8 bytes long}) } it { is_expected.to run.with_params('Pa55w0rd', 'Using s0m3 s@lt', '50000').and_raise_error(ArgumentError, %r{third argument must be an integer}) } it { is_expected.to run.with_params('Pa55w0rd', 'Using s0m3 s@lt', 1).and_raise_error(ArgumentError, %r{third argument must be between 40,000 and 70,000}) } context 'when running with "Pa55w0rd", "Using s0m3 s@lt",and "50000" as params' do - # rubocop:disable Metrics/LineLength + # rubocop:disable Layout/LineLength it { is_expected.to run.with_params('Pa55w0rd', 'Using s0m3 s@lt', 50_000) .and_return('password_hex' => '3577f79f7d2e73df1cf1eecc36da16fffcd3650126d79e797a8b227492d13de4cdd0656933b43118b7361692f755e5b3c1e0536f826d12442400f3467bcc8fb4ac2235d5648b0f1b0906d0712aecd265834319b5a42e98af2ced81597fd78d1ac916f6eff6122c3577bb120a9f534e2a5c9a58c7d1209e3914c967c6a467b594', 'salt_hex' => '5573696e672073306d332073406c74', 'iterations' => 50_000) } - # rubocop:enable Metrics/LineLength + # rubocop:enable Layout/LineLength end end diff --git a/spec/functions/str2saltedsha512_spec.rb b/spec/functions/str2saltedsha512_spec.rb index e7513c9..ae50ea7 100644 --- a/spec/functions/str2saltedsha512_spec.rb +++ b/spec/functions/str2saltedsha512_spec.rb @@ -1,26 +1,28 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'str2saltedsha512' do it { is_expected.not_to eq(nil) } 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') } end end diff --git a/spec/functions/strip_spec.rb b/spec/functions/strip_spec.rb index 28f8d86..1328baa 100644 --- a/spec/functions/strip_spec.rb +++ b/spec/functions/strip_spec.rb @@ -1,35 +1,37 @@ +# frozen_string_literal: true + require 'spec_helper' -describe 'strip', :if => Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do +describe 'strip', if: Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do it { is_expected.not_to eq(nil) } 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, %r{wrong number of arguments}i) } 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('') } it { is_expected.to run.with_params("\t").and_return('') } it { is_expected.to run.with_params("\t ").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').and_return('one') } it { is_expected.to run.with_params("\tone").and_return('one') } it { is_expected.to run.with_params("\t 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 ').and_return('one') } it { is_expected.to run.with_params("\tone ").and_return('one') } it { is_expected.to run.with_params("\t one ").and_return('one') } it { is_expected.to run.with_params("one \t").and_return('one') } it { is_expected.to run.with_params(" one \t").and_return('one') } it { is_expected.to run.with_params(" one \t").and_return('one') } it { is_expected.to run.with_params("\tone \t").and_return('one') } it { is_expected.to run.with_params("\t one \t").and_return('one') } it { is_expected.to run.with_params(' o n e ').and_return('o n e') } it { is_expected.to run.with_params(' ỏŋέ ').and_return('ỏŋέ') } it { is_expected.to run.with_params(AlsoString.new(' one ')).and_return('one') } end diff --git a/spec/functions/suffix_spec.rb b/spec/functions/suffix_spec.rb index 802d598..0c12100 100644 --- a/spec/functions/suffix_spec.rb +++ b/spec/functions/suffix_spec.rb @@ -1,30 +1,32 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'suffix' do it { is_expected.not_to eq(nil) } 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, %r{wrong number of arguments}i) } 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([], '').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(['ỗńέ', 'ťשׂǿ', 'ŧҺř℮ə'], 'рổŝţ').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) } 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' }, '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') } end diff --git a/spec/functions/swapcase_spec.rb b/spec/functions/swapcase_spec.rb index 8370140..49d2117 100644 --- a/spec/functions/swapcase_spec.rb +++ b/spec/functions/swapcase_spec.rb @@ -1,40 +1,42 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'swapcase' do it { is_expected.not_to eq(nil) } 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, %r{wrong number of arguments}i) } 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') } it { is_expected.to run.with_params('ONE').and_return('one') } it { is_expected.to run.with_params('oNe').and_return('OnE') } end describe 'with arrays as inputs' do it { is_expected.to run.with_params([]).and_return([]) } describe 'only containing strings' do 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']).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']) } end describe 'containing mixed types' do it { is_expected.to run.with_params(['OnE', {}]).and_return(['oNe', {}]) } it { is_expected.to run.with_params(['OnE', 1]).and_return(['oNe', 1]) } it { is_expected.to run.with_params(['OnE', []]).and_return(['oNe', []]) } it { is_expected.to run.with_params(['OnE', ['two']]).and_return(['oNe', ['two']]) } end end 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 239e2ab..181bb05 100644 --- a/spec/functions/time_spec.rb +++ b/spec/functions/time_spec.rb @@ -1,21 +1,23 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'time' do it { is_expected.not_to eq(nil) } 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) do # get a value before stubbing the function test_time = Time.utc(2006, 10, 13, 8, 15, 11) allow(Time).to receive(:new).with(no_args).and_return(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 f3efd90..71ee00f 100644 --- a/spec/functions/to_bytes_spec.rb +++ b/spec/functions/to_bytes_spec.rb @@ -1,70 +1,72 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'to_bytes' do it { is_expected.not_to eq(nil) } 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) } it { is_expected.to run.with_params(1).and_return(1) } it { is_expected.to run.with_params(-1).and_return(-1) } 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 describe 'when passing numbers as strings' do describe 'without a unit' do it { is_expected.to run.with_params('1').and_return(1) } it { is_expected.to run.with_params('-1').and_return(-1) } # these are so wrong it { is_expected.to run.with_params('1.1').and_return(1) } it { is_expected.to run.with_params('-1.1').and_return(-1) } end 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('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('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) } it { is_expected.to run.with_params('-1.0001 kB').and_return(-1024) } end describe 'with a unknown unit' do 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 # these are so wrong describe 'when passing random stuff' do it { is_expected.to run.with_params('-1....1').and_return(-1) } it { is_expected.to run.with_params('-1.e.e.e.1').and_return(-1) } it { is_expected.to run.with_params('-1+1').and_return(-1) } it { is_expected.to run.with_params('1-1').and_return(1) } it { is_expected.to run.with_params('1 kaboom').and_return(1024) } it { is_expected.to run.with_params('kaboom').and_return(0) } end end diff --git a/spec/functions/to_json_pretty_spec.rb b/spec/functions/to_json_pretty_spec.rb index 6f1b3fa..071e88a 100644 --- a/spec/functions/to_json_pretty_spec.rb +++ b/spec/functions/to_json_pretty_spec.rb @@ -1,27 +1,29 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'to_json_pretty' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params([]).and_return("[\n\n]\n") } it { is_expected.to run.with_params(['one']).and_return("[\n \"one\"\n]\n") } it { is_expected.to run.with_params(['one', 'two']).and_return("[\n \"one\",\n \"two\"\n]\n") } it { is_expected.to run.with_params({}).and_return("{\n}\n") } it { is_expected.to run.with_params('key' => 'value').and_return("{\n \"key\": \"value\"\n}\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}\n") # rubocop:disable Metrics/LineLength : Unable to reduce line to required length + .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}\n") # rubocop:disable Layout/LineLength : Unable to reduce line to required length } it { is_expected.to run.with_params({ 'one' => '1', 'two' => nil }, true).and_return("{\n \"one\": \"1\"\n}\n") } it { is_expected.to run.with_params(['one', 'two', nil, 'three'], true).and_return("[\n \"one\",\n \"two\",\n \"three\"\n]\n") } it { is_expected.to run.with_params(['one', 'two', nil, 'three'], true, 'indent' => '@@@@').and_return("[\n@@@@\"one\",\n@@@@\"two\",\n@@@@\"three\"\n]\n") } it { pending('Current implementation only elides nil values for arrays of depth=1') is_expected.to run.with_params([[nil], 'two', nil, 'three'], true).and_return("[\n [\n\n ],\n \"two\",\n \"three\"\n]\n") } it { pending('Current implementation only elides nil values for hashes of depth=1') is_expected.to run.with_params({ 'omg' => { 'lol' => nil }, 'what' => nil }, true).and_return("{\n}\n") } end diff --git a/spec/functions/to_json_spec.rb b/spec/functions/to_json_spec.rb index 83bb886..32184d6 100644 --- a/spec/functions/to_json_spec.rb +++ b/spec/functions/to_json_spec.rb @@ -1,22 +1,24 @@ +# frozen_string_literal: true + require 'spec_helper' 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('竹').and_return('"竹"') } it { is_expected.to run.with_params('Ü').and_return('"Ü"') } it { is_expected.to run.with_params('∇').and_return('"∇"') } end diff --git a/spec/functions/to_yaml_spec.rb b/spec/functions/to_yaml_spec.rb index eecb8a4..98985c4 100644 --- a/spec/functions/to_yaml_spec.rb +++ b/spec/functions/to_yaml_spec.rb @@ -1,22 +1,24 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'to_yaml' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params('').and_return("--- ''\n") } it { is_expected.to run.with_params(true).and_return(%r{--- true\n}) } it { is_expected.to run.with_params('one').and_return(%r{--- one\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({}).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('‰').and_return("--- \"‰\"\n") } it { is_expected.to run.with_params('∇').and_return("--- \"∇\"\n") } - it { is_expected.to run.with_params({ 'foo' => { 'bar' => true, 'baz' => false } }, :indentation => 4).and_return("---\nfoo:\n bar: true\n baz: false\n") } + it { is_expected.to run.with_params({ 'foo' => { 'bar' => true, 'baz' => false } }, indentation: 4).and_return("---\nfoo:\n bar: true\n baz: false\n") } end diff --git a/spec/functions/try_get_value_spec.rb b/spec/functions/try_get_value_spec.rb index 6fe9c10..2b9b96c 100644 --- a/spec/functions/try_get_value_spec.rb +++ b/spec/functions/try_get_value_spec.rb @@ -1,112 +1,114 @@ +# frozen_string_literal: true + 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', } end context 'with single values' do it 'exists' do is_expected.not_to eq(nil) end it 'is able to return a single value' do is_expected.to run.with_params('test').and_return('test') end 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 'returns default if there is no data' do is_expected.to run.with_params(nil, nil, 'default').and_return('default') end 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 'with structure values' 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 '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 '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 '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 'supports an array index in the path' do is_expected.to run.with_params(data, 'a/e/1', 'default').and_return('f1') end 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 '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 '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 '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 '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 '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 '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 it 'is able to throw an error with incorrect params' do is_expected.to run.with_params.and_raise_error(ArgumentError, %r{Wrong number of arguments}i) end end end diff --git a/spec/functions/type3x_spec.rb b/spec/functions/type3x_spec.rb index a53362d..7507526 100644 --- a/spec/functions/type3x_spec.rb +++ b/spec/functions/type3x_spec.rb @@ -1,41 +1,43 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'type3x' do it 'exists' do expect(Puppet::Parser::Functions.function('type3x')).to eq('function_type3x') end it 'raises a ParseError if there is less than 1 arguments' do expect { scope.function_type3x([]) }.to(raise_error(Puppet::ParseError)) end it 'returns string when given a string' do result = scope.function_type3x(['aaabbbbcccc']) expect(result).to(eq('string')) end it 'returns array when given an array' do result = scope.function_type3x([['aaabbbbcccc', 'asdf']]) expect(result).to(eq('array')) end it 'returns hash when given a hash' do result = scope.function_type3x([{ 'a' => 1, 'b' => 2 }]) expect(result).to(eq('hash')) end it 'returns integer when given an integer' do result = scope.function_type3x(['1']) expect(result).to(eq('integer')) end it 'returns float when given a float' do result = scope.function_type3x(['1.34']) expect(result).to(eq('float')) end it 'returns boolean when given a boolean' do result = scope.function_type3x([true]) expect(result).to(eq('boolean')) end end diff --git a/spec/functions/type_of_spec.rb b/spec/functions/type_of_spec.rb index 4f55b2c..243b173 100644 --- a/spec/functions/type_of_spec.rb +++ b/spec/functions/type_of_spec.rb @@ -1,25 +1,27 @@ +# frozen_string_literal: true + require 'spec_helper' 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) } end end end 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 'gives the type of a string' do expect(subject.call({}, 'hello world')).to be_kind_of(Puppet::Pops::Types::PStringType) end it 'gives the type of an integer' do expect(subject.call({}, 5)).to be_kind_of(Puppet::Pops::Types::PIntegerType) end end end diff --git a/spec/functions/type_spec.rb b/spec/functions/type_spec.rb index e1d687b..8a0f2a1 100644 --- a/spec/functions/type_spec.rb +++ b/spec/functions/type_spec.rb @@ -1,42 +1,44 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'type' do it 'exists' do expect(Puppet::Parser::Functions.function('type')).to eq('function_type') end it 'gives a deprecation warning when called' do - expect(scope).to receive(: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 + expect(scope).to receive(: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 Layout/LineLength : Unable to reduce to required length scope.function_type(['aoeu']) end it 'returns string when given a string' do result = scope.function_type(['aaabbbbcccc']) expect(result).to(eq('string')) end it 'returns array when given an array' do result = scope.function_type([['aaabbbbcccc', 'asdf']]) expect(result).to(eq('array')) end it 'returns hash when given a hash' do result = scope.function_type([{ 'a' => 1, 'b' => 2 }]) expect(result).to(eq('hash')) end it 'returns integer when given an integer' do result = scope.function_type(['1']) expect(result).to(eq('integer')) end it 'returns float when given a float' do result = scope.function_type(['1.34']) expect(result).to(eq('float')) end it 'returns boolean when given a boolean' do result = scope.function_type([true]) expect(result).to(eq('boolean')) end end diff --git a/spec/functions/union_spec.rb b/spec/functions/union_spec.rb index 5492298..d5ab617 100644 --- a/spec/functions/union_spec.rb +++ b/spec/functions/union_spec.rb @@ -1,25 +1,27 @@ +# frozen_string_literal: true + require 'spec_helper' 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, %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 'does not confuse types' do is_expected.to run.with_params(['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 1cdb934..92234fa 100644 --- a/spec/functions/unique_spec.rb +++ b/spec/functions/unique_spec.rb @@ -1,31 +1,33 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'unique' do 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, %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, %r{wrong number of arguments}i) } 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(['ã', 'ъ']) } end context 'when called with a string' 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('aaba').and_return('ab') } it { is_expected.to run.with_params('ããъã').and_return('ãъ') } end end end diff --git a/spec/functions/unix2dos_spec.rb b/spec/functions/unix2dos_spec.rb index a6af64f..cd94e15 100644 --- a/spec/functions/unix2dos_spec.rb +++ b/spec/functions/unix2dos_spec.rb @@ -1,40 +1,42 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'unix2dos' do context 'when checking parameter validity' do it { is_expected.not_to eq(nil) } it do 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, %r{Wrong number of arguments}) end it do is_expected.to run.with_params([]).and_raise_error(Puppet::ParseError) end it do is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError) end it do is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError) end end context 'when converting from unix to dos format' do sample_text = "Hello\nWorld\n" desired_output = "Hello\r\nWorld\r\n" it 'outputs dos format' do is_expected.to run.with_params(sample_text).and_return(desired_output) end end context 'when converting from dos to dos format' do sample_text = "Hello\r\nWorld\r\n" desired_output = "Hello\r\nWorld\r\n" 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 5b5e426..d110ee1 100644 --- a/spec/functions/upcase_spec.rb +++ b/spec/functions/upcase_spec.rb @@ -1,26 +1,28 @@ +# frozen_string_literal: true + require 'spec_helper' -describe 'upcase', :if => Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do +describe 'upcase', if: Puppet::Util::Package.versioncmp(Puppet.version, '6.0.0') < 0 do describe 'signature validation' do it { is_expected.not_to eq(nil) } 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') } end describe 'handling classes derived from String' do 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']) } end end diff --git a/spec/functions/uriescape_spec.rb b/spec/functions/uriescape_spec.rb index fdc3e20..3ac632a 100644 --- a/spec/functions/uriescape_spec.rb +++ b/spec/functions/uriescape_spec.rb @@ -1,36 +1,38 @@ +# frozen_string_literal: true + require 'spec_helper' 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, %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, %r{wrong number of arguments}i) } 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 'calls ruby\'s URI.escape function' do expect(URI).to receive(:escape).with('uri_string').and_return('escaped_uri_string').once is_expected.to run.with_params('uri_string').and_return('escaped_uri_string') end end describe 'handling classes derived from String' do it 'calls ruby\'s URI.escape function' do uri_string = AlsoString.new('uri_string') expect(URI).to receive(:escape).with(uri_string).and_return('escaped_uri_string').once 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']) } end end diff --git a/spec/functions/validate_absolute_path_spec.rb b/spec/functions/validate_absolute_path_spec.rb index ba73a21..4365229 100644 --- a/spec/functions/validate_absolute_path_spec.rb +++ b/spec/functions/validate_absolute_path_spec.rb @@ -1,51 +1,53 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'validate_absolute_path' do after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end # Checking for deprecation warning it 'displays a single deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' expect(scope).to receive(:warning).with(include('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, %r{wrong number of arguments}i) } end describe 'valid paths handling' do ['C:/', 'C:\\', 'C:\\WINDOWS\\System32', 'C:/windows/system32', 'X:/foo/bar', 'X:\\foo\\bar', '\\\\host\\windows', '//host/windows', '/', '/var/tmp', '/var/opt/../lib/puppet'].each do |path| it { is_expected.to run.with_params(path) } it { is_expected.to run.with_params(['/tmp', path]) } end end describe 'invalid path handling' do context 'with garbage inputs' do [ nil, [nil], [nil, nil], { 'foo' => 'bar' }, {}, '', ].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 context 'with relative paths' do ['relative1', '.', '..', './foo', '../foo', 'etc/puppetlabs/puppet', 'relative\\windows'].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 87b7c24..da8b093 100644 --- a/spec/functions/validate_array_spec.rb +++ b/spec/functions/validate_array_spec.rb @@ -1,36 +1,38 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'validate_array' do describe 'signature validation' do after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end it { is_expected.not_to eq(nil) } # Checking for deprecation warning it 'displays a single deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' expect(scope).to receive(:warning).with(include('This method is deprecated')) is_expected.to run.with_params([]) end 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([]) } it { is_expected.to run.with_params(['one']) } it { is_expected.to run.with_params([], ['two']) } it { is_expected.to run.with_params(['one'], ['two']) } end describe 'invalid inputs' do 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}) } it { is_expected.to run.with_params(nil).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 2dd0df8..04ee0eb 100644 --- a/spec/functions/validate_augeas_spec.rb +++ b/spec/functions/validate_augeas_spec.rb @@ -1,75 +1,77 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'validate_augeas' do 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, %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'], ] inputs.each do |input| it { is_expected.to run.with_params(*input) } end end describe 'valid inputs which fail augeas validation' do # The intent here is to make sure valid inputs raise exceptions when they # 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'], ] inputs.each do |input| 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 # 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'], ] inputs.each do |input| it { is_expected.to run.with_params(*input).and_raise_error(Puppet::ParseError, %r{#{input[3]}}) } end end 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']], ] inputs.each do |input| it { is_expected.to run.with_params(*input) } end end 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']], ] inputs.each do |input| 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 72c1e2d..ffcf1ba 100644 --- a/spec/functions/validate_bool_spec.rb +++ b/spec/functions/validate_bool_spec.rb @@ -1,38 +1,40 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'validate_bool' do after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end # Checking for deprecation warning it 'displays a single deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' expect(scope).to receive(:warning).with(include('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, %r{wrong number of arguments}i) } end describe 'acceptable values' do it { is_expected.to run.with_params(true) } it { is_expected.to run.with_params(false) } it { is_expected.to run.with_params(true, false, false, true) } end describe 'validation failures' do it { is_expected.to run.with_params([]).and_raise_error(Puppet::ParseError, %r{is not a boolean}) } it { is_expected.to run.with_params({}).and_raise_error(Puppet::ParseError, %r{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 91fd0d1..7d8a8a1 100644 --- a/spec/functions/validate_cmd_spec.rb +++ b/spec/functions/validate_cmd_spec.rb @@ -1,41 +1,43 @@ +# frozen_string_literal: true + require 'spec_helper' -describe 'validate_cmd', :unless => Puppet::Util::Platform.windows? do +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, %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, %r{content must be a string}) } it { pending('should implement stricter type checking') 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, %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, %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, %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 0ac1a3d..f48d31a 100644 --- a/spec/functions/validate_domain_name_spec.rb +++ b/spec/functions/validate_domain_name_spec.rb @@ -1,35 +1,37 @@ +# frozen_string_literal: true + require 'spec_helper' 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, %r{wrong number of arguments}i) } end describe 'valid inputs' do it { is_expected.to run.with_params('com', 'com.') } it { is_expected.to run.with_params('x.com', 'x.com.') } it { is_expected.to run.with_params('foo.example.com', 'foo.example.com.') } it { is_expected.to run.with_params('2foo.example.com', '2foo.example.com.') } it { is_expected.to run.with_params('www.2foo.example.com', 'www.2foo.example.com.') } it { is_expected.to run.with_params('domain.tld', 'puppet.com') } end describe 'invalid inputs' do 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, %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, %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 520c7a4..9d87061 100644 --- a/spec/functions/validate_email_address_spec.rb +++ b/spec/functions/validate_email_address_spec.rb @@ -1,23 +1,25 @@ +# frozen_string_literal: true + require 'spec_helper' 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, %r{wrong number of arguments}i) } end describe 'valid inputs' do it { is_expected.to run.with_params('bob@gmail.com') } it { is_expected.to run.with_params('alice+puppetlabs.com@gmail.com') } end describe 'invalid inputs' do 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 1c6213b..89fe882 100644 --- a/spec/functions/validate_hash_spec.rb +++ b/spec/functions/validate_hash_spec.rb @@ -1,39 +1,41 @@ +# frozen_string_literal: true + require 'spec_helper' 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, %r{wrong number of arguments}i) } describe 'check for deprecation warning' do after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end # Checking for deprecation warning it 'displays a single deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' expect(scope).to receive(:warning).with(include('This method is deprecated')) 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') } end describe 'invalid inputs' do 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}) } it { is_expected.to run.with_params("{ 'number' => '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 cf29cf8..6252a6d 100644 --- a/spec/functions/validate_integer_spec.rb +++ b/spec/functions/validate_integer_spec.rb @@ -1,101 +1,103 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'validate_integer' do after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end # Checking for deprecation warning it 'displays a single deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' expect(scope).to receive(:warning).with(include('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, %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, %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 + 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 + 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, %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 it { is_expected.to run.with_params(1) } it { is_expected.to run.with_params(-1) } it { is_expected.to run.with_params('1') } it { is_expected.to run.with_params('-1') } it { is_expected.to run.with_params([1, 2, 3, 4]) } it { is_expected.to run.with_params([1, '2', '3', 4]) } end 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, %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 it { is_expected.to run.with_params(10, 10) } it { is_expected.to run.with_params(1, 10) } it { is_expected.to run.with_params(-1, 10) } it { is_expected.to run.with_params('1', 10) } it { is_expected.to run.with_params('-1', 10) } 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, %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, %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 end it { is_expected.to run.with_params(10, 10, 10) } describe 'empty upper limit is interpreted as infinity' do it { is_expected.to run.with_params(11, '', 10) } end end diff --git a/spec/functions/validate_ip_address_spec.rb b/spec/functions/validate_ip_address_spec.rb index 8fd145e..ded6df9 100644 --- a/spec/functions/validate_ip_address_spec.rb +++ b/spec/functions/validate_ip_address_spec.rb @@ -1,64 +1,66 @@ +# frozen_string_literal: true + 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, %r{wrong number of arguments}i) } end describe 'valid inputs' do it { is_expected.to run.with_params('0.0.0.0') } it { is_expected.to run.with_params('8.8.8.8') } it { is_expected.to run.with_params('127.0.0.1') } it { is_expected.to run.with_params('10.10.10.10') } it { is_expected.to run.with_params('194.232.104.150') } it { is_expected.to run.with_params('244.24.24.24') } it { is_expected.to run.with_params('255.255.255.255') } it { is_expected.to run.with_params('1.2.3.4', '5.6.7.8') } it { is_expected.to run.with_params('3ffe:0505:0002::') } it { is_expected.to run.with_params('3ffe:0505:0002::', '3ffe:0505:0002::2') } it { is_expected.to run.with_params('::1/64') } 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 + context 'Checking for deprecation warning', if: Puppet.version.to_f < 4.0 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 'displays a single deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' expect(scope).to receive(:warning).with(include('This method is deprecated')) is_expected.to run.with_params('1.2.3.4') end it 'displays no warning for deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'false' expect(scope).to receive(:warning).with(include('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') } it { is_expected.to run.with_params('8.8.8.8/32') } it { is_expected.to run.with_params('8.8.8.8/255.255.0.0') } end end describe 'invalid inputs' do 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 72c3e7a..bc8ed76 100644 --- a/spec/functions/validate_ipv4_address_spec.rb +++ b/spec/functions/validate_ipv4_address_spec.rb @@ -1,45 +1,47 @@ +# frozen_string_literal: true + 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, %r{wrong number of arguments}i) } end - context 'Checking for deprecation warning', :if => Puppet.version.to_f < 4.0 do + context 'Checking for deprecation warning', if: Puppet.version.to_f < 4.0 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 'displays a single deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' expect(scope).to receive(:warning).with(include('This method is deprecated')) is_expected.to run.with_params(SharedData::IPV4_PATTERNS.first) end it 'displays no warning for deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'false' expect(scope).to receive(:warning).with(include('This method is deprecated')).never is_expected.to run.with_params(SharedData::IPV4_PATTERNS.first) end end SharedData::IPV4_PATTERNS.each do |value| it { is_expected.to run.with_params(value) } end SharedData::IPV4_NEGATIVE_PATTERNS.each do |value| 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, %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 describe 'multiple inputs' do it { is_expected.to run.with_params(SharedData::IPV4_PATTERNS[0], SharedData::IPV4_PATTERNS[1]) } it { is_expected.to run.with_params(SharedData::IPV4_PATTERNS[0], 'invalid ip').and_raise_error(Puppet::ParseError, %r{is not a valid IPv4}) } end end diff --git a/spec/functions/validate_ipv6_address_spec.rb b/spec/functions/validate_ipv6_address_spec.rb index 0834307..3e1563e 100644 --- a/spec/functions/validate_ipv6_address_spec.rb +++ b/spec/functions/validate_ipv6_address_spec.rb @@ -1,59 +1,61 @@ +# frozen_string_literal: true + 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, %r{wrong number of arguments}i) } end - context 'Checking for deprecation warning', :if => Puppet.version.to_f < 4.0 do + context 'Checking for deprecation warning', if: Puppet.version.to_f < 4.0 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 'displays a single deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' expect(scope).to receive(:warning).with(include('This method is deprecated')) is_expected.to run.with_params('3ffe:0505:0002::') end it 'displays no warning for deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'false' expect(scope).to receive(:warning).with(include('This method is deprecated')).never is_expected.to run.with_params('3ffe:0505:0002::') end end describe 'valid inputs' do it { is_expected.to run.with_params('3ffe:0505:0002::') } it { is_expected.to run.with_params('3ffe:0505:0002::', '3ffe:0505:0002::2') } it { is_expected.to run.with_params('::1/64') } it { is_expected.to run.with_params('fe80::a00:27ff:fe94:44d6/64') } it { is_expected.to run.with_params('fe80:0000:0000:0000:0204:61ff:fe9d:f156') } it { is_expected.to run.with_params('fe80:0:0:0:204:61ff:fe9d:f156') } it { is_expected.to run.with_params('fe80::204:61ff:fe9d:f156') } it { is_expected.to run.with_params('fe80:0:0:0:0204:61ff:254.157.241.86') } it { is_expected.to run.with_params('::1') } it { is_expected.to run.with_params('fe80::') } it { is_expected.to run.with_params('2001::') } end describe 'invalid inputs' do 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 + 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 6c65d5e..0998cf6 100644 --- a/spec/functions/validate_legacy_spec.rb +++ b/spec/functions/validate_legacy_spec.rb @@ -1,56 +1,58 @@ +# frozen_string_literal: true + require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.4.0') >= 0 describe 'validate_legacy' do it { is_expected.not_to eq(nil) } it { is_expected.to run.with_params.and_raise_error(ArgumentError) } describe 'when passing the type assertion and passing the previous validation' do it 'passes without notice' do expect(scope).to receive(:function_validate_foo).with([5]).once expect(Puppet).to receive(:notice).never is_expected.to run.with_params('Integer', 'validate_foo', 5) end end describe 'when passing the type assertion and failing the previous validation' do it 'passes with a notice about newly accepted value' do expect(scope).to receive(:function_validate_foo).with([5]).and_raise(Puppet::ParseError, 'foo').once expect(Puppet).to receive(:notice).with(include('Accepting previously invalid value for target type')) is_expected.to run.with_params('Integer', 'validate_foo', 5) end end describe 'when failing the type assertion and passing the previous validation' do it 'passes with a deprecation message' do expect(scope).to receive(:function_validate_foo).with(['5']).once expect(subject.func).to receive(:call_function).with('deprecation', 'validate_legacy', include('Integer')).once is_expected.to run.with_params('Integer', 'validate_foo', '5') end end describe 'when failing the type assertion and failing the previous validation' do it 'fails with a helpful message' do expect(scope).to receive(:function_validate_foo).with(['5']).and_raise(Puppet::ParseError, 'foo').once expect(subject.func).to receive(:call_function).with('fail', include('Integer')).once is_expected.to run.with_params('Integer', 'validate_foo', '5') end end describe 'when passing in undef' do it 'works' do expect(scope).to receive(:function_validate_foo).with([:undef]).once expect(Puppet).to receive(:notice).never is_expected.to run.with_params('Optional[Integer]', 'validate_foo', :undef) end end describe 'when passing in multiple arguments' do it 'passes with a deprecation message' do expect(scope).to receive(:function_validate_foo).with([:undef, 1, 'foo']).once expect(Puppet).to receive(:notice).never is_expected.to run.with_params('Optional[Integer]', 'validate_foo', :undef, 1, 'foo') end end end end diff --git a/spec/functions/validate_numeric_spec.rb b/spec/functions/validate_numeric_spec.rb index 80b3e37..8b593c3 100644 --- a/spec/functions/validate_numeric_spec.rb +++ b/spec/functions/validate_numeric_spec.rb @@ -1,100 +1,102 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'validate_numeric' do after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end # Checking for deprecation warning it 'displays a single deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' expect(scope).to receive(:warning).with(include('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, %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, %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 + 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 + 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, %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 it { is_expected.to run.with_params(1) } it { is_expected.to run.with_params(-1) } it { is_expected.to run.with_params('1') } it { is_expected.to run.with_params('-1') } it { is_expected.to run.with_params([1, 2, 3, 4]) } it { is_expected.to run.with_params([1, '2', '3', 4]) } end 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, %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 it { is_expected.to run.with_params(10.0, 10.0) } it { is_expected.to run.with_params(1, 10.0) } it { is_expected.to run.with_params(-1, 10.0) } it { is_expected.to run.with_params('1', 10.0) } it { is_expected.to run.with_params('-1', 10.0) } 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, %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, %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 end it { is_expected.to run.with_params(10.0, 10.0, 10.0) } describe 'empty upper limit is interpreted as infinity' do it { is_expected.to run.with_params(11, '', 10.0) } end end diff --git a/spec/functions/validate_re_spec.rb b/spec/functions/validate_re_spec.rb index 2a50689..bfa824e 100644 --- a/spec/functions/validate_re_spec.rb +++ b/spec/functions/validate_re_spec.rb @@ -1,56 +1,58 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'validate_re' do after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end # Checking for deprecation warning it 'displays a single deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' expect(scope).to receive(:warning).with(include('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, %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') } end describe 'invalid inputs' do 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 + { 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 end diff --git a/spec/functions/validate_slength_spec.rb b/spec/functions/validate_slength_spec.rb index b11444d..6ff44c7 100644 --- a/spec/functions/validate_slength_spec.rb +++ b/spec/functions/validate_slength_spec.rb @@ -1,81 +1,83 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'validate_slength' do after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end # Checking for deprecation warning it 'displays a single deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' expect(scope).to receive(:warning).with(include('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, %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 describe 'rejects strings longer than the limit' do 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(['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) } 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, %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, %r{Expected length}) } it { is_expected.to run.with_params(['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 end describe 'corner cases' do 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, %r{Expected length}) } end end diff --git a/spec/functions/validate_string_spec.rb b/spec/functions/validate_string_spec.rb index 40522c6..515747f 100644 --- a/spec/functions/validate_string_spec.rb +++ b/spec/functions/validate_string_spec.rb @@ -1,34 +1,36 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'validate_string' do after(:each) do ENV.delete('STDLIB_LOG_DEPRECATIONS') end # Checking for deprecation warning it 'displays a single deprecation' do ENV['STDLIB_LOG_DEPRECATIONS'] = 'true' expect(scope).to receive(:warning).with(include('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, %r{wrong number of arguments}i) } describe 'valid inputs' do it { is_expected.to run.with_params('') } it { is_expected.to run.with_params(nil) } it { is_expected.to run.with_params('one') } it { is_expected.to run.with_params('one', 'two') } end describe 'invalid inputs' do 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('one', 2).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 937c189..08a2423 100644 --- a/spec/functions/validate_x509_rsa_key_pair_spec.rb +++ b/spec/functions/validate_x509_rsa_key_pair_spec.rb @@ -1,180 +1,181 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'validate_x509_rsa_key_pair' do let(:valid_cert) do < Puppet::Util::Package.versioncmp(Puppet.version, '5.5.0') < 0 do +describe 'values', if: Puppet::Util::Package.versioncmp(Puppet.version, '5.5.0') < 0 do it { is_expected.not_to eq(nil) } 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, %r{wrong number of arguments}i) } 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(['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']) end it 'runs with UTF8 and double byte characters' do result = subject.call([{ 'かぎ' => '使用', 'ҝĕұ' => '√ẩŀứệ', 'ҝĕұďŭрļǐçằťè' => '√ẩŀứệ' }]) expect(result).to match_array(['使用', '√ẩŀứệ', '√ẩŀứệ']) end end diff --git a/spec/functions/zip_spec.rb b/spec/functions/zip_spec.rb index c2b4e3b..77c7f94 100644 --- a/spec/functions/zip_spec.rb +++ b/spec/functions/zip_spec.rb @@ -1,23 +1,25 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'zip' do it { is_expected.not_to eq(nil) } 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, %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, 'four'], [true, true, false]).and_return([[1, true], [2, true], ['four', false]]) } it { is_expected.to run.with_params([1, 2, 3], [4, 5]).and_return([[1, 4], [2, 5], [3, nil]]) } it { is_expected.to run.with_params('A string', [4, 5]).and_raise_error(Puppet::ParseError, %r{Requires array}i) } context '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([['ペ', 'ッ'], ['含', '文'], ['値', 'イ']]) } end end diff --git a/spec/monkey_patches/alias_should_to_must.rb b/spec/monkey_patches/alias_should_to_must.rb index 51a7b9d..beb36bf 100644 --- a/spec/monkey_patches/alias_should_to_must.rb +++ b/spec/monkey_patches/alias_should_to_must.rb @@ -1,8 +1,10 @@ +# frozen_string_literal: true + require 'rspec' # class Object class Object # This is necessary because the RAL has a 'should' # method. 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 70cf4f0..91eca2f 100644 --- a/spec/monkey_patches/publicize_methods.rb +++ b/spec/monkey_patches/publicize_methods.rb @@ -1,10 +1,12 @@ +# frozen_string_literal: true + # Some monkey-patching to allow us to test private methods. class Class def publicize_methods(*methods) saved_private_instance_methods = methods.empty? ? private_instance_methods : methods class_eval { public(*saved_private_instance_methods) } yield class_eval { private(*saved_private_instance_methods) } end end diff --git a/spec/spec_helper_local.rb b/spec/spec_helper_local.rb index 5fea4da..8772943 100644 --- a/spec/spec_helper_local.rb +++ b/spec/spec_helper_local.rb @@ -1,31 +1,33 @@ +# frozen_string_literal: true + # automatically load any shared examples or contexts 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 RSpec::Mocks::Syntax.enable_expect(RSpec::Puppet::ManifestMatchers) RSpec.configure do |config| # supply tests with a possibility to test for the future parser config.add_setting :puppet_future config.puppet_future = Puppet.version.to_f >= 4.0 config.before :each do # Ensure that we don't accidentally cache facts and environment between # test cases. This requires each example group to explicitly load the # facts being exercised with something like # Facter.collection.loader.load(:ipaddress) Facter.clear Facter.clear_messages RSpec::Mocks.setup end config.after :each do RSpec::Mocks.verify RSpec::Mocks.teardown end end # Helper class to test handling of arguments which are derived from string class AlsoString < String end diff --git a/spec/support/shared_data.rb b/spec/support/shared_data.rb index 013ec10..e19f824 100644 --- a/spec/support/shared_data.rb +++ b/spec/support/shared_data.rb @@ -1,38 +1,40 @@ +# frozen_string_literal: true + module SharedData IPV4_PATTERNS = [ '0.0.0.0', '1.2.3.4', '10.10.10.10', '127.0.0.1', '192.88.99.0', '194.232.104.150', '224.0.0.0', '244.24.24.24', '255.255.255.255', '8.8.8.8', '8.8.8.8/0', '8.8.8.8/16', '8.8.8.8/255.255.0.0', '8.8.8.8/32', ].freeze IPV4_NEGATIVE_PATTERNS = [ '', '0000', '0.0.0.0.', '0.0.0.0./0.0.0.0.', '0.0.0.0./1', '0.0.0.0.0', '0.0.0.0/0.0.0.0.', '0.0.0.256', '0.0.0', '1.2.3.4.5', '1.2.3', '10.010.10.10', '2001:0db8:85a3:0000:0000:8a2e:0370:73342001:0db8:85a3:0000:0000:8a2e:0370:7334', '4.4.4', '77', '9999.9999.9999.9999', 'affe::beef', 'nope', ].freeze end diff --git a/spec/type_aliases/absolute_path_spec.rb b/spec/type_aliases/absolute_path_spec.rb index 0e5564f..ba41955 100644 --- a/spec/type_aliases/absolute_path_spec.rb +++ b/spec/type_aliases/absolute_path_spec.rb @@ -1,39 +1,41 @@ +# frozen_string_literal: true + require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::Compat::Absolute_path' do describe 'valid paths handling' do ['C:/', 'C:\\', 'C:\\WINDOWS\\System32', 'C:/windows/system32', 'X:/foo/bar', 'X:\\foo\\bar', '\\\\host\\windows', '//host/windows', '/', '/var/tmp', '/var/opt/../lib/puppet', '/var/opt//lib/puppet', '/var/ůťƒ8', '/var/ネット'].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'invalid path handling' do context 'with garbage inputs' do [ nil, [nil], [nil, nil], { 'foo' => 'bar' }, {}, '', ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end context 'with relative paths' do ['relative1', '.', '..', './foo', '../foo', 'etc/puppetlabs/puppet', 'opt/puppet/bin', 'relative\\windows', '\\var\\ůťƒ8', '\\var\\ネット'].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end end diff --git a/spec/type_aliases/array_spec.rb b/spec/type_aliases/array_spec.rb index 0b0da3c..07bc7cc 100644 --- a/spec/type_aliases/array_spec.rb +++ b/spec/type_aliases/array_spec.rb @@ -1,32 +1,34 @@ +# frozen_string_literal: true + require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::Compat::Array' do describe 'accepts arrays' do [ [], ['one'], [1], [{}], [[]], ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'rejects other values' do [ '', 'one', '1', {}, ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end diff --git a/spec/type_aliases/base32_spec.rb b/spec/type_aliases/base32_spec.rb index 48c4745..b50dc94 100644 --- a/spec/type_aliases/base32_spec.rb +++ b/spec/type_aliases/base32_spec.rb @@ -1,42 +1,44 @@ +# frozen_string_literal: true + require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::Base32' do describe 'valid handling' do ['ASDASDDASD3453453', 'ASDASDDASD3453453=', 'ASDASDDASD3453453==', 'ASDASDDASD3453453===', 'ASDASDDASD3453453====', 'ASDASDDASD3453453=====', 'ASDASDDASD3453453======', 'asdasddasd3453453', 'asdasddasd3453453=', 'asdasddasd3453453==', 'asdasddasd3453453===', 'asdasddasd3453453====', 'asdasddasd3453453=====', 'asdasddasd3453453======'].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'invalid path handling' do context 'garbage inputs' do [ [nil], [nil, nil], { 'foo' => 'bar' }, {}, "\nASDASDDASD3453453", "\nASDASDDASD3453453\n", "ASDASDDASD3453453\n", '', 'asdasd!@#$', '=asdasd9879876876+/', 'asda=sd9879876876+/', 'asdaxsd9879876876+/===', 'asdads asdasd', 'asdasddasd3453453=======', 'asdaSddasd', 'asdasddasd1', 'asdasddasd9', ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end end diff --git a/spec/type_aliases/base64_spec.rb b/spec/type_aliases/base64_spec.rb index 0de9e6d..ddb2970 100644 --- a/spec/type_aliases/base64_spec.rb +++ b/spec/type_aliases/base64_spec.rb @@ -1,37 +1,39 @@ +# frozen_string_literal: true + require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::Base64' do describe 'valid handling' do ['asdasdASDSADA342386832/746+=', 'asdasdASDSADA34238683274/6+', 'asdasdASDSADA3423868327/46+=='].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'invalid path handling' do context 'garbage inputs' do [ [nil], [nil, nil], { 'foo' => 'bar' }, {}, '', "\nasdasdASDSADA342386832/746+=", "\nasdasdASDSADA342386832/746+=\n", "asdasdASDSADA342386832/746+=\n", 'asdasd!@#$', '=asdasd9879876876+/', 'asda=sd9879876876+/', 'asdaxsd9879876876+/===', 'asdads asdasd', ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end end diff --git a/spec/type_aliases/bool_spec.rb b/spec/type_aliases/bool_spec.rb index bdc8f75..6b8da7c 100644 --- a/spec/type_aliases/bool_spec.rb +++ b/spec/type_aliases/bool_spec.rb @@ -1,30 +1,32 @@ +# frozen_string_literal: true + require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::Compat::Bool' do describe 'accepts booleans' do [ true, false, ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'rejects other values' do [ [1], [{}], [true], 'true', 'false', ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end diff --git a/spec/type_aliases/compat__ip_address.rb b/spec/type_aliases/compat__ip_address.rb index 671c64b..c98c45c 100644 --- a/spec/type_aliases/compat__ip_address.rb +++ b/spec/type_aliases/compat__ip_address.rb @@ -1,38 +1,40 @@ +# frozen_string_literal: true + require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::Compat::Ip_address' do describe 'accepts ipv4 and ipv6 addresses' do [ '224.0.0.0', '255.255.255.255', '0.0.0.0', '192.88.99.0', '2001:0db8:85a3:0000:0000:8a2e:0370:7334', 'fa76:8765:34ac:0823:ab76:eee9:0987:1111', ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'rejects other values' do [ nil, [nil], [nil, nil], { 'foo' => 'bar' }, {}, '', 'nope', '77', '4.4.4', '2001:0db8:85a3:000000:0000:8a2e:0370:7334', ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end diff --git a/spec/type_aliases/compat__ipv4_spec.rb b/spec/type_aliases/compat__ipv4_spec.rb index dfd4be1..fb5ad79 100644 --- a/spec/type_aliases/compat__ipv4_spec.rb +++ b/spec/type_aliases/compat__ipv4_spec.rb @@ -1,20 +1,22 @@ +# frozen_string_literal: true + require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::Compat::Ipv4' do describe 'accepts ipv4 addresses' do SharedData::IPV4_PATTERNS.each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'rejects other values' do SharedData::IPV4_NEGATIVE_PATTERNS.each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end diff --git a/spec/type_aliases/compat__ipv6_spec.rb b/spec/type_aliases/compat__ipv6_spec.rb index 94211b6..c9214b6 100644 --- a/spec/type_aliases/compat__ipv6_spec.rb +++ b/spec/type_aliases/compat__ipv6_spec.rb @@ -1,44 +1,46 @@ +# frozen_string_literal: true + require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::Compat::Ipv6' do describe 'accepts ipv6 addresses' do [ '2001:0db8:85a3:0000:0000:8a2e:0370:7334', 'fa76:8765:34ac:0823:ab76:eee9:0987:1111', 'fe80:0000:0000:0000:0204:61ff:fe9d:f156', 'fe80:0:0:0:204:61ff:fe9d:f156', 'fe80::204:61ff:fe9d:f156', 'fe80:0:0:0:0204:61ff:254.157.241.86', '::1', 'fe80::', '2001::', ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'rejects other values' do [ nil, [nil], [nil, nil], { 'foo' => 'bar' }, {}, '', 'nope', '77', '4.4.4', '2000:7334', '::ffff:2.3.4', '::ffff:257.1.2.3', '::ffff:12345678901234567890.1.26', ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end diff --git a/spec/type_aliases/datasize_spec.rb b/spec/type_aliases/datasize_spec.rb index b5976fd..c7c6b4c 100644 --- a/spec/type_aliases/datasize_spec.rb +++ b/spec/type_aliases/datasize_spec.rb @@ -1,40 +1,42 @@ +# frozen_string_literal: true + require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::Datasize' do describe 'valid handling' do ['42b', '42B', '42k', '42K', '42m', '42M', '42g', '42G', '42t', '42T', '42kb', '42Kb', '42mb', '42Mb', '42gb', '42Gb', '42Tb', '42Tb', '42kB', '42KB', '42mB', '42MB', '42gB', '42GB', '42TB', '42TB'].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'invalid path handling' do context 'garbage inputs' do [ [nil], [nil, nil], { 'foo' => 'bar' }, {}, 1024, '1024', '1024byte', '1024bit', '1024Gig', '1024Meg', '1024BM', '1024bg', '1024Meb', 'asdaSddasd', ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end end diff --git a/spec/type_aliases/email_spec.rb b/spec/type_aliases/email_spec.rb index 5c262c9..add96ee 100644 --- a/spec/type_aliases/email_spec.rb +++ b/spec/type_aliases/email_spec.rb @@ -1,70 +1,72 @@ +# frozen_string_literal: true + require 'spec_helper' # Test cases are a combination of the test cases used in MediaWiki[1] and a # Reference found on line[2]. Some of the test cases in the later list have # been dropped as the regex used in the HTML5 specification[3] (and in this type) # allows for wilful violation of the RFC's # # [1]https://github.com/wikimedia/mediawiki/blob/master/tests/phpunit/integration \ # /includes/SanitizerValidateEmailTest.php # [2]https://gist.github.com/cjaoude/fd9910626629b53c4d25 # [3]https://html.spec.whatwg.org/multipage/input.html#valid-e-mail-address describe 'Stdlib::Email' do describe 'valid handling' do ['email@example.com', 'EMAIL@example.com', 'email@EXAMPLE.com', 'email@192.0.2.1', '_______@example.com', 'firstname.lastname@example.com', 'firstname+lastname@example.com', 'firstname-lastname@example.com', '1234567890@example.com', 'email@subdomain.example.com', 'email@example-one.com', 'email@example.name', 'email@example.museum', 'email@example.co.jp', 'email@example', 'user@example.1234', 'user@a'].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'invalid handling' do ['plainaddress', '#@%^%#$@#$@#.com', '@example.com', ' email@example.com', 'email@example.com ', "email@example.com\t", 'user email@example.com', 'useremail@example com', 'user,email@example.com', 'useremail@example,com', 'useremail@.', 'useremail@.example.org', 'useremail@a......', 'useràexample.com', 'Joe Smith ', 'email.example.com', 'email@example@example.com', 'あいうえお@example.com', 'email@example.com (Joe Smith)', 'email@-example.com', 'email@example..com', 'random stuff multiline valid@email.com more random stuff $^*!', '”(),:;<>[\]@example.com', 'just”not”right@example.com', 'this\ is"really"not\allowed@example.com'].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end diff --git a/spec/type_aliases/filemode_spec.rb b/spec/type_aliases/filemode_spec.rb index c5a6085..09a47a3 100644 --- a/spec/type_aliases/filemode_spec.rb +++ b/spec/type_aliases/filemode_spec.rb @@ -1,62 +1,63 @@ # coding: utf-8 +# frozen_string_literal: true require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::Filemode' do describe 'valid modes' do [ '7', '12', '666', '0000', '0644', '1644', '2644', '4644', '0123', '0777', 'a=,o-r,u+X,g=w', 'a=Xr,+0', 'u=rwx,g+rX', 'u+s,g-s', ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'invalid modes' do context 'with garbage inputs' do [ true, false, :keyword, nil, [nil], [nil, nil], { 'foo' => 'bar' }, {}, '', "\n0644", "\n0644\n", "0644\n", 'ネット', '55555', '0x123', '0649', '=8,X', 'x=r,a=wx', ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end end diff --git a/spec/type_aliases/filesource_spec.rb b/spec/type_aliases/filesource_spec.rb index 544a90e..8c13b13 100644 --- a/spec/type_aliases/filesource_spec.rb +++ b/spec/type_aliases/filesource_spec.rb @@ -1,64 +1,66 @@ +# frozen_string_literal: true + require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::Filesource' do describe 'valid handling' do [ 'https://hello.com', 'https://notcreative.org', 'https://canstillaccepthttps.co.uk', 'http://anhttp.com', 'http://runningoutofideas.gov', 'file:///hello/bla', 'file:///foo/bar.log', 'puppet:///modules/foo/bar.log', 'puppet://pm.example.com/modules/foo/bar.log', 'puppet://192.0.2.1/modules/foo/bar.log', '/usr2/username/bin:/usr/local/bin:/usr/bin:.', 'C:/', 'C:\\', 'C:\\WINDOWS\\System32', 'C:/windows/system32', 'X:/foo/bar', 'X:\\foo\\bar', '\\\\host\\windows', '//host/windows', '/var/tmp', '/var/opt/../lib/puppet', 'puppet:///a_custom_mount_point/foo/bar/foobar.conf', ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'invalid path handling' do context 'garbage inputs' do [ nil, [nil], [nil, nil], { 'foo' => 'bar' }, {}, '', "\nfile:///foo/bar.log", "\nfile:///foo/bar.log\n", "file:///foo/bar.log\n", "\npuppet:///modules/foo/bar.log", "\npuppet:///modules/foo/bar.log\n", "puppet:///modules/foo/bar.log\n", '*/Users//nope', '\\Users/hc/wksp/stdlib', 'C:noslashes', '\\var\\tmp', 'puppet://bob@pm.example.com/modules/foo/bar.log', ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end end diff --git a/spec/type_aliases/float_spec.rb b/spec/type_aliases/float_spec.rb index 3d1d667..fe4810e 100644 --- a/spec/type_aliases/float_spec.rb +++ b/spec/type_aliases/float_spec.rb @@ -1,26 +1,28 @@ +# frozen_string_literal: true + require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::Compat::Float' do describe 'accepts floats' do [ 3.7, '3.7', -3.7, '-342.2315e-12', ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } 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| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end diff --git a/spec/type_aliases/fqdn_spec.rb b/spec/type_aliases/fqdn_spec.rb index c8dfef1..904716c 100644 --- a/spec/type_aliases/fqdn_spec.rb +++ b/spec/type_aliases/fqdn_spec.rb @@ -1,34 +1,36 @@ +# frozen_string_literal: true + require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::Fqdn' do describe 'valid handling' do ['example', 'example.com', 'www.example.com'].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'invalid path handling' do context 'garbage inputs' do [ [nil], [nil, nil], { 'foo' => 'bar' }, {}, '', "\nexample", "\nexample\n", "example\n", '2001:DB8::1', 'www www.example.com', ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end end diff --git a/spec/type_aliases/hash_spec.rb b/spec/type_aliases/hash_spec.rb index 6e88a42..e5960d0 100644 --- a/spec/type_aliases/hash_spec.rb +++ b/spec/type_aliases/hash_spec.rb @@ -1,30 +1,32 @@ +# frozen_string_literal: true + require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::Compat::Hash' do describe 'accepts hashes' do [ {}, { 'one' => 'two' }, { 'wan' => 3 }, { '001' => 'helly' }, ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'rejects other values' do [ '', 'one', '1', [], ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end diff --git a/spec/type_aliases/host_spec.rb b/spec/type_aliases/host_spec.rb index acf9b1f..e0a4034 100644 --- a/spec/type_aliases/host_spec.rb +++ b/spec/type_aliases/host_spec.rb @@ -1,34 +1,36 @@ +# frozen_string_literal: true + require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::Host' do describe 'valid handling' do ['example', 'example.com', 'www.example.com', '2001:0db8:85a3:0000:0000:8a2e:0370:7334', 'fa76:8765:34ac:0823:ab76:eee9:0987:1111', '2001:0db8::1', '224.0.0.0', '255.255.255.255', '0.0.0.0', '192.88.99.0'].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'invalid handling' do context 'garbage inputs' do [ [nil], [nil, nil], { 'foo' => 'bar' }, {}, '', 'www www.example.com', 'bob@example.com', '%.example.com', '2001:0d8', ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end end diff --git a/spec/type_aliases/httpstatus_spec.rb b/spec/type_aliases/httpstatus_spec.rb index 16721be..0e7b2a3 100644 --- a/spec/type_aliases/httpstatus_spec.rb +++ b/spec/type_aliases/httpstatus_spec.rb @@ -1,40 +1,42 @@ +# frozen_string_literal: true + require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::HttpStatus' do describe 'valid HTTP Status' do [ 200, 302, 404, 418, 503, ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'invalid path handling' do context 'garbage inputs' do [ nil, [nil], [nil, nil], { 'foo' => 'bar' }, {}, '', 'https', '199', 600, 1_000, ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end end diff --git a/spec/type_aliases/httpsurl_spec.rb b/spec/type_aliases/httpsurl_spec.rb index 07f6804..f0e99b7 100644 --- a/spec/type_aliases/httpsurl_spec.rb +++ b/spec/type_aliases/httpsurl_spec.rb @@ -1,38 +1,40 @@ +# frozen_string_literal: true + require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::HTTPSUrl' do describe 'valid handling' do ['https://hello.com', 'https://notcreative.org', 'https://notexciting.co.uk', 'https://graphemica.com/❤', 'https://graphemica.com/緩', 'HTTPS://FOO.com'].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'invalid path handling' do context 'with garbage inputs' do [ nil, [nil], [nil, nil], { 'foo' => 'bar' }, {}, '', "\nhttps://hello.com", "\nhttps://hello.com\n", "https://hello.com\n", 'httds://notquiteright.org', 'hptts:/nah', 'https;//notrightbutclose.org', 'http://graphemica.com/❤', 'http://graphemica.com/緩', ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end end diff --git a/spec/type_aliases/httpurl_spec.rb b/spec/type_aliases/httpurl_spec.rb index 420b06e..9459479 100644 --- a/spec/type_aliases/httpurl_spec.rb +++ b/spec/type_aliases/httpurl_spec.rb @@ -1,39 +1,41 @@ +# frozen_string_literal: true + require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::HTTPUrl' do describe 'valid handling' do ['https://hello.com', 'https://notcreative.org', 'https://canstillaccepthttps.co.uk', 'http://anhttp.com', 'http://runningoutofideas.gov', 'http://', 'http://graphemica.com/❤', 'http://graphemica.com/緩', 'HTTPS://FOO.COM', 'HTTP://BAR.COM'].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'invalid path handling' do context 'with garbage inputs' do [ nil, [nil], [nil, nil], { 'foo' => 'bar' }, {}, '', "\nhttp://hello.com", "\nhttp://hello.com\n", "http://hello.com\n", 'httds://notquiteright.org', 'hptts:/nah', 'https;//notrightbutclose.org', 'hts://graphemica.com/❤', 'https:graphemica.com/緩', ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end end diff --git a/spec/type_aliases/integer_spec.rb b/spec/type_aliases/integer_spec.rb index 29298fa..eefac67 100644 --- a/spec/type_aliases/integer_spec.rb +++ b/spec/type_aliases/integer_spec.rb @@ -1,29 +1,31 @@ +# frozen_string_literal: true + require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::Compat::Integer' do describe 'accepts integers' do [ 3, '3', -3, '-3', "123\nfoo", "foo\n123", ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } 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| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end diff --git a/spec/type_aliases/ip_address_nosubnet_spec.rb b/spec/type_aliases/ip_address_nosubnet_spec.rb index 921d957..e82181e 100644 --- a/spec/type_aliases/ip_address_nosubnet_spec.rb +++ b/spec/type_aliases/ip_address_nosubnet_spec.rb @@ -1,44 +1,46 @@ +# frozen_string_literal: true + require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::IP::Address::Nosubnet' do describe 'accepts ipv4 and ipv6 addresses without subnets' do [ '224.0.0.0', '255.255.255.255', '0.0.0.0', '192.88.99.0', '2001:0db8:85a3:0000:0000:8a2e:0370:7334', 'fa76:8765:34ac:0823:ab76:eee9:0987:1111', '127.0.0.1', '8.8.4.4', '52.10.10.141', 'FEDC:BA98:7654:3210:FEDC:BA98:7654:3210', 'FF01:0:0:0:0:0:0:101', 'FF01::101', '::', '12AB::CD30:192.168.0.1', ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'rejects other values' do [ '10.1.240.4/24', 'FF01:0:0:0:0:0:0:101/32', 'FF01::101/60', 'nope', '77', '4.4.4', '2001:0db8:85a3:000000:0000:8a2e:0370:7334', ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end diff --git a/spec/type_aliases/ip_address_spec.rb b/spec/type_aliases/ip_address_spec.rb index e603350..9b226ea 100644 --- a/spec/type_aliases/ip_address_spec.rb +++ b/spec/type_aliases/ip_address_spec.rb @@ -1,44 +1,46 @@ +# frozen_string_literal: true + require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::IP::Address' do describe 'accepts ipv4 and ipv6 addresses' do [ '224.0.0.0', '255.255.255.255', '0.0.0.0', '192.88.99.0', '2001:0db8:85a3:0000:0000:8a2e:0370:7334', 'fa76:8765:34ac:0823:ab76:eee9:0987:1111', '127.0.0.1', '8.8.4.4', '10.1.240.4/24', '52.10.10.141', 'FEDC:BA98:7654:3210:FEDC:BA98:7654:3210', 'FF01:0:0:0:0:0:0:101', 'FF01::101', 'FF01:0:0:0:0:0:0:101/32', 'FF01::101/60', '::', '12AB::CD30:192.168.0.1', ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'rejects other values' do [ 'nope', '77', '4.4.4', '2001:0db8:85a3:000000:0000:8a2e:0370:7334', ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end diff --git a/spec/type_aliases/ip_address_v4_nosubnet_spec.rb b/spec/type_aliases/ip_address_v4_nosubnet_spec.rb index ab74f8c..8dc9aa6 100644 --- a/spec/type_aliases/ip_address_v4_nosubnet_spec.rb +++ b/spec/type_aliases/ip_address_v4_nosubnet_spec.rb @@ -1,30 +1,32 @@ +# frozen_string_literal: true + require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::IP::Address::V4::Nosubnet' do describe 'accepts ipv4 addresses without subnets' do [ '127.0.0.1', '8.8.4.4', '52.10.10.141', ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'rejects other values' do [ '10.1.240.4/24', '192.168.1', 'FEDC:BA98:7654:3210:FEDC:BA98:7654:3210', '12AB::CD30:192.168.0.1', ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end diff --git a/spec/type_aliases/ip_address_v4_spec.rb b/spec/type_aliases/ip_address_v4_spec.rb index 10854c8..cd61c2d 100644 --- a/spec/type_aliases/ip_address_v4_spec.rb +++ b/spec/type_aliases/ip_address_v4_spec.rb @@ -1,30 +1,32 @@ +# frozen_string_literal: true + require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::IP::Address::V4' do describe 'accepts ipv4 addresses' do [ '127.0.0.1', '8.8.4.4', '10.1.240.4/24', '52.10.10.141', ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'rejects other values' do [ '192.168.1', 'FEDC:BA98:7654:3210:FEDC:BA98:7654:3210', '12AB::CD30:192.168.0.1', ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end diff --git a/spec/type_aliases/ip_address_v6_alternative_spec.rb b/spec/type_aliases/ip_address_v6_alternative_spec.rb index 9fbf7ca..90bf40a 100644 --- a/spec/type_aliases/ip_address_v6_alternative_spec.rb +++ b/spec/type_aliases/ip_address_v6_alternative_spec.rb @@ -1,28 +1,30 @@ +# frozen_string_literal: true + require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::IP::Address::V6::Alternative' do describe 'accepts ipv6 addresses in alternative format' do [ '0:0:0:0:0:0:13.1.68.3', '0:0:0:0:0:FFFF:129.144.52.38', '0:0:0:0:0:FFFF:129.144.52.38/60', ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'rejects other values' do [ 'nope', '127.0.0.1', ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end diff --git a/spec/type_aliases/ip_address_v6_cidr_spec.rb b/spec/type_aliases/ip_address_v6_cidr_spec.rb index 4b8fee3..1cc2031 100644 --- a/spec/type_aliases/ip_address_v6_cidr_spec.rb +++ b/spec/type_aliases/ip_address_v6_cidr_spec.rb @@ -1,33 +1,34 @@ +# frozen_string_literal: true require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::IP::Address::V6::CIDR' do describe 'accepts ipv6 addresses in cidr format' do [ 'FF01:0:0:0:0:0:0:101/32', 'FF01::101/60', '::/0', ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'rejects other values' do [ 'FEDC:BA98:7654:3210:FEDC:BA98:7654:3210', 'FF01:0:0:0:0:0:0:101', 'FF01::101', '12AB::CD30:192.168.0.1', '127.0.0.1', '10.1.240.4/24', ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end diff --git a/spec/type_aliases/ip_address_v6_compressed_spec.rb b/spec/type_aliases/ip_address_v6_compressed_spec.rb index e2b7dd5..968fcd2 100644 --- a/spec/type_aliases/ip_address_v6_compressed_spec.rb +++ b/spec/type_aliases/ip_address_v6_compressed_spec.rb @@ -1,31 +1,33 @@ +# frozen_string_literal: true + require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::IP::Address::V6::Compressed' do describe 'accepts ipv6 addresses in compressed format' do [ '1080::8:800:200C:417A', '1080::8:800:200C:417A/60', 'FF01::101', '::1', '::', ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'rejects other values' do [ 'nope', '127.0.0.1', 'FEDC::BA98:7654:3210::3210', ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end diff --git a/spec/type_aliases/ip_address_v6_full_spec.rb b/spec/type_aliases/ip_address_v6_full_spec.rb index cc8013d..c69ed1d 100644 --- a/spec/type_aliases/ip_address_v6_full_spec.rb +++ b/spec/type_aliases/ip_address_v6_full_spec.rb @@ -1,28 +1,30 @@ +# frozen_string_literal: true + require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::IP::Address::V6::Full' do describe 'accepts ipv6 addresses in full format' do [ 'FEDC:BA98:7654:3210:FEDC:BA98:7654:3210', 'FEDC:BA98:7654:3210:FEDC:BA98:7654:3210/60', '1080:0:0:0:8:800:200C:417A', ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'rejects other values' do [ 'nope', '127.0.0.1', ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end diff --git a/spec/type_aliases/ip_address_v6_nosubnet_alternative_spec.rb b/spec/type_aliases/ip_address_v6_nosubnet_alternative_spec.rb index 0b36cb9..85f037a 100644 --- a/spec/type_aliases/ip_address_v6_nosubnet_alternative_spec.rb +++ b/spec/type_aliases/ip_address_v6_nosubnet_alternative_spec.rb @@ -1,28 +1,30 @@ +# frozen_string_literal: true + require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::IP::Address::V6::Nosubnet::Alternative' do describe 'accepts ipv6 addresses in alternative format without subnets' do [ '0:0:0:0:0:0:13.1.68.3', '0:0:0:0:0:FFFF:129.144.52.38', ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'rejects other values' do [ '0:0:0:0:0:FFFF:129.144.52.38/60', 'nope', '127.0.0.1', ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end diff --git a/spec/type_aliases/ip_address_v6_nosubnet_compressed_spec.rb b/spec/type_aliases/ip_address_v6_nosubnet_compressed_spec.rb index 96af035..bbca083 100644 --- a/spec/type_aliases/ip_address_v6_nosubnet_compressed_spec.rb +++ b/spec/type_aliases/ip_address_v6_nosubnet_compressed_spec.rb @@ -1,31 +1,33 @@ +# frozen_string_literal: true + require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::IP::Address::V6::Nosubnet::Compressed' do describe 'accepts ipv6 addresses in compressed format without subnets' do [ '1080::8:800:200C:417A', 'FF01::101', '::1', '::', ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'rejects other values' do [ '1080::8:800:200C:417A/60', 'nope', '127.0.0.1', 'FEDC::BA98:7654:3210::3210', ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end diff --git a/spec/type_aliases/ip_address_v6_nosubnet_full_spec.rb b/spec/type_aliases/ip_address_v6_nosubnet_full_spec.rb index 9135e00..6ef0a31 100644 --- a/spec/type_aliases/ip_address_v6_nosubnet_full_spec.rb +++ b/spec/type_aliases/ip_address_v6_nosubnet_full_spec.rb @@ -1,28 +1,30 @@ +# frozen_string_literal: true + require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::IP::Address::V6::Nosubnet::Full' do describe 'accepts ipv6 addresses in full format without subnets' do [ 'FEDC:BA98:7654:3210:FEDC:BA98:7654:3210', '1080:0:0:0:8:800:200C:417A', ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'rejects other values' do [ 'FEDC:BA98:7654:3210:FEDC:BA98:7654:3210/60', 'nope', '127.0.0.1', ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end diff --git a/spec/type_aliases/ip_address_v6_spec.rb b/spec/type_aliases/ip_address_v6_spec.rb index 864c565..a44ea32 100644 --- a/spec/type_aliases/ip_address_v6_spec.rb +++ b/spec/type_aliases/ip_address_v6_spec.rb @@ -1,32 +1,34 @@ +# frozen_string_literal: true + require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::IP::Address::V6' do describe 'accepts ipv6 addresses' do [ 'FEDC:BA98:7654:3210:FEDC:BA98:7654:3210', 'FF01:0:0:0:0:0:0:101', 'FF01::101', 'FF01:0:0:0:0:0:0:101/32', 'FF01::101/60', '::', '12AB::CD30:192.168.0.1', ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'rejects other values' do [ '127.0.0.1', '10.1.240.4/24', ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end diff --git a/spec/type_aliases/mac_spec.rb b/spec/type_aliases/mac_spec.rb index af8cd17..67c08e2 100644 --- a/spec/type_aliases/mac_spec.rb +++ b/spec/type_aliases/mac_spec.rb @@ -1,40 +1,42 @@ +# frozen_string_literal: true + require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::MAC' do describe 'valid handling' do [ '00:a0:1f:12:7f:a0', '00:A0:1F:12:7F:A0', '00-A0-1F-12-7F-A0', '80:00:02:09:fe:80:00:00:00:00:00:00:00:24:65:ff:ff:91:a3:12', ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'invalid path handling' do context 'with garbage inputs' do [ nil, [nil], [nil, nil], { 'foo' => 'bar' }, {}, '', 'one', '00:00:00:00:00:0g', "\n00:a0:1f:12:7f:a0", "\n00:a0:1f:12:7f:a0\n", "00:a0:1f:12:7f:a0\n", ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end end diff --git a/spec/type_aliases/numeric_spec.rb b/spec/type_aliases/numeric_spec.rb index a59b4e2..3a7aabb 100644 --- a/spec/type_aliases/numeric_spec.rb +++ b/spec/type_aliases/numeric_spec.rb @@ -1,30 +1,32 @@ +# frozen_string_literal: true + require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::Compat::Numeric' do describe 'accepts numerics' do [ 3, '3', -3, '-3', 3.7, '3.7', -3.7, '-342.2315e-12', ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } 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| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end diff --git a/spec/type_aliases/objectstore_gsuri_spec.rb b/spec/type_aliases/objectstore_gsuri_spec.rb index 5b9390a..c4c728a 100644 --- a/spec/type_aliases/objectstore_gsuri_spec.rb +++ b/spec/type_aliases/objectstore_gsuri_spec.rb @@ -1,35 +1,37 @@ +# frozen_string_literal: true + require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::ObjectStore::GSUri' do describe 'accepts case-sensitive google cloud gs uris' do [ 'gs://mybucket/myfile.csv', 'gs://bucket/path/to/file.tar.gz', ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'rejects other values' do [ '', "\ngs://mybucket/myfile.csv", "\ngs://mybucket/myfile.csv\n", "gs://mybucket/myfile.csv\n", 'GS://mybucket/myfile.csv', 5, 'gs//mybucket/myfile.csv', 'gs:/mybucket/myfile.csv', 'gs:mybucket/myfile.csv', 'gs-mybucket/myfile.csv', ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end diff --git a/spec/type_aliases/objectstore_s3uri_spec.rb b/spec/type_aliases/objectstore_s3uri_spec.rb index c4785ab..efcbbd6 100644 --- a/spec/type_aliases/objectstore_s3uri_spec.rb +++ b/spec/type_aliases/objectstore_s3uri_spec.rb @@ -1,35 +1,37 @@ +# frozen_string_literal: true + require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::ObjectStore::S3Uri' do describe 'accepts case-sensitive amazon web services s3 uris' do [ 's3://bucket-name/path', 's3://bucket/path/to/file.txt', ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'rejects other values' do [ '', "\ns3://bucket-name/path", "\ns3://bucket-name/path\n", "s3://bucket-name/path\n", 'S3://bucket-name/path', 3, 's3:/bucket-name/path', 's3//bucket-name/path', 's3:bucket-name/path', 's3-bucket-name/path', ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end diff --git a/spec/type_aliases/objectstore_spec.rb b/spec/type_aliases/objectstore_spec.rb index ae3c2ca..a1f61ef 100644 --- a/spec/type_aliases/objectstore_spec.rb +++ b/spec/type_aliases/objectstore_spec.rb @@ -1,34 +1,36 @@ +# frozen_string_literal: true + require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::ObjectStore' do describe 'accepts case-sensitive google cloud gs or amazon web services s3 uris' do [ 's3://bucket-name/path', 's3://bucket/path/to/file.txt', 'gs://mybucket/myfile.csv', 'gs://bucket/path/to/file.tar.gz', ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'rejects other values' do [ '', 'S3://bucket/path', 'GS://bucket/path', 5, 3, 'gs//bucket/path/to/file', 's3//bucket/path/to/file', ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end diff --git a/spec/type_aliases/port__dynamic_spec.rb b/spec/type_aliases/port__dynamic_spec.rb index 5503e7c..a282f51 100644 --- a/spec/type_aliases/port__dynamic_spec.rb +++ b/spec/type_aliases/port__dynamic_spec.rb @@ -1,43 +1,45 @@ +# frozen_string_literal: true + require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::Port::Ephemeral' do describe 'valid ephemeral port' do [ 49_152, 51_337, 65_000, ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'invalid path handling' do context 'garbage inputs' do [ nil, [nil], [nil, nil], { 'foo' => 'bar' }, {}, '', 'https', '443', -1, 80, 443, 1023, 1337, 8080, 28_080, ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end end diff --git a/spec/type_aliases/port__privileged_spec.rb b/spec/type_aliases/port__privileged_spec.rb index 51ddd24..7260188 100644 --- a/spec/type_aliases/port__privileged_spec.rb +++ b/spec/type_aliases/port__privileged_spec.rb @@ -1,39 +1,41 @@ +# frozen_string_literal: true + require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::Port::Privileged' do describe 'valid ports' do [ 80, 443, 1023, ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'invalid path handling' do context 'garbage inputs' do [ nil, [nil], [nil, nil], { 'foo' => 'bar' }, {}, '', 'https', '443', -1, 1337, 1024, ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end end diff --git a/spec/type_aliases/port__unprivileged_spec.rb b/spec/type_aliases/port__unprivileged_spec.rb index 0009e1f..a3fa392 100644 --- a/spec/type_aliases/port__unprivileged_spec.rb +++ b/spec/type_aliases/port__unprivileged_spec.rb @@ -1,40 +1,42 @@ +# frozen_string_literal: true + require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::Port::Unprivileged' do describe 'valid unprivilegedport' do [ 1024, 1337, 65_000, ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'invalid path handling' do context 'garbage inputs' do [ nil, [nil], [nil, nil], { 'foo' => 'bar' }, {}, '', 'https', '443', -1, 80, 443, 1023, ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end end diff --git a/spec/type_aliases/port__user_spec.rb b/spec/type_aliases/port__user_spec.rb index c34e9b2..061d570 100644 --- a/spec/type_aliases/port__user_spec.rb +++ b/spec/type_aliases/port__user_spec.rb @@ -1,41 +1,43 @@ +# frozen_string_literal: true + require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::Port::User' do describe 'valid user' do [ 1024, 1337, 49_151, ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'invalid path handling' do context 'garbage inputs' do [ nil, [nil], [nil, nil], { 'foo' => 'bar' }, {}, '', 'https', '443', -1, 80, 443, 1023, 49_152, ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end end diff --git a/spec/type_aliases/port_spec.rb b/spec/type_aliases/port_spec.rb index 3c9582c..02f0944 100644 --- a/spec/type_aliases/port_spec.rb +++ b/spec/type_aliases/port_spec.rb @@ -1,39 +1,41 @@ +# frozen_string_literal: true + require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::Port' do describe 'valid ports' do [ 80, 443, 1337, 65_000, ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'invalid path handling' do context 'garbage inputs' do [ nil, [nil], [nil, nil], { 'foo' => 'bar' }, {}, '', 'https', '443', -1, 65_536, ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end end diff --git a/spec/type_aliases/string_spec.rb b/spec/type_aliases/string_spec.rb index 93a9d0f..b3cdd2d 100644 --- a/spec/type_aliases/string_spec.rb +++ b/spec/type_aliases/string_spec.rb @@ -1,30 +1,32 @@ +# frozen_string_literal: true + require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::Compat::String' do describe 'accepts strings' do [ '', 'one', nil, ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'rejects other values' do [ [], {}, 1, true, ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end diff --git a/spec/type_aliases/unixpath_spec.rb b/spec/type_aliases/unixpath_spec.rb index 3f8372d..3c9f4a7 100644 --- a/spec/type_aliases/unixpath_spec.rb +++ b/spec/type_aliases/unixpath_spec.rb @@ -1,39 +1,41 @@ +# frozen_string_literal: true + require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::Unixpath' do describe 'valid handling' do ['/usr2/username/bin:/usr/local/bin:/usr/bin:.', '/var/tmp', '/Users/helencampbell/workspace/puppetlabs-stdlib', '/var/ůťƒ8', '/var/ネット', '/var//tmp', '/var/../tmp'].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'invalid path handling' do context 'with garbage inputs' do [ nil, [nil], [nil, nil], { 'foo' => 'bar' }, {}, '', "\n/var/tmp", "\n/var/tmp\n", "/var/tmp\n", 'C:/whatever', '\\var\\tmp', '\\Users/hc/wksp/stdlib', '*/Users//nope', "var\ůťƒ8", "var\ネット", ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end end diff --git a/spec/type_aliases/windowspath_spec.rb b/spec/type_aliases/windowspath_spec.rb index fb0baaf..00b4ee4 100644 --- a/spec/type_aliases/windowspath_spec.rb +++ b/spec/type_aliases/windowspath_spec.rb @@ -1,39 +1,41 @@ +# frozen_string_literal: true + require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '4.5.0') >= 0 describe 'Stdlib::Windowspath' do describe 'valid handling' do ['C:\\', 'C:\\WINDOWS\\System32', 'C:/windows/system32', 'X:/foo/bar', 'X:\\foo\\bar', '\\\\host\\windows', 'X:/var/ůťƒ8', 'X:/var/ネット'].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'invalid path handling' do context 'with garbage inputs' do [ nil, [nil], [nil, nil], { 'foo' => 'bar' }, {}, "\nC:\\", "\nC:\\\n", "C:\\\n", '', '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 it { is_expected.not_to allow_value(value) } end end end end end end diff --git a/spec/type_aliases/yes_no_spec.rb b/spec/type_aliases/yes_no_spec.rb index 9416c6a..b61d10a 100644 --- a/spec/type_aliases/yes_no_spec.rb +++ b/spec/type_aliases/yes_no_spec.rb @@ -1,44 +1,45 @@ # coding: utf-8 +# frozen_string_literal: true require 'spec_helper' describe 'Stdlib::Yes_no' do describe 'valid types' do [ 'yes', 'no', 'YES', 'Yes', 'NO', 'No', ].each do |value| describe value.inspect do it { is_expected.to allow_value(value) } end end end describe 'invalid types' do context 'with garbage inputs' do [ true, false, :keyword, nil, ['yes', 'no'], { 'foo' => 'bar' }, {}, '', 'ネット', '55555', '0x123', 'yess', 'nooo', ].each do |value| describe value.inspect do it { is_expected.not_to allow_value(value) } end end end end end diff --git a/spec/unit/facter/package_provider_spec.rb b/spec/unit/facter/package_provider_spec.rb index 011d3ed..3e75c28 100644 --- a/spec/unit/facter/package_provider_spec.rb +++ b/spec/unit/facter/package_provider_spec.rb @@ -1,43 +1,45 @@ +# frozen_string_literal: true + require 'spec_helper' require 'puppet/type' require 'puppet/type/package' -describe 'package_provider', :type => :fact do +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 before :each do allow(Facter).to receive(:value).and_return(puppetversion) end context 'when darwin' do it 'returns pkgdmg' do provider = Puppet::Type.type(:package).provider(:pkgdmg) allow(Puppet::Type.type(:package)).to receive(:defaultprovider).and_return(provider) expect(Facter.fact(:package_provider).value).to eq('pkgdmg') end end context 'when centos 7' do it 'returns yum' do provider = Puppet::Type.type(:package).provider(:yum) allow(Puppet::Type.type(:package)).to receive(:defaultprovider).and_return(provider) expect(Facter.fact(:package_provider).value).to eq('yum') end end context 'when ubuntu' do it 'returns apt' do provider = Puppet::Type.type(:package).provider(:apt) allow(Puppet::Type.type(:package)).to receive(:defaultprovider).and_return(provider) expect(Facter.fact(:package_provider).value).to eq('apt') end end end end end diff --git a/spec/unit/facter/pe_version_spec.rb b/spec/unit/facter/pe_version_spec.rb index ba90582..e152548 100644 --- a/spec/unit/facter/pe_version_spec.rb +++ b/spec/unit/facter/pe_version_spec.rb @@ -1,79 +1,81 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'PE Version specs' do # we mock calls for the puppetversion fact, it is not normal to expect nil responses when mocking. RSpec::Mocks.configuration.allow_message_expectations_on_nil = true context 'when puppetversion is nil' do before :each do allow(Facter.fact(:puppetversion)).to receive(:value).and_return(nil) end 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 'when PE is installed' do ['2.6.1', '2.10.300'].each do |version| puppetversion = "2.7.19 (Puppet Enterprise #{version})" context "puppetversion => #{puppetversion}" do before :each do allow(Facter).to receive(:value).with(anything).and_call_original allow(Facter).to receive(:value).with('puppetversion').and_return(puppetversion) end (major, minor, patch) = version.split('.') it 'returns true' do expect(Facter.fact(:is_pe).value).to eq(true) end - it "Should have a version of #{version}" do + it "has a version of #{version}" do expect(Facter.fact(:pe_version).value).to eq(version) end - it "Should have a major version of #{major}" do + it "has a major version of #{major}" do expect(Facter.fact(:pe_major_version).value).to eq(major) end - it "Should have a minor version of #{minor}" do + it "has a minor version of #{minor}" do expect(Facter.fact(:pe_minor_version).value).to eq(minor) end - it "Should have a patch version of #{patch}" do + it "has a patch version of #{patch}" do expect(Facter.fact(:pe_patch_version).value).to eq(patch) end end end end context 'when PE is not installed' do before :each do allow(Facter.fact(:puppetversion)).to receive(:value).and_return('2.7.19') end it 'is_pe is false' do expect(Facter.fact(:is_pe).value).to eq(false) end it 'pe_version is nil' do expect(Facter.fact(:pe_version).value).to be_nil end 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 expect(Facter.fact(:pe_minor_version).value).to be_nil end 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 5e5b0bf..5421f3e 100644 --- a/spec/unit/facter/root_home_spec.rb +++ b/spec/unit/facter/root_home_spec.rb @@ -1,65 +1,67 @@ +# frozen_string_literal: true + require 'spec_helper' require 'facter/root_home' describe 'Root Home Specs' do describe Facter::Util::RootHome do context 'when solaris' do let(:root_ent) { 'root:x:0:0:Super-User:/:/sbin/sh' } let(:expected_root_home) { '/' } it 'returns /' do expect(Facter::Util::Resolution).to receive(:exec).with('getent passwd root').and_return(root_ent) expect(described_class.returnt_root_home).to eq(expected_root_home) end end context 'when linux' do let(:root_ent) { 'root:x:0:0:root:/root:/bin/bash' } let(:expected_root_home) { '/root' } it 'returns /root' do expect(Facter::Util::Resolution).to receive(:exec).with('getent passwd root').and_return(root_ent) expect(described_class.returnt_root_home).to eq(expected_root_home) end end context 'when windows' do it 'is nil on windows' do expect(Facter::Util::Resolution).to receive(:exec).with('getent passwd root').and_return(nil) expect(described_class.returnt_root_home).to be_nil end end end - describe 'root_home', :type => :fact do + describe 'root_home', type: :fact do before(:each) { Facter.clear } after(:each) { Facter.clear } context 'when macosx' do before(:each) do allow(Facter.fact(:kernel)).to receive(:value).and_return('Darwin') allow(Facter.fact(:osfamily)).to receive(:value).and_return('Darwin') end let(:expected_root_home) { '/var/root' } sample_dscacheutil = File.read(fixtures('dscacheutil', 'root')) it 'returns /var/root' do allow(Facter::Util::Resolution).to receive(:exec).with('dscacheutil -q user -a name root').and_return(sample_dscacheutil) expect(Facter.fact(:root_home).value).to eq(expected_root_home) end end context 'when aix' do before(:each) do allow(Facter.fact(:kernel)).to receive(:value).and_return('AIX') allow(Facter.fact(:osfamily)).to receive(:value).and_return('AIX') end let(:expected_root_home) { '/root' } sample_lsuser = File.read(fixtures('lsuser', 'root')) it 'returns /root' do allow(Facter::Util::Resolution).to receive(:exec).with('lsuser -c -a home root').and_return(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 b3d4aec..4d7d4e1 100644 --- a/spec/unit/facter/service_provider_spec.rb +++ b/spec/unit/facter/service_provider_spec.rb @@ -1,35 +1,37 @@ +# frozen_string_literal: true + require 'spec_helper' require 'puppet/type' require 'puppet/type/service' -describe 'service_provider', :type => :fact do +describe 'service_provider', type: :fact do before(:each) { Facter.clear } after(:each) { Facter.clear } context 'when macosx' do it 'returns launchd' do provider = Puppet::Type.type(:service).provider(:launchd) allow(Puppet::Type.type(:service)).to receive(:defaultprovider).and_return(provider) expect(Facter.fact(:service_provider).value).to eq('launchd') end end context 'when systemd' do it 'returns systemd' do provider = Puppet::Type.type(:service).provider(:systemd) allow(Puppet::Type.type(:service)).to receive(:defaultprovider).and_return(provider) expect(Facter.fact(:service_provider).value).to eq('systemd') end end context 'when redhat' do it 'returns redhat' do provider = Puppet::Type.type(:service).provider(:redhat) allow(Puppet::Type.type(:service)).to receive(:defaultprovider).and_return(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 05dff89..edd63a8 100644 --- a/spec/unit/facter/util/puppet_settings_spec.rb +++ b/spec/unit/facter/util/puppet_settings_spec.rb @@ -1,36 +1,38 @@ +# frozen_string_literal: true + require 'spec_helper' require 'facter/util/puppet_settings' describe Facter::Util::PuppetSettings do describe '#with_puppet' do context 'without Puppet loaded' do before(:each) do allow(Module).to receive(:const_get).with('Puppet').and_raise(NameError) end it 'is nil' do expect(subject.with_puppet { Puppet[:vardir] }).to be_nil end it 'does not yield to the block' do expect(Puppet).to receive(:[]).never expect(subject.with_puppet { Puppet[:vardir] }).to be_nil end end context 'with Puppet loaded' do # module Puppet module Puppet; end let(:vardir) { '/var/lib/puppet' } before :each do allow(Puppet).to receive(:[]).with(:vardir).and_return(vardir) end it 'yields to the block' do subject.with_puppet { Puppet[:vardir] } end it 'returns the nodes vardir' do expect(subject.with_puppet { Puppet[:vardir] }).to eq vardir end end 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 39d3b7a..ca815de 100644 --- a/spec/unit/puppet/parser/functions/enclose_ipv6_spec.rb +++ b/spec/unit/puppet/parser/functions/enclose_ipv6_spec.rb @@ -1,68 +1,70 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'the enclose_ipv6 function' do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } it 'exists' do expect(Puppet::Parser::Functions.function('enclose_ipv6')).to eq('function_enclose_ipv6') end it 'raises a ParseError if there is less than 1 arguments' do expect { scope.function_enclose_ipv6([]) }.to(raise_error(Puppet::ParseError)) end it 'raises a ParseError if there is more than 1 arguments' do expect { scope.function_enclose_ipv6(['argument1', 'argument2']) }.to(raise_error(Puppet::ParseError)) end it 'raises a ParseError when given garbage' do expect { scope.function_enclose_ipv6(['garbage']) }.to(raise_error(Puppet::ParseError)) end 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 '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 'does not raise a ParseError when given * as ip string' do expect { scope.function_enclose_ipv6(['*']) }.not_to raise_error end 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 '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 '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 '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 'raises a ParseError when given a wrong ipv6 address' do expect { scope.function_enclose_ipv6(['fe80:::1']) }.to(raise_error(Puppet::ParseError)) end 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 'embraces a single ipv6 adresse' do result = scope.function_enclose_ipv6(['fe80::1']) expect(result).to(eq(['[fe80::1]'])) end 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 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 589ad82..097b3db 100644 --- a/spec/unit/puppet/parser/functions/is_absolute_path_spec.rb +++ b/spec/unit/puppet/parser/functions/is_absolute_path_spec.rb @@ -1,87 +1,89 @@ +# frozen_string_literal: true + require 'spec_helper' describe 'is_absolute_path' do let(:scope) { PuppetlabsSpec::PuppetInternals.scope } let(:function_args) do [] end let(:function) do scope.function_is_absolute_path(function_args) end describe 'validate arity' do let(:function_args) do [1, 2] end it 'raises a ParseError if there is more than 1 arguments' do -> { function }.should(raise_error(ArgumentError)) end end it 'exists' do Puppet::Parser::Functions.function(subject).should == "function_#{subject}" end # help enforce good function defination it 'contains arity' do end 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 end describe 'windows' do let(:function_args) do ['c:\temp\test.txt'] end it 'returns data' do function.should eq(return_value) end end describe 'non-windows' do let(:function_args) do ['/temp/test.txt'] end it 'returns data' do function.should eq(return_value) end end end describe 'should return false' do let(:return_value) do false end describe 'windows' do let(:function_args) do ['..\temp\test.txt'] end it 'returns data' do function.should eq(return_value) end end describe 'non-windows' do let(:function_args) do ['../var/lib/puppet'] end it 'returns data' do function.should eq(return_value) end end end end diff --git a/spec/unit/puppet/provider/file_line/ruby_spec.rb b/spec/unit/puppet/provider/file_line/ruby_spec.rb index d0f653a..506160b 100644 --- a/spec/unit/puppet/provider/file_line/ruby_spec.rb +++ b/spec/unit/puppet/provider/file_line/ruby_spec.rb @@ -1,258 +1,260 @@ +# frozen_string_literal: true + 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 +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', + 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 'line parameter' do context 'when line exists' do let(:content) { 'foo' } it 'detects the line' do expect(provider).to be_exists end end context 'when line does not exist' do let(:content) { 'foo bar' } it 'requests changes' do expect(provider).not_to be_exists end it 'appends the line' do provider.create expect(File.read(tmpfile).chomp).to eq("foo bar\nfoo") end end end describe 'match parameter' do - let(:params) { { :match => '^bar' } } + 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 end describe 'does not match line - line does not exist - appending' do - let(:params) { super().merge(:replace => false) } + 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 'when does not match line - line exists' do let(:content) { "foo\nbar" } it 'detects the line' do expect(provider).to be_exists end end context 'when matches line - line exists' do - let(:params) { { :match => '^foo' } } + let(:params) { { match: '^foo' } } let(:content) { "foo\nbar" } it 'detects the line' do expect(provider).to be_exists end end context 'when matches line - line does not exist' do - let(:params) { { :match => '^foo' } } + let(:params) { { match: '^foo' } } 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\nbar") end end end describe 'append_on_no_match' do let(:params) do { - :append_on_no_match => false, - :match => '^foo1$', + append_on_no_match: false, + match: '^foo1$', } end context 'when matching' do let(:content) { "foo1\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 eql("foo\nbar") end end context 'when not matching' do let(:content) { "foo3\nbar" } it 'does not affect the file' do expect(provider).to be_exists end end end describe 'replace_all_matches_not_matching_line' do context 'when replace is false' do let(:params) do { - :replace_all_matches_not_matching_line => true, - :replace => false, + replace_all_matches_not_matching_line: true, + replace: false, } end it 'raises an error' do expect { provider.exists? }.to raise_error(Puppet::Error, %r{replace must be true}) end end context 'when match matches line - when there are more matches than lines' do let(:params) do { - :replace_all_matches_not_matching_line => true, - :match => '^foo', - :multiple => true, + replace_all_matches_not_matching_line: true, + match: '^foo', + multiple: true, } end let(:content) { "foo\nfoo bar\nbar\nfoo baz" } it 'requests changes' do expect(provider).not_to be_exists end it 'replaces the matches' do provider.create expect(File.read(tmpfile).chomp).to eql("foo\nfoo\nbar\nfoo") end end context 'when match matches line - when there are the same matches and lines' do let(:params) do { - :replace_all_matches_not_matching_line => true, - :match => '^foo', - :multiple => true, + replace_all_matches_not_matching_line: true, + match: '^foo', + multiple: true, } end let(:content) { "foo\nfoo\nbar" } it 'does not request changes' do expect(provider).to be_exists end end context 'when match does not match line - when there are more matches than lines' do let(:params) do { - :replace_all_matches_not_matching_line => true, - :match => '^bar', - :multiple => true, + replace_all_matches_not_matching_line: true, + match: '^bar', + multiple: true, } end let(:content) { "foo\nfoo bar\nbar\nbar baz" } it 'requests changes' do expect(provider).not_to be_exists end it 'replaces the matches' do provider.create expect(File.read(tmpfile).chomp).to eql("foo\nfoo bar\nfoo\nfoo") end end context 'when match does not match line - when there are the same matches and lines' do let(:params) do { - :replace_all_matches_not_matching_line => true, - :match => '^bar', - :multiple => true, + replace_all_matches_not_matching_line: true, + match: '^bar', + multiple: true, } end let(:content) { "foo\nfoo\nbar\nbar baz" } it 'requests changes' do expect(provider).not_to be_exists end it 'replaces the matches' do provider.create expect(File.read(tmpfile).chomp).to eql("foo\nfoo\nfoo\nfoo") end end end 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, + replace_all_matches_not_matching_line: true, + match: '^bar', + multiple: true, } end let(:content) { "foo\nfoo bar" } it 'does not request changes' do expect(provider).to be_exists end end 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, + replace_all_matches_not_matching_line: true, + match: '^bar', + multiple: true, } end let(:content) { 'foo bar' } it 'requests changes' do expect(provider).not_to be_exists end 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 index c2b30ff..f6f7e93 100644 --- a/spec/unit/puppet/provider/file_line/ruby_spec_alter.rb +++ b/spec/unit/puppet/provider/file_line/ruby_spec_alter.rb @@ -1,374 +1,376 @@ +# frozen_string_literal: true + 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 +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', + 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, + 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 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', + 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*=.*$', + 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 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) + @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) + @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', + 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) + @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) + @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', + name: 'foo', + path: tmpfile, + line: 'inserted = line', + after: '^foo1', ) end let :provider do provider_class.new(resource) end context 'when match and after set' do shared_context 'when 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, + 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 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) + @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', + 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') + @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, + 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) + @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) + @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) + @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$') + @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) + @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 @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 + 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) + @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 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 index 5114dec..456ddd6 100644 --- a/spec/unit/puppet/provider/file_line/ruby_spec_use_cases.rb +++ b/spec/unit/puppet/provider/file_line/ruby_spec_use_cases.rb @@ -1,135 +1,137 @@ +# frozen_string_literal: true + 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 +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', + 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, + 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, + 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, + line: "*\thard\tcore\t0", + match: "^[ \t]*\\*[ \t]+hard[ \t]+core[ \t]+.*", + multiple: true, - }.merge(:replace_all_matches_not_matching_line => 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$', + 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$', + 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$', + 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 c2d9779..9dc4ebd 100644 --- a/spec/unit/puppet/type/anchor_spec.rb +++ b/spec/unit/puppet/type/anchor_spec.rb @@ -1,9 +1,11 @@ +# frozen_string_literal: true + 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 '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 627bdf0..e506b13 100644 --- a/spec/unit/puppet/type/file_line_spec.rb +++ b/spec/unit/puppet/type/file_line_spec.rb @@ -1,111 +1,113 @@ +# frozen_string_literal: true + require 'spec_helper' require 'tempfile' describe Puppet::Type.type(:file_line) do let :tmp_path do if Puppet::Util::Platform.windows? 'C:\tmp\path' else '/tmp/path' end end let :my_path do if Puppet::Util::Platform.windows? 'C:\my\path' else '/my/path' 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 '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 'accepts a match regex' do file_line[:match] = '^foo.*$' expect(file_line[:match]).to eq('^foo.*$') end 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$', + name: 'foo', path: my_path, line: 'foo=bar', match: '^bar=blah$', ) }.not_to raise_error end 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=.*$', + name: 'foo', path: my_path, line: 'foo=bar', match: '^\s*foo=.*$', ) }.not_to raise_error end it 'accepts utf8 characters' do expect { Puppet::Type.type(:file_line).new( - :name => 'ƒồỗ', :path => my_path, :line => 'ƒồỗ=ьåя', :match => '^ьåя=βļάħ$', + name: 'ƒồỗ', path: my_path, line: 'ƒồỗ=ьåя', match: '^ьåя=βļάħ$', ) }.not_to raise_error end it 'accepts double byte characters' do expect { Puppet::Type.type(:file_line).new( - :name => 'フーバー', :path => my_path, :line => 'この=それ', :match => '^この=ああ$', + name: 'フーバー', path: my_path, line: 'この=それ', match: '^この=ああ$', ) }.not_to raise_error end it 'accepts posix filenames' do file_line[:path] = tmp_path expect(file_line[:path]).to eq(tmp_path) end 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 '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}) + 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 '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 # rubocop:disable Metrics/LineLength + 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 # rubocop:disable Metrics/LineLength + 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 '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}) + expect { Puppet::Type.type(:file_line).new(name: 'foo', line: 'path') }.to raise_error(Puppet::Error, %r{path is a required attribute}) end it 'defaults to ensure => present' do expect(file_line[:ensure]).to eq :present end it 'defaults to replace => true' do expect(file_line[:replace]).to eq :true end it 'defaults to encoding => UTF-8' do expect(file_line[:encoding]).to eq 'UTF-8' end 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 + 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 'autorequires the file it manages' do 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}]") && (rel.target.to_s == file_line.to_s) end expect(relationship).to be_a Puppet::Relationship end 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 end end