From 1cf21cdb2ba53f6dfb76391556158bc65c708605 Mon Sep 17 00:00:00 2001 From: Ian Saultz <52051793+atierian@users.noreply.github.com> Date: Tue, 19 Dec 2023 15:47:32 -0500 Subject: [PATCH 1/5] chore: update action depedency versions (#3427) --- .../download_test_configuration/action.yml | 2 +- .github/workflows/build_amplify_swift.yml | 2 +- .github/workflows/canary.yml | 2 +- .github/workflows/codeql.yml | 2 +- .github/workflows/dependency-review.yml | 2 +- .github/workflows/deploy_package.yml | 4 ++-- .github/workflows/deploy_release.yml | 4 ++-- .github/workflows/deploy_unstable.yml | 4 ++-- .github/workflows/fortify_scan.yml | 4 ++-- .github/workflows/integ_test_push_notifications.yml | 4 ++-- .github/workflows/release_block_manual_pr.yml | 2 +- .github/workflows/release_doc.yml | 4 ++-- .github/workflows/release_kickoff.yml | 2 +- .github/workflows/run_integration_tests.yml | 2 +- .github/workflows/run_unit_tests.yml | 4 ++-- .github/workflows/stress_test.yml | 12 ++++++------ .github/workflows/upload_coverage_report.yml | 4 ++-- 17 files changed, 30 insertions(+), 30 deletions(-) diff --git a/.github/composite_actions/download_test_configuration/action.yml b/.github/composite_actions/download_test_configuration/action.yml index 146a1c3e6c..82cd7413ab 100644 --- a/.github/composite_actions/download_test_configuration/action.yml +++ b/.github/composite_actions/download_test_configuration/action.yml @@ -23,7 +23,7 @@ runs: using: "composite" steps: - name: Configure AWS credentials for {{ inputs.resource_subfolder }} - uses: aws-actions/configure-aws-credentials@5fd3084fc36e372ff1fff382a39b10d03659f355 #v2 + uses: aws-actions/configure-aws-credentials@v4 with: role-to-assume: ${{ inputs.aws_role_to_assume }} aws-region: ${{ inputs.aws_region }} diff --git a/.github/workflows/build_amplify_swift.yml b/.github/workflows/build_amplify_swift.yml index 67b5a835b6..bfefc79014 100644 --- a/.github/workflows/build_amplify_swift.yml +++ b/.github/workflows/build_amplify_swift.yml @@ -16,7 +16,7 @@ jobs: runs-on: macos-13 steps: - name: Checkout repository - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 #v3.5.3 + uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 #v4.1.1 with: persist-credentials: false diff --git a/.github/workflows/canary.yml b/.github/workflows/canary.yml index 7bb1939fb8..9b1631d149 100644 --- a/.github/workflows/canary.yml +++ b/.github/workflows/canary.yml @@ -27,7 +27,7 @@ jobs: runs-on: ${{ matrix.os }} steps: - name: Checkout Code - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # v3.5.3 + uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 #v4.1.1 with: persist-credentials: false diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index d867191665..8084087bc4 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -39,7 +39,7 @@ jobs: steps: - name: Checkout repository - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 #v3.5.3 + uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 #v4.1.1 # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL diff --git a/.github/workflows/dependency-review.yml b/.github/workflows/dependency-review.yml index 199ee76507..087370ee0e 100644 --- a/.github/workflows/dependency-review.yml +++ b/.github/workflows/dependency-review.yml @@ -15,7 +15,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout Code - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # v3.5.3 + uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 #v4.1.1 with: persist-credentials: false diff --git a/.github/workflows/deploy_package.yml b/.github/workflows/deploy_package.yml index 37e6b7c75e..6141a074ae 100644 --- a/.github/workflows/deploy_package.yml +++ b/.github/workflows/deploy_package.yml @@ -43,7 +43,7 @@ jobs: GITHUB_USER: aws-amplify-ops steps: - name: Configure AWS credentials - uses: aws-actions/configure-aws-credentials@5fd3084fc36e372ff1fff382a39b10d03659f355 #v2 + uses: aws-actions/configure-aws-credentials@v4 with: role-to-assume: ${{ secrets.AWS_ROLE_TO_ASSUME }} role-session-name: ${{ format('{0}.release', github.run_id) }} @@ -60,7 +60,7 @@ jobs: echo "token=$PAT" >> $GITHUB_OUTPUT - name: Checkout repo - uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c # v3.3.0 + uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 #v4.1.1 with: fetch-depth: 100 token: ${{steps.retrieve-token.outputs.token}} diff --git a/.github/workflows/deploy_release.yml b/.github/workflows/deploy_release.yml index 906bed60be..289e12ab45 100644 --- a/.github/workflows/deploy_release.yml +++ b/.github/workflows/deploy_release.yml @@ -39,7 +39,7 @@ jobs: GITHUB_USER: aws-amplify-ops steps: - name: Configure AWS credentials - uses: aws-actions/configure-aws-credentials@5fd3084fc36e372ff1fff382a39b10d03659f355 #v2 + uses: aws-actions/configure-aws-credentials@v4 with: role-to-assume: ${{ secrets.AWS_ROLE_TO_ASSUME }} role-session-name: ${{ format('{0}.release', github.run_id) }} @@ -56,7 +56,7 @@ jobs: echo "token=$PAT" >> $GITHUB_OUTPUT - name: Checkout repo - uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c # v3.3.0 + uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 #v4.1.1 with: fetch-depth: 100 token: ${{steps.retrieve-token.outputs.token}} diff --git a/.github/workflows/deploy_unstable.yml b/.github/workflows/deploy_unstable.yml index fb025ece56..a91c4e7d06 100644 --- a/.github/workflows/deploy_unstable.yml +++ b/.github/workflows/deploy_unstable.yml @@ -39,7 +39,7 @@ jobs: GITHUB_USER: aws-amplify-ops steps: - name: Configure AWS credentials - uses: aws-actions/configure-aws-credentials@5fd3084fc36e372ff1fff382a39b10d03659f355 #v2 + uses: aws-actions/configure-aws-credentials@v4 with: role-to-assume: ${{ secrets.AWS_ROLE_TO_ASSUME }} role-session-name: ${{ format('{0}.release', github.run_id) }} @@ -56,7 +56,7 @@ jobs: echo "token=$PAT" >> $GITHUB_OUTPUT - name: Checkout repo - uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c # v3.3.0 + uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 #v4.1.1 with: fetch-depth: 100 token: ${{steps.retrieve-token.outputs.token}} diff --git a/.github/workflows/fortify_scan.yml b/.github/workflows/fortify_scan.yml index c601d1f92f..5d9e6184fb 100644 --- a/.github/workflows/fortify_scan.yml +++ b/.github/workflows/fortify_scan.yml @@ -25,7 +25,7 @@ jobs: runs-on: macos-latest environment: Fortify steps: - - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 #v3.5.3 + - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 #v4.1.1 with: persist-credentials: false @@ -35,7 +35,7 @@ jobs: cp -r Amplify source cp -r AmplifyPlugins source - name: Configure AWS credentials for fetching fortify resources - uses: aws-actions/configure-aws-credentials@5fd3084fc36e372ff1fff382a39b10d03659f355 #v2 + uses: aws-actions/configure-aws-credentials@v4 with: role-to-assume: ${{ secrets.AWS_ROLE_TO_ASSUME }} aws-region: ${{ secrets.AWS_REGION }} diff --git a/.github/workflows/integ_test_push_notifications.yml b/.github/workflows/integ_test_push_notifications.yml index 5f0e1df437..a600fbd68b 100644 --- a/.github/workflows/integ_test_push_notifications.yml +++ b/.github/workflows/integ_test_push_notifications.yml @@ -39,7 +39,7 @@ jobs: - platform: ${{ github.event.inputs.watchos == 'false' && 'watchOS' || 'None' }} steps: - name: Checkout repository - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 #v3.5.3 + uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1 with: persist-credentials: false @@ -63,7 +63,7 @@ jobs: destination: ~/.aws-amplify/amplify-ios/testconfiguration/ - name: Set up node - uses: actions/setup-node@64ed1c7eab4cce3362f8c340dee64e5eaeef8f7c + uses: actions/setup-node@b39b52d1213e96004bfcb1c61a8a6fa8ab84f3e8 # v4.0.1 with: node-version: 16.x diff --git a/.github/workflows/release_block_manual_pr.yml b/.github/workflows/release_block_manual_pr.yml index b9665b1441..1d86a8288b 100644 --- a/.github/workflows/release_block_manual_pr.yml +++ b/.github/workflows/release_block_manual_pr.yml @@ -21,7 +21,7 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@2541b1294d2704b0964813337f33b291d3f8596b + - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 #v4.1.1 - name: Close PR shell: bash diff --git a/.github/workflows/release_doc.yml b/.github/workflows/release_doc.yml index 88cc91ba93..309d9dca89 100644 --- a/.github/workflows/release_doc.yml +++ b/.github/workflows/release_doc.yml @@ -14,7 +14,7 @@ jobs: environment: Release steps: - name: Configure AWS credentials - uses: aws-actions/configure-aws-credentials@5fd3084fc36e372ff1fff382a39b10d03659f355 #v2 + uses: aws-actions/configure-aws-credentials@v4 with: role-to-assume: ${{ secrets.AWS_ROLE_TO_ASSUME }} role-session-name: ${{ format('{0}.release-doc', github.run_id) }} @@ -31,7 +31,7 @@ jobs: echo "token=$PAT" >> $GITHUB_OUTPUT - name: Checkout repo - uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c # v3.3.0 + uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 #v4.1.1 with: token: ${{steps.retrieve-token.outputs.token}} diff --git a/.github/workflows/release_kickoff.yml b/.github/workflows/release_kickoff.yml index d26d5a0cc0..86145a487c 100644 --- a/.github/workflows/release_kickoff.yml +++ b/.github/workflows/release_kickoff.yml @@ -13,7 +13,7 @@ jobs: runs-on: macos-12 steps: - - uses: actions/checkout@2541b1294d2704b0964813337f33b291d3f8596b + - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 #v4.1.1 - name: Create PR to push main to release branch env: diff --git a/.github/workflows/run_integration_tests.yml b/.github/workflows/run_integration_tests.yml index 500f10095a..41bec24f2b 100644 --- a/.github/workflows/run_integration_tests.yml +++ b/.github/workflows/run_integration_tests.yml @@ -39,7 +39,7 @@ jobs: environment: IntegrationTest steps: - name: Checkout repository - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 #v3.5.3 + uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 #v4.1.1 with: persist-credentials: false diff --git a/.github/workflows/run_unit_tests.yml b/.github/workflows/run_unit_tests.yml index 518f74b1a4..e87cd68de8 100644 --- a/.github/workflows/run_unit_tests.yml +++ b/.github/workflows/run_unit_tests.yml @@ -38,7 +38,7 @@ jobs: timeout-minutes: ${{ inputs.timeout-minutes }} steps: - name: Checkout repository - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 #v3.5.3 + uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 #v4.1.1 with: persist-credentials: false @@ -102,7 +102,7 @@ jobs: - name: Store Coverage Report File if: ${{ inputs.generate_coverage_report == true }} - uses: actions/upload-artifact@0b7f8abb1508181956e8e162db84b466c27e18ce #v3.1.2 + uses: actions/upload-artifact@c7d193f32edcb7bfad88892161225aeda64e9392 # v4.0.0 with: name: ${{ inputs.scheme }}-Coverage-${{ github.sha }} path: ${{ github.workspace }}/${{ inputs.scheme }}-Coverage.lcov diff --git a/.github/workflows/stress_test.yml b/.github/workflows/stress_test.yml index 7988fb7123..805d6232d3 100644 --- a/.github/workflows/stress_test.yml +++ b/.github/workflows/stress_test.yml @@ -17,7 +17,7 @@ jobs: runs-on: macos-13 environment: IntegrationTest steps: - - uses: actions/checkout@2541b1294d2704b0964813337f33b291d3f8596b + - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 #v4.1.1 with: persist-credentials: false @@ -34,7 +34,7 @@ jobs: runs-on: macos-13 environment: IntegrationTest steps: - - uses: actions/checkout@2541b1294d2704b0964813337f33b291d3f8596b + - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 #v4.1.1 with: persist-credentials: false @@ -62,7 +62,7 @@ jobs: runs-on: macos-13 environment: IntegrationTest steps: - - uses: actions/checkout@2541b1294d2704b0964813337f33b291d3f8596b + - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 #v4.1.1 with: persist-credentials: false @@ -90,7 +90,7 @@ jobs: runs-on: macos-13 environment: IntegrationTest steps: - - uses: actions/checkout@2541b1294d2704b0964813337f33b291d3f8596b + - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 #v4.1.1 with: persist-credentials: false @@ -118,7 +118,7 @@ jobs: runs-on: macos-13 environment: IntegrationTest steps: - - uses: actions/checkout@2541b1294d2704b0964813337f33b291d3f8596b + - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 #v4.1.1 with: persist-credentials: false @@ -146,7 +146,7 @@ jobs: runs-on: macos-13 environment: IntegrationTest steps: - - uses: actions/checkout@2541b1294d2704b0964813337f33b291d3f8596b + - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 #v4.1.1 with: persist-credentials: false diff --git a/.github/workflows/upload_coverage_report.yml b/.github/workflows/upload_coverage_report.yml index 287e9fc154..3ce54a81ce 100644 --- a/.github/workflows/upload_coverage_report.yml +++ b/.github/workflows/upload_coverage_report.yml @@ -21,12 +21,12 @@ jobs: timeout-minutes: 2 runs-on: ubuntu-latest steps: - - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 #v3.5.3 + - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 #v4.1.1 with: persist-credentials: false - name: Retrieve Coverage report - uses: actions/download-artifact@9bc31d5ccc31df68ecc42ccf4149144866c47d8a #v3.0.2 + uses: actions/download-artifact@f44cd7b40bfd40b6aa1cc1b9b5b7bf03d3c67110 # 4.1.0 with: name: ${{ inputs.scheme }}-Coverage-${{ github.sha }} path: ${{ github.workspace }} From a55e899ea4f07314ad6ddd5a9cfc38a19ed7ec32 Mon Sep 17 00:00:00 2001 From: Ian Saultz <52051793+atierian@users.noreply.github.com> Date: Tue, 19 Dec 2023 15:50:02 -0500 Subject: [PATCH 2/5] consolidate issue open, comment, and closed into event based workflows (#3428) --- .../workflows/cleanup_labels_issue_close.yml | 26 -------------- .github/workflows/closed_issue_message.yml | 21 ----------- .github/workflows/issue_closed.yml | 34 ++++++++++++++++++ .github/workflows/issue_comment.yml | 35 +++++++++++++++++++ .github/workflows/issue_opened.yml | 33 +++++++++++++++++ .github/workflows/new_issue_maintainer.yml | 21 ----------- .github/workflows/notify_new_issue.yml | 34 ------------------ 7 files changed, 102 insertions(+), 102 deletions(-) delete mode 100644 .github/workflows/cleanup_labels_issue_close.yml delete mode 100644 .github/workflows/closed_issue_message.yml create mode 100644 .github/workflows/issue_closed.yml create mode 100644 .github/workflows/issue_comment.yml create mode 100644 .github/workflows/issue_opened.yml delete mode 100644 .github/workflows/new_issue_maintainer.yml delete mode 100644 .github/workflows/notify_new_issue.yml diff --git a/.github/workflows/cleanup_labels_issue_close.yml b/.github/workflows/cleanup_labels_issue_close.yml deleted file mode 100644 index 84be33bad6..0000000000 --- a/.github/workflows/cleanup_labels_issue_close.yml +++ /dev/null @@ -1,26 +0,0 @@ -# Removes pending-response and closing-soon labels when an issue is closed. - -name: Cleanup Labels on Issue Close - -on: - issues: - types: [closed] - -permissions: - issues: write - -jobs: - cleanup: - name: Remove labels - runs-on: ubuntu-latest - if: ${{ !github.event.issue.pull_request && (contains(github.event.issue.labels.*.name, 'pending-response') || contains(github.event.issue.labels.*.name, 'closing soon') || contains(github.event.issue.labels.*.name, 'pending-release')) }} - - steps: - - uses: actions/checkout@2541b1294d2704b0964813337f33b291d3f8596b - - name: remove unnecessary labels after closing - shell: bash - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - ISSUE_NUMBER: ${{ github.event.issue.number }} - run: | - gh issue edit $ISSUE_NUMBER --remove-label "closing soon" --remove-label "pending-response" --remove-label "pending-release" diff --git a/.github/workflows/closed_issue_message.yml b/.github/workflows/closed_issue_message.yml deleted file mode 100644 index a07fc9b14e..0000000000 --- a/.github/workflows/closed_issue_message.yml +++ /dev/null @@ -1,21 +0,0 @@ - -name: Closed Issue Message -on: - issues: - types: [closed] - -permissions: - issues: write - -jobs: - auto_comment: - runs-on: ubuntu-latest - steps: - - uses: aws-actions/closed-issue-message@v1 - with: - repo-token: "${{ secrets.GITHUB_TOKEN }}" - message: | - ### ⚠️COMMENT VISIBILITY WARNING⚠️ - Comments on closed issues are hard for our team to see. - If you need more assistance, please either tag a team member or open a new issue that references this one. - If you wish to keep having a conversation with other community members under this issue feel free to do so. diff --git a/.github/workflows/issue_closed.yml b/.github/workflows/issue_closed.yml new file mode 100644 index 0000000000..929ad0ebf2 --- /dev/null +++ b/.github/workflows/issue_closed.yml @@ -0,0 +1,34 @@ +name: Issue Closed + +on: + issues: + types: [closed] + +permissions: + issues: write + +jobs: + cleanup-labels: + runs-on: ubuntu-latest + if: ${{ (contains(github.event.issue.labels.*.name, 'pending-response') || contains(github.event.issue.labels.*.name, 'closing soon') || contains(github.event.issue.labels.*.name, 'pending-release')) }} + steps: + - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 #v4.1.1 + - name: remove unnecessary labels after closing + shell: bash + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + ISSUE_NUMBER: ${{ github.event.issue.number }} + run: | + gh issue edit $ISSUE_NUMBER --remove-label "closing soon" --remove-label "pending-response" --remove-label "pending-release" + + comment-visibility-warning: + runs-on: ubuntu-latest + steps: + - uses: aws-actions/closed-issue-message@v1 + with: + repo-token: "${{ secrets.GITHUB_TOKEN }}" + message: | + ### ⚠️COMMENT VISIBILITY WARNING⚠️ + Comments on closed issues are hard for our team to see. + If you need more assistance, please either tag a team member or open a new issue that references this one. + If you wish to keep having a conversation with other community members under this issue feel free to do so. diff --git a/.github/workflows/issue_comment.yml b/.github/workflows/issue_comment.yml new file mode 100644 index 0000000000..55c66ea87e --- /dev/null +++ b/.github/workflows/issue_comment.yml @@ -0,0 +1,35 @@ +name: Issue Comment + +on: + issue_comment: + types: [created] + +jobs: + notify: + runs-on: ubuntu-latest + permissions: {} + if: ${{ !github.event.issue.pull_request && !contains(fromJSON('["MEMBER", "OWNER"]'), github.event.comment.author_association) }} + steps: + - name: Run webhook curl command + env: + WEBHOOK_URL: ${{ secrets.SLACK_COMMENT_WEBHOOK_URL }} + COMMENT: ${{toJson(github.event.comment.body)}} + USER: ${{github.event.comment.user.login}} + COMMENT_URL: ${{github.event.comment.html_url}} + shell: bash + run: echo $COMMENT | sed "s/\\\n/. /g; s/\\\r//g; s/[^a-zA-Z0-9 &().,:]//g" | xargs -I {} curl -s POST "$WEBHOOK_URL" -H "Content-Type:application/json" --data '{"comment":"{}", "commentUrl":"'$COMMENT_URL'", "user":"'$USER'"}' + + remove-pending-response-label: + runs-on: ubuntu-latest + permissions: + issues: write + if: ${{ !github.event.issue.pull_request && contains(github.event.issue.labels.*.name, 'pending-response') }} + steps: + - uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 #v4.1.1 + - name: remove unnecessary labels after closing + shell: bash + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + ISSUE_NUMBER: ${{ github.event.issue.number }} + run: | + gh issue edit $ISSUE_NUMBER --remove-label "pending-response" \ No newline at end of file diff --git a/.github/workflows/issue_opened.yml b/.github/workflows/issue_opened.yml new file mode 100644 index 0000000000..7ea510ba0e --- /dev/null +++ b/.github/workflows/issue_opened.yml @@ -0,0 +1,33 @@ +name: Issue Opened +on: + issues: + types: [opened] + +jobs: + notify: + runs-on: ubuntu-latest + permissions: {} + if: ${{ !contains(fromJSON('["MEMBER", "OWNER"]'), github.event.issue.author_association) }} + steps: + - name: Run webhook curl command + env: + WEBHOOK_URL: ${{ secrets.SLACK_ISSUE_WEBHOOK_URL }} + ISSUE: ${{toJson(github.event.issue.title)}} + ISSUE_URL: ${{github.event.issue.html_url}} + USER: ${{github.event.issue.user.login}} + shell: bash + run: echo $ISSUE | sed 's/[^a-zA-Z0-9 &().,:]//g' | xargs -I {} curl -s POST "$WEBHOOK_URL" -H "Content-Type:application/json" --data '{"issue":"{}", "issueUrl":"'$ISSUE_URL'", "user":"'$USER'"}' + + maintainer-opened: + runs-on: ubuntu-latest + permissions: + issues: write + if: ${{ contains(fromJSON('["MEMBER", "OWNER"]'), github.event.issue.author_association) }} + steps: + - name: Post comment if maintainer opened. + shell: bash + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + ISSUE_NUMBER: ${{ github.event.issue.number }} + run: | + gh issue comment $ISSUE_NUMBER --repo aws-amplify/amplify-swift -b "This issue was opened by a maintainer of this repository; updates will be posted here. If you are also experiencing this issue, please comment here with any relevant information so that we're aware and can prioritize accordingly." diff --git a/.github/workflows/new_issue_maintainer.yml b/.github/workflows/new_issue_maintainer.yml deleted file mode 100644 index 188fce06b2..0000000000 --- a/.github/workflows/new_issue_maintainer.yml +++ /dev/null @@ -1,21 +0,0 @@ -name: New Issue by Maintainer - -on: - issues: - types: [opened] - -permissions: - issues: write - -jobs: - maintainer-opened: - runs-on: ubuntu-latest - if: ${{ !github.event.issue.pull_request && contains(fromJSON('["palpatim", "5d", "jcjimenez", "lawmicha", "harsh62", "thisisabhash", "royjit", "atierian", "ukhan-amazon", "ruisebas", "phantumcode"]'), github.event.issue.user.login) }} - steps: - - name: add message if maintainer opened - shell: bash - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - ISSUE_NUMBER: ${{ github.event.issue.number }} - run: | - gh issue comment $ISSUE_NUMBER --repo aws-amplify/amplify-ios -b "This issue was opened by a maintainer of this repository; updates will be posted here. If you are also experiencing this issue, please comment here with any relevant information so that we're aware and can prioritize accordingly." diff --git a/.github/workflows/notify_new_issue.yml b/.github/workflows/notify_new_issue.yml deleted file mode 100644 index 2c32e33645..0000000000 --- a/.github/workflows/notify_new_issue.yml +++ /dev/null @@ -1,34 +0,0 @@ -# This is a basic workflow to help you get started with Actions - -name: Notify New Issues - -# Controls when the workflow will run -on: - # Triggers the workflow on comment events on pending response issues - issues: - types: [opened] - -# Limit the GITHUB_TOKEN permissions -permissions: {} - -# A workflow run is made up of one or more jobs that can run sequentially or in parallel -jobs: - # This workflow contains a single job called "notify" - notify: - # The type of runner that the job will run on - runs-on: ubuntu-latest - - # Exclude issues opened by maintainers - if: ${{ !contains(fromJSON('["MEMBER", "OWNER"]'), github.event.issue.author_association) }} - - # Steps represent a sequence of tasks that will be executed as part of the job - steps: - # Runs a single command using the runners shell - - name: Run webhook curl command - env: - WEBHOOK_URL: ${{ secrets.SLACK_ISSUE_WEBHOOK_URL }} - ISSUE: ${{toJson(github.event.issue.title)}} - ISSUE_URL: ${{github.event.issue.html_url}} - USER: ${{github.event.issue.user.login}} - shell: bash - run: echo $ISSUE | sed 's/[^a-zA-Z0-9 &().,:]//g' | xargs -I {} curl -s POST "$WEBHOOK_URL" -H "Content-Type:application/json" --data '{"issue":"{}", "issueUrl":"'$ISSUE_URL'", "user":"'$USER'"}' From 006e04580c5302ca83c7d63e98449a51ae0a1865 Mon Sep 17 00:00:00 2001 From: Michael Law <1365977+lawmicha@users.noreply.github.com> Date: Wed, 20 Dec 2023 09:28:28 -0500 Subject: [PATCH 3/5] fix(DataStore): Add 'weak self' to prevent retain cycles in OutgoingMutationQueue (#3429) * fix(DataStore): Add 'weak self' to prevent retain cycles * update to use optional binding directly --- .../OutgoingMutationQueue.swift | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/OutgoingMutationQueue/OutgoingMutationQueue.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/OutgoingMutationQueue/OutgoingMutationQueue.swift index 2acb52f892..5e833b41a5 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/OutgoingMutationQueue/OutgoingMutationQueue.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Sync/MutationSync/OutgoingMutationQueue/OutgoingMutationQueue.swift @@ -70,9 +70,8 @@ final class OutgoingMutationQueue: OutgoingMutationQueueBehavior { self.stateMachineSink = self.stateMachine .$state .sink { [weak self] newState in - guard let self = self else { - return - } + guard let self else { return } + self.log.verbose("New state: \(newState)") self.mutationDispatchQueue.async { self.respond(to: newState) @@ -138,7 +137,9 @@ final class OutgoingMutationQueue: OutgoingMutationQueueBehavior { self.api = api self.reconciliationQueue = reconciliationQueue - queryMutationEventsFromStorage { + queryMutationEventsFromStorage { [weak self] in + guard let self = self else { return } + self.operationQueue.isSuspended = false // State machine notification to ".receivedSubscription" will be handled in `receive(subscription:)` mutationEventPublisher.publisher.subscribe(self) @@ -319,7 +320,8 @@ final class OutgoingMutationQueue: OutgoingMutationQueueBehavior { self.dispatchOutboxMutationProcessedEvent(mutationEvent: mutationEvent, mutationSync: mutationSync) } - self.queryMutationEventsFromStorage { + self.queryMutationEventsFromStorage { [weak self] in + guard let self else { return } self.stateMachine.notify(action: .processedEvent) } } @@ -333,7 +335,9 @@ final class OutgoingMutationQueue: OutgoingMutationQueueBehavior { predicate: predicate, sort: nil, paginationInput: nil, - eagerLoad: true) { result in + eagerLoad: true) { [weak self] result in + guard let self else { return } + switch result { case .success(let events): self.dispatchOutboxStatusEvent(isEmpty: events.isEmpty) From 92ff97d9c7301b294c661e5dda6b669a5a6977fc Mon Sep 17 00:00:00 2001 From: Ian Saultz <52051793+atierian@users.noreply.github.com> Date: Wed, 20 Dec 2023 10:03:10 -0500 Subject: [PATCH 4/5] fix: use non-failable UTF8View Data init when converting from String (#3430) --- .../Model/Internal/Model+Codable.swift | 9 +-------- .../Internal/Schema/ModelValueConverter.swift | 5 +---- ...mplifyConfigurationInitFromFileTests.swift | 2 +- .../AuthenticationTokenAuthInterceptor.swift | 4 ++-- .../IAMAuthInterceptor.swift | 6 +++--- .../Operation/AWSHTTPURLResponseTests.swift | 4 ++-- .../Operation/GraphQLMutateCombineTests.swift | 4 ++-- .../Operation/GraphQLQueryCombineTests.swift | 4 ++-- .../GraphQLSubscribeCombineTests.swift | 10 +++++----- .../Operation/GraphQLSubscribeTaskTests.swift | 10 +++++----- .../Operation/GraphQLSubscribeTests.swift | 10 +++++----- .../ASF/CognitoUserPoolASF.swift | 8 ++------ ...VerifyDevicePasswordSRP+Calculations.swift | 6 +++--- .../VerifyPasswordSRP+Calculations.swift | 6 +++--- .../CodeGen/Data/RespondToAuthChallenge.swift | 19 +++++++------------ .../Support/Helpers/ClientSecretHelper.swift | 4 ++-- .../HostedUI/HostedUIRequestHelper.swift | 9 ++++----- .../Auth/Sources/AmplifySRP/HKDF.swift | 7 +++---- .../MockCredentialStoreBehavior.swift | 2 +- ...erifyDevicePasswordSRPSignatureTests.swift | 6 +++--- .../Support/DefaultConfig.swift | 2 +- .../Support/HostedUIRequestHelperTests.swift | 5 ++--- .../Support/QueryPredicate+GraphQL.swift | 4 ++-- .../MutationSyncMetadataTests.swift | 12 ++---------- .../Sync/PaginatedListTests.swift | 12 ++---------- ...MutationErrorFromCloudOperationTests.swift | 4 +--- .../Comment3Wrapper.swift | 2 +- .../Comment4Wrapper.swift | 2 +- .../Post3Wrapper.swift | 2 +- .../Post4Wrapper.swift | 2 +- .../Post5Wrapper.swift | 2 +- .../Post6Wrapper.swift | 2 +- .../SerializedModelWrappers/PostWrapper.swift | 2 +- .../TestFlutterModelRegistration.swift | 2 +- ...pointAnalyticsKeychainMigrationTests.swift | 2 +- .../EndpointClientTests.swift | 10 +++++----- .../AWSCloudWatchLoggingSession.swift | 5 +---- .../Persistence/LogEntryCodec.swift | 4 +--- .../LogEntryTests.swift | 2 +- ...ificationsPluginClientBehaviourTests.swift | 2 +- .../PredictionsPluginConfigurationTests.swift | 16 ++++++++-------- ...AWSS3StoragePluginAsyncBehaviorTests.swift | 2 +- .../AWSS3StoragePutDataOperationTests.swift | 2 +- .../Storage/AWSS3StorageServiceTests.swift | 4 ++-- .../Support/Internal/FileHandleTests.swift | 2 +- .../Support/Internal/FileSystemTests.swift | 5 +---- .../StorageMultipartUploadSessionTests.swift | 6 +----- .../Internal/StorageTransferTaskTests.swift | 4 ++-- .../StorageRequestUtilsGetterTests.swift | 2 +- .../StorageRequestUtilsValidatorTests.swift | 2 +- ...ragePluginAccelerateIntegrationTests.swift | 8 ++++---- .../AWSS3StoragePluginAccessLevelTests.swift | 13 +++---------- ...S3StoragePluginBasicIntegrationTests.swift | 12 ++++++------ ...3StoragePluginPrefixKeyResolverTests.swift | 4 ++-- ...hNotificationsCategoryClientAPITests.swift | 2 +- ...lifyConfigurationInitializationTests.swift | 4 ++-- .../CoreTests/ConfigurationTests.swift | 2 +- AmplifyTests/CoreTests/JSONValueTests.swift | 4 ++-- 58 files changed, 125 insertions(+), 184 deletions(-) diff --git a/Amplify/Categories/DataStore/Model/Internal/Model+Codable.swift b/Amplify/Categories/DataStore/Model/Internal/Model+Codable.swift index 58505ada18..2eff95f1e7 100644 --- a/Amplify/Categories/DataStore/Model/Internal/Model+Codable.swift +++ b/Amplify/Categories/DataStore/Model/Internal/Model+Codable.swift @@ -33,14 +33,7 @@ extension Model where Self: Codable { resolvedDecoder = JSONDecoder(dateDecodingStrategy: ModelDateFormatting.decodingStrategy) } - guard let data = json.data(using: .utf8) else { - throw DataStoreError.decodingError( - "Invalid JSON string. Could not convert the passed JSON string into a UTF-8 Data object", - "Ensure the JSON doesn't contain any invalid UTF-8 data:\n\n\(json)" - ) - } - - return try resolvedDecoder.decode(Self.self, from: data) + return try resolvedDecoder.decode(Self.self, from: Data(json.utf8)) } /// De-serialize a `Dictionary` into an instance of the concrete type that conforms diff --git a/Amplify/Categories/DataStore/Model/Internal/Schema/ModelValueConverter.swift b/Amplify/Categories/DataStore/Model/Internal/Schema/ModelValueConverter.swift index de961101ec..812de4ecc1 100644 --- a/Amplify/Categories/DataStore/Model/Internal/Schema/ModelValueConverter.swift +++ b/Amplify/Categories/DataStore/Model/Internal/Schema/ModelValueConverter.swift @@ -63,9 +63,6 @@ extension ModelValueConverter { /// application making any change to these `public` types should be backward compatible, otherwise it will be a /// breaking change. public static func fromJSON(_ value: String) throws -> Any? { - guard let data = value.data(using: .utf8) else { - return nil - } - return try JSONSerialization.jsonObject(with: data) + return try JSONSerialization.jsonObject(with: Data(value.utf8)) } } diff --git a/AmplifyFunctionalTests/AmplifyConfigurationInitFromFileTests.swift b/AmplifyFunctionalTests/AmplifyConfigurationInitFromFileTests.swift index 360cae31f3..dfa4039a44 100644 --- a/AmplifyFunctionalTests/AmplifyConfigurationInitFromFileTests.swift +++ b/AmplifyFunctionalTests/AmplifyConfigurationInitFromFileTests.swift @@ -22,7 +22,7 @@ class AmplifyConfigurationInitFromFileTests: XCTestCase { } """ - let configData = configString.data(using: .utf8)! + let configData = Data(configString.utf8) let configURL = FileManager .default .temporaryDirectory diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/SubscriptionInterceptor/AuthenticationTokenAuthInterceptor.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/SubscriptionInterceptor/AuthenticationTokenAuthInterceptor.swift index 0f57c87df4..02028de7db 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/SubscriptionInterceptor/AuthenticationTokenAuthInterceptor.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/SubscriptionInterceptor/AuthenticationTokenAuthInterceptor.swift @@ -55,8 +55,8 @@ class AuthenticationTokenAuthInterceptor: AuthInterceptorAsync { let authHeader = TokenAuthHeader(token: authToken, host: host) let base64Auth = AppSyncJSONHelper.base64AuthenticationBlob(authHeader) - let payloadData = SubscriptionConstants.emptyPayload.data(using: .utf8) - let payloadBase64 = payloadData?.base64EncodedString() + let payloadData = Data(SubscriptionConstants.emptyPayload.utf8) + let payloadBase64 = payloadData.base64EncodedString() guard var urlComponents = URLComponents(url: request.url, resolvingAgainstBaseURL: false) else { return request diff --git a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/SubscriptionInterceptor/IAMAuthInterceptor.swift b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/SubscriptionInterceptor/IAMAuthInterceptor.swift index 7d1bb4df11..5598190755 100644 --- a/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/SubscriptionInterceptor/IAMAuthInterceptor.swift +++ b/AmplifyPlugins/API/Sources/AWSAPIPlugin/Interceptor/SubscriptionInterceptor/IAMAuthInterceptor.swift @@ -54,8 +54,8 @@ class IAMAuthInterceptor: AuthInterceptorAsync { } let base64Auth = AppSyncJSONHelper.base64AuthenticationBlob(authHeader) - let payloadData = payloadString.data(using: .utf8) - let payloadBase64 = payloadData?.base64EncodedString() + let payloadData = Data(payloadString.utf8) + let payloadBase64 = payloadData.base64EncodedString() guard var urlComponents = URLComponents(url: request.url, resolvingAgainstBaseURL: false) else { return request @@ -91,7 +91,7 @@ class IAMAuthInterceptor: AuthInterceptorAsync { .withHeader(name: RealtimeProviderConstants.contentEncodingKey, value: RealtimeProviderConstants.iamEncoding) .withHeader(name: URLRequestConstants.Header.contentType, value: RealtimeProviderConstants.iamConentType) .withHeader(name: URLRequestConstants.Header.host, value: host) - .withBody(.data(payload.data(using: .utf8))) + .withBody(.data(Data(payload.utf8))) /// 2. The request is SigV4 signed by using all the available headers on the request. By signing the request, the signature is added to /// the request headers as authorization and security token. diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/AWSHTTPURLResponseTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/AWSHTTPURLResponseTests.swift index 145eeb33f6..9cc06f34f6 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/AWSHTTPURLResponseTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/AWSHTTPURLResponseTests.swift @@ -11,7 +11,7 @@ import XCTest class AWSHTTPURLResponseTests: XCTestCase { func testAWSHTTPURLResponse() throws { - let body = "responseBody".data(using: .utf8) + let body = Data("responseBody".utf8) let httpResponse = HTTPURLResponse(url: URL(string: "dummyString")!, statusCode: 200, httpVersion: "1.1", @@ -35,7 +35,7 @@ class AWSHTTPURLResponseTests: XCTestCase { } func testAWSHTTPURLResponseNSCoding() { - let body = "responseBody".data(using: .utf8) + let body = Data("responseBody".utf8) let httpResponse = HTTPURLResponse(url: URL(string: "dummyString")!, statusCode: 200, httpVersion: "1.1", diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/GraphQLMutateCombineTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/GraphQLMutateCombineTests.swift index e5fbdffc79..830cdacf3b 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/GraphQLMutateCombineTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/GraphQLMutateCombineTests.swift @@ -16,7 +16,7 @@ class GraphQLMutateCombineTests: OperationTestBase { func testMutateSucceeds() throws { let testJSONData: JSONValue = ["foo": true] - let sentData = #"{"data": {"foo": true}}"# .data(using: .utf8)! + let sentData = Data(#"{"data": {"foo": true}}"#.utf8) try setUpPluginForSingleResponse(sending: sentData, for: .graphQL) let request = GraphQLRequest(document: testDocument, variables: nil, responseType: JSONValue.self) @@ -52,7 +52,7 @@ class GraphQLMutateCombineTests: OperationTestBase { } func testMutateHandlesResponseError() throws { - let sentData = #"{"data": {"foo": true}, "errors": []}"# .data(using: .utf8)! + let sentData = Data(#"{"data": {"foo": true}, "errors": []}"#.utf8) try setUpPluginForSingleResponse(sending: sentData, for: .graphQL) let request = GraphQLRequest(document: testDocument, variables: nil, responseType: JSONValue.self) diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/GraphQLQueryCombineTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/GraphQLQueryCombineTests.swift index 6dd8a54326..9109d093af 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/GraphQLQueryCombineTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/GraphQLQueryCombineTests.swift @@ -16,7 +16,7 @@ class GraphQLQueryCombineTests: OperationTestBase { func testQuerySucceeds() throws { let testJSONData: JSONValue = ["foo": true] - let sentData = #"{"data": {"foo": true}}"# .data(using: .utf8)! + let sentData = Data(#"{"data": {"foo": true}}"#.utf8) try setUpPluginForSingleResponse(sending: sentData, for: .graphQL) let request = GraphQLRequest(document: testDocument, variables: nil, responseType: JSONValue.self) @@ -52,7 +52,7 @@ class GraphQLQueryCombineTests: OperationTestBase { } func testQueryHandlesResponseError() throws { - let sentData = #"{"data": {"foo": true}, "errors": []}"# .data(using: .utf8)! + let sentData = Data(#"{"data": {"foo": true}, "errors": []}"#.utf8) try setUpPluginForSingleResponse(sending: sentData, for: .graphQL) let request = GraphQLRequest(document: testDocument, variables: nil, responseType: JSONValue.self) diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/GraphQLSubscribeCombineTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/GraphQLSubscribeCombineTests.swift index 8fbc7bcbbc..b21b7f6528 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/GraphQLSubscribeCombineTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/GraphQLSubscribeCombineTests.swift @@ -72,7 +72,7 @@ class GraphQLSubscribeCombineTests: OperationTestBase { receivedDataValueError.isInverted = true let testJSON: JSONValue = ["foo": true] - let testData = #"{"data": {"foo": true}}"# .data(using: .utf8)! + let testData = Data(#"{"data": {"foo": true}}"#.utf8) try await subscribe(expecting: testJSON) await fulfillment(of: [onSubscribeInvoked], timeout: 0.05) @@ -117,7 +117,7 @@ class GraphQLSubscribeCombineTests: OperationTestBase { } func testDecodingError() async throws { - let testData = #"{"data": {"foo": true}, "errors": []}"# .data(using: .utf8)! + let testData = Data(#"{"data": {"foo": true}, "errors": []}"#.utf8) receivedCompletionFailure.isInverted = true receivedDataValueSuccess.isInverted = true @@ -134,7 +134,7 @@ class GraphQLSubscribeCombineTests: OperationTestBase { func testMultipleSuccessValues() async throws { let testJSON: JSONValue = ["foo": true] - let testData = #"{"data": {"foo": true}}"# .data(using: .utf8)! + let testData = Data(#"{"data": {"foo": true}}"#.utf8) receivedCompletionFailure.isInverted = true receivedDataValueError.isInverted = true receivedDataValueSuccess.expectedFulfillmentCount = 2 @@ -152,8 +152,8 @@ class GraphQLSubscribeCombineTests: OperationTestBase { } func testMixedSuccessAndErrorValues() async throws { - let successfulTestData = #"{"data": {"foo": true}}"# .data(using: .utf8)! - let invalidTestData = #"{"data": {"foo": true}, "errors": []}"# .data(using: .utf8)! + let successfulTestData = Data(#"{"data": {"foo": true}}"#.utf8) + let invalidTestData = Data(#"{"data": {"foo": true}, "errors": []}"#.utf8) receivedCompletionFailure.isInverted = true receivedDataValueSuccess.expectedFulfillmentCount = 2 diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/GraphQLSubscribeTaskTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/GraphQLSubscribeTaskTests.swift index b637a816f9..7568eff886 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/GraphQLSubscribeTaskTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/GraphQLSubscribeTaskTests.swift @@ -76,7 +76,7 @@ class GraphQLSubscribeTasksTests: OperationTestBase { receivedDataValueError.isInverted = true let testJSON: JSONValue = ["foo": true] - let testData = #"{"data": {"foo": true}}"# .data(using: .utf8)! + let testData = Data(#"{"data": {"foo": true}}"#.utf8) try await subscribe(expecting: testJSON) await fulfillment(of: [onSubscribeInvoked], timeout: 0.05) @@ -169,7 +169,7 @@ class GraphQLSubscribeTasksTests: OperationTestBase { } func testDecodingError() async throws { - let testData = #"{"data": {"foo": true}, "errors": []}"# .data(using: .utf8)! + let testData = Data(#"{"data": {"foo": true}, "errors": []}"#.utf8) receivedCompletionFailure.isInverted = true receivedDataValueSuccess.isInverted = true @@ -186,7 +186,7 @@ class GraphQLSubscribeTasksTests: OperationTestBase { func testMultipleSuccessValues() async throws { let testJSON: JSONValue = ["foo": true] - let testData = #"{"data": {"foo": true}}"# .data(using: .utf8)! + let testData = Data(#"{"data": {"foo": true}}"#.utf8) receivedCompletionFailure.isInverted = true receivedDataValueError.isInverted = true @@ -205,8 +205,8 @@ class GraphQLSubscribeTasksTests: OperationTestBase { } func testMixedSuccessAndErrorValues() async throws { - let successfulTestData = #"{"data": {"foo": true}}"# .data(using: .utf8)! - let invalidTestData = #"{"data": {"foo": true}, "errors": []}"# .data(using: .utf8)! + let successfulTestData = Data(#"{"data": {"foo": true}}"#.utf8) + let invalidTestData = Data(#"{"data": {"foo": true}, "errors": []}"#.utf8) receivedCompletionFailure.isInverted = true receivedDataValueSuccess.expectedFulfillmentCount = 2 diff --git a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/GraphQLSubscribeTests.swift b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/GraphQLSubscribeTests.swift index 5b5e70791e..5624f14c0b 100644 --- a/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/GraphQLSubscribeTests.swift +++ b/AmplifyPlugins/API/Tests/AWSAPIPluginTests/Operation/GraphQLSubscribeTests.swift @@ -64,7 +64,7 @@ class GraphQLSubscribeTests: OperationTestBase { /// - The completion handler is invoked with a normal termination func testHappyPath() throws { let testJSON: JSONValue = ["foo": true] - let testData = #"{"data": {"foo": true}}"# .data(using: .utf8)! + let testData = Data(#"{"data": {"foo": true}}"#.utf8) receivedCompletionFinish.shouldTrigger = true receivedCompletionFailure.shouldTrigger = false receivedConnected.shouldTrigger = true @@ -152,7 +152,7 @@ class GraphQLSubscribeTests: OperationTestBase { /// - The value handler is invoked with a disconnection message /// - The completion handler is invoked with a normal termination func testDecodingError() throws { - let testData = #"{"data": {"foo": true}, "errors": []}"# .data(using: .utf8)! + let testData = Data(#"{"data": {"foo": true}, "errors": []}"#.utf8) receivedCompletionFinish.shouldTrigger = true receivedCompletionFailure.shouldTrigger = false receivedConnected.shouldTrigger = true @@ -173,7 +173,7 @@ class GraphQLSubscribeTests: OperationTestBase { func testMultipleSuccessValues() throws { let testJSON: JSONValue = ["foo": true] - let testData = #"{"data": {"foo": true}}"# .data(using: .utf8)! + let testData = Data(#"{"data": {"foo": true}}"#.utf8) receivedCompletionFinish.shouldTrigger = true receivedCompletionFailure.shouldTrigger = false receivedConnected.shouldTrigger = true @@ -195,8 +195,8 @@ class GraphQLSubscribeTests: OperationTestBase { } func testMixedSuccessAndErrorValues() throws { - let successfulTestData = #"{"data": {"foo": true}}"# .data(using: .utf8)! - let invalidTestData = #"{"data": {"foo": true}, "errors": []}"# .data(using: .utf8)! + let successfulTestData = Data(#"{"data": {"foo": true}}"#.utf8) + let invalidTestData = Data(#"{"data": {"foo": true}, "errors": []}"#.utf8) receivedCompletionFinish.shouldTrigger = true receivedCompletionFailure.shouldTrigger = false receivedConnected.shouldTrigger = true diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ASF/CognitoUserPoolASF.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ASF/CognitoUserPoolASF.swift index 0ab6fb35a8..4d9568f270 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ASF/CognitoUserPoolASF.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/ASF/CognitoUserPoolASF.swift @@ -103,9 +103,7 @@ struct CognitoUserPoolASF: AdvancedSecurityBehavior { } let key = SymmetricKey(data: keyData) let content = "\(Self.asfVersion)\(contextJson)" - guard let data = content.data(using: .utf8) else { - throw ASFError.hashData - } + let data = Data(content.utf8) let hmac = HMAC.authenticationCode(for: data, using: key) let hmacData = Data(hmac) return hmacData.base64EncodedString() @@ -121,9 +119,7 @@ struct CognitoUserPoolASF: AdvancedSecurityBehavior { guard let jsonString = String(data: jsonData, encoding: .utf8) else { throw ASFError.stringConversion } - guard let data = jsonString.data(using: .utf8) else { - throw ASFError.dataConversion - } + let data = Data(jsonString.utf8) return data.base64EncodedString() } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/DeviceSRPAuth/VerifyDevicePasswordSRP+Calculations.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/DeviceSRPAuth/VerifyDevicePasswordSRP+Calculations.swift index 1a5e1f7b9d..59cf47a99f 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/DeviceSRPAuth/VerifyDevicePasswordSRP+Calculations.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/DeviceSRPAuth/VerifyDevicePasswordSRP+Calculations.swift @@ -86,10 +86,10 @@ extension VerifyDevicePasswordSRP { serviceSecretBlock: Data) -> Data { let key = SymmetricKey(data: authenticationKey) var hmac = HMAC.init(key: key) - hmac.update(data: deviceGroupKey.data(using: .utf8)!) - hmac.update(data: deviceKey.data(using: .utf8)!) + hmac.update(data: Data(deviceGroupKey.utf8)) + hmac.update(data: Data(deviceKey.utf8)) hmac.update(data: serviceSecretBlock) - hmac.update(data: srpTimeStamp.data(using: .utf8)!) + hmac.update(data: Data(srpTimeStamp.utf8)) return Data(hmac.finalize()) } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/VerifyPasswordSRP+Calculations.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/VerifyPasswordSRP+Calculations.swift index 0f4e83bfed..4d70f76521 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/VerifyPasswordSRP+Calculations.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Actions/SignIn/SRPAuth/VerifyPasswordSRP+Calculations.swift @@ -93,10 +93,10 @@ extension VerifyPasswordSRP { serviceSecretBlock: Data) -> Data { let key = SymmetricKey(data: authenticationKey) var hmac = HMAC.init(key: key) - hmac.update(data: poolName.data(using: .utf8)!) - hmac.update(data: srpUserName.data(using: .utf8)!) + hmac.update(data: Data(poolName.utf8)) + hmac.update(data: Data(srpUserName.utf8)) hmac.update(data: serviceSecretBlock) - hmac.update(data: srpTimeStamp.data(using: .utf8)!) + hmac.update(data: Data(srpTimeStamp.utf8)) return Data(hmac.finalize()) } } diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/RespondToAuthChallenge.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/RespondToAuthChallenge.swift index 02adc4211b..0ee7a963d3 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/RespondToAuthChallenge.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/StateMachine/CodeGen/Data/RespondToAuthChallenge.swift @@ -49,20 +49,15 @@ extension RespondToAuthChallenge { /// Helper method to extract MFA types from parameters private func getMFATypes(forKey key: String) -> Set { - var mfaTypes = Set() - guard let mfaTypeParametersData = parameters?[key]?.data(using: .utf8), + guard let mfaTypeParameters = parameters?[key], let mfaTypesArray = try? JSONDecoder().decode( - [String].self, from: mfaTypeParametersData) else { - return mfaTypes - } - - for mfaTypeValue in mfaTypesArray { - if let mfaType = MFAType(rawValue: String(mfaTypeValue)) { - mfaTypes.insert(mfaType) - } - } + [String].self, + from: Data(mfaTypeParameters.utf8) + ) + else { return .init() } - return mfaTypes + let mfaTypes = mfaTypesArray.compactMap(MFAType.init(rawValue:)) + return Set(mfaTypes) } var debugDictionary: [String: Any] { diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/ClientSecretHelper.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/ClientSecretHelper.swift index a470cf1677..341ac58617 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/ClientSecretHelper.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/Helpers/ClientSecretHelper.swift @@ -31,11 +31,11 @@ enum ClientSecretHelper { userPoolClientId: String, clientSecret: String ) -> String { - let clientSecretData = clientSecret.data(using: .utf8)! + let clientSecretData = Data(clientSecret.utf8) let clientSecretByteArray = [UInt8](clientSecretData) let key = SymmetricKey(data: clientSecretByteArray) - let clientData = (username + userPoolClientId).data(using: .utf8)! + let clientData = Data((username + userPoolClientId).utf8) let mac = HMAC.authenticationCode(for: clientData, using: key) let macBase64 = Data(mac).base64EncodedString() diff --git a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/HostedUI/HostedUIRequestHelper.swift b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/HostedUI/HostedUIRequestHelper.swift index e5d62eafd3..7e06e9ac77 100644 --- a/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/HostedUI/HostedUIRequestHelper.swift +++ b/AmplifyPlugins/Auth/Sources/AWSCognitoAuthPlugin/Support/HostedUI/HostedUIRequestHelper.swift @@ -115,7 +115,7 @@ struct HostedUIRequestHelper { var urlRequest = URLRequest(url: url) urlRequest.httpMethod = "POST" - urlRequest.httpBody = body.data(using: .utf8) + urlRequest.httpBody = Data(body.utf8) urlRequest.addHeaders(using: configuration) return urlRequest } @@ -145,7 +145,7 @@ struct HostedUIRequestHelper { var urlRequest = URLRequest(url: url) urlRequest.httpMethod = "POST" - urlRequest.httpBody = body.data(using: .utf8) + urlRequest.httpBody = Data(body.utf8) urlRequest.addHeaders(using: configuration) return urlRequest } @@ -159,11 +159,10 @@ struct HostedUIRequestHelper { private extension URLRequest { mutating func addHeaders(using configuration: HostedUIConfigurationData) { - guard let clientSecret = configuration.clientSecret, - let value = "\(configuration.clientId):\(clientSecret)".data(using: .utf8) else { + guard let clientSecret = configuration.clientSecret else { return } - + let value = Data("\(configuration.clientId):\(clientSecret)".utf8) setValue("Basic \(value.base64EncodedString())", forHTTPHeaderField: "Authorization") } } diff --git a/AmplifyPlugins/Auth/Sources/AmplifySRP/HKDF.swift b/AmplifyPlugins/Auth/Sources/AmplifySRP/HKDF.swift index 2071402a66..9db66655e2 100644 --- a/AmplifyPlugins/Auth/Sources/AmplifySRP/HKDF.swift +++ b/AmplifyPlugins/Auth/Sources/AmplifySRP/HKDF.swift @@ -23,7 +23,7 @@ public enum HMACKeyDerivationFunction { outputLength: outputLength) } else { let pseudoRandomKey = extractPseudoRandomKey(salt: salt, inputKeyMaterial: keyingMaterial) - return expand(pseudoRandomKey: pseudoRandomKey, info: info?.data(using: .utf8), outputLength: outputLength) + return expand(pseudoRandomKey: pseudoRandomKey, info: info.map { Data($0.utf8) }, outputLength: outputLength) } } @@ -34,11 +34,10 @@ public enum HMACKeyDerivationFunction { outputLength: Int) -> Data { let key = SymmetricKey(data: keyingMaterial) var hkdf: SymmetricKey - if let infoData = info?.data(using: .utf8) { + if let info { hkdf = HKDF.deriveKey(inputKeyMaterial: key, - salt: salt, info: infoData, + salt: salt, info: Data(info.utf8), outputByteCount: outputLength) - } else { hkdf = HKDF.deriveKey(inputKeyMaterial: key, salt: salt, diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/CredentialStore/MockCredentialStoreBehavior.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/CredentialStore/MockCredentialStoreBehavior.swift index 343516b07f..97b9201818 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/CredentialStore/MockCredentialStoreBehavior.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/CredentialStore/MockCredentialStoreBehavior.swift @@ -28,7 +28,7 @@ class MockKeychainStoreBehavior: KeychainStoreBehavior { } func _getData(_ key: String) throws -> Data { - return data.data(using: .utf8)! + return Data(data.utf8) } func _set(_ value: String, key: String) throws { } diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/InitiateAuthSRP/VerifyDevicePasswordSRPSignatureTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/InitiateAuthSRP/VerifyDevicePasswordSRPSignatureTests.swift index acc686e5dc..d33a7f05c0 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/InitiateAuthSRP/VerifyDevicePasswordSRPSignatureTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/ActionTests/InitiateAuthSRP/VerifyDevicePasswordSRPSignatureTests.swift @@ -119,7 +119,7 @@ class VerifyDevicePasswordSRPSignatureTests: XCTestCase { deviceKey: "deviceKey", deviceSecret: "deviceSecret", saltHex: "saltHex", - secretBlock: "secretBlock".data(using: .utf8) ?? Data(), + secretBlock: Data("secretBlock".utf8), serverPublicBHexString: "serverPublicBHexString", srpClient: srpClient ) @@ -136,7 +136,7 @@ private class MockSRPClientBehavior: SRPClientBehavior { return "UHexValue" } - static var authenticationKey: Result = .success("AuthenticationKey".data(using: .utf8)!) + static var authenticationKey: Result = .success(Data("AuthenticationKey".utf8)) static func generateAuthenticationKey( sharedSecretHexValue: String, uHexValue: String @@ -145,7 +145,7 @@ private class MockSRPClientBehavior: SRPClientBehavior { } static func reset() { - authenticationKey = .success("AuthenticationKey".data(using: .utf8)!) + authenticationKey = .success(Data("AuthenticationKey".utf8)) } func generateClientKeyPair() -> SRPKeys { diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/DefaultConfig.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/DefaultConfig.swift index 1c7505fbec..13e5a8781e 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/DefaultConfig.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/DefaultConfig.swift @@ -382,7 +382,7 @@ struct MockASF: AdvancedSecurityBehavior { extension AmplifyConfiguration { static func testData() -> AmplifyConfiguration { - return try! AmplifyConfiguration.decodeAmplifyConfiguration(from: json.data(using: .utf8)!) + return try! AmplifyConfiguration.decodeAmplifyConfiguration(from: Data(json.utf8)) } static let json: String = """ diff --git a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/HostedUIRequestHelperTests.swift b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/HostedUIRequestHelperTests.swift index d6d144b486..374a53371d 100644 --- a/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/HostedUIRequestHelperTests.swift +++ b/AmplifyPlugins/Auth/Tests/AWSCognitoAuthPluginUnitTests/Support/HostedUIRequestHelperTests.swift @@ -36,11 +36,10 @@ class HostedUIRequestHelperTests: XCTestCase { } private var encodedSecret: String? { - guard let clientSecret = configuration.clientSecret, - let value = "\(configuration.clientId):\(clientSecret)".data(using: .utf8) else { + guard let clientSecret = configuration.clientSecret else { return nil } - + let value = Data("\(configuration.clientId):\(clientSecret)".utf8) return value.base64EncodedString() } diff --git a/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/QueryPredicate+GraphQL.swift b/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/QueryPredicate+GraphQL.swift index bc6a302141..a8aca2529e 100644 --- a/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/QueryPredicate+GraphQL.swift +++ b/AmplifyPlugins/Core/AWSPluginsCore/Model/Support/QueryPredicate+GraphQL.swift @@ -58,8 +58,8 @@ public struct GraphQLFilterConverter { /// Deserialize the JSON string converted with `GraphQLFilterConverter.toJSON()` to `GraphQLFilter` public static func fromJSON(_ value: String) throws -> GraphQLFilter { - guard let data = value.data(using: .utf8), - let filter = try JSONSerialization.jsonObject(with: data) as? GraphQLFilter else { + let data = Data(value.utf8) + guard let filter = try JSONSerialization.jsonObject(with: data) as? GraphQLFilter else { return Fatal.preconditionFailure("Could not serialize to GraphQLFilter from: \(self))") } diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Sync/MutationSync/MutationSyncMetadataTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Sync/MutationSync/MutationSyncMetadataTests.swift index 1f77b4d5f0..fda07a1915 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Sync/MutationSync/MutationSyncMetadataTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Sync/MutationSync/MutationSyncMetadataTests.swift @@ -47,11 +47,7 @@ class MutationSyncMetadataTests: XCTestCase { func testDecodeMutationSync() { do { let decoder = JSONDecoder(dateDecodingStrategy: ModelDateFormatting.decodingStrategy) - - guard let data = postSyncJSON.data(using: .utf8) else { - XCTFail("JSON could not be converted into data") - return - } + let data = Data(postSyncJSON.utf8) let mutationSync = try decoder.decode(MutationSync.self, from: data) let model = mutationSync.model XCTAssertEqual(model.id, "post-id") @@ -75,11 +71,7 @@ class MutationSyncMetadataTests: XCTestCase { func testDecodeAnyModelMutationSync() { do { let decoder = JSONDecoder(dateDecodingStrategy: ModelDateFormatting.decodingStrategy) - - guard let data = postSyncJSON.data(using: .utf8) else { - XCTFail("JSON could not be converted into data") - return - } + let data = Data(postSyncJSON.utf8) let mutationSync = try decoder.decode(MutationSync.self, from: data) let model = mutationSync.model XCTAssertEqual(model.id, "post-id") diff --git a/AmplifyPlugins/Core/AWSPluginsCoreTests/Sync/PaginatedListTests.swift b/AmplifyPlugins/Core/AWSPluginsCoreTests/Sync/PaginatedListTests.swift index 8f3386d52f..58fe5ee517 100644 --- a/AmplifyPlugins/Core/AWSPluginsCoreTests/Sync/PaginatedListTests.swift +++ b/AmplifyPlugins/Core/AWSPluginsCoreTests/Sync/PaginatedListTests.swift @@ -63,11 +63,7 @@ class PaginatedListTests: XCTestCase { func testDecodePaginatedList() { do { let decoder = JSONDecoder(dateDecodingStrategy: ModelDateFormatting.decodingStrategy) - - guard let data = syncQueryJSON.data(using: .utf8) else { - XCTFail("JSON could not be converted into data") - return - } + let data = Data(syncQueryJSON.utf8) let paginatedList = try decoder.decode(PaginatedList.self, from: data) XCTAssertNotNil(paginatedList) XCTAssertNotNil(paginatedList.startedAt) @@ -85,11 +81,7 @@ class PaginatedListTests: XCTestCase { func testDecodePaginatedListFromEmptyItems() { do { let decoder = JSONDecoder(dateDecodingStrategy: ModelDateFormatting.decodingStrategy) - - guard let data = emptyItemsSyncQueryJSON.data(using: .utf8) else { - XCTFail("JSON could not be converted into data") - return - } + let data = Data(emptyItemsSyncQueryJSON.utf8) let paginatedList = try decoder.decode(PaginatedList.self, from: data) XCTAssertNotNil(paginatedList) XCTAssertNotNil(paginatedList.startedAt) diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/ProcessMutationErrorFromCloudOperationTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/ProcessMutationErrorFromCloudOperationTests.swift index 6ba1d9d3ad..2163442dca 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/ProcessMutationErrorFromCloudOperationTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Sync/MutationQueue/ProcessMutationErrorFromCloudOperationTests.swift @@ -1220,9 +1220,7 @@ extension ProcessMutationErrorFromCloudOperationTests { version: Int = 1, errorType: AppSyncErrorType? = .conflictUnhandled) throws -> GraphQLResponseError>? { - guard let data = try post.toJSON().data(using: .utf8) else { - return nil - } + let data = Data(try post.toJSON().utf8) let decoder = JSONDecoder() decoder.dateDecodingStrategy = ModelDateFormatting.decodingStrategy let remoteData = try decoder.decode(JSONValue.self, from: data) diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Comment3Wrapper.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Comment3Wrapper.swift index 28c2c3bac8..c680e500ed 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Comment3Wrapper.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Comment3Wrapper.swift @@ -35,7 +35,7 @@ class Comment3Wrapper: NSCopying { } init(json: String) throws { - let data = json.data(using: .utf8)! + let data = Data(json.utf8) let map = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any] self.model = FlutterSerializedModel(id: map!["id"] as! String, map: try FlutterDataStoreRequestUtils.getJSONValue(map!)) } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Comment4Wrapper.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Comment4Wrapper.swift index 62c20b5483..ca57fcb2cc 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Comment4Wrapper.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Comment4Wrapper.swift @@ -26,7 +26,7 @@ class Comment4Wrapper: NSCopying { } init(json: String) throws { - let data = json.data(using: .utf8)! + let data = Data(json.utf8) let map = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any] self.model = FlutterSerializedModel(id: map!["id"] as! String, map: try FlutterDataStoreRequestUtils.getJSONValue(map!)) } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Post3Wrapper.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Post3Wrapper.swift index 799f7aba0b..ad8b6e3c96 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Post3Wrapper.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Post3Wrapper.swift @@ -38,7 +38,7 @@ class Post3Wrapper: NSCopying { } init(json: String) throws { - let data = json.data(using: .utf8)! + let data = Data(json.utf8) let map = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any] self.model = FlutterSerializedModel(id: map!["id"] as! String, map: try FlutterDataStoreRequestUtils.getJSONValue(map!)) } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Post4Wrapper.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Post4Wrapper.swift index d97b8c43f9..a9ae659d5c 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Post4Wrapper.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Post4Wrapper.swift @@ -39,7 +39,7 @@ class Post4Wrapper: NSCopying { } init(json: String) throws { - let data = json.data(using: .utf8)! + let data = Data(json.utf8) let map = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any] self.model = FlutterSerializedModel(id: map!["id"] as! String, map: try FlutterDataStoreRequestUtils.getJSONValue(map!)) } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Post5Wrapper.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Post5Wrapper.swift index 8a3548938c..44b3d51016 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Post5Wrapper.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Post5Wrapper.swift @@ -29,7 +29,7 @@ class Post5Wrapper: NSCopying { } init(json: String) throws { - let data = json.data(using: .utf8)! + let data = Data(json.utf8) let map = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any] self.model = FlutterSerializedModel(id: map!["id"] as! String, map: try FlutterDataStoreRequestUtils.getJSONValue(map!)) } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Post6Wrapper.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Post6Wrapper.swift index b5c6ea4ce7..1a9951d7fe 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Post6Wrapper.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/Post6Wrapper.swift @@ -30,7 +30,7 @@ class Post6Wrapper: NSCopying { } init(json: String) throws { - let data = json.data(using: .utf8)! + let data = Data(json.utf8) let map = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any] self.model = FlutterSerializedModel(id: map!["id"] as! String, map: try FlutterDataStoreRequestUtils.getJSONValue(map!)) } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/PostWrapper.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/PostWrapper.swift index a6d637242b..b2a447858f 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/PostWrapper.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/SerializedModelWrappers/PostWrapper.swift @@ -32,7 +32,7 @@ class PostWrapper: NSCopying { } init(json: String) throws { - let data = json.data(using: .utf8)! + let data = Data(json.utf8) let map = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any] self.model = FlutterSerializedModel(id: map!["id"] as! String, map: try FlutterDataStoreRequestUtils.getJSONValue(map!)) } diff --git a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/TestFlutterModelRegistration.swift b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/TestFlutterModelRegistration.swift index 1b9cdb5820..3ca55b63cf 100644 --- a/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/TestFlutterModelRegistration.swift +++ b/AmplifyPlugins/DataStore/Tests/DataStoreHostApp/AWSDataStorePluginFlutterTests/TestSupport/TestFlutterModelRegistration.swift @@ -17,7 +17,7 @@ struct TestFlutterModelRegistration: AmplifyModelRegistration { resolvedDecoder = JSONDecoder(dateDecodingStrategy: ModelDateFormatting.decodingStrategy) } // Convert jsonstring to object - let data = jsonString.data(using: .utf8)! + let data = Data(jsonString.utf8) let jsonValue = try resolvedDecoder.decode(JSONValue.self, from: data) if case .array(let jsonArray) = jsonValue, case .object(let jsonObj) = jsonArray[0], diff --git a/AmplifyPlugins/Internal/Tests/InternalAWSPinpointUnitTests/AwsPinpointAnalyticsKeychainMigrationTests.swift b/AmplifyPlugins/Internal/Tests/InternalAWSPinpointUnitTests/AwsPinpointAnalyticsKeychainMigrationTests.swift index afc60273ba..8eba2b8a4d 100644 --- a/AmplifyPlugins/Internal/Tests/InternalAWSPinpointUnitTests/AwsPinpointAnalyticsKeychainMigrationTests.swift +++ b/AmplifyPlugins/Internal/Tests/InternalAWSPinpointUnitTests/AwsPinpointAnalyticsKeychainMigrationTests.swift @@ -33,7 +33,7 @@ class AWSPinpointAnalyticsKeyValueStoreTests: XCTestCase { func testDeviceTokenMigrateFromUserDefaultsToKeychain() { let deviceToken = "000102030405060708090a0b0c0d0e0f" - let deviceTokenData = deviceToken.data(using: .utf8) + let deviceTokenData = Data(deviceToken.utf8) userDefaults.setValue(deviceTokenData, forKey: EndpointClient.Constants.deviceTokenKey) var currentKeychainDeviceToken = try? self.keychain._getData(EndpointClient.Constants.deviceTokenKey) diff --git a/AmplifyPlugins/Internal/Tests/InternalAWSPinpointUnitTests/EndpointClientTests.swift b/AmplifyPlugins/Internal/Tests/InternalAWSPinpointUnitTests/EndpointClientTests.swift index a4b5798dac..5931cc7154 100644 --- a/AmplifyPlugins/Internal/Tests/InternalAWSPinpointUnitTests/EndpointClientTests.swift +++ b/AmplifyPlugins/Internal/Tests/InternalAWSPinpointUnitTests/EndpointClientTests.swift @@ -56,10 +56,10 @@ class EndpointClientTests: XCTestCase { endpointId: "oldEndpoint", deviceToken: "oldToken", demographic: oldDemographic) - let newToken = "newToken".data(using: .utf8) + let newToken = Data("newToken".utf8) do { try keychain._set(Data(), key: EndpointClient.Constants.endpointProfileKey) - try keychain._set(newToken!, key: EndpointClient.Constants.deviceTokenKey) + try keychain._set(newToken, key: EndpointClient.Constants.deviceTokenKey) } catch { XCTFail("Fail to setup test data") } @@ -78,7 +78,7 @@ class EndpointClientTests: XCTestCase { XCTAssertTrue(endpointProfile === storedEndpointProfile, "Expected stored PinpointEndpointProfile object") XCTAssertEqual(endpointProfile.applicationId, currentApplicationId) XCTAssertEqual(endpointProfile.endpointId, currentEndpointId) - XCTAssertEqual(endpointProfile.deviceToken, newToken?.asHexString()) + XCTAssertEqual(endpointProfile.deviceToken, newToken.asHexString()) XCTAssertNotEqual(endpointProfile.demographic, oldDemographic) XCTAssertEqual(endpointProfile.demographic.appVersion, endpointInformation.appVersion) XCTAssertEqual(endpointProfile.demographic.make, "apple") @@ -198,9 +198,9 @@ class EndpointClientTests: XCTestCase { @discardableResult private func storeToken(_ deviceToken: String) -> Data? { - let newToken = Data(hexString: deviceToken) ?? deviceToken.data(using: .utf8) + let newToken = Data(hexString: deviceToken) ?? Data(deviceToken.utf8) do { - try keychain._set(newToken!, key: EndpointClient.Constants.deviceTokenKey) + try keychain._set(newToken, key: EndpointClient.Constants.deviceTokenKey) } catch { XCTFail("Fail to setup test data") } diff --git a/AmplifyPlugins/Logging/Sources/AWSCloudWatchLoggingPlugin/AWSCloudWatchLoggingSession.swift b/AmplifyPlugins/Logging/Sources/AWSCloudWatchLoggingPlugin/AWSCloudWatchLoggingSession.swift index f9970c67aa..cccc6ba408 100644 --- a/AmplifyPlugins/Logging/Sources/AWSCloudWatchLoggingPlugin/AWSCloudWatchLoggingSession.swift +++ b/AmplifyPlugins/Logging/Sources/AWSCloudWatchLoggingPlugin/AWSCloudWatchLoggingSession.swift @@ -68,10 +68,7 @@ final class AWSCloudWatchLoggingSession { return "guest" } - guard let userIdentifierData = userIdentifier.data(using: .utf8) else { - throw AWSCloudWatchLoggingError.sessionInternalErrorForUserId - } - + let userIdentifierData = Data(userIdentifier.utf8) var hash = SHA256() hash.update(data: userIdentifierData) diff --git a/AmplifyPlugins/Logging/Sources/AWSCloudWatchLoggingPlugin/Persistence/LogEntryCodec.swift b/AmplifyPlugins/Logging/Sources/AWSCloudWatchLoggingPlugin/Persistence/LogEntryCodec.swift index 253979b5f3..43f0349848 100644 --- a/AmplifyPlugins/Logging/Sources/AWSCloudWatchLoggingPlugin/Persistence/LogEntryCodec.swift +++ b/AmplifyPlugins/Logging/Sources/AWSCloudWatchLoggingPlugin/Persistence/LogEntryCodec.swift @@ -35,9 +35,7 @@ struct LogEntryCodec { func decode(string: String) throws -> LogEntry? { let trimmed = string.trim() - guard let data = trimmed.data(using: .utf8) else { - throw DecodingError.stringNotUtf8(string) - } + let data = Data(trimmed.utf8) return try decode(data: data) } diff --git a/AmplifyPlugins/Logging/Tests/AWSCloudWatchLoggingPluginTests/LogEntryTests.swift b/AmplifyPlugins/Logging/Tests/AWSCloudWatchLoggingPluginTests/LogEntryTests.swift index ab1fa97d84..9438899a7e 100644 --- a/AmplifyPlugins/Logging/Tests/AWSCloudWatchLoggingPluginTests/LogEntryTests.swift +++ b/AmplifyPlugins/Logging/Tests/AWSCloudWatchLoggingPluginTests/LogEntryTests.swift @@ -63,7 +63,7 @@ final class LogEntryTests: XCTestCase { "message": "\(message)" } """ - let encoded = try XCTUnwrap(json.data(using: .utf8)) + let encoded = Data(json.utf8) let decoder = JSONDecoder() decoder.dateDecodingStrategy = .millisecondsSince1970 let decoded = try decoder.decode(LogEntry.self, from: encoded) diff --git a/AmplifyPlugins/Notifications/Push/Tests/AWSPinpointPushNotificationsPluginUnitTests/AWSPinpointPushNotificationsPluginClientBehaviourTests.swift b/AmplifyPlugins/Notifications/Push/Tests/AWSPinpointPushNotificationsPluginUnitTests/AWSPinpointPushNotificationsPluginClientBehaviourTests.swift index f7ed2622d3..c1b57e7396 100644 --- a/AmplifyPlugins/Notifications/Push/Tests/AWSPinpointPushNotificationsPluginUnitTests/AWSPinpointPushNotificationsPluginClientBehaviourTests.swift +++ b/AmplifyPlugins/Notifications/Push/Tests/AWSPinpointPushNotificationsPluginUnitTests/AWSPinpointPushNotificationsPluginClientBehaviourTests.swift @@ -135,7 +135,7 @@ class AWSPinpointPushNotificationsPluginClientBehaviourTests: AWSPinpointPushNot // MARK: - Register Device tests func testRegisterDevice_shouldUpdateDeviceToken() async throws { - let apnsToken = "apnsToken".data(using: .utf8)! + let apnsToken = Data("apnsToken".utf8) try await plugin.registerDevice(apnsToken: apnsToken) XCTAssertEqual(mockPinpoint.currentEndpointProfileCount, 1) diff --git a/AmplifyPlugins/Predictions/Tests/AWSPredictionsPluginUnitTests/ConfigurationTests/PredictionsPluginConfigurationTests.swift b/AmplifyPlugins/Predictions/Tests/AWSPredictionsPluginUnitTests/ConfigurationTests/PredictionsPluginConfigurationTests.swift index 92cdb35a4f..d8522f23ac 100644 --- a/AmplifyPlugins/Predictions/Tests/AWSPredictionsPluginUnitTests/ConfigurationTests/PredictionsPluginConfigurationTests.swift +++ b/AmplifyPlugins/Predictions/Tests/AWSPredictionsPluginUnitTests/ConfigurationTests/PredictionsPluginConfigurationTests.swift @@ -20,7 +20,7 @@ class PredictionsPluginConfigurationTests: XCTestCase { /// - I should get a valid configuration object /// func testConfiguration() { - let inputJsonData = """ + let inputJsonData = Data(""" { "defaultRegion": "us-west-2", "convert": { @@ -65,7 +65,7 @@ class PredictionsPluginConfigurationTests: XCTestCase { } } } - """.data(using: .utf8)! + """.utf8) do { let configuration = try JSONDecoder().decode(PredictionsPluginConfiguration.self, from: inputJsonData) XCTAssertNotNil(configuration, "Configuration should not be nil") @@ -89,7 +89,7 @@ class PredictionsPluginConfigurationTests: XCTestCase { /// - I should get a valid configuration object /// func testConfigurationWithOnlyConvert() { - let inputJsonData = """ + let inputJsonData = Data(""" { "defaultRegion": "us-west-2", "convert": { @@ -109,7 +109,7 @@ class PredictionsPluginConfigurationTests: XCTestCase { } } } - """.data(using: .utf8)! + """.utf8) do { let configuration = try JSONDecoder().decode(PredictionsPluginConfiguration.self, from: inputJsonData) XCTAssertNotNil(configuration, "Configuration should not be nil") @@ -127,7 +127,7 @@ class PredictionsPluginConfigurationTests: XCTestCase { /// - I should get an error /// func testNoRegionUnderSubsection() { - let inputJsonData = """ + let inputJsonData = Data(""" { "defaultRegion": "us-west-2", "convert": { @@ -137,7 +137,7 @@ class PredictionsPluginConfigurationTests: XCTestCase { } } } - """.data(using: .utf8)! + """.utf8) do { _ = try JSONDecoder().decode(PredictionsPluginConfiguration.self, from: inputJsonData) XCTFail("Should throw an error because region is not present") @@ -155,11 +155,11 @@ class PredictionsPluginConfigurationTests: XCTestCase { /// - I should get a valid configuration object /// func testConfigurationWithNoSubsections() { - let inputJsonData = """ + let inputJsonData = Data(""" { "defaultRegion": "us-west-2" } - """.data(using: .utf8)! + """.utf8) do { let configuration = try JSONDecoder().decode(PredictionsPluginConfiguration.self, from: inputJsonData) XCTAssertNotNil(configuration, "Configuration should not be nil") diff --git a/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/AWSS3StoragePluginAsyncBehaviorTests.swift b/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/AWSS3StoragePluginAsyncBehaviorTests.swift index 83a5121764..001883ce09 100644 --- a/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/AWSS3StoragePluginAsyncBehaviorTests.swift +++ b/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/AWSS3StoragePluginAsyncBehaviorTests.swift @@ -48,7 +48,7 @@ class AWSS3StoragePluginAsyncBehaviorTests: XCTestCase { } func testPluginDownloadDataAsync() async throws { - let input = "AWS".data(using: .utf8)! + let input = Data("AWS".utf8) storageService.storageServiceDownloadEvents = [.completed(input)] let task = storagePlugin.downloadData(key: testKey, options: nil) diff --git a/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Operation/AWSS3StoragePutDataOperationTests.swift b/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Operation/AWSS3StoragePutDataOperationTests.swift index 2abd07f580..c93b6975f3 100644 --- a/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Operation/AWSS3StoragePutDataOperationTests.swift +++ b/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Operation/AWSS3StoragePutDataOperationTests.swift @@ -177,7 +177,7 @@ class AWSS3StorageUploadDataOperationTests: AWSS3StorageOperationTestBase { for _ in 1 ... 20 { testLargeDataString += testLargeDataString } - let testLargeData = testLargeDataString.data(using: .utf8)! + let testLargeData = Data(testLargeDataString.utf8) XCTAssertTrue(testLargeData.count > StorageUploadDataRequest.Options.multiPartUploadSizeThreshold, "Could not create data object greater than MultiPartUploadSizeThreshold") let expectedUploadSource = UploadSource.data(testLargeData) diff --git a/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Service/Storage/AWSS3StorageServiceTests.swift b/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Service/Storage/AWSS3StorageServiceTests.swift index 25f5410d4a..7555e75ad1 100644 --- a/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Service/Storage/AWSS3StorageServiceTests.swift +++ b/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Service/Storage/AWSS3StorageServiceTests.swift @@ -338,7 +338,7 @@ class AWSS3StorageServiceTests: XCTestCase { /// When: upload is invoked /// Then: A .failed event is dispatched with an .unknown error func testUpload_withoutPreSignedURL_shouldSendFailEvent() { - let data = "someData".data(using: .utf8)! + let data = Data("someData".utf8) let expectation = self.expectation(description: "Upload") service.upload( serviceKey: "key", @@ -364,7 +364,7 @@ class AWSS3StorageServiceTests: XCTestCase { /// When: upload is invoked /// Then: An .initiated event is dispatched func testUpload_withPreSignedURL_shouldSendInitiatedEvent() { - let data = "someData".data(using: .utf8)! + let data = Data("someData".utf8) let expectation = self.expectation(description: "Upload") service.preSignedURLBuilder = MockAWSS3PreSignedURLBuilder() service.upload( diff --git a/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Support/Internal/FileHandleTests.swift b/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Support/Internal/FileHandleTests.swift index 8d12cca7af..f623af2a51 100644 --- a/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Support/Internal/FileHandleTests.swift +++ b/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Support/Internal/FileHandleTests.swift @@ -15,7 +15,7 @@ class FileHandleTests: XCTestCase { /// Then: Only `bytesReadLimit` bytes will be read at a time, but all `bytes` will be read and returned func testRead_withBytesHigherThanLimit_shouldSucceedByReadingMultipleTimes() throws { let sourceString = "012345678910" // 11 bytes - let sourceData = sourceString.data(using: .utf8)! + let sourceData = Data(sourceString.utf8) let sourceFile = try createFile(from: sourceData) XCTAssertEqual(try StorageRequestUtils.getSize(sourceFile), UInt64(sourceString.count)) diff --git a/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Support/Internal/FileSystemTests.swift b/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Support/Internal/FileSystemTests.swift index 7c573bd843..af1ea79b90 100644 --- a/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Support/Internal/FileSystemTests.swift +++ b/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Support/Internal/FileSystemTests.swift @@ -166,10 +166,7 @@ class FileSystemTests: XCTestCase { let fs = FileSystem() - guard let data = string.data(using: .utf8) else { - XCTFail("Failed to create data for file") - return - } + let data = Data(string.utf8) let fileURL = try fs.createTemporaryFile(data: data) defer { fs.removeFileIfExists(fileURL: fileURL) diff --git a/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Support/Internal/StorageMultipartUploadSessionTests.swift b/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Support/Internal/StorageMultipartUploadSessionTests.swift index 1ae2882915..f51f974e34 100644 --- a/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Support/Internal/StorageMultipartUploadSessionTests.swift +++ b/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Support/Internal/StorageMultipartUploadSessionTests.swift @@ -332,11 +332,7 @@ class StorageMultipartUploadSessionTests: XCTestCase { ] let string = parts.joined() - guard let data = string.data(using: .utf8) else { - XCTFail("Failed to create data for file") - throw Failure.unableToCreateData - } - + let data = Data(string.utf8) let fileURL = try FileSystem.default.createTemporaryFile(data: data) return fileURL } diff --git a/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Support/Internal/StorageTransferTaskTests.swift b/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Support/Internal/StorageTransferTaskTests.swift index c9b96aea8d..0f47e20249 100644 --- a/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Support/Internal/StorageTransferTaskTests.swift +++ b/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Support/Internal/StorageTransferTaskTests.swift @@ -448,8 +448,8 @@ class StorageTransferTaskTests: XCTestCase { sessionTask: nil, proxyStorageTask: nil ) - task.responseData = "Test".data(using: .utf8) - + task.responseData = Data("Test".utf8) + XCTAssertEqual(task.responseText, "Test") } diff --git a/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Support/Utils/StorageRequestUtilsGetterTests.swift b/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Support/Utils/StorageRequestUtilsGetterTests.swift index 295ffbd3f0..4e0e7c3122 100644 --- a/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Support/Utils/StorageRequestUtilsGetterTests.swift +++ b/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Support/Utils/StorageRequestUtilsGetterTests.swift @@ -73,7 +73,7 @@ class StorageRequestUtilsGetterTests: XCTestCase { let key = "testGetSizeForFileUploadSourceReturnsSize" let filePath = NSTemporaryDirectory() + key + ".tmp" let fileURL = URL(fileURLWithPath: filePath) - FileManager.default.createFile(atPath: filePath, contents: key.data(using: .utf8), attributes: nil) + FileManager.default.createFile(atPath: filePath, contents: Data(key.utf8), attributes: nil) let result = try StorageRequestUtils.getSize(fileURL) XCTAssertNotNil(result) } diff --git a/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Support/Utils/StorageRequestUtilsValidatorTests.swift b/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Support/Utils/StorageRequestUtilsValidatorTests.swift index f69a56dbf1..b72f197724 100644 --- a/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Support/Utils/StorageRequestUtilsValidatorTests.swift +++ b/AmplifyPlugins/Storage/Tests/AWSS3StoragePluginTests/Support/Utils/StorageRequestUtilsValidatorTests.swift @@ -111,7 +111,7 @@ class StorageRequestUtilsValidatorTests: XCTestCase { let key = "testValidateFileExistsForUrlSuccess" let filePath = NSTemporaryDirectory() + key + ".tmp" let fileURL = URL(fileURLWithPath: filePath) - FileManager.default.createFile(atPath: filePath, contents: key.data(using: .utf8), attributes: nil) + FileManager.default.createFile(atPath: filePath, contents: Data(key.utf8), attributes: nil) let result = StorageRequestUtils.validateFileExists(fileURL) XCTAssertNil(result) diff --git a/AmplifyPlugins/Storage/Tests/StorageHostApp/AWSS3StoragePluginIntegrationTests/AWSS3StoragePluginAccelerateIntegrationTests.swift b/AmplifyPlugins/Storage/Tests/StorageHostApp/AWSS3StoragePluginIntegrationTests/AWSS3StoragePluginAccelerateIntegrationTests.swift index 45087632de..937a239daf 100644 --- a/AmplifyPlugins/Storage/Tests/StorageHostApp/AWSS3StoragePluginIntegrationTests/AWSS3StoragePluginAccelerateIntegrationTests.swift +++ b/AmplifyPlugins/Storage/Tests/StorageHostApp/AWSS3StoragePluginIntegrationTests/AWSS3StoragePluginAccelerateIntegrationTests.swift @@ -21,7 +21,7 @@ class AWSS3StoragePluginAccelerateIntegrationTests: AWSS3StoragePluginTestBase { /// Then: The operation completes successfully. func testUploadDataWithAccelerateDisabledExplicitly() async throws { let key = UUID().uuidString - let data = try XCTUnwrap(key.data(using: .utf8)) + let data = Data(key.utf8) let task = Amplify.Storage.uploadData(key: key, data: data, options: .init(pluginOptions:["useAccelerateEndpoint": useAccelerateEndpoint])) @@ -34,7 +34,7 @@ class AWSS3StoragePluginAccelerateIntegrationTests: AWSS3StoragePluginTestBase { /// Then: The operation fails. func testUploadDataWithAccelerateDisabledExplicitlyToWrongType() async throws { let key = UUID().uuidString - let data = try XCTUnwrap(key.data(using: .utf8)) + let data = Data(key.utf8) do { let task = Amplify.Storage.uploadData(key: key, data: data, @@ -55,7 +55,7 @@ class AWSS3StoragePluginAccelerateIntegrationTests: AWSS3StoragePluginTestBase { let filePath = NSTemporaryDirectory() + key + ".tmp" let fileURL = URL(fileURLWithPath: filePath) - FileManager.default.createFile(atPath: filePath, contents: key.data(using: .utf8), attributes: nil) + FileManager.default.createFile(atPath: filePath, contents: Data(key.utf8), attributes: nil) defer { try? FileManager.default.removeItem(at: fileURL) } @@ -84,7 +84,7 @@ class AWSS3StoragePluginAccelerateIntegrationTests: AWSS3StoragePluginTestBase { /// Then: The operation completes successfully with the data retrieved. func testDownloadDataToMemory() async throws { let key = UUID().uuidString - let data = try XCTUnwrap(key.data(using: .utf8)) + let data = Data(key.utf8) let uploadTask = Amplify.Storage.uploadData(key: key, data: data, options: .init(pluginOptions:["useAccelerateEndpoint": useAccelerateEndpoint])) diff --git a/AmplifyPlugins/Storage/Tests/StorageHostApp/AWSS3StoragePluginIntegrationTests/AWSS3StoragePluginAccessLevelTests.swift b/AmplifyPlugins/Storage/Tests/StorageHostApp/AWSS3StoragePluginIntegrationTests/AWSS3StoragePluginAccessLevelTests.swift index 276d1e8633..ba6f883e4b 100644 --- a/AmplifyPlugins/Storage/Tests/StorageHostApp/AWSS3StoragePluginIntegrationTests/AWSS3StoragePluginAccessLevelTests.swift +++ b/AmplifyPlugins/Storage/Tests/StorageHostApp/AWSS3StoragePluginIntegrationTests/AWSS3StoragePluginAccessLevelTests.swift @@ -66,11 +66,7 @@ class AWSS3StoragePluginAccessLevelTests: AWSS3StoragePluginTestBase { } let key = UUID().uuidString - guard let dataInput = UUID().uuidString.data(using: .utf8) else { - XCTFail("Failed to create test data") - return - } - + let dataInput = Data(UUID().uuidString.utf8) do { logger.debug("Upload [\(accessLevel)]") let uploadDataOptions = StorageUploadDataRequest.Options(accessLevel: accessLevel) @@ -122,10 +118,7 @@ class AWSS3StoragePluginAccessLevelTests: AWSS3StoragePluginTestBase { logger.debug("Testing storage access level: \(accessLevel)") let key = UUID().uuidString - guard let dataInput = UUID().uuidString.data(using: .utf8) else { - XCTFail("Failed to create test data") - return - } + let dataInput = Data(UUID().uuidString.utf8) logger.debug("Upload [\(accessLevel)]") let uploadDataOptions = StorageUploadDataRequest.Options(accessLevel: accessLevel) let uploadKey = try await Amplify.Storage.uploadData(key: key, data: dataInput, options: uploadDataOptions).value @@ -190,7 +183,7 @@ class AWSS3StoragePluginAccessLevelTests: AWSS3StoragePluginTestBase { logger.debug("Uploading as user1 with \(testRun.accessLevel) access level") let options = StorageUploadDataRequest.Options(accessLevel: testRun.accessLevel) - _ = try await Amplify.Storage.uploadData(key: testRun.key, data: testRun.key.data(using: .utf8)!, options: options).value + _ = try await Amplify.Storage.uploadData(key: testRun.key, data: Data(testRun.key.utf8), options: options).value logger.debug("Getting list as user1") let listOptions1 = StorageListRequest.Options(accessLevel: testRun.accessLevel, diff --git a/AmplifyPlugins/Storage/Tests/StorageHostApp/AWSS3StoragePluginIntegrationTests/AWSS3StoragePluginBasicIntegrationTests.swift b/AmplifyPlugins/Storage/Tests/StorageHostApp/AWSS3StoragePluginIntegrationTests/AWSS3StoragePluginBasicIntegrationTests.swift index 6a2a1ad007..8aadc25de6 100644 --- a/AmplifyPlugins/Storage/Tests/StorageHostApp/AWSS3StoragePluginIntegrationTests/AWSS3StoragePluginBasicIntegrationTests.swift +++ b/AmplifyPlugins/Storage/Tests/StorageHostApp/AWSS3StoragePluginIntegrationTests/AWSS3StoragePluginBasicIntegrationTests.swift @@ -61,7 +61,7 @@ class AWSS3StoragePluginBasicIntegrationTests: AWSS3StoragePluginTestBase { /// Then: The operation completes successfully func testUploadData() async throws { let key = UUID().uuidString - let data = key.data(using: .utf8)! + let data = Data(key.utf8) _ = try await Amplify.Storage.uploadData(key: key, data: data, options: nil).value _ = try await Amplify.Storage.remove(key: key) @@ -79,7 +79,7 @@ class AWSS3StoragePluginBasicIntegrationTests: AWSS3StoragePluginTestBase { /// Then: The operation completes successfully func testUploadEmptyData() async throws { let key = UUID().uuidString - let data = "".data(using: .utf8)! + let data = Data("".utf8) _ = try await Amplify.Storage.uploadData(key: key, data: data, options: nil).value _ = try await Amplify.Storage.remove(key: key) @@ -95,7 +95,7 @@ class AWSS3StoragePluginBasicIntegrationTests: AWSS3StoragePluginTestBase { let filePath = NSTemporaryDirectory() + key + ".tmp" let fileURL = URL(fileURLWithPath: filePath) - FileManager.default.createFile(atPath: filePath, contents: key.data(using: .utf8), attributes: nil) + FileManager.default.createFile(atPath: filePath, contents: Data(key.utf8), attributes: nil) _ = try await Amplify.Storage.uploadFile(key: key, local: fileURL, options: nil).value _ = try await Amplify.Storage.remove(key: key) @@ -115,7 +115,7 @@ class AWSS3StoragePluginBasicIntegrationTests: AWSS3StoragePluginTestBase { let key = UUID().uuidString let filePath = NSTemporaryDirectory() + key + ".tmp" let fileURL = URL(fileURLWithPath: filePath) - FileManager.default.createFile(atPath: filePath, contents: "".data(using: .utf8), attributes: nil) + FileManager.default.createFile(atPath: filePath, contents: Data("".utf8), attributes: nil) _ = try await Amplify.Storage.uploadFile(key: key, local: fileURL, options: nil).value _ = try await Amplify.Storage.remove(key: key) @@ -173,7 +173,7 @@ class AWSS3StoragePluginBasicIntegrationTests: AWSS3StoragePluginTestBase { /// Then: The operation completes successfully with the data retrieved func testDownloadDataToMemory() async throws { let key = UUID().uuidString - try await uploadData(key: key, data: key.data(using: .utf8)!) + try await uploadData(key: key, data: Data(key.utf8)) _ = try await Amplify.Storage.downloadData(key: key, options: .init()).value _ = try await Amplify.Storage.remove(key: key) } @@ -184,7 +184,7 @@ class AWSS3StoragePluginBasicIntegrationTests: AWSS3StoragePluginTestBase { func testDownloadFile() async throws { let key = UUID().uuidString let timestamp = String(Date().timeIntervalSince1970) - let timestampData = timestamp.data(using: .utf8)! + let timestampData = Data(timestamp.utf8) try await uploadData(key: key, data: timestampData) let filePath = NSTemporaryDirectory() + key + ".tmp" let fileURL = URL(fileURLWithPath: filePath) diff --git a/AmplifyPlugins/Storage/Tests/StorageHostApp/AWSS3StoragePluginIntegrationTests/AWSS3StoragePluginPrefixKeyResolverTests.swift b/AmplifyPlugins/Storage/Tests/StorageHostApp/AWSS3StoragePluginIntegrationTests/AWSS3StoragePluginPrefixKeyResolverTests.swift index 3ff2fb16b5..4a9c09c564 100644 --- a/AmplifyPlugins/Storage/Tests/StorageHostApp/AWSS3StoragePluginIntegrationTests/AWSS3StoragePluginPrefixKeyResolverTests.swift +++ b/AmplifyPlugins/Storage/Tests/StorageHostApp/AWSS3StoragePluginIntegrationTests/AWSS3StoragePluginPrefixKeyResolverTests.swift @@ -48,7 +48,7 @@ class AWSS3StoragePluginKeyResolverTests: AWSS3StoragePluginTestBase { /// func testUploadListDownload() async throws { let key = UUID().uuidString - let data = key.data(using: .utf8)! + let data = Data(key.utf8) let uploadCompleted = expectation(description: "upload completed") Task { do { @@ -88,7 +88,7 @@ class AWSS3StoragePluginKeyResolverTests: AWSS3StoragePluginTestBase { /// func testUploadRemoveDownload() async { let key = UUID().uuidString - let data = key.data(using: .utf8)! + let data = Data(key.utf8) let done = expectation(description: "done") Task { diff --git a/AmplifyTests/CategoryTests/Notifications/Push/PushNotificationsCategoryClientAPITests.swift b/AmplifyTests/CategoryTests/Notifications/Push/PushNotificationsCategoryClientAPITests.swift index bd5d44a782..6f18b35b6a 100644 --- a/AmplifyTests/CategoryTests/Notifications/Push/PushNotificationsCategoryClientAPITests.swift +++ b/AmplifyTests/CategoryTests/Notifications/Push/PushNotificationsCategoryClientAPITests.swift @@ -48,7 +48,7 @@ class PushNotificationsCategoryClientAPITests: XCTestCase { } func testRegisterDeviceToken_shouldSucceed() async throws { - let data = "Data".data(using: .utf8)! + let data = Data("Data".utf8) let expectedMessage = "registerDevice(token:\(data))" let methodInvoked = expectation(description: "Expected method was invoked on plugin") plugin.listeners.append { message in diff --git a/AmplifyTests/CoreTests/AmplifyConfigurationInitializationTests.swift b/AmplifyTests/CoreTests/AmplifyConfigurationInitializationTests.swift index ca7e49c381..af9794abb8 100644 --- a/AmplifyTests/CoreTests/AmplifyConfigurationInitializationTests.swift +++ b/AmplifyTests/CoreTests/AmplifyConfigurationInitializationTests.swift @@ -97,7 +97,7 @@ class AmplifyConfigurationInitializationTests: XCTestCase { .appendingPathComponent("amplifyconfiguration.json") let poorlyFormedJSON = #"{"foo"}"# - let configData = poorlyFormedJSON.data(using: .utf8)! + let configData = Data(poorlyFormedJSON.utf8) try configData.write(to: configFilePath) XCTAssertThrowsError(try AmplifyConfiguration(configurationFile: configFilePath)) { error in @@ -117,7 +117,7 @@ class AmplifyConfigurationInitializationTests: XCTestCase { .appendingPathComponent("amplifyconfiguration.json") let poorlyFormedJSON = #"{"foo": true}"# - let configData = poorlyFormedJSON.data(using: .utf8)! + let configData = Data(poorlyFormedJSON.utf8) try configData.write(to: configFilePath) let amplifyConfig = try AmplifyConfiguration(configurationFile: configFilePath) diff --git a/AmplifyTests/CoreTests/ConfigurationTests.swift b/AmplifyTests/CoreTests/ConfigurationTests.swift index 08f5c25b44..fd24835b15 100644 --- a/AmplifyTests/CoreTests/ConfigurationTests.swift +++ b/AmplifyTests/CoreTests/ConfigurationTests.swift @@ -134,7 +134,7 @@ class ConfigurationTests: XCTestCase { {"UserAgent":"aws-amplify-cli/2.0","Version":"1.0","storage":{"plugins":{"MockStorageCategoryPlugin":{}}}} """ - let jsonData = jsonString.data(using: .utf8)! + let jsonData = Data(jsonString.utf8) let decoder = JSONDecoder() let config = try decoder.decode(AmplifyConfiguration.self, from: jsonData) XCTAssertNotNil(config.storage) diff --git a/AmplifyTests/CoreTests/JSONValueTests.swift b/AmplifyTests/CoreTests/JSONValueTests.swift index 50a1fbbdec..c719746893 100644 --- a/AmplifyTests/CoreTests/JSONValueTests.swift +++ b/AmplifyTests/CoreTests/JSONValueTests.swift @@ -13,8 +13,8 @@ class JSONValueTests: XCTestCase { func testDecode() throws { let decoder = JSONDecoder() let sourceString = #"{"stringValue": "a string", "numberValue": 123.45, "booleanValue": true}"# - let sourceData = sourceString.data(using: .utf8) - let decodedObject = try decoder.decode(JSONValue.self, from: sourceData!) + let sourceData = Data(sourceString.utf8) + let decodedObject = try decoder.decode(JSONValue.self, from: sourceData) let expectedObject: JSONValue = [ "booleanValue": true, From 22a0cf01b78addcfe7dea06a163707ac38b6105c Mon Sep 17 00:00:00 2001 From: Michael Law <1365977+lawmicha@users.noreply.github.com> Date: Wed, 20 Dec 2023 14:11:35 -0500 Subject: [PATCH 5/5] fix(DataStore): watchOS subscription disabled configuration value (#3432) --- .../Configuration/DataStoreConfiguration+Helper.swift | 2 +- .../Core/DataStoreCategoryConfigurationTests.swift | 10 ++++++++-- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Configuration/DataStoreConfiguration+Helper.swift b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Configuration/DataStoreConfiguration+Helper.swift index cf518f0882..04487a2ed0 100644 --- a/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Configuration/DataStoreConfiguration+Helper.swift +++ b/AmplifyPlugins/DataStore/Sources/AWSDataStorePlugin/Configuration/DataStoreConfiguration+Helper.swift @@ -90,7 +90,7 @@ extension DataStoreConfiguration { /// enabled is only possible during special circumstances such as actively streaming audio. /// See https://github.com/aws-amplify/amplify-swift/pull/3368 for more details. public static var subscriptionsDisabled: DataStoreConfiguration { - .custom(disableSubscriptions: { false }) + .custom(disableSubscriptions: { true }) } #else /// The default configuration. diff --git a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/DataStoreCategoryConfigurationTests.swift b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/DataStoreCategoryConfigurationTests.swift index 8aa3354572..490c453cfd 100644 --- a/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/DataStoreCategoryConfigurationTests.swift +++ b/AmplifyPlugins/DataStore/Tests/AWSDataStorePluginTests/Core/DataStoreCategoryConfigurationTests.swift @@ -14,7 +14,13 @@ class AWSDataStorePluginConfigurationTests: XCTestCase { override func setUp() async throws { await Amplify.reset() } - + + #if os(watchOS) + func testSubscriptionDisabledTrue() throws { + XCTAssertTrue(DataStoreConfiguration.subscriptionsDisabled.disableSubscriptions()) + } + #endif + func testDoesNotThrowOnMissingConfig() throws { #if os(watchOS) let plugin = AWSDataStorePlugin(modelRegistration: TestModelRegistration(), @@ -33,5 +39,5 @@ class AWSDataStorePluginConfigurationTests: XCTestCase { XCTFail("Should not throw even if not supplied with a plugin-specific config.") } } - + }